diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7fd7e89 --- /dev/null +++ b/.gitignore @@ -0,0 +1,60 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# PyBuilder +target/ + +# pyenv +.python-version + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ \ No newline at end of file diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000..17d6cef --- /dev/null +++ b/.pylintrc @@ -0,0 +1,558 @@ +[MASTER] + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. +extension-pkg-whitelist= + +# Add files or directories to the blacklist. They should be base names, not +# paths. +ignore=CVS + +# Add files or directories matching the regex patterns to the blacklist. The +# regex matches against base names, not paths. +ignore-patterns= + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the +# number of processors available to use. +jobs=1 + +# Control the amount of potential inferred values when inferring a single +# object. This can help the performance when dealing with large functions or +# complex, nested conditions. +limit-inference-results=100 + +# List of plugins (as comma separated values of python modules names) to load, +# usually to register additional checkers. +load-plugins= + +# Pickle collected data for later comparisons. +persistent=yes + +# Specify a configuration file. +#rcfile= + +# When enabled, pylint would attempt to guess common misconfiguration and emit +# user-friendly hints instead of false-positive error messages. +suggestion-mode=yes + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED. +confidence= + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once). You can also use "--disable=all" to +# disable everything first and then reenable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use "--disable=all --enable=classes +# --disable=W". +disable=print-statement, + parameter-unpacking, + unpacking-in-except, + old-raise-syntax, + backtick, + long-suffix, + old-ne-operator, + old-octal-literal, + import-star-module-level, + non-ascii-bytes-literal, + raw-checker-failed, + bad-inline-option, + locally-disabled, + locally-enabled, + file-ignored, + suppressed-message, + useless-suppression, + deprecated-pragma, + use-symbolic-message-instead, + apply-builtin, + basestring-builtin, + buffer-builtin, + cmp-builtin, + coerce-builtin, + execfile-builtin, + file-builtin, + long-builtin, + raw_input-builtin, + reduce-builtin, + standarderror-builtin, + unicode-builtin, + xrange-builtin, + coerce-method, + delslice-method, + getslice-method, + setslice-method, + no-absolute-import, + old-division, + dict-iter-method, + dict-view-method, + next-method-called, + metaclass-assignment, + indexing-exception, + raising-string, + reload-builtin, + oct-method, + hex-method, + nonzero-method, + cmp-method, + input-builtin, + round-builtin, + intern-builtin, + unichr-builtin, + map-builtin-not-iterating, + zip-builtin-not-iterating, + range-builtin-not-iterating, + filter-builtin-not-iterating, + using-cmp-argument, + eq-without-hash, + div-method, + idiv-method, + rdiv-method, + exception-message-attribute, + invalid-str-codec, + sys-max-int, + bad-python3-import, + deprecated-string-function, + deprecated-str-translate-call, + deprecated-itertools-function, + deprecated-types-field, + next-method-defined, + dict-items-not-iterating, + dict-keys-not-iterating, + dict-values-not-iterating, + deprecated-operator-function, + deprecated-urllib-function, + xreadlines-attribute, + deprecated-sys-function, + exception-escape, + comprehension-escape + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +enable=c-extension-no-member + + +[REPORTS] + +# Python expression which should return a note less than 10 (10 is the highest +# note). You have access to the variables errors warning, statement which +# respectively contain the number of errors / warnings messages and the total +# number of statements analyzed. This is used by the global evaluation report +# (RP0004). +evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details. +#msg-template= + +# Set the output format. Available formats are text, parseable, colorized, json +# and msvs (visual studio). You can also give a reporter class, e.g. +# mypackage.mymodule.MyReporterClass. +output-format=text + +# Tells whether to display a full report or only the messages. +reports=no + +# Activate the evaluation score. +score=yes + + +[REFACTORING] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + +# Complete name of functions that never returns. When checking for +# inconsistent-return-statements if a never returning function is called then +# it will be considered as an explicit return statement and no message will be +# printed. +never-returning-functions=sys.exit + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME, + XXX, + TODO + + +[FORMAT] + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +expected-line-ending-format= + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Maximum number of characters on a single line. +max-line-length=120 + +# Maximum number of lines in a module. +max-module-lines=1000 + +# List of optional constructs for which whitespace checking is disabled. `dict- +# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. +# `trailing-comma` allows a space between comma and closing bracket: (a, ). +# `empty-line` allows space-only lines. +no-space-check=trailing-comma, + dict-separator + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid to define new builtins when possible. +additional-builtins= + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=yes + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_, + _cb + +# A regular expression matching the name of dummy variables (i.e. expected to +# not be used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. Default to name +# with leading underscore. +ignored-argument-names=_.*|^ignored_|^unused_ + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io + + +[SIMILARITIES] + +# Ignore comments when computing similarities. +ignore-comments=yes + +# Ignore docstrings when computing similarities. +ignore-docstrings=yes + +# Ignore imports when computing similarities. +ignore-imports=no + +# Minimum lines number of a similarity. +min-similarity-lines=4 + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + +# Tells whether missing members accessed in mixin class should be ignored. A +# mixin class is detected if its name ends with "mixin" (case insensitive). +ignore-mixin-members=yes + +# Tells whether to warn about missing members when the owner of the attribute +# is inferred to be None. +ignore-none=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis. It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules= + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + + +[BASIC] + +# Naming style matching correct argument names. +argument-naming-style=snake_case + +# Regular expression matching correct argument names. Overrides argument- +# naming-style. +#argument-rgx= + +# Naming style matching correct attribute names. +attr-naming-style=snake_case + +# Regular expression matching correct attribute names. Overrides attr-naming- +# style. +#attr-rgx= + +# Bad variable names which should always be refused, separated by a comma. +bad-names=foo, + bar, + baz, + toto, + tutu, + tata + +# Naming style matching correct class attribute names. +class-attribute-naming-style=any + +# Regular expression matching correct class attribute names. Overrides class- +# attribute-naming-style. +#class-attribute-rgx= + +# Naming style matching correct class names. +class-naming-style=PascalCase + +# Regular expression matching correct class names. Overrides class-naming- +# style. +#class-rgx= + +# Naming style matching correct constant names. +const-naming-style=UPPER_CASE + +# Regular expression matching correct constant names. Overrides const-naming- +# style. +#const-rgx= + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + +# Naming style matching correct function names. +function-naming-style=snake_case + +# Regular expression matching correct function names. Overrides function- +# naming-style. +#function-rgx= + +# Good variable names which should always be accepted, separated by a comma. +good-names=i, + j, + k, + ex, + Run, + _ + +# Include a hint for the correct naming format with invalid-name. +include-naming-hint=no + +# Naming style matching correct inline iteration names. +inlinevar-naming-style=any + +# Regular expression matching correct inline iteration names. Overrides +# inlinevar-naming-style. +#inlinevar-rgx= + +# Naming style matching correct method names. +method-naming-style=snake_case + +# Regular expression matching correct method names. Overrides method-naming- +# style. +#method-rgx= + +# Naming style matching correct module names. +module-naming-style=snake_case + +# Regular expression matching correct module names. Overrides module-naming- +# style. +#module-rgx= + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=^_ + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +# These decorators are taken in consideration only for invalid-name. +property-classes=abc.abstractproperty + +# Naming style matching correct variable names. +variable-naming-style=snake_case + +# Regular expression matching correct variable names. Overrides variable- +# naming-style. +#variable-rgx= + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. Available dictionaries: none. To make it working +# install python-enchant package.. +spelling-dict= + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to indicated private dictionary in +# --spelling-private-dict-file option instead of raising a message. +spelling-store-unknown-words=no + + +[LOGGING] + +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules=logging + + +[IMPORTS] + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Deprecated modules which should not be used, separated by a comma. +deprecated-modules=optparse,tkinter.tix + +# Create a graph of external dependencies in the given file (report RP0402 must +# not be disabled). +ext-import-graph= + +# Create a graph of every (i.e. internal and external) dependencies in the +# given file (report RP0402 must not be disabled). +import-graph= + +# Create a graph of internal dependencies in the given file (report RP0402 must +# not be disabled). +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + + +[DESIGN] + +# Maximum number of arguments for function / method. +max-args=5 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Maximum number of boolean expressions in an if statement. +max-bool-expr=5 + +# Maximum number of branch for function / method body. +max-branches=12 + +# Maximum number of locals for function / method body. +max-locals=15 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + +# Maximum number of return / yield for function / method body. +max-returns=6 + +# Maximum number of statements in function / method body. +max-statements=50 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=0 + + +[CLASSES] + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict, + _fields, + _replace, + _source, + _make + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=cls + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when being caught. Defaults to +# "Exception". +overgeneral-exceptions=Exception diff --git a/README.md b/README.md index db61c2d..ce44c81 100644 --- a/README.md +++ b/README.md @@ -1 +1,31 @@ # RestPyTAC +Short description + +# Setup +### Prerequisites +- Python [3.4 or higher](https://www.python.org/downloads/) +- Virtual environment [Virtualenvwrapper](https://virtualenvwrapper.readthedocs.io/en/latest/) +- Cloned repository [git](https://github.com/Social-projects-Rivne/RestPyTAC) +- Docker [install](https://docs.docker.com/install/) +- Docker-compose [install](https://docs.docker.com/compose/install/) + +### Setting up the project +- create new virtual env `mkvirtualenv api-tests -p ` +- activate the env by running `workon api-tests` +- Install modules `pip install -r ~//requirements.pip` +- Clone repository [rest_Spring_Docker](https://github.com/momel/rest_Spring_Docker) +- Run docker image from cloned repository: `cd ~/` and `docker-compose up -d` + +# Libs +- lib [unittest-2.4.0](https://docs.python.org/3/library/unittest.html?highlight=unittest#module-unittest) +- lib [requests-2.20.0](http://docs.python-requests.org/en/master/) +- lib [nose-1.3.7](https://nose.readthedocs.io/en/latest/index.html) + +## Code quality +Project supports code style inspections with [pycodestyle]() tool. + +Run `pip install pycodestyle` to perform project code inspection using `pep8`. + +## Run tests +- To run unit tests execute: `cd ~//tests/unit` and run terminal command`nosetests -v`. +- To run functional tests execute: `cd ~//tests/functional` and run terminal command `nosetests -v`. \ No newline at end of file diff --git a/requirements.pip b/requirements.pip new file mode 100644 index 0000000..2216f50 --- /dev/null +++ b/requirements.pip @@ -0,0 +1,5 @@ +pycodestyle==2.4.0 +requests==2.20.0 +nose==1.3.7 +pylint==2.1.1 +ddt==1.2.0 \ No newline at end of file diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/application/__init__.py b/tests/application/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/application/application.py b/tests/application/application.py new file mode 100644 index 0000000..0d3472e --- /dev/null +++ b/tests/application/application.py @@ -0,0 +1,165 @@ +"""Functions for Spring API testing""" + +import requests +from requests import request + +from tests.constants.constants import Endpoints + + +class ApiWrapper: + """Wrapper for REST API""" + + def __init__(self, app_url): + """Initialize the attributes of a class""" + self.request_session = requests.session() + self.base_url = app_url + + def __del__(self): + """Close request session""" + self.request_session.close() + + def _generate_full_url(self, path): + """Generate the full url with base url and path""" + return "{}{}".format(self.base_url, path) + + def reset(self): + """Reset API""" + return self.request_session.get(self._generate_full_url(Endpoints.reset)) + + def login(self, name: str, password: str) -> request: + """Login user with name and password.""" + return self.request_session.post(self._generate_full_url(Endpoints.login), + params={"name": name, "password": password}) + + def logout(self, name: str, token: str) -> request: + """Logout user with name and user token.""" + return self.request_session.post(self._generate_full_url(Endpoints.logout), + params={"name": name, "token": token}) + + def login_admins(self, token: str) -> request: + """Logged admins""" + return self.request_session.get(self._generate_full_url(Endpoints.login_admins), + params={"token": token}) + + def login_users(self, token: str) -> request: + """Logged users""" + return self.request_session.get(self._generate_full_url(Endpoints.login_users), + params={"token": token}) + + def login_tockens(self, token: str) -> request: + """Alive tokens""" + return self.request_session.get(self._generate_full_url(Endpoints.login_tockens), + params={"token": token}) + + def admins(self, token: str) -> request: + """All admins""" + return self.request_session.get(self._generate_full_url(Endpoints.admins), + params={"token": token}) + + def get_user_all_items(self, user, admin_token): + """Get all user items""" + return self.request_session.get(self._generate_full_url(Endpoints.item_user).format(name=user), + params={"token": admin_token}) + + def get_user_item_by_index(self, index, user, admin_token): + """Get user item by index""" + return self.request_session.get(self._generate_full_url(Endpoints.item_user_by_index).format(index=index, + name=user), + params={"token": admin_token}) + + def add_item(self, index, token, item): + """Add item""" + return self.request_session.post(self._generate_full_url(Endpoints.item).format(index=index), + params={"token": token, "item": item}) + + def delete_item(self, index, token): + """Delete item""" + return self.request_session.delete(self._generate_full_url(Endpoints.item).format(index=index), + params={"token": token}) + + def update_item(self, index, token, item): + """Update item""" + return self.request_session.put(self._generate_full_url(Endpoints.item).format(index=index), + params={"token": token, "item": item}) + + def get_item(self, index, token): + """Get item by index""" + return self.request_session.get(self._generate_full_url(Endpoints.item).format(index=index), + params={"token": token}) + + def get_item_indexes(self, token): + """Get all item indexes""" + return self.request_session.get(self._generate_full_url(Endpoints.itemindexes), params={"token": token}) + + def get_all_items(self, token): + """Get all items by user""" + return self.request_session.get(self._generate_full_url(Endpoints.items), params={"token": token}) + + def change_cool_down_time(self, admin_token, new_value): + """Change cool down time""" + return self.request_session.put(self._generate_full_url(Endpoints.cooldowntime), + params={"token": admin_token, "time": new_value}) + + def get_cool_down_time(self): + """Get cool down time""" + return self.request_session.get(self._generate_full_url(Endpoints.cooldowntime)) + + def change_token_life_time(self, admin_token, new_value): + """Change token life time""" + return self.request_session.put(self._generate_full_url(Endpoints.tokenlifetime), + params={"token": admin_token, "time": new_value}) + + def get_token_life_time(self): + """Get token life time""" + return self.request_session.get(self._generate_full_url(Endpoints.tokenlifetime)) + + def get_all_users(self, admin_token): + """Get all users""" + return self.request_session.get(self._generate_full_url(Endpoints.users), params={"token": admin_token}) + + def get_locked_users(self, admin_token): + """Get locked users""" + return self.request_session.get(self._generate_full_url(Endpoints.locked_users), + params={"token": admin_token}) + + def get_locked_admins(self, admin_token): + """Get locked admins""" + return self.request_session.get(self._generate_full_url(Endpoints.locked_admins), + params={"token": admin_token}) + + def lock_user(self, admin_token, user_to_lock): + """Lock user by manual command""" + return self.request_session.post((self._generate_full_url(Endpoints.locked_user) + user_to_lock), + params={"token": admin_token, 'name': user_to_lock}) + + def unlock_all_users(self, admin_token): + """Unlock all users""" + return self.request_session.put(self._generate_full_url(Endpoints.locked_reset), + params={"token": admin_token}) + + def unlock_user(self, admin_token, user_to_unlock): + """Unlock user by manual command""" + return self.request_session.put((self._generate_full_url(Endpoints.locked_user) + user_to_unlock), + params={"token": admin_token, 'name': user_to_unlock}) + + def create_new_user(self, admin_token, new_name, new_password, admin_rights): + """Create new user""" + return self.request_session.post(self._generate_full_url(Endpoints.user), + {"token": admin_token, "name": new_name, + "password": new_password, + "rights": admin_rights}) + + def change_pass(self, token, old_password, new_password): + """change pass""" + return self.request_session.put(self._generate_full_url(Endpoints.user), {"token": token, + "oldpassword": old_password, + "newpassword": new_password}) + + def get_user_name(self, token): + """get user name of logged user""" + return self.request_session.get(self._generate_full_url(Endpoints.user), params={"token": token}) + + def delete_user(self, admin_token, name): + """delete user""" + return self.request_session.delete(self._generate_full_url(Endpoints.user), params={"token": admin_token, + "name": name}) diff --git a/tests/constants/__init__.py b/tests/constants/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/constants/constants.py b/tests/constants/constants.py new file mode 100644 index 0000000..75e400e --- /dev/null +++ b/tests/constants/constants.py @@ -0,0 +1,121 @@ +"""Default constants""" + + +ITEM_NAMES = ["Product", "Car", "Soap", "TV", "Wine", "Tea", "Coffee", "Bread", "apple", "laptop", + "fish", "cat", "dog", "pineapple", "phone", "number1", "number2"] +VALID_STATUS_CODE = 200 +INVALID_TOKEN = "2134rfvsd231g45" + + +class DefaultUser: + """Default user with admin rights. Has admin token""" + user = "admin" + password = "qwerty" + user_akimatc = "akimatc" + user_admin = "admin" + password_akimatc = "qwerty" + password_admin = "qwerty" + + +class Users: + """Default valid user, password and fake user, password""" + valid_user = "vvasylystc" + valid_password = "qwerty" + fake_user = "vVASYLystc333" + fake_password = "Qwerty123" + + +class DefaultToken: + """Default token""" + token = "0123456789ABCDEF0123456789ABCDEF" + + +class DefaultItem: + """Default item for items""" + item = "empty" + + +class DefaultNum: + """Default number for items""" + num = 1000 + + +class DefaultBool: + """Default bool for items""" + bool = False + + +class InitUsers: + """The dictionary of all valid users""" + users = {"akimatc": "qwerty", + "khalaktc": "qwerty", + "kilinatc": "qwerty", + "OKonokhtc": "qwerty", + "otlumtc": "qwerty", + "slototc": "qwerty", + "vbudktc": "qwerty", + "vvasylystc": "qwerty"} + + +class InitInvalidUsers: + """The dictionary with fake users""" + invalid_users = {"admin": "QWERTY", + "akimatc1": "qwerty", + "khalaktc": "", + "": "qwerty", + "OKonokhtc": "OKonokhtc"} + + +class UserToTest: + """User to test""" + login = "otlumtc" + password = "qwerty" + + +class InvalidValues: + """Invalid values for login and passwords""" + values = ("qwerty ", " ", "", "!@#$%^&*()><", "ываываыва", "ÆðÆðÆðÆð", + "本本本本", "555555555555555555555555555555555555555555555555555555555555555555555555555555555", "k") + + +class BaseUrl: + """Url for connecting to API""" + base_url = "http://localhost:8080" + + +class InvalidUrl: + """Invalid url for testing exceptions""" + invalid_url = "http://localhost:80801" + + +class NewUser: + """Constants to create new user""" + name = "Username" + password = "newtestpass" + isAdmin = "true" + isUser = "false" + wrong_rights = "admen" + + +class Endpoints: + """All endpoints in API""" + reset = "/reset" + login = "/login" + logout = "/logout" + user = "/user" + cooldowntime = "/cooldowntime" + tokenlifetime = "/tokenlifetime" + admins = "/admins" + login_admins = "/login/admins" + locked_admins = "/locked/admins" + users = "/users" + login_users = "/login/users" + login_tockens = "/login/tockens" + locked_users = "/locked/users" + locked_user = "/locked/user/" + locked_reset = "/locked/reset" + item_user = "/item/user/{name}" + item_user_by_index = "/item/{index}/user/{name}" + item = "/item/{index}" + items = "/items" + itemindexes = "/itemindexes" diff --git a/tests/functional/__init__.py b/tests/functional/__init__.py new file mode 100644 index 0000000..0386201 --- /dev/null +++ b/tests/functional/__init__.py @@ -0,0 +1,23 @@ +"""Base class and functions for testing""" + +import unittest + +from tests.application.application import ApiWrapper +from tests.constants.constants import BaseUrl + + +class ApiTestBase(unittest.TestCase): + """Main class for testing""" + + @classmethod + def setUpClass(cls): + """Define open request session that will be executed before each class test method.""" + cls.application = ApiWrapper(BaseUrl.base_url) + + def setUp(self): + """Define open request session that will be executed before each test method.""" + self.application.reset() + + def tearDown(self): + """Reset API data that will be executed after each test method.""" + self.application.reset() diff --git a/tests/functional/tests_add_item.py b/tests/functional/tests_add_item.py new file mode 100644 index 0000000..4a375d0 --- /dev/null +++ b/tests/functional/tests_add_item.py @@ -0,0 +1,65 @@ +"""Functional tests for add item""" + +from random import choice, randint + +from tests.functional import ApiTestBase +from tests.constants.constants import InitUsers, INVALID_TOKEN, VALID_STATUS_CODE, ITEM_NAMES + + +ITEM_INDEX = randint(0, 1000) +ITEM_NAME = choice(ITEM_NAMES) + + +class TestAddItem(ApiTestBase): + """Class for tests add item""" + + def test_add_item_positive(self): + """Test add item with valid token""" + counter = 0 + for user, password in InitUsers.users.items(): + with self.subTest(i=user): + token = self.application.login(user, password).json()["content"] + add_item_user_response = self.application.add_item(counter, token, ITEM_NAME) + counter = counter + 1 + self.assertEqual(VALID_STATUS_CODE, add_item_user_response.status_code) + self.assertTrue(add_item_user_response.json()["content"]) + + def test_add_specific_item(self): + """Test add item with specific item""" + for user, password in InitUsers.users.items(): + with self.subTest(i=user): + token = self.application.login(user, password).json()["content"] + self.application.add_item(ITEM_INDEX, token, ITEM_NAME) + get_item_response = self.application.get_item(ITEM_INDEX, token) + self.assertEqual(ITEM_NAME, get_item_response.json()["content"]) + + def test_add_item_negative(self): + """Test can not add item with invalid token""" + add_item_user_response = self.application.add_item(ITEM_INDEX, INVALID_TOKEN, ITEM_NAME) + self.assertEqual(VALID_STATUS_CODE, add_item_user_response.status_code) + self.assertFalse(add_item_user_response.json()["content"]) + + def test_add_item_invalid_index(self): + """Test can not add item when index not int""" + for user, password in InitUsers.users.items(): + with self.subTest(i=user): + token = self.application.login(user, password).json()["content"] + add_item_user_response = self.application.add_item(ITEM_NAME, token, ITEM_NAME) + self.assertNotEqual(VALID_STATUS_CODE, add_item_user_response.status_code) + + def test_add_item_invalid_index1(self): + """Test can not add item when index four zeros""" + for user, password in InitUsers.users.items(): + with self.subTest(i=user): + token = self.application.login(user, password).json()["content"] + add_item_user_response = self.application.add_item(0000, token, ITEM_NAME) + self.assertNotEqual(VALID_STATUS_CODE, add_item_user_response.status_code) + + def test_add_int_item(self): + """Test can not add item with only numbers""" + for user, password in InitUsers.users.items(): + with self.subTest(i=user): + token = self.application.login(user, password).json()["content"] + add_item_user_response = self.application.add_item(ITEM_INDEX, token, ITEM_INDEX) + self.assertEqual(VALID_STATUS_CODE, add_item_user_response.status_code) + self.assertFalse(add_item_user_response.json()["content"]) diff --git a/tests/functional/tests_admins.py b/tests/functional/tests_admins.py new file mode 100644 index 0000000..f08aa33 --- /dev/null +++ b/tests/functional/tests_admins.py @@ -0,0 +1,34 @@ +"""Functional tests for admins""" + +from ddt import data, ddt + +from tests.constants.constants import DefaultToken, DefaultUser, Users, VALID_STATUS_CODE +from tests.functional import ApiTestBase + + +@ddt +class TestAdmins(ApiTestBase): + """Class for testing""" + + def test_admins(self): + """Get all admins with admin token. If list not empty test pass (positive)""" + login = self.application.login(DefaultUser.user, DefaultUser.password) + self.assertEqual(VALID_STATUS_CODE, login.status_code) + all_admins = self.application.admins(login.json().get("content")) + self.assertEqual(VALID_STATUS_CODE, all_admins.status_code) + self.assertTrue(all_admins.json().get("content"), "Content is empty") + + def test_admins_user(self): + """Get all admins with user token. If list empty test pass (negative)""" + login = self.application.login(Users.valid_user, Users.valid_password) + self.assertEqual(VALID_STATUS_CODE, login.status_code) + all_admins = self.application.admins(login.json().get("content")) + self.assertEqual(VALID_STATUS_CODE, all_admins.status_code) + self.assertFalse(all_admins.json().get("content"), "Content is not empty") + + @data(DefaultToken.token, "") + def test_admins_token(self, value): + """Get all admins with default and empty token. If list empty test pass (negative)""" + all_admins = self.application.admins(value) + self.assertEqual(VALID_STATUS_CODE, all_admins.status_code) + self.assertFalse(all_admins.json().get("content"), "Content is not empty") diff --git a/tests/functional/tests_all_items.py b/tests/functional/tests_all_items.py new file mode 100644 index 0000000..44fa1da --- /dev/null +++ b/tests/functional/tests_all_items.py @@ -0,0 +1,40 @@ +"""Functional tests for all items""" + +from tests.constants.constants import InitUsers, INVALID_TOKEN, VALID_STATUS_CODE +from tests.functional import ApiTestBase + + +class TestAllItems(ApiTestBase): + """Class for tests of all items""" + + def test_without_items(self): + """Test get all items when user has not any items""" + for user, password in InitUsers.users.items(): + with self.subTest(i=user): + token = self.application.login(user, password).json()["content"] + get_all_items_response = self.application.get_all_items(token) + self.assertEqual(VALID_STATUS_CODE, get_all_items_response.status_code) + self.assertFalse(get_all_items_response.json()["content"]) + + def test_with_items(self): + """Test get all items when user has items""" + for user, password in InitUsers.users.items(): + with self.subTest(i=user): + token = self.application.login(user, password).json()["content"] + self.application.add_item(1, token, "Product") + self.application.add_item(2, token, "Car") + get_all_items_response = self.application.get_all_items(token) + self.assertEqual(VALID_STATUS_CODE, get_all_items_response.status_code) + self.assertNotEqual("", get_all_items_response.json()["content"]) + self.assertTrue(get_all_items_response.json()["content"]) + + def test_items_by_invalid_token(self): + """Test can not get all items with invalid token""" + for user, password in InitUsers.users.items(): + with self.subTest(i=user): + token = self.application.login(user, password).json()["content"] + self.application.add_item(1, token, "Product") + self.application.add_item(2, token, "Car") + get_all_items_response = self.application.get_all_items(INVALID_TOKEN) + self.assertEqual(VALID_STATUS_CODE, get_all_items_response.status_code) + self.assertFalse(get_all_items_response.json()["content"]) diff --git a/tests/functional/tests_cooldowntime.py b/tests/functional/tests_cooldowntime.py new file mode 100644 index 0000000..4a8ad21 --- /dev/null +++ b/tests/functional/tests_cooldowntime.py @@ -0,0 +1,164 @@ +""" +Testing response of "/cooldowntime" module +""" + +from tests.functional import ApiTestBase +from tests.constants.constants import DefaultUser +from tests.utils.helper import get_new_value_different_func + + +class TestCoolDownTime(ApiTestBase): + """ + Testing response of "/cooldowntime" + """ + + def test_get_cool_down_time(self): + """ + Get the value of cool down time (positive test) + """ + + resp = self.application.get_cool_down_time() + + self.assertEqual(resp.status_code, 200) + self.assertTrue(resp.json()["content"] or resp.json()["content"] == 0) + + def test_set_cool_down_time_admin_positive(self): + """ + Change the cool down time value by admin (positive test) + """ + + new_cdt = get_new_value_different_func(self.application.get_cool_down_time, 200000, 100000) + + login = self.application.login(DefaultUser.user_admin, DefaultUser.password_admin) + token = login.json()["content"] + + resp = self.application.change_cool_down_time(token, new_cdt) + + last_resp = self.application.get_cool_down_time() + cdt_after = last_resp.json()["content"] + + self.assertEqual(resp.status_code, 200) + self.assertTrue(resp.json()["content"]) + self.assertEqual(cdt_after, new_cdt) + + def test_set_cool_down_time_admin_negative(self): + """ + Change the cool down time value by admin with invalid value (negative test) + """ + + new_cdt = get_new_value_different_func(self.application.get_cool_down_time, -200000, -100000) + + login = self.application.login(DefaultUser.user_admin, DefaultUser.password_admin) + token = login.json()["content"] + + resp = self.application.change_cool_down_time(token, new_cdt) + + last_resp = self.application.get_cool_down_time() + cdt_after = last_resp.json()["content"] + + self.assertEqual(resp.status_code, 200) + self.assertTrue(resp.json()["content"]) + self.assertEqual(cdt_after, new_cdt) + + def test_set_cool_down_time_admin_zero(self): + """ + Change the cool down time value by admin to zero (positive test) + """ + + new_cdt = get_new_value_different_func(self.application.get_cool_down_time, 0, 0) + + login = self.application.login(DefaultUser.user_admin, DefaultUser.password_admin) + token = login.json()["content"] + + resp = self.application.change_cool_down_time(token, new_cdt) + + last_resp = self.application.get_cool_down_time() + cdt_after = last_resp.json()["content"] + + self.assertEqual(resp.status_code, 200) + self.assertTrue(resp.json()["content"]) + self.assertEqual(cdt_after, new_cdt) + + def test_set_cool_down_time_admin_none(self): + """ + Change the cool down time value by admin to None (negative test) + """ + + new_cdt = None + def_cdt = 1000 + + login = self.application.login(DefaultUser.user_admin, DefaultUser.password_admin) + token = login.json()["content"] + + resp = self.application.change_cool_down_time(token, new_cdt) + + last_resp = self.application.get_cool_down_time() + cdt_after = last_resp.json()["content"] + + self.assertEqual(resp.status_code, 200) + self.assertTrue(resp.json()["content"]) + self.assertEqual(cdt_after, def_cdt) + + def test_set_cool_down_time_admin_float(self): + """ + Change the cool down time value by admin to float value (negative test) + """ + + new_cdt = get_new_value_different_func(self.application.get_cool_down_time, 200000.555, 100000) + + resp = self.application.get_cool_down_time() + curr_cdt = resp.json()["content"] + + login = self.application.login(DefaultUser.user_admin, DefaultUser.password_admin) + token = login.json()["content"] + + resp = self.application.change_cool_down_time(token, new_cdt) + + last_resp = self.application.get_cool_down_time() + cdt_after = last_resp.json()["content"] + + self.assertEqual(resp.status_code, 400) + self.assertEqual(cdt_after, curr_cdt) + + def test_set_cool_down_time_admin_text(self): + """ + Change the cool down time value by admin to text (negative test) + """ + + new_cdt = "f%kdm525!(" + + resp = self.application.get_cool_down_time() + curr_cdt = resp.json()["content"] + + login = self.application.login(DefaultUser.user_admin, DefaultUser.password_admin) + token = login.json()["content"] + + resp = self.application.change_cool_down_time(token, new_cdt) + + last_resp = self.application.get_cool_down_time() + cdt_after = last_resp.json()["content"] + + self.assertEqual(resp.status_code, 400) + self.assertEqual(cdt_after, curr_cdt) + + def test_set_cool_down_time_user(self): + """ + Change the cool down time value by user (negative test) + """ + + new_cdt = get_new_value_different_func(self.application.get_cool_down_time, 500000, 100000) + + resp = self.application.get_cool_down_time() + curr_cdt = resp.json()["content"] + + login = self.application.login(DefaultUser.user_akimatc, DefaultUser.password_akimatc) + token = login.json()["content"] + + resp = self.application.change_cool_down_time(token, new_cdt) + + last_resp = self.application.get_cool_down_time() + cdt_after = last_resp.json()["content"] + + self.assertEqual(resp.status_code, 200) + self.assertFalse(resp.json()["content"]) + self.assertEqual(cdt_after, curr_cdt) diff --git a/tests/functional/tests_delete_item.py b/tests/functional/tests_delete_item.py new file mode 100644 index 0000000..378f5f6 --- /dev/null +++ b/tests/functional/tests_delete_item.py @@ -0,0 +1,43 @@ +"""Functional tests for delete item""" + +from random import randint, choice + +from tests.constants.constants import InitUsers, VALID_STATUS_CODE, ITEM_NAMES, INVALID_TOKEN +from tests.functional import ApiTestBase + + +ITEM_NAME = choice(ITEM_NAMES) +ITEM_INDEX = randint(0, 1000) + + +class TestDeleteItem(ApiTestBase): + """Class for tests of delete item""" + + def test_delete_item(self): + """Test delete item when user has item""" + for user, password in InitUsers.users.items(): + with self.subTest(i=user): + token = self.application.login(user, password).json()["content"] + self.application.add_item(ITEM_INDEX, token, ITEM_NAME) + delete_item_response = self.application.delete_item(ITEM_INDEX, token) + self.assertEqual(VALID_STATUS_CODE, delete_item_response.status_code) + self.assertTrue(delete_item_response.json()["content"]) + + def test_delete_empty_item(self): + """Test can not delete item when user has not any items""" + for user, password in InitUsers.users.items(): + with self.subTest(i=user): + token = self.application.login(user, password).json()["content"] + delete_item_response = self.application.delete_item(ITEM_INDEX, token) + self.assertEqual(VALID_STATUS_CODE, delete_item_response.status_code) + self.assertFalse(delete_item_response.json()["content"]) + + def test_delete_item_invalid_token(self): + """Test can not delete item with invalid token""" + for user, password in InitUsers.users.items(): + with self.subTest(i=user): + token = self.application.login(user, password).json()["content"] + self.application.add_item(ITEM_INDEX, token, ITEM_NAME) + delete_item_response = self.application.delete_item(ITEM_INDEX, INVALID_TOKEN) + self.assertEqual(VALID_STATUS_CODE, delete_item_response.status_code) + self.assertFalse(delete_item_response.json()["content"]) diff --git a/tests/functional/tests_get_all_items_user.py b/tests/functional/tests_get_all_items_user.py new file mode 100644 index 0000000..4053734 --- /dev/null +++ b/tests/functional/tests_get_all_items_user.py @@ -0,0 +1,72 @@ +"""Functional tests for get all items""" + +from random import choice, randint + +from tests.constants.constants import InitUsers, DefaultUser, VALID_STATUS_CODE, ITEM_NAMES, INVALID_TOKEN +from tests.functional import ApiTestBase + + +ITEM_INDEX = randint(0, 1000) +ITEM_NAME = choice(ITEM_NAMES) + + +class TestAllUserItems(ApiTestBase): + """Class for tests of get all items""" + + def test_get_items_by_admin(self): + """Test get user items with admin_token""" + admin_token = self.application.login(DefaultUser.user, DefaultUser.password).json()["content"] + for user in InitUsers.users: + with self.subTest(i=user): + get_items_user_response = self.application.get_user_all_items(user, admin_token) + self.assertEqual(VALID_STATUS_CODE, get_items_user_response.status_code) + self.assertFalse(get_items_user_response.json()["content"]) + + def test_get_items_by_admin_with_invalid_token(self): + """Test can not get items by admin with invalid token""" + self.application.login(DefaultUser.user, DefaultUser.password) + for user in InitUsers.users: + with self.subTest(i=user): + get_items_user_response = self.application.get_user_all_items(user, INVALID_TOKEN) + self.assertEqual(VALID_STATUS_CODE, get_items_user_response.status_code) + self.assertFalse(get_items_user_response.json()["content"]) + + def test_get_added_items_by_admin(self): + """Test get added user items by admin""" + for user, password in InitUsers.users.items(): + token = self.application.login(user, password).json()["content"] + self.application.add_item(ITEM_INDEX, token, ITEM_NAME) + admin_token = self.application.login(DefaultUser.user, DefaultUser.password).json()["content"] + for user in InitUsers.users: + with self.subTest(i=user): + get_items_user_response = self.application.get_user_all_items(user, admin_token) + self.assertEqual(VALID_STATUS_CODE, get_items_user_response.status_code) + self.assertTrue(get_items_user_response.json()["content"]) + + def test_get_items_invalid_user(self): + """Test can not get item invalid user""" + admin_token = self.application.login(DefaultUser.user, DefaultUser.password).json()["content"] + get_items_user_response = self.application.get_user_all_items(ITEM_NAME, admin_token) + self.assertNotEqual(VALID_STATUS_CODE, get_items_user_response.status_code) + self.assertIn("Error", get_items_user_response.text) + + def test_get_items_by_user(self): + """Test can not get user items with user token""" + for user in InitUsers.users: + with self.subTest(i=user): + token = self.application.login("kilinatc", "qwerty").json()["content"] + get_items_user_response = self.application.get_user_all_items(user, token) + self.assertEqual(VALID_STATUS_CODE, get_items_user_response.status_code) + self.assertFalse(get_items_user_response.json()["content"]) + + def test_get_added_items_by_user(self): + """Test can not get added user items by user token""" + for user, password in InitUsers.users.items(): + token = self.application.login(user, password).json()["content"] + self.application.add_item(ITEM_INDEX, token, ITEM_NAME) + token = self.application.login("kilinatc", "qwerty").json()["content"] + for user in InitUsers.users: + with self.subTest(i=user): + get_items_user_response = self.application.get_user_all_items(user, token) + self.assertEqual(VALID_STATUS_CODE, get_items_user_response.status_code) + self.assertFalse(get_items_user_response.json()["content"]) diff --git a/tests/functional/tests_get_item_by_index.py b/tests/functional/tests_get_item_by_index.py new file mode 100644 index 0000000..235725d --- /dev/null +++ b/tests/functional/tests_get_item_by_index.py @@ -0,0 +1,53 @@ +"""Functional tests for get item by index""" + +from random import choice, randint + +from tests.constants.constants import InitUsers, VALID_STATUS_CODE, ITEM_NAMES, INVALID_TOKEN +from tests.functional import ApiTestBase + + +ITEM_INDEX = randint(0, 1000) +ITEM_NAME = choice(ITEM_NAMES) + + +class TestGetItemByIndex(ApiTestBase): + """Class for tests of get item by index""" + + def test_get_empty_item(self): + """Test get item by index when user has not items""" + for user, password in InitUsers.users.items(): + with self.subTest(i=user): + token = self.application.login(user, password).json()["content"] + get_item_response = self.application.get_item(ITEM_INDEX, token) + self.assertEqual(VALID_STATUS_CODE, get_item_response.status_code) + self.assertFalse(get_item_response.json()["content"]) + + def test_get_item(self): + """Test get item by index when user has item""" + for user, password in InitUsers.users.items(): + with self.subTest(i=user): + token = self.application.login(user, password).json()["content"] + self.application.add_item(ITEM_INDEX, token, ITEM_NAME) + get_item_response = self.application.get_item(ITEM_INDEX, token) + self.assertEqual(VALID_STATUS_CODE, get_item_response.status_code) + self.assertTrue(get_item_response.json()["content"]) + self.assertEqual(ITEM_NAME, get_item_response.json()["content"]) + + def test_get_item_index_str(self): + """Test can not get item by index when index consists of letters""" + for user, password in InitUsers.users.items(): + with self.subTest(i=user): + token = self.application.login(user, password).json()["content"] + self.application.add_item(ITEM_INDEX, token, ITEM_NAME) + get_item_response = self.application.get_item(ITEM_NAME, token) + self.assertNotEqual(VALID_STATUS_CODE, get_item_response.status_code) + self.assertIn("Bad Request", get_item_response.text) + + def test_get_item_index_invalid_token(self): + """Test can not get item by index with invalid token""" + for user, password in InitUsers.users.items(): + with self.subTest(i=user): + self.application.login(user, password) + get_item_response = self.application.get_item(ITEM_INDEX, INVALID_TOKEN) + self.assertEqual(VALID_STATUS_CODE, get_item_response.status_code) + self.assertFalse(get_item_response.json()["content"]) diff --git a/tests/functional/tests_get_item_indexes.py b/tests/functional/tests_get_item_indexes.py new file mode 100644 index 0000000..39f25de --- /dev/null +++ b/tests/functional/tests_get_item_indexes.py @@ -0,0 +1,43 @@ +"""Functional tests for get item indexes""" + +from random import choice, randint + +from tests.constants.constants import InitUsers, VALID_STATUS_CODE, ITEM_NAMES, INVALID_TOKEN +from tests.functional import ApiTestBase + + +ITEM_NAME = choice(ITEM_NAMES) +ITEM_INDEX = randint(0, 1000) + + +class TestGetItemIndexes(ApiTestBase): + """Class for tests of get item indexes""" + + def test_get_empty_item_indexes(self): + """Test get item indexes when user has not item indexes""" + for user, password in InitUsers.users.items(): + with self.subTest(i=user): + token = self.application.login(user, password).json()["content"] + get_item_indexes_response = self.application.get_item_indexes(token) + self.assertEqual(VALID_STATUS_CODE, get_item_indexes_response.status_code) + self.assertFalse(get_item_indexes_response.json()["content"]) + + def test_get_item_indexes(self): + """Test get item indexes when user has any item""" + for user, password in InitUsers.users.items(): + with self.subTest(i=user): + token = self.application.login(user, password).json()["content"] + self.application.add_item(ITEM_INDEX, token, ITEM_NAME) + get_item_indexes_response = self.application.get_item_indexes(token) + self.assertEqual(VALID_STATUS_CODE, get_item_indexes_response.status_code) + self.assertTrue(get_item_indexes_response.json()["content"]) + + def test_get_item_indexes_by_invalid_token(self): + """Test can not get item indexes with invalid token""" + for user, password in InitUsers.users.items(): + with self.subTest(i=user): + token = self.application.login(user, password).json()["content"] + self.application.add_item(ITEM_INDEX, token, ITEM_NAME) + get_item_indexes_response = self.application.get_item_indexes(INVALID_TOKEN) + self.assertEqual(VALID_STATUS_CODE, get_item_indexes_response.status_code) + self.assertFalse(get_item_indexes_response.json()["content"]) diff --git a/tests/functional/tests_get_user_item_by_index.py b/tests/functional/tests_get_user_item_by_index.py new file mode 100644 index 0000000..25b5c25 --- /dev/null +++ b/tests/functional/tests_get_user_item_by_index.py @@ -0,0 +1,39 @@ +"""Functional tests for get user item by index""" + +from random import randint + +from tests.constants.constants import InitUsers, DefaultUser, VALID_STATUS_CODE, INVALID_TOKEN +from tests.functional import ApiTestBase + + +ITEM_INDEX = randint(0, 1000) + + +class TestUserItemByIndex(ApiTestBase): + """Class for tests of get user item by index""" + + def test_get_user_item_by_admin(self): + """Test get user item by index with admin token""" + for user in dict.keys(InitUsers.users): + admin_token = self.application.login(DefaultUser.user, DefaultUser.password).json()["content"] + get_item_user_response = self.application.get_user_item_by_index(ITEM_INDEX, user, admin_token) + self.assertEqual(VALID_STATUS_CODE, get_item_user_response.status_code) + self.assertFalse(get_item_user_response.json()["content"]) + + def test_get_user_item_by_user(self): + """Test can not get user item by index with user token""" + counter = 0 + for user, password in InitUsers.users.items(): + token = self.application.login(user, password).json()["content"] + get_item_user_response = self.application.get_user_item_by_index(counter, user, token) + counter = counter + 1 + self.assertEqual(VALID_STATUS_CODE, get_item_user_response.status_code) + self.assertFalse(get_item_user_response.json()["content"]) + + def test_get_user_item_by_invalid_token(self): + """Test can not get user item by index with invalid token""" + for user in dict.keys(InitUsers.users): + self.application.login(DefaultUser.user, DefaultUser.password) + get_item_user_response = self.application.get_user_item_by_index(ITEM_INDEX, user, INVALID_TOKEN) + self.assertEqual(VALID_STATUS_CODE, get_item_user_response.status_code) + self.assertFalse(get_item_user_response.json()["content"]) diff --git a/tests/functional/tests_get_user_name.py b/tests/functional/tests_get_user_name.py new file mode 100644 index 0000000..ac50b78 --- /dev/null +++ b/tests/functional/tests_get_user_name.py @@ -0,0 +1,35 @@ +"""Get user name. For getting valid response we need only token of logged in user""" +from tests.constants.constants import UserToTest +from tests.functional import ApiTestBase + + +class TestGetLoggedName(ApiTestBase): + """Getting logged in name with existing user""" + + def setUp(self): + """Get user token""" + + super().setUp() + response = self.application.login(UserToTest.login, UserToTest.password) + self.token = response.json()['content'] + self.assertEqual(200, response.status_code, "login error") + + def test_get_user_name(self): + """Getting logged in name with existing user(positive)""" + + # get user name from response + response = self.application.get_user_name(self.token) + returned_user_name = response.json()['content'] + self.assertEqual(200, response.status_code) + self.assertEqual(UserToTest.login, returned_user_name) + + def test_invalid_token(self): + """Get username with invalid token(negative)""" + + wrong_token = self.token + "WK" + + # get user name from response + response = self.application.get_user_name(wrong_token) + returned_user_name = response.json()['content'] + self.assertEqual(200, response.status_code) + self.assertEqual("", returned_user_name) diff --git a/tests/functional/tests_locked.py b/tests/functional/tests_locked.py new file mode 100644 index 0000000..71f39f2 --- /dev/null +++ b/tests/functional/tests_locked.py @@ -0,0 +1,187 @@ +"""Testing functionality of locking users""" + +from random import choice + +from tests.constants.constants import DefaultUser, InitUsers, NewUser, Users +from tests.functional import ApiTestBase + + +class TestLocked(ApiTestBase): + """Testing functionality of locking users""" + + def setUp(self): + """Return admin token""" + super().setUp() + response = self.application.login(DefaultUser.user_admin, DefaultUser.password_admin) + self.admin_token = response.json()['content'] + self.kwargs = {'token': self.admin_token} + + def test_locked(self): + """Test functionality of locking user after 3 wrong password attempts (user should be locked) + """ + + users = InitUsers.users.copy() + user = choice(list(users.keys())) # returning random user + wrong_password = Users.fake_password + for _ in range(3): + self.application.login(user, wrong_password) + locked_users_request = self.application.get_locked_users(self.admin_token) + locked_users = locked_users_request.json()['content'] + self.assertIn(user, locked_users) + + def test_not_locked(self): + """User should not be locked after 2 wrong password attempts (user should not be locked) + """ + + users = InitUsers.users.copy() + user = choice(list(users.keys())) # returning random user + wrong_passwords = ['', 'password'] + for wrong_password in wrong_passwords: + self.application.login(user, wrong_password) + locked_users_request = self.application.get_locked_users(self.admin_token) + locked_users = locked_users_request.json()['content'] + self.assertNotIn(user, locked_users) + + def test_manual_lock(self): + """Test functionality of locking users by manual command with admin token (user should be locked) + """ + + users = InitUsers.users.copy() + user_to_lock = choice(list(users.keys())) # returning random user + self.application.lock_user(self.admin_token, user_to_lock) + locked_users_request = self.application.get_locked_users(self.admin_token) + self.assertIn(user_to_lock, locked_users_request.text) + + def test_manual_unlock(self): + """Test functionality of unlocking user by manual command with admin token (user should be unlocked) + """ + + users = InitUsers.users.copy() + user_to_lock = choice(list(users.keys())) # returning random user + wrong_password = Users.fake_password + for _ in range(3): + self.application.login(user_to_lock, wrong_password) + self.application.unlock_user(self.admin_token, user_to_lock) + locked_users_request = self.application.get_locked_users(self.admin_token) + locked_users = locked_users_request.text + self.assertNotIn(user_to_lock, locked_users) + + def test_reset_locked_admin_token(self): + """Test functionality of unlocking all users with admin token (all users should be unlocked) + """ + + users = InitUsers.users.copy() + wrong_password = Users.fake_password + for user in users.keys(): + self.application.login(user, wrong_password) + self.application.unlock_all_users(self.admin_token) + locked_users_request = self.application.get_locked_users(self.admin_token) + locked_users = locked_users_request.json()['content'] + self.assertEqual(locked_users, '') + + def test_locked_admins(self): + """Test functionality of locking admins after 3 wrong password attempts (admin should be locked) + """ + + new_user_name = NewUser.name + new_user_pass = NewUser.password + self.application.create_new_user(self.admin_token, new_user_name, new_user_pass, 'true') + wrong_password = Users.fake_password + for _ in range(3): + self.application.login(new_user_name, wrong_password) + locked_admins = self.application.get_locked_admins(self.admin_token) + self.assertIn(new_user_name, locked_admins.text) + + def test_not_locked_admin(self): + """Admin should not be locked after 2 wrong password attempts (admin should not be locked) + """ + + new_user_name = NewUser.name + new_user_pass = NewUser.password + self.application.create_new_user(self.admin_token, new_user_name, new_user_pass, 'true') + passwords = ['', 'password', new_user_pass] + for password in passwords: + self.application.login(new_user_name, password) + locked_admins = self.application.get_locked_admins(self.admin_token) + logined_admins = self.application.login_admins(self.admin_token) + self.assertNotIn(new_user_name, locked_admins.text) + self.assertIn(new_user_name, logined_admins.text) + + def test_manual_lock_user_token(self): + """Test functionality of locking users by manual command with user token (user should not be locked) + """ + + users = InitUsers.users.copy() + user, password = users.popitem() # user for login + user_to_lock = choice(list(users.keys())) # returning random user for lock + login_for_token = self.application.login(user, password) + token = login_for_token.json()['content'] + self.application.lock_user(token, user_to_lock) + locked_users_request = self.application.get_locked_users(self.admin_token) + self.assertNotIn(user_to_lock, locked_users_request.text) + + def test_locking_unexisting_user(self): + """Test functionality of locking unexisting user (unexisting user should not be locked) + """ + + fake_user = Users.fake_user + fake_password = Users.fake_password + for _ in range(3): + self.application.login(fake_user, fake_password) + locked_users_request = self.application.get_locked_users(self.admin_token) + locked_users = locked_users_request.json()['content'] + self.assertEqual(locked_users, '') + + def test_get_locked_admins_user_token(self): + """Discovering locked admins with user token (locked admins should not be displayed) + """ + + users = InitUsers.users.copy() + user, password = choice(list(users.items())) + for _ in range(3): + self.application.login(DefaultUser.user_admin, Users.fake_password) # locking admin + login_for_token = self.application.login(user, password) + user_token = login_for_token.json()['content'] + locked_admins_request = self.application.get_locked_admins(user_token) + locked_admin = locked_admins_request.json()['content'] + self.assertEqual(locked_admin, '') + + def test_get_locked_admins_empty_token(self): + """Discovering locked admins with empty token (locked admins should not be displayed) + """ + + for _ in range(3): + self.application.login(DefaultUser.user_admin, Users.fake_password) + token = '' + locked_admins_request = self.application.get_locked_admins(token) + locked_admin = locked_admins_request.json()['content'] + self.assertEqual(locked_admin, '') + + def test_get_locked_users_user_token(self): + """Discovering locked users with user token (locked users should not be displayed) + """ + + users = InitUsers.users.copy() + users.pop('admin', None) + user, pasword = users.popitem() + login_for_user_token = self.application.login(user, pasword) + user_token = login_for_user_token.json()['content'] + user_to_lock = list(users.keys())[0] + self.application.login(user_to_lock, Users.fake_password) + locked_users_request = self.application.get_locked_users(user_token) + locked_users = locked_users_request.json()['content'] + self.assertEqual(locked_users, '') + + def test_get_locked_users_empty_token(self): + """Discovering locked users with empty token (locked users should not be displayed) + """ + + users = InitUsers.users.copy() + users.pop('admin', None) + user_to_lock = list(users.keys())[0] + for _ in range(3): + self.application.login(user_to_lock, Users.fake_password) + token = '' + locked_users_request = self.application.get_locked_users(token) + locked_users = locked_users_request.json()['content'] + self.assertEqual(locked_users, '') diff --git a/tests/functional/tests_login.py b/tests/functional/tests_login.py new file mode 100644 index 0000000..dcda788 --- /dev/null +++ b/tests/functional/tests_login.py @@ -0,0 +1,106 @@ +"""Functional tests for logging users""" + +from ddt import data, ddt + +from tests.constants.constants import DefaultToken, DefaultUser, Users, VALID_STATUS_CODE +from tests.functional import ApiTestBase + + +@ddt +class TestLogin(ApiTestBase): + """Class for testing""" + + def test_login(self): + """Login user. If user got token test pass (positive)""" + login = self.application.login(DefaultUser.user, DefaultUser.password) + self.assertEqual(VALID_STATUS_CODE, login.status_code) + self.assertEqual(len(login.json().get("content")), 32, "Invalid token") + + def test_login_user_not_found(self): + """Login fake user name. If user not found test pass (negative)""" + login = self.application.login(Users.fake_user, Users.fake_password) + self.assertEqual(VALID_STATUS_CODE, login.status_code) + self.assertIn("ERROR, user not found", login.text, "User founded") + + def test_login_user_locked(self): + """Login 4 times with valid user and fake password to lock. If user locked test pass (negative)""" + for _ in range(4): + login = self.application.login(Users.valid_user, Users.fake_password) + self.assertEqual(VALID_STATUS_CODE, login.status_code) + self.assertIn("ERROR, user locked", login.text, "User not locked") + + def test_login_fake_user_locked(self): + """Login 4 times with fake user and password to lock. If user not found test pass (negative)""" + for _ in range(4): + login = self.application.login(Users.fake_user, Users.fake_password) + self.assertEqual(VALID_STATUS_CODE, login.status_code) + self.assertIn("ERROR, user not found", login.text, "User locked") + + def test_login_admins(self): + """Get logged admins with admin token. If got the list of logged admins test pass (positive)""" + login = self.application.login(DefaultUser.user, DefaultUser.password) + self.assertEqual(VALID_STATUS_CODE, login.status_code) + logged_admins = self.application.login_admins(login.json().get("content")) + self.assertEqual(VALID_STATUS_CODE, logged_admins.status_code) + self.assertTrue(logged_admins.json().get("content"), "Content is empty") + + def test_login_admins_user(self): + """Get logged admins with user token. If empty response test pass (positive)""" + login = self.application.login(Users.valid_user, Users.valid_password) + self.assertEqual(VALID_STATUS_CODE, login.status_code) + logged_admins = self.application.login_admins(login.json().get("content")) + self.assertEqual(VALID_STATUS_CODE, logged_admins.status_code) + self.assertFalse(logged_admins.json().get("content"), "Content is not empty") + + @data(DefaultToken.token, "") + def test_login_admins_token(self, value): + """Get logged admins with default and empty token. If empty response test pass (negative)""" + logged_admins = self.application.login_admins(value) + self.assertEqual(VALID_STATUS_CODE, logged_admins.status_code) + self.assertFalse(logged_admins.json().get("content"), "Content is not empty") + + def test_login_users_admin(self): + """Get logged users with admin token. If got the list of logged users test pass (positive)""" + login = self.application.login(DefaultUser.user, DefaultUser.password) + self.assertEqual(VALID_STATUS_CODE, login.status_code) + logged_admins = self.application.login_users(login.json().get("content")) + self.assertEqual(VALID_STATUS_CODE, logged_admins.status_code) + self.assertTrue(logged_admins.json().get("content"), "Content is empty") + + def test_login_users(self): + """Get logged users with user token. If list of users empty test pass (negative)""" + login = self.application.login(Users.valid_user, Users.valid_password) + self.assertEqual(VALID_STATUS_CODE, login.status_code) + logged_users = self.application.login_users(login.json().get("content")) + self.assertEqual(VALID_STATUS_CODE, logged_users.status_code) + self.assertFalse(logged_users.json().get("content"), "Content is not empty") + + @data(DefaultToken.token, "") + def test_login_users_token(self, value): + """Get logged users with default and empty token. If list of users empty test pass (negative)""" + logged_users = self.application.login_users(value) + self.assertEqual(VALID_STATUS_CODE, logged_users.status_code) + self.assertFalse(logged_users.json().get("content"), "Content is not empty") + + def test_login_tockens_admin(self): + """Get alive tockens with admin token. If got list of tokens test pass (positive)""" + login = self.application.login(DefaultUser.user, DefaultUser.password) + self.assertEqual(VALID_STATUS_CODE, login.status_code) + alive_tokens = self.application.login_tockens(login.json().get("content")) + self.assertEqual(VALID_STATUS_CODE, alive_tokens.status_code) + self.assertTrue(alive_tokens.json().get("content"), "Content is empty") + + def test_login_tockens_users(self): + """Get alive tockens with user token. If list of tokens empty test pass (negative)""" + login = self.application.login(Users.valid_user, Users.valid_password) + self.assertEqual(VALID_STATUS_CODE, login.status_code) + alive_tokens = self.application.login_tockens(login.json().get("content")) + self.assertEqual(VALID_STATUS_CODE, alive_tokens.status_code) + self.assertFalse(alive_tokens.json().get("content"), "Content is not empty") + + @data(DefaultToken.token, "") + def test_login_tockens_users_token(self, value): + """Get alive tockens with default and empty token. If list of tokens empty test pass (negative)""" + alive_tokens = self.application.login_tockens(value) + self.assertEqual(VALID_STATUS_CODE, alive_tokens.status_code) + self.assertFalse(alive_tokens.json().get("content"), "Content is not empty") diff --git a/tests/functional/tests_logout.py b/tests/functional/tests_logout.py new file mode 100644 index 0000000..c30b822 --- /dev/null +++ b/tests/functional/tests_logout.py @@ -0,0 +1,66 @@ +"""Functional tests for logout users""" + +from tests.constants.constants import DefaultToken, DefaultUser, Users, VALID_STATUS_CODE +from tests.functional import ApiTestBase + + +class TestLogout(ApiTestBase): + """Class for testing""" + + def test_logout(self): + """Logout user. If request true test pass (positive)""" + login = self.application.login(DefaultUser.user, DefaultUser.password) + self.assertEqual(VALID_STATUS_CODE, login.status_code) + logged_admins = self.application.login_admins(login.json().get("content")) + self.assertEqual(VALID_STATUS_CODE, logged_admins.status_code) + self.assertTrue(logged_admins.json().get("content"), "Content is empty") + logout = self.application.logout(DefaultUser.user, login.json().get("content")) + self.assertEqual(VALID_STATUS_CODE, logout.status_code) + self.assertTrue(logout.json().get("content"), "User not logout") + logged_admins = self.application.login_admins(login.json().get("content")) + self.assertEqual(VALID_STATUS_CODE, logged_admins.status_code) + self.assertFalse(logged_admins.json().get("content"), "Content is not empty") + + def test_double_logout(self): + """Double logout user. If request true than false test pass (negative)""" + login = self.application.login(DefaultUser.user, DefaultUser.password) + self.assertEqual(VALID_STATUS_CODE, login.status_code) + logout1 = self.application.logout(DefaultUser.user, login.json().get("content")) + self.assertEqual(VALID_STATUS_CODE, logout1.status_code) + self.assertTrue(logout1.json().get("content"), "User not logout") + logout2 = self.application.logout(DefaultUser.user, login.json().get("content")) + self.assertEqual(VALID_STATUS_CODE, logout2.status_code) + self.assertFalse(logout2.json().get("content"), "User not logout") + + def test_logout_another_user(self): + """Login user1, logout another user2 with user1 token. If user2 didn't logout test pass (negative)""" + login = self.application.login(DefaultUser.user, DefaultUser.password) + self.assertEqual(VALID_STATUS_CODE, login.status_code) + logout = self.application.logout(Users.valid_user, login.json().get("content")) + self.assertEqual(VALID_STATUS_CODE, logout.status_code) + self.assertFalse(logout.json().get("content"), "User logout") + + def test_logout_another_token(self): + """Login user, logout with another token. If user didn't logout test pass (negative)""" + login = self.application.login(DefaultUser.user, DefaultUser.password) + self.assertEqual(VALID_STATUS_CODE, login.status_code) + logout = self.application.logout(DefaultUser.user, DefaultToken.token) + self.assertEqual(VALID_STATUS_CODE, logout.status_code) + self.assertFalse(logout.json().get("content"), "User logout") + + def test_logout_fake_users(self): + """Logout fake user. If user didn't logout test pass (negative)""" + login = self.application.login(Users.fake_user, Users.fake_password) + self.assertEqual(VALID_STATUS_CODE, login.status_code) + logout = self.application.logout(Users.fake_user, login.json().get("content")) + self.assertEqual(VALID_STATUS_CODE, logout.status_code) + self.assertFalse(logout.json().get("content"), "User logout") + + def test_logout_locked_users(self): + """Logout locked user. If user didn't logout and test pass (negative)""" + for _ in range(4): + login = self.application.login(Users.valid_user, Users.fake_password) + self.assertEqual(VALID_STATUS_CODE, login.status_code) + logout = self.application.logout(Users.fake_user, login.json().get("content")) + self.assertEqual(VALID_STATUS_CODE, logout.status_code) + self.assertFalse(logout.json().get("content"), "User logout") diff --git a/tests/functional/tests_tokenlifetime.py b/tests/functional/tests_tokenlifetime.py new file mode 100644 index 0000000..21e263c --- /dev/null +++ b/tests/functional/tests_tokenlifetime.py @@ -0,0 +1,165 @@ +""" +Testing response of "/tokenlifetime" module +""" + +from tests.constants.constants import DefaultUser +from tests.functional import ApiTestBase +from tests.utils.helper import get_new_value_different_func + + +class TestTokenLifeTime(ApiTestBase): + """ + Testing response of "/tokenlifetime" + """ + + def test_get_token_life_time(self): + """ + Get the value of token life time. If got tlt test pass (positive) + """ + + resp = self.application.get_token_life_time() + + self.assertEqual(resp.status_code, 200) + # self.assertTrue(resp.json()["content"] or resp.json()["content"] == 0) + self.assertTrue(resp.json()["content"]) + + def test_set_token_life_time_admin_positive(self): + """ + Change the token life time value by admin (200000). If tlt changed test pass (positive) + """ + + new_tlt = get_new_value_different_func(self.application.get_token_life_time, 200000, 100000) + + login = self.application.login(DefaultUser.user_admin, DefaultUser.password_admin) + token = login.json()["content"] + + resp = self.application.change_token_life_time(token, new_tlt) + + last_resp = self.application.get_token_life_time() + tlt_after = last_resp.json()["content"] + + self.assertEqual(resp.status_code, 200) + self.assertTrue(resp.json()["content"]) + self.assertEqual(tlt_after, new_tlt) + + def test_set_token_life_time_admin_negative(self): + """ + Change the token life time value by admin (-200000). If tft not changed test pass (negative) + """ + + new_tlt = get_new_value_different_func(self.application.get_token_life_time, -200000, -100000) + + login = self.application.login(DefaultUser.user_admin, DefaultUser.password_admin) + token = login.json()["content"] + + resp = self.application.change_token_life_time(token, new_tlt) + + last_resp = self.application.get_token_life_time() + tlt_after = last_resp.json()["content"] + + self.assertEqual(resp.status_code, 200) + self.assertTrue(resp.json()["content"]) + self.assertNotEqual(tlt_after, new_tlt) + + def test_set_token_life_time_admin_zero(self): + """ + Change the token life time value by admin (zero). If tlt changed test pass (positive) + """ + + new_tlt = get_new_value_different_func(self.application.get_token_life_time, 0, 0) + + login = self.application.login(DefaultUser.user_admin, DefaultUser.password_admin) + token = login.json()["content"] + + resp = self.application.change_token_life_time(token, new_tlt) + + last_resp = self.application.get_token_life_time() + tlt_after = last_resp.json()["content"] + + self.assertEqual(resp.status_code, 200) + self.assertTrue(resp.json()["content"]) + self.assertNotEqual(tlt_after, new_tlt) + + def test_set_token_life_time_admin_none(self): + """ + Change the token life time value by admin (None). If tlt stand 1000 (default value) test pass (negative) + """ + + new_tlt = None + def_tlt = 1000 + + login = self.application.login(DefaultUser.user_admin, DefaultUser.password_admin) + token = login.json()["content"] + + resp = self.application.change_token_life_time(token, new_tlt) + + last_resp = self.application.get_token_life_time() + tlt_after = last_resp.json()["content"] + + self.assertEqual(resp.status_code, 200) + self.assertTrue(resp.json()["content"]) + self.assertEqual(tlt_after, def_tlt) + + def test_set_token_life_time_admin_float(self): + """ + Change the token life time value by admin (float 200000.555). If tlt didn't change test pass (negative) + """ + + new_tlt = get_new_value_different_func(self.application.get_token_life_time, 200000.555, 100000) + + resp = self.application.get_token_life_time() + curr_tlt = resp.json()["content"] + + login = self.application.login(DefaultUser.user_admin, DefaultUser.password_admin) + token = login.json()["content"] + + resp = self.application.change_token_life_time(token, new_tlt) + + last_resp = self.application.get_token_life_time() + tlt_after = last_resp.json()["content"] + + self.assertEqual(resp.status_code, 400) + self.assertEqual(tlt_after, curr_tlt) + + def test_set_token_life_time_admin_text(self): + """ + Change the token life time value by admin (text). If tlt didn't change test pass (negative) + """ + + new_tlt = "f%kdm525!(" + + resp = self.application.get_token_life_time() + curr_tlt = resp.json()["content"] + + login = self.application.login(DefaultUser.user_admin, DefaultUser.password_admin) + token = login.json()["content"] + + resp = self.application.change_token_life_time(token, new_tlt) + + last_resp = self.application.get_token_life_time() + tlt_after = last_resp.json()["content"] + + self.assertEqual(resp.status_code, 400) + self.assertEqual(tlt_after, curr_tlt) + + def test_set_token_life_time_user(self): + """ + Change the token life time value by user (without admin rights). If tlt didn't change test pass (negative) + """ + + new_tlt = get_new_value_different_func(self.application.get_token_life_time, 500000, 100000) + + resp = self.application.get_token_life_time() + curr_tlt = resp.json()["content"] + + login = self.application.login(DefaultUser.user_akimatc, DefaultUser.password_akimatc) + token = login.json()["content"] + + resp = self.application.change_token_life_time(token, new_tlt) + + last_resp = self.application.get_token_life_time() + tlt_after = last_resp.json()["content"] + + self.assertEqual(resp.status_code, 200) + self.assertFalse(resp.json()["content"]) + self.assertEqual(tlt_after, curr_tlt) diff --git a/tests/functional/tests_update_item.py b/tests/functional/tests_update_item.py new file mode 100644 index 0000000..fb3d8f1 --- /dev/null +++ b/tests/functional/tests_update_item.py @@ -0,0 +1,51 @@ +"""Functional tests for update item""" + +from random import choice, randint + +from tests.constants.constants import InitUsers, VALID_STATUS_CODE, ITEM_NAMES, INVALID_TOKEN +from tests.functional import ApiTestBase + + +ITEM_INDEX = randint(0, 1000) +ITEM_NAME = choice(ITEM_NAMES) + + +class TestUpdateItem(ApiTestBase): + """Class for tests of update item""" + + def test_update_item(self): + """Test update item when user has item""" + for user, password in InitUsers.users.items(): + token = self.application.login(user, password).json()["content"] + self.application.add_item(ITEM_INDEX, token, ITEM_NAME) + update_item_response = self.application.update_item(ITEM_INDEX, token, ITEM_NAME) + self.assertEqual(VALID_STATUS_CODE, update_item_response.status_code) + self.assertTrue(update_item_response.json()["content"]) + + def test_update_empty_item(self): + """Test can not update item when user has no item""" + for user, password in InitUsers.users.items(): + with self.subTest(i=user): + token = self.application.login(user, password).json()["content"] + update_item_response = self.application.update_item(ITEM_INDEX, token, ITEM_NAME) + self.assertEqual(VALID_STATUS_CODE, update_item_response.status_code) + self.assertFalse(update_item_response.json()["content"]) + + def test_update_item_invalid_index(self): + """Test can not update item when index not int""" + for user, password in InitUsers.users.items(): + with self.subTest(i=user): + token = self.application.login(user, password).json()["content"] + self.application.add_item(ITEM_INDEX, token, ITEM_NAME) + update_item_response = self.application.update_item(ITEM_NAME, token, ITEM_NAME) + self.assertNotEqual(VALID_STATUS_CODE, update_item_response.status_code) + self.assertIn("Bad Request", update_item_response.text) + + def test_update_item_invalid_token(self): + """Test can not update item with invalid token""" + for user, password in InitUsers.users.items(): + with self.subTest(i=user): + self.application.login(user, password) + update_item_response = self.application.update_item(ITEM_INDEX, INVALID_TOKEN, ITEM_NAME) + self.assertEqual(VALID_STATUS_CODE, update_item_response.status_code) + self.assertFalse(update_item_response.json()["content"]) diff --git a/tests/functional/tests_user_change_pass.py b/tests/functional/tests_user_change_pass.py new file mode 100644 index 0000000..6a5e3e3 --- /dev/null +++ b/tests/functional/tests_user_change_pass.py @@ -0,0 +1,50 @@ +"""Testing ability to change password with existing users +For getting valid response we need token of that user, old password and new password""" + +from tests.constants.constants import UserToTest, InvalidValues +from tests.functional import ApiTestBase +from ddt import ddt, idata + + +@ddt +class TestChangePass(ApiTestBase): + """Testing server for ability to change pass with valid data and not valid data""" + + def setUp(self): + """Get user token""" + + super().setUp() + response = self.application.login(UserToTest.login, UserToTest.password) + self.token = response.json()['content'] + self.assertEqual(200, response.status_code, "login error") + + def test_change_pass_valid_data(self): + """Change pass with valid data""" + + # change pass + new_pass = UserToTest.password + "wk" + change_pass = self.application.change_pass(self.token, UserToTest.password, new_pass) + self.assertEqual(200, change_pass.status_code) + self.assertIn("true", change_pass.text) + + + # login with changed pass + login_with_new_pass = self.application.login(UserToTest.login, new_pass) + len_token = len(login_with_new_pass.json()['content']) + self.assertEqual(200, login_with_new_pass.status_code) + self.assertEqual(32, len_token) + + @idata(InvalidValues.values) + def test_change_pass(self, value): + """Change pass with invalid values(negative)""" + + # change pass + change_pass = self.application.change_pass(self.token, UserToTest.password, value) + self.assertEqual(200, change_pass.status_code) + self.assertNotIn('true', change_pass.text) + + # login with changed pass + login_with_new_pass = self.application.login(UserToTest.login, value) + len_token = len(login_with_new_pass.json()['content']) + self.assertEqual(200, login_with_new_pass.status_code) + self.assertIn("ERROR, user not found", len_token, "Pass changed to wrong: " + value) diff --git a/tests/functional/tests_user_create_new.py b/tests/functional/tests_user_create_new.py new file mode 100644 index 0000000..92803f7 --- /dev/null +++ b/tests/functional/tests_user_create_new.py @@ -0,0 +1,102 @@ +"""Testing ability to create new user +For getting valid response we need admin token, new user name, new password and give him admin rights""" + +from ddt import ddt, idata +from tests.constants.constants import DefaultUser, InvalidValues, NewUser, UserToTest +from tests.functional import ApiTestBase + + +@ddt +class TestCreateNewUser(ApiTestBase): + """Create new user with valid and invalid data""" + + def setUp(self): + """login admin and get admin token""" + + super().setUp() + response = self.application.login(DefaultUser.user, DefaultUser.password) + self.admin_token = response.json()['content'] + + def test_create_new_user(self): + + """create new user with valid data(positive)""" + + create_new_user = self.application.create_new_user(self.admin_token, NewUser.name, + NewUser.password, NewUser.isUser) + self.assertTrue(create_new_user.text) + self.assertEqual(200, create_new_user.status_code) + + # try to login with new user + login = self.application.login(NewUser.name, NewUser.password) + len_of_new_user_token = len(login.json()['content']) + self.assertEqual(200, login.status_code) + self.assertEqual(32, len_of_new_user_token) + + def test_create_new_with_exist_name(self): + """create new user with already exist name(negative)""" + + create_new_user = self.application.create_new_user(self.admin_token, DefaultUser.user, + NewUser.password, NewUser.isUser) + self.assertEqual(200, create_new_user.status_code) + self.assertIn('false', create_new_user.text, "User was created with a name what already exist") + + # try to login with new user + login = self.application.login(DefaultUser.user, NewUser.password) + len_of_new_user_token = len(login.json()['content']) + self.assertEqual(200, login.status_code) + self.assertNotEqual(32, len_of_new_user_token) + + def test_with_non_admin_token(self): + """create new user with usage of non admin token(negative)""" + + # login with existed user + login = self.application.login(UserToTest.login, UserToTest.password) + user_token = login.json()['content'] + + # create new user with user token + create_new_user = self.application.create_new_user(user_token, NewUser.name, NewUser.password, NewUser.isUser) + self.assertEqual(200, create_new_user.status_code) + self.assertIn('false', create_new_user.text) + + # try to login with new user + login_new_user = self.application.login(NewUser.name, NewUser.password) + self.assertEqual(200, login_new_user.status_code) + self.assertIn("ERROR, user not found", login_new_user.text, "User was created with user token") + + def test_give_invalid_admin_rights(self): + """create new user with invalid admin rights""" + + create_new_user = self.application.create_new_user(self.admin_token, NewUser.name, + NewUser.password, NewUser.wrong_rights) + self.assertEqual(400, create_new_user.status_code) + self.assertIn("Bad Request", create_new_user.text) + + # try to login with new user + login = self.application.login(NewUser.name, NewUser.password) + text_of_login_message = str(login.content) + self.assertIn("ERROR, user not found", text_of_login_message, "User was created with invalid admin rights") + + @idata(InvalidValues.values) + def test_wrong_new_login(self, value): + """create new user with spaces on login""" + + create_new_user = self.application.create_new_user(self.admin_token, value, NewUser.password, NewUser.isUser) + self.assertEqual(200, create_new_user.status_code) + self.assertIn('false', create_new_user.text, "User with '{}' login was created".format(value)) + + # try to login with new user + login = self.application.login(value, NewUser.password) + self.assertEqual(200, create_new_user.status_code) + self.assertIn("ERROR, user not found", login.text) + + @idata(InvalidValues.values) + def test_wrong_new_pass(self, value): + """create new user with only spaces on login""" + create_new_user = self.application.create_new_user(self.admin_token, NewUser.name, value, NewUser.isUser) + self.assertEqual(200, create_new_user.status_code) + self.assertIn('false', create_new_user.text, "User with '{}' pass was found".format(value)) + + # try to login with new user + login = self.application.login(NewUser.name, value) + self.assertEqual(200, login.status_code) + self.assertIn("ERROR, user not found", login.text) diff --git a/tests/functional/tests_user_remove.py b/tests/functional/tests_user_remove.py new file mode 100644 index 0000000..1195fc9 --- /dev/null +++ b/tests/functional/tests_user_remove.py @@ -0,0 +1,124 @@ +"""Testing ability to remove user +For getting valid response we need admin token and user name""" + +from tests.functional import ApiTestBase +from tests.constants.constants import DefaultUser, DefaultToken, InvalidValues, UserToTest + + +class TestRemoveUser(ApiTestBase): + + """Remove user with valid and not valid data""" + + def setUp(self): + """Get admin token""" + + super().setUp() + response = self.application.login(DefaultUser.user, DefaultUser.password) + self.admin_token = response.json()['content'] + + def test_remove_user(self): + """delete user with valid data""" + + removed_user = self.application.delete_user(self.admin_token, UserToTest.login) + self.assertTrue(removed_user.text) + self.assertEqual(200, removed_user.status_code) + + # search user in user list + get_user_list = self.application.get_all_users(self.admin_token) + self.assertEqual(200, get_user_list.status_code) + self.assertNotIn(UserToTest.login, get_user_list.text, "User was not deleted") + + def test_delete_without_name(self): + """Try to delete user without name, only with token(negative)""" + + name_empty = InvalidValues.values[2] + removed_user = self.application.delete_user(self.admin_token, name_empty) + self.assertEqual(200, removed_user.status_code) + self.assertIn("false", removed_user.text, "Error. User was deleted without name") + + def test_delete_without_token(self): + """Try to delete user without token, only with name(negative)""" + + token_empty = InvalidValues.values[2] + removed_user = self.application.delete_user(token_empty, UserToTest.login) + self.assertEqual(200, removed_user.status_code) + self.assertIn("false", removed_user.text, "Error, we got deletion without token") + + def test_admin_delete_himself(self): + """Delete admin(negative)""" + + removed_user = self.application.delete_user(self.admin_token, DefaultUser.user) + get_answer = str(removed_user.json()['content']) + self.assertEqual(200, removed_user.status_code) + self.assertNotIn('True', get_answer) + + # search user in user list + get_user_list = self.application.get_all_users(self.admin_token) + self.assertIn(DefaultUser.user, get_user_list.text, "Error, admin has deleted himself") + + def test_user_delete_himself(self): + """User delete himself with user token(negative)""" + + login = self.application.login(UserToTest.login, UserToTest.password) + token = login.json()['content'] + let_token = len(login.json()['content']) + self.assertEqual(200, login.status_code) + self.assertEqual(32, let_token) + + # Use User token to delete himself + removed_user = self.application.delete_user(token, UserToTest.login) + get_answer = str(removed_user.json()['content']) + self.assertEqual(200, removed_user.status_code) + self.assertIn('False', get_answer, 'ERROR. User was deleted with user token!') + self.assertNotEqual(32, len(get_answer)) + + # search deleted user in user list + get_user_list = self.application.get_all_users(self.admin_token) + self.assertIn(UserToTest.login, get_user_list.text, "Error, user delete himself with user token") + + def test_user_token_delete_admin(self): + """Login with user and use user token to delete admin(negative)""" + + # login with user and get user token + login = self.application.login(UserToTest.login, UserToTest.password) + token = login.json()['content'] + let_token = len(login.json()['content']) + self.assertEqual(200, login.status_code) + self.assertEqual(32, let_token) + + # del admin with user token + removed_user = self.application.delete_user(token, DefaultUser.user) + get_answer = str(removed_user.json()['content']) + self.assertEqual(200, removed_user.status_code) + self.assertIn('False', get_answer, 'ERROR. Admin was deleted with user token!') + self.assertNotEqual(32, len(get_answer)) + + # search admin in user list + get_user_list = self.application.get_all_users(self.admin_token) + self.assertIn(DefaultUser.user, get_user_list.text, "Error, user delete admin with user token") + + def test_admin_token_not_right(self): + """Use wrong token(negative)""" + + invalid_token = DefaultToken.token + removed_user = self.application.delete_user(invalid_token, UserToTest.login) + get_answer = str(removed_user.json()['content']) + len_token = len(get_answer) + self.assertEqual(200, removed_user.status_code) + self.assertNotIn('True', get_answer) + self.assertNotEqual(32, len_token) + + # search deleted user in user list + get_user_list = self.application.get_all_users(self.admin_token) + self.assertIn(UserToTest.login, get_user_list.text, "Error, user was deleted with wrong token") + + def test_user_not_exist_deletion(self): + """Delete not exist user(negative)""" + + removed_user = self.application.delete_user(self.admin_token, "testuser") + self.assertEqual(200, removed_user.status_code) + self.assertIn('false', removed_user.text) + + # search test user in user list + get_user_list = self.application.get_all_users(self.admin_token) + self.assertNotIn("testuser", get_user_list.text, "Error, not exist user was deleted") diff --git a/tests/functional/tests_users.py b/tests/functional/tests_users.py new file mode 100644 index 0000000..6eb8a35 --- /dev/null +++ b/tests/functional/tests_users.py @@ -0,0 +1,38 @@ +""" +Testing response of "/users" module +""" + +from tests.functional import ApiTestBase +from tests.constants.constants import DefaultUser + + +class TestUsers(ApiTestBase): + """ + Testing response of "/users" + """ + + def test_get_all_users_admin(self): + """ + Get the list of all users by admin + """ + + login = self.application.login(DefaultUser.user_admin, DefaultUser.password_admin) + token = login.json()["content"] + + req = self.application.get_all_users(token) + + self.assertEqual(req.status_code, 200) + self.assertTrue(req.json()["content"]) + + def test_get_all_users_user(self): + """ + Get the list of all users by user (without admin rights) + """ + + login = self.application.login(DefaultUser.user_akimatc, DefaultUser.password_akimatc) + token = login.json()["content"] + + req = self.application.get_all_users(token) + + self.assertEqual(req.status_code, 200) + self.assertFalse(req.json()["content"]) diff --git a/tests/utils/__init__.py b/tests/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/utils/helper.py b/tests/utils/helper.py new file mode 100644 index 0000000..5fe1578 --- /dev/null +++ b/tests/utils/helper.py @@ -0,0 +1,15 @@ +"""Help functions for testing""" + + +def get_new_value_different_func(func, new_value, step): + """ + Get new value which is different from returned function value. + The function compare returned func() value and new_value (parameters). + If they are equal then new_value increases by step. + The function return either new_value or new_value + step + """ + + resp = func() + func_value = resp.json()["content"] + + return new_value + step if func_value == new_value else new_value