diff --git a/.coveragerc b/.coveragerc new file mode 100644 index 0000000..c3e2677 --- /dev/null +++ b/.coveragerc @@ -0,0 +1,13 @@ +[run] + +source = + custom_user + task + todolist + utils + +omit = + *migrations* + *apps.py* + *urls.py* + *__init__.py* diff --git a/.github/workflows/develop.yml b/.github/workflows/develop.yml index c78d2c0..e165c9d 100644 --- a/.github/workflows/develop.yml +++ b/.github/workflows/develop.yml @@ -17,6 +17,9 @@ jobs: build: # The type of runner that the job will run on runs-on: ubuntu-latest + strategy: + matrix: + python-version: [3.8] # Steps represent a sequence of tasks that will be executed as part of the job steps: @@ -32,8 +35,15 @@ jobs: # POSTGRES_PASSWORD - superuser password postgresql password: postgres # optional, default is # Runs a single command using the runners shell - - name: Run a one-line script + - uses: actions/checkout@v2 + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: '3.8' + - name: Install dependencies run: | + python -m pip install --upgrade pip pip install -r requirements.txt + - name: Run coverage + run: | coverage run manage.py test tests - diff --git a/.gitignore b/.gitignore index b6e4761..7701c80 100644 --- a/.gitignore +++ b/.gitignore @@ -127,3 +127,7 @@ dmypy.json # Pyre type checker .pyre/ + +#pyCha +.idea + diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000..94ae496 --- /dev/null +++ b/.pylintrc @@ -0,0 +1,597 @@ +[MASTER] + +disable= + c0114, + c0115, + c0116, + E5110 + +# 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= + +# Specify a score threshold to be exceeded before program exits with error. +fail-under=10.0 + +# Add files or directories to the blacklist. They should be base names, not +# paths. +ignore=CVS, migrations, apps.py, settings.py, local_settings.py, manage.py, tests, urls.py + +# 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 module names) to load, +# usually to register additional checkers. +load-plugins=pylint_django + +# Pickle collected data for later comparisons. +persistent=yes + +# 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, + 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 score less than or equal to 10. You +# have access to the variables 'error', 'warning', 'refactor', and 'convention' +# which contain the number of messages in each category, as well as 'statement' +# which is the total number of statements analyzed. This score 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 + + +[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 + +# Bad variable names regexes, separated by a comma. If names match any regex, +# they will always be refused +bad-names-rgxs= + +# 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, + _ + +# Good variable names regexes, separated by a comma. If names match any regex, +# they will always be accepted +good-names-rgxs= + +# 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= + + +[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=100 + +# Maximum number of lines in a module. +max-module-lines=1000 + +# 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 + + +[LOGGING] + +# The type of string formatting that logging methods do. `old` means using % +# formatting, `new` is for `{}` formatting. +logging-format-style=old + +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules=logging + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME, + XXX, + TODO + +# Regular expression of note tags to take in consideration. +#notes-rgx= + + +[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 + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. Available dictionaries: none. To make it work, +# install the 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 the private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to the private dictionary (see the +# --spelling-private-dict-file option) instead of raising a message. +spelling-store-unknown-words=no + + +[STRING] + +# This flag controls whether inconsistent-quotes generates a warning when the +# character used as a quote delimiter is used inconsistently within a module. +check-quote-consistency=no + +# This flag controls whether the implicit-str-concat should generate a warning +# on implicit string concatenation in sequences defined over several lines. +check-str-concat-over-line-jumps=no + + +[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 + +# List of decorators that change the signature of a decorated function. +signature-mutators= + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid defining 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 + + +[CLASSES] + +# Warn about protected attribute access inside special methods +check-protected-access-in-special-methods=no + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp, + __post_init__ + +# 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 + + +[DESIGN] + +# Maximum number of arguments for function / method. +max-args=7 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Maximum number of boolean expressions in an if statement (see R0916). +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=2 + + +[IMPORTS] + +# List of modules that can be imported at any level, not just the top level +# one. +allow-any-import-level= + +# 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 + +# Couples of modules and preferred modules, separated by a comma. +preferred-modules= + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when being caught. Defaults to +# "BaseException, Exception". +overgeneral-exceptions=BaseException, + Exception diff --git a/README.md b/README.md index f6e1b69..d2c7011 100644 --- a/README.md +++ b/README.md @@ -1 +1,27 @@ -# todoProject \ No newline at end of file +# todoProject + +create file `local_settings.py` with property +``` +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.postgresql_psycopg2', + 'NAME': 'your_bd_name', + 'USER': 'user_name', + 'PASSWORD': 'user_password', + 'HOST': '127.0.0.1', + 'PORT': '5432', + } +} + +SECRET_KEY = 'SECRET_KEY' +``` + +## Other +* Code Convention. For analyzing and establishing clean code (according to PEP8) we use **pylint**. +In addition since project uses Django **pylint_django** plugin for pylint is used. All pylint +configurations are in **.pylintrc** config file. To check specific file or package use: + + ```sh + pylint --rcfile='path' filename.py + ``` + Additional information: [Pylint User Manual](https://pylint.readthedocs.io/en/latest/) diff --git a/custom_user/__init__.py b/custom_user/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/custom_user/apps.py b/custom_user/apps.py new file mode 100644 index 0000000..2001f3b --- /dev/null +++ b/custom_user/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class UserConfig(AppConfig): + name = 'custom_user' diff --git a/custom_user/migrations/0001_initial.py b/custom_user/migrations/0001_initial.py new file mode 100644 index 0000000..2fb4e2a --- /dev/null +++ b/custom_user/migrations/0001_initial.py @@ -0,0 +1,28 @@ +# Generated by Django 3.1.7 on 2021-03-11 10:18 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='CustomUser', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('password', models.CharField(max_length=128, verbose_name='password')), + ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), + ('first_name', models.CharField(max_length=55, verbose_name='First Name')), + ('last_name', models.CharField(max_length=55, verbose_name='Last Name')), + ('email', models.EmailField(max_length=254, unique=True, verbose_name='Email')), + ], + options={ + 'abstract': False, + }, + ), + ] diff --git a/custom_user/migrations/__init__.py b/custom_user/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/custom_user/models.py b/custom_user/models.py new file mode 100644 index 0000000..64c3fbd --- /dev/null +++ b/custom_user/models.py @@ -0,0 +1,50 @@ +from django.contrib.auth.models import AbstractBaseUser +from django.db import models, DatabaseError +from utils.abstract_model import AbstractModel + + +class CustomUser(AbstractBaseUser, AbstractModel): + objects = models.Manager() + + first_name = models.CharField('First Name', max_length=55, null=False, blank=False) + last_name = models.CharField('Last Name', max_length=55, null=False, blank=False) + email = models.EmailField('Email', unique=True) + + USERNAME_FIELD = 'email' + EMAIL_FIELD = 'email' + + def __str__(self): + return str(self.first_name) + ' ' + str(self.last_name) + + def to_dict(self): + return {'first_name': self.first_name, + 'last_name': self.last_name, + 'email': self.email} + + @classmethod + def create(cls, email, password, **extra_fields): + if not email: + raise ValueError('User must have an email address') + user = CustomUser( + email=email, + **extra_fields + ) + user.set_password(password) + try: + user.save() + return user + except (ValueError, TypeError, DatabaseError): + return False + + def update(self, first_name=None, last_name=None, email=None): + if first_name: + self.first_name = first_name + if last_name: + self.last_name = last_name + if email: + self.email = email + try: + self.save() + return self + except (TypeError, ValueError, DatabaseError): + return None diff --git a/custom_user/urls.py b/custom_user/urls.py new file mode 100644 index 0000000..76f4488 --- /dev/null +++ b/custom_user/urls.py @@ -0,0 +1,8 @@ +from django.urls import path + +from . import views + +urlpatterns = [ + path('profile//', views.ProfileView.as_view(), name='profile'), + path('create/', views.ProfileView.as_view(), name='create'), +] diff --git a/custom_user/views.py b/custom_user/views.py new file mode 100644 index 0000000..9d8de35 --- /dev/null +++ b/custom_user/views.py @@ -0,0 +1,53 @@ +from django.http import JsonResponse, HttpResponse +from rest_framework.views import APIView + +from .models import CustomUser + + +class ProfileView(APIView): + + def get(self, request, user_id=None): + user = CustomUser.get_by_id(user_id) + if user: + return JsonResponse(user.to_dict()) + return HttpResponse(status=400) + + def post(self, request): + if not request.body: + return HttpResponse("Empty data input", status=400) + + body = request.body + + data = {'first_name': body.get('first_name'), + 'last_name': body.get('last_name'), + 'password': body.get('password'), + 'email': body.get('email')} + + new_user = CustomUser.create(**data) + if new_user: + return JsonResponse(new_user.to_dict(), status=200) + return HttpResponse('Something went wrong', status=400) + + def put(self, request, user_id=None): + user = CustomUser.get_by_id(user_id) + + if not user: + return HttpResponse(status=404) + + if not request.body: + return HttpResponse("Empty data input", status=400) + + body = request.body + + updated_user = CustomUser.update(user, **body) + + if updated_user: + return JsonResponse(user.to_dict(), status=200) + return HttpResponse(status=400) + + def delete(self, request, user_id=None): + user = CustomUser.get_by_id(user_id) + if user: + CustomUser.remove(user_id) + return HttpResponse('User removed.', status=200) + return HttpResponse('User not found', status=400) diff --git a/manage.py b/manage.py new file mode 100644 index 0000000..9319666 --- /dev/null +++ b/manage.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" + +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_config.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/project_config/__init__.py b/project_config/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/project_config/asgi.py b/project_config/asgi.py new file mode 100644 index 0000000..85f4b34 --- /dev/null +++ b/project_config/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for project_config project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_config.settings') + +application = get_asgi_application() diff --git a/project_config/settings.py b/project_config/settings.py new file mode 100644 index 0000000..7f88c71 --- /dev/null +++ b/project_config/settings.py @@ -0,0 +1,129 @@ +""" +Django settings for project_config project. + +Generated by 'django-admin startproject' using Django 3.1.7. + +For more information on this file, see +https://docs.djangoproject.com/en/3.1/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/3.1/ref/settings/ +""" + +from pathlib import Path + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'SECRET_KEY' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = [] + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'todolist', + 'custom_user', + 'task', + 'rest_framework', + 'drf_yasg', +] + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', + 'utils.middleware.middleware.JSONMiddleware' +] + +ROOT_URLCONF = 'project_config.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'project_config.wsgi.application' + +# Database +# https://docs.djangoproject.com/en/3.1/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.postgresql_psycopg2', + 'NAME': 'postgres', + 'USER': 'postgres', + 'PASSWORD': 'postgres', + 'HOST': '127.0.0.1', + 'PORT': '5432', + } +} + +# Password validation +# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + +# Internationalization +# https://docs.djangoproject.com/en/3.1/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/3.1/howto/static-files/ + +STATIC_URL = '/static/' + +AUTH_USER_MODEL = 'custom_user.CustomUser' + +try: + from project_config.local_settings import * +except ImportError: + pass diff --git a/project_config/urls.py b/project_config/urls.py new file mode 100644 index 0000000..d1253e2 --- /dev/null +++ b/project_config/urls.py @@ -0,0 +1,40 @@ +"""project_config URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/3.1/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.urls import path, include +from drf_yasg import openapi +from drf_yasg.views import get_schema_view +from rest_framework import permissions + +schema_view = get_schema_view( + openapi.Info( + title="ToDoList API", + default_version='v1', + description="API for CRUD", + terms_of_service="https://todolist/policies/terms/", + contact=openapi.Contact(email="contact@todolist.remote"), + license=openapi.License(name="ToDoList License"), + ), + public=True, + permission_classes=(permissions.AllowAny,), +) + +urlpatterns = [ + path('custom-user/', include('custom_user.urls')), + path('todolist/', include('todolist.urls')), + path('tasks/', include('task.urls')), + path('swagger', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), + path('swagger-redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), +] diff --git a/project_config/wsgi.py b/project_config/wsgi.py new file mode 100644 index 0000000..ffe9180 --- /dev/null +++ b/project_config/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for project_config project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_config.settings') + +application = get_wsgi_application() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..59db430 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,21 @@ +asgiref==3.3.1 +astroid==2.5.1 +colorama==0.4.4 +Django==3.1.7 +isort==5.7.0 +lazy-object-proxy==1.5.2 +mccabe==0.6.1 +psycopg2==2.8.6 +pylint==2.7.2 +pylint-django==2.4.2 +pylint-plugin-utils==0.6 +pytz==2021.1 +sqlparse==0.4.1 +toml==0.10.2 +wrapt==1.12.1 +coverage==5.5 +djangorestframework~=3.12.2 +pip~=21.0.1 +setuptools~=54.1.1 +Jinja2~=2.11.3 +drf-yasg==1.20.0 diff --git a/task/__init__.py b/task/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/task/apps.py b/task/apps.py new file mode 100644 index 0000000..3c5f70a --- /dev/null +++ b/task/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class TaskConfig(AppConfig): + name = 'task' diff --git a/task/migrations/0001_initial.py b/task/migrations/0001_initial.py new file mode 100644 index 0000000..91ee613 --- /dev/null +++ b/task/migrations/0001_initial.py @@ -0,0 +1,24 @@ +# Generated by Django 3.1.7 on 2021-03-11 12:46 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Task', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(max_length=30)), + ('description', models.TextField(max_length=256)), + ('is_completed', models.BooleanField(default=False)), + ('deadline', models.DateField()), + ], + ), + ] diff --git a/task/migrations/0002_auto_20210312_0909.py b/task/migrations/0002_auto_20210312_0909.py new file mode 100644 index 0000000..9595d33 --- /dev/null +++ b/task/migrations/0002_auto_20210312_0909.py @@ -0,0 +1,29 @@ +# Generated by Django 3.1.7 on 2021-03-12 09:09 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('todolist', '0002_todolist_members'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('task', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='task', + name='list_id', + field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='todolist.todolist'), + preserve_default=False, + ), + migrations.AddField( + model_name='task', + name='user_id', + field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='custom_user.customuser'), + preserve_default=False, + ), + ] diff --git a/task/migrations/0003_auto_20210317_1551.py b/task/migrations/0003_auto_20210317_1551.py new file mode 100644 index 0000000..9cfb607 --- /dev/null +++ b/task/migrations/0003_auto_20210317_1551.py @@ -0,0 +1,28 @@ +# Generated by Django 3.1.7 on 2021-03-17 15:51 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('task', '0002_auto_20210312_0909'), + ] + + operations = [ + migrations.RenameField( + model_name='task', + old_name='list_id', + new_name='todolist', + ), + migrations.RenameField( + model_name='task', + old_name='user_id', + new_name='user', + ), + migrations.AlterField( + model_name='task', + name='description', + field=models.TextField(default='', max_length=256), + ), + ] diff --git a/task/migrations/__init__.py b/task/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/task/models.py b/task/models.py new file mode 100644 index 0000000..6b9cb3b --- /dev/null +++ b/task/models.py @@ -0,0 +1,65 @@ +from abc import abstractmethod +from datetime import date +from django.db import models, IntegrityError, DataError +from custom_user.models import CustomUser +from todolist.models import ToDoList +from utils.abstract_model import AbstractModel + + +class Task(AbstractModel): + title = models.CharField(max_length=30) + description = models.TextField(max_length=256, default="") + is_completed = models.BooleanField(default=False) + deadline = models.DateField() + user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) + todolist = models.ForeignKey(ToDoList, on_delete=models.CASCADE) + + def __str__(self): + return self.title + + @classmethod + def get_by_list_id(cls,todolist: ToDoList): + tasks = Task.objects.filter(todolist_id=todolist.pk) + return tasks + + @classmethod + def create(cls, + title: str, + description: str, + deadline: date, + user: CustomUser, + todolist: ToDoList): # pylint disable=W0221 + task = Task(title=title, description=description, deadline=deadline) + task.user = user + task.todolist = todolist + try: + task.save() + return task + except (ValueError, DataError, IntegrityError): + return None + + @abstractmethod + def update(self, + title: str, + description: str, + is_completed: bool, + deadline: date, + user: CustomUser, + todolist: ToDoList): # pylint disable=W0221 + try: + if title: + self.title = title + if description: + self.description = description + if deadline: + self.deadline = deadline + if is_completed: + self.is_completed = is_completed + if user: + self.user = user + if todolist: + self.todolist = todolist + self.save() + return True + except (ValueError, DataError, TypeError, IntegrityError): + return None diff --git a/task/urls.py b/task/urls.py new file mode 100644 index 0000000..3475c07 --- /dev/null +++ b/task/urls.py @@ -0,0 +1,9 @@ +from django.urls import path + +from .views import TaskAPIView + +urlpatterns = [ + path('by_list//', TaskAPIView.as_view()), + path('/', TaskAPIView.as_view()), + path('', TaskAPIView.as_view(), name='task_api_view'), +] \ No newline at end of file diff --git a/task/views.py b/task/views.py new file mode 100644 index 0000000..8683966 --- /dev/null +++ b/task/views.py @@ -0,0 +1,135 @@ +from django.http import JsonResponse +from django.core.serializers import serialize +from django.db.utils import IntegrityError, DataError +from django.core.exceptions import ValidationError +from rest_framework.views import APIView +from task.models import Task +from todolist.models import ToDoList +from custom_user.models import CustomUser + + +class TaskAPIView(APIView): + + def get(self, request, list_id): + todolist = ToDoList.get_by_id(list_id) + task = Task.get_by_list_id(todolist) + + task_serialized_data = serialize('python', task) + + data = { + 'tasks': task_serialized_data, + } + return JsonResponse(data) + + def post(self, request): + body = request.body + + list_id = body.get('todolist') + user_id = body.get('user') + + todolist = ToDoList.get_by_id(list_id) + user = CustomUser.get_by_id(user_id) + + task_data = { + 'title': body.get('title'), + 'description': body.get('description'), + 'deadline': body.get('deadline'), + 'user': user, + 'todolist': todolist, + } + + try: + task = Task.create(**task_data) + task.save() + + success_message = { + 'message': f'New task object has been created with ID {task.id}' + } + + return JsonResponse(success_message, status=201) + + # Missing parameters + except (IntegrityError, AttributeError): + integrity_message = { + 'message': 'Cannot create task! One or more parameters are missing' + } + return JsonResponse(integrity_message, status=400) + + # Invalid input + except (DataError, ValidationError, ValueError): + invalid_data_message = { + 'message': 'Cannot create task! One or more parameters are invalid' + } + return JsonResponse(invalid_data_message, status=400) + + def put(self, request, task_id=None): + body = request.body + user = None + todolist = None + + if body.get('todolist'): + list_id = body.get('todolist') + todolist = ToDoList.get_by_id(list_id) + if body.get('user'): + user_id = body.get('user') + user = CustomUser.get_by_id(user_id) + + task_data = { + 'title': body.get('title'), + 'description': body.get('description'), + 'deadline': body.get('deadline'), + 'user': user, + 'todolist': todolist, + 'is_completed': body.get('list_id'), + } + + # Missing ID + if not task_id: + missing_id_message = { + 'message': 'Cannot update task! Task ID is missing!' + } + return JsonResponse(missing_id_message, status=400) + + task = Task.get_by_id(pk=task_id) + + # ID of non-existing task + if not task: + not_exist_message = { + 'message': f'Cannot update task! Task with ID {task_id} does not exist' + } + return JsonResponse(not_exist_message, status=400) + + # Update + try: + task.update(**task_data) + + success_message = { + 'message': f'Task with ID {task_id} has been updated' + } + return JsonResponse(success_message, status=200) + + # Invalid input + except (DataError, ValidationError, ValueError): + invalid_data_message = { + 'message': 'Cannot update task! One or more parameters are invalid' + } + return JsonResponse(invalid_data_message, status=400) + + def delete(self, request, task_id=None): + # Missing ID + if not task_id: + missing_id_message = { + 'message': 'Cannot delete task! Task ID is missing!' + } + return JsonResponse(missing_id_message, status=400) + + if Task.remove(pk=task_id): + success = { + 'message': f'Task with ID {task_id} has been deleted' + } + return JsonResponse(success, status=200) + else: + failure = { + 'message': f'Task with ID {task_id} does not exist!' + } + return JsonResponse(failure, status=400) diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/abstract/__init__.py b/tests/abstract/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/abstract/tests.py b/tests/abstract/tests.py new file mode 100644 index 0000000..0b4f887 --- /dev/null +++ b/tests/abstract/tests.py @@ -0,0 +1,18 @@ +from django.test import TestCase +from utils.abstract_model import AbstractModel + + +class TaskModelsTest(TestCase): + def test_not_implemented_update(self): + class TestModel(AbstractModel): + class Meta: + abstract = True + + self.assertRaises(NotImplementedError, TestModel.update, 'test') + + def test_not_implemented_create(self): + class TestModel(AbstractModel): + class Meta: + abstract = True + + self.assertRaises(NotImplementedError, TestModel.create, 'test') diff --git a/tests/custom_user/__init__.py b/tests/custom_user/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/custom_user/tests.py b/tests/custom_user/tests.py new file mode 100644 index 0000000..24ee4f8 --- /dev/null +++ b/tests/custom_user/tests.py @@ -0,0 +1,170 @@ +import json + +from django.test import TestCase + +from custom_user.models import CustomUser + + +class CustomUserModelsTestCase(TestCase): + def setUp(self): + self.user = CustomUser.create(id=1, + first_name='Test', + last_name='User', + email='testuser@gmail.com', + password='test') + + def test_create_user(self): + user = CustomUser.create(id=2, + first_name='Test1', + last_name='User1', + email='testuser1@gmail.com', + password='test1') + self.assertIsInstance(user, CustomUser) + + def test_create_user_invalid_data(self): + user = CustomUser.create(id='a', + first_name='Test1', + last_name='User1', + email='testuser1@gmail.com', + password='test1') + self.assertEqual(user, False) + + def test_create_user_no_email(self): + def create_user(): + res = CustomUser.create(id=2, + first_name='Test1', + last_name='User1', + email='', + password='test1') + return res + + self.assertRaises(ValueError, create_user) + + def test_str(self): + result = self.user.__str__() + self.assertEqual(result, 'Test User') + + def test_to_dict(self): + result = self.user.to_dict() + self.assertTrue(type(result) == dict) + + def test_find_by_id(self): + user = CustomUser.get_by_id(1) + self.assertIsInstance(user, CustomUser) + + def test_find_by_id_not_found(self): + user = CustomUser.get_by_id(3) + self.assertTrue(user is None) + + def test_update(self): + result = self.user.update(first_name='User', last_name='Test', email='testuser@gmail.com') + self.assertEqual(self.user.first_name, 'User') + self.assertEqual(self.user.last_name, 'Test') + self.assertEqual(self.user.email, 'testuser@gmail.com') + self.assertTrue(result) + + def test_update_fail(self): + result = self.user.update(first_name='123123123123123123123123123123123123123123123123123123123123123123123123', + last_name='Test', + email='testuser@gmail.com') + self.assertEqual(result, None) + + def test_remove_user(self): + user = CustomUser.objects.create(id=2, + first_name='Test1', + last_name='User1', + email='testuser1@gmail.com', + password='test1') + user.remove(user.id) + user = CustomUser.get_by_id(user.id) + self.assertEqual(None, user) + + +class CustomUserViewsTestCase(TestCase): + def setUp(self): + self.user = CustomUser.create(id=2, + first_name="Test", + last_name="User", + email="testuser@gmail.com", + password="test") + + self.user = CustomUser.create(id=3, + first_name="Test2", + last_name="User2", + email="testuser2@gmail.com", + password="test2") + + def test_get_by_id(self): + data = {'first_name': 'Test', 'last_name': 'User', 'email': 'testuser@gmail.com'} + responce = self.client.get('/custom-user/profile/2/') + self.assertEqual(responce.json(), data) + + def test_get_user_not_exist(self): + responce = self.client.get('/custom-user/profile/10/') + self.assertEqual(responce.status_code, 400) + + + def test_create_user(self): + data = {'first_name': 'Test3', 'last_name': 'User3', 'email': 'testuser3@gmail.com'} + response = self.client.generic('POST', '/custom-user/create/', json.dumps({'first_name': 'Test3', + 'last_name': 'User3', + 'email': 'testuser3@gmail.com'})) + self.assertEqual(response.json(), data) + + def test_create_user_empty_json(self): + response = self.client.generic('POST', '/custom-user/create/', json.dumps({})) + self.assertEqual(response.status_code, 400) + + + def test_create_user_bad_save(self): + response = self.client.generic('POST', '/custom-user/create/', json.dumps({ + 'first_name': 'Test3Test3Test3Test3Test3Test3Test3Test3Test3Test3Test3Test3Test3Test3Test3Test3Test3Test3', + 'last_name': 'User3', + 'email': 'testuser3@gmail.com'})) + self.assertEqual(response.status_code, 400) + + + + def test_put_all_input_data(self): + data = {'first_name': 'NewName', 'last_name': 'User', 'email': 'testuser@gmail.com'} + response = self.client.generic('PUT', '/custom-user/profile/2/', json.dumps({'first_name': 'NewName', + 'last_name': 'User', + 'email': 'testuser@gmail.com'})) + self.assertEqual(response.json(), data) + + def test_put_not_all_input_data(self): + data = {'first_name': 'Test', 'last_name': 'NewUser', 'email': 'testuser@gmail.com'} + response = self.client.generic('PUT', '/custom-user/profile/2/', json.dumps({'last_name': 'NewUser', + 'email': 'testuser@gmail.com'})) + self.assertEqual(response.json(), data) + + def test_put_no_user(self): + response = self.client.generic('PUT', '/custom-user/profile/100/', json.dumps({'first_name': 'NewName', + 'last_name': 'User', + 'email': 'testuser@gmail.com'})) + self.assertEqual(response.status_code, 404) + + + def test_put_empty_data(self): + response = self.client.generic('PUT', '/custom-user/profile/2/', json.dumps({})) + self.assertEqual(response.status_code, 400) + + def test_update_user_bad_save(self): + response = self.client.generic('PUT', '/custom-user/profile/2/', json.dumps({ + 'first_name': "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890", + 'last_name': 'User', + 'email': 'testuser@gmail.com'}) + ) + self.assertEqual(response.status_code, 400) + + def test_delete(self): + response = self.client.generic('DELETE', '/custom-user/profile/2/') + self.assertEqual(response.status_code, 200) + + def test_delete_user_not_found(self): + response = self.client.generic('DELETE', '/custom-user/profile/200/') + self.assertEqual(response.status_code, 400) + + + + diff --git a/tests/task/__init__.py b/tests/task/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/task/test_models.py b/tests/task/test_models.py new file mode 100644 index 0000000..80e01e0 --- /dev/null +++ b/tests/task/test_models.py @@ -0,0 +1,114 @@ +import json +from datetime import date + +from django.test import TestCase +from task.models import Task +from custom_user.models import CustomUser +from todolist.models import ToDoList + + +class TaskModelsTest(TestCase): + def setUp(self): + self.user = CustomUser.objects.create(id=1, + first_name='Test', + last_name='User', + email='testuser@gmail.com', + password='test') + self.todolist = ToDoList.create(name="list 1", description="list1 descr") + self.todolist.update_members(members_to_add=[self.user.pk]) + self.todolist.id = 1 + self.todolist.save() + self.task1 = Task.create(title="Task #1", + description="Task #1 Description", + deadline=date(2021, 1, 1), + user=self.user, + todolist=self.todolist) + + def test_str(self): + test = self.task1.__str__() + self.assertEqual(test, "Task #1") + + def test_create(self): + task = Task.create(title="Task #2", + description="Task #2 Description", + deadline=date(2021, 2, 2), + user=self.user, + todolist=self.todolist) + self.assertIsInstance(task, Task) + + def test_create_invalid(self): + task = Task.create(title="gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg", + description="Task #2 Description", + deadline=date(2021, 2, 2), + user=self.user, + todolist=self.todolist) + self.assertEqual(task, None) + + def test_update_task(self): + self.task = Task.create(title="Task #3", + description="Task #3 Description", + deadline=date(2021, 3, 3), + user=self.user, + todolist=self.todolist) + self.task.update("New task", + "new task description", + True, + date(2021, 3, 3), + self.user, + self.todolist) + self.assertEqual(self.task.title, "New task") + self.assertEqual(self.task.description, "new task description") + self.assertEqual(self.task.is_completed, True) + self.assertEqual(self.task.deadline, date(2021, 3, 3)) + self.assertEqual(self.task.user.pk, 1) + self.assertEqual(self.task.todolist.pk, 1) + self.assertTrue(self.task) + + def test_update_invalid(self): + self.task = Task.create(title="Task #3", + description="Task #3 Description", + deadline=date(2021, 3, 3), + user=self.user, + todolist=self.todolist) + res = self.task.update("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "new task description", + True, + date(2021, 3, 3), + self.user, + self.todolist) + self.assertEqual(res, None) + + def test_get_by_id(self): + self.task = Task.create(title="Task #4", + description="Task #4 Description", + deadline=date(2021, 5, 3), + user=self.user, + todolist=self.todolist) + result = Task.get_by_id(self.task.pk) + self.assertIsInstance(result, Task) + + def test_get_by_non_existent_id(self): + task = Task.get_by_id(100) + self.assertTrue(task is None) + + def test_remove_task(self): + self.task = Task.create(title="Task #5", + description="Task #5 Description", + deadline=date(2021, 4, 4), + user=self.user, + todolist=self.todolist) + result = Task.remove(self.task.pk) + self.assertNotIn(result, Task.get_by_list_id(self.todolist)) + + def test_remove_non_existed_task(self): + result = Task.remove(100) + self.assertEqual(result, False) + + def test_find_all_for_list(self): + self.task = Task.create(title="Task #6", + description="Task #6 Description", + deadline=date(2021, 6, 7), + user=self.user, + todolist=self.todolist) + result = Task.get_by_list_id(self.todolist) + self.assertEqual(len(result), 2) diff --git a/tests/task/tests_views.py b/tests/task/tests_views.py new file mode 100644 index 0000000..8e09913 --- /dev/null +++ b/tests/task/tests_views.py @@ -0,0 +1,160 @@ +import json +from datetime import date + +from django.test import TestCase +from task.models import Task +from custom_user.models import CustomUser +from todolist.models import ToDoList + + + +class ByListTaskView(TestCase): + """ Test view that returns all tasks for list """ + + def setUp(self): + self.user = CustomUser.objects.create(first_name="Test", + last_name="User", + email="mail@mail.com", + password="secret" + ) + self.list = ToDoList.create(name='List', + description='About list') + self.list.update_members(members_to_add=[self.user.id]) + self.task = Task.create(title='Task', + description='Task', + deadline=date(2020, 1, 1), + user=self.user, + todolist=self.list) + + def test_get_all_by_list_id(self): + response = self.client.generic('GET', f'/tasks/by_list/{self.list.id}/') + self.assertEqual(response.status_code, 200) + + +class DeleteTaskView(TestCase): + """ Test view for deleting an existing task """ + + def setUp(self): + self.user = CustomUser.objects.create(first_name="Test", + last_name="User", + email="mail@mail.com", + password="secret" + ) + self.list = ToDoList.create(name='List', + description='About list') + self.list.update_members(members_to_add=[self.user.id]) + self.task = Task.create(title='Task', + description='Task', + deadline=date(2020, 1, 1), + user=self.user, + todolist=self.list) + + def test_delete_task_existing(self): + response = self.client.generic('DELETE', f'/tasks/{self.task.id}/') + self.assertEqual(response.status_code, 200) + + def test_delete_task_non_existing(self): + response = self.client.generic('DELETE', '/tasks/100/') + self.assertEqual(response.status_code, 400) + + def test_delete_task_no_id(self): + response = self.client.generic('DELETE', '/tasks/') + self.assertEqual(response.status_code, 400) + + +class CreateTaskView(TestCase): + """ Test view for creating new task """ + + def setUp(self): + self.user = CustomUser.objects.create(first_name="Test", + last_name="User", + email="mail@mail.com", + password="secret") + self.list = ToDoList.create(name='List', + description='About list') + self.list.update_members(members_to_add=[self.user.id]) + + def test_create_task_data_valid(self): + response = self.client.generic('POST', '/tasks/', json.dumps({ + "title": "Task", + "description": "Task", + "deadline": "2020-01-01", + "user": self.user.id, + "todolist": self.list.id + })) + self.assertEqual(response.status_code, 201) + + def test_create_task_long_title(self): + response = self.client.generic('POST', '/tasks/', json.dumps({ + "title": "Task name that way beyond 30 symbol limit", + "description": "Task", + "deadline": "2020-01-01", + "user": self.user.id, + "todolist": self.list.id + })) + self.assertEqual(response.status_code, 400) + + def test_create_task_data_invalid(self): + response = self.client.generic('POST', '/tasks/', json.dumps({ + "title": "Task", + "description": "Task", + "deadline": "May 2020", + "user": self.user.id, + "todolist": self.list.id + })) + self.assertEqual(response.status_code, 400) + + def test_create_task_missing(self): + response = self.client.generic('POST', '/tasks/', json.dumps({"description": "Task"})) + self.assertEqual(response.status_code, 400) + + +class UpdateTaskView(TestCase): + """ Test view for updating existing task """ + + def setUp(self): + self.user = CustomUser.objects.create(first_name="Test", + last_name="User", + email="mail@mail.com", + password="secret") + self.list = ToDoList.create(name='List', + description='About list') + self.list.update_members(members_to_add=[self.user.id]) + self.task = Task.create(title='Task', + description='Task', + deadline=date(2020, 1, 1), + todolist=self.list, + user=self.user) + + def test_update_task_existing(self): + response = self.client.generic('PUT', f'/tasks/{self.task.id}/', json.dumps({ + "title": "UPDATE!" + })) + self.assertEqual(response.status_code, 200) + + def test_update_task_non_existing(self): + response = self.client.generic('PUT', '/tasks/100/', json.dumps({ + "title": "UPDATE!" + })) + self.assertEqual(response.status_code, 400) + + def test_update_task_data_valid(self): + response = self.client.generic('PUT', f'/tasks/{self.task.id}/', json.dumps({ + "deadline": "May 2021", + "user": self.user.id, + "todolist": self.list.id + })) + self.assertEqual(response.status_code, 400) + + def test_update_task_data_invalid(self): + response = self.client.generic('PUT', f'/tasks/{self.task.id}/', json.dumps({ + "deadline": "May 2021" + })) + self.assertEqual(response.status_code, 400) + + def test_update_task_id_missing(self): + response = self.client.generic('PUT', '/tasks/', json.dumps({ + "deadline": "2020-01-01" + })) + self.assertEqual(response.status_code, 400) + diff --git a/tests/todolist/__init__.py b/tests/todolist/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/todolist/tests.py b/tests/todolist/tests.py new file mode 100644 index 0000000..c8eca47 --- /dev/null +++ b/tests/todolist/tests.py @@ -0,0 +1,236 @@ +import json +from django.test import TestCase +from todolist.models import ToDoList +from custom_user.models import CustomUser + + +class ToDoListViewTest(TestCase): + + def setUp(self): + self.user = CustomUser.objects.create(id=1, + first_name="TestUser", + last_name="UserLastName", + email="test@gmail.com", + password="adminpassword") + self.user2 = CustomUser.objects.create(id=2, + first_name="TestUser2", + last_name="UserLastName2", + email="test2@gmail.com", + password="adminpassword2") + self.todo_list = ToDoList.objects.create(id=10, + name="TestList", + description="Test description") + self.todo_list.members.add(self.user.id) + + # Testing GET method + + def test_get_one_list(self): + response = self.client.get('/todolist/10/') + self.assertEqual(response.status_code, 200) + + def test_get_not_existing_list(self): + response = self.client.get('/todolist/28/') + self.assertEqual(response.status_code, 404) + + def test_get_one_wrong_list_pk(self): + response = self.client.get('/todolist/w/') + self.assertEqual(response.status_code, 404) + + def test_get_all_lists(self): + response = self.client.get('/todolist/') + self.assertEqual(response.status_code, 200) + + # Testing Post method + + def test_post_data_valid_data(self): + response = self.client.generic('POST', '/todolist/', json.dumps({ + "name": "name1", + "description": "LIST1", "members": [self.user.id] + })) + self.assertEqual(response.status_code, 201) + + def test_post_data_no_data(self): + response = self.client.generic('POST', '/todolist/') + self.assertEqual(response.status_code, 400) + + def test_post_data_name_missing_fail(self): + response = self.client.generic('POST', '/todolist/', json.dumps({ + "description": "LIST1", + "members": [self.user.id] + })) + self.assertEqual(response.status_code, 400) + + def test_post_data_description_missing_pass(self): + response = self.client.generic('POST', '/todolist/', json.dumps({ + "name": "name1", + "members": [self.user.id] + })) + self.assertEqual(response.status_code, 201) + + def test_post_data_members_missing_pass(self): + response = self.client.generic('POST', '/todolist/', json.dumps({ + "name": "name1", + "description": "LIST1" + })) + self.assertEqual(response.status_code, 201) + + def test_post_too_long_data_field(self): + name = "f"*60 + response = self.client.generic('POST', '/todolist/', json.dumps({ + "name": name, "description": "LIST1", "members": [self.user.id] + })) + self.assertEqual(response.status_code, 400) + + def test_post_wrong_json(self): + response = self.client.generic('POST', '/todolist/', '{"name": instance1, ') + self.assertEqual(response.status_code, 400) + + # Testing PUT method + + def test_put_missing_todo_list_pk(self): + response = self.client.generic('PUT', '/todolist/', json.dumps({ + "name": "namePUT", + "description": "LIST1PUT", + "members": [self.user.id] + })) + self.assertEqual(response.status_code, 404) + + def test_put_not_existing_todo_list_pk(self): + response = self.client.generic('PUT', '/todolist/42/', json.dumps({ + "name": "namePUT", + "description": "LIST1PUT", + "members": [self.user.id] + })) + self.assertEqual(response.status_code, 404) + + def test_put_wrong_todo_list_pk(self): + response = self.client.generic('PUT', '/todolist/w/', json.dumps({ + "name": "namePUT", + "description": "LIST1PUT", + "members": [self.user.id] + })) + self.assertEqual(response.status_code, 404) + + def test_put_no_data(self): + response = self.client.generic('PUT', '/todolist/10/') + self.assertEqual(response.status_code, 400) + + def test_put_valid_data(self): + response = self.client.generic('PUT', '/todolist/10/', json.dumps({ + "name": "namePUT", + "description": "LIST1PUT", + "members_to_add": [self.user2.id] + })) + self.assertEqual(response.status_code, 200) + + def test_put_wrong_json(self): + response = self.client.generic('PUT', '/todolist/10/', '{"name": instance1, ') + self.assertEqual(response.status_code, 400) + + def test_put_too_long_data_field(self): + name = "f" * 60 + response = self.client.generic('PUT', '/todolist/10/', json.dumps({ + "name": name, "description": "LIST1" + })) + self.assertEqual(response.status_code, 400) + + def test_put_members_to_add_pass(self): + response = self.client.generic('PUT', '/todolist/10/', json.dumps({ + "members_to_add": [2] + })) + self.assertEqual(response.status_code, 200) + + def test_put_members_to_delete_pass(self): + response = self.client.generic('PUT', '/todolist/10/', json.dumps({ + "members_to_delete": [1] + })) + self.assertEqual(response.status_code, 200) + + def test_put_members_to_add_fail(self): + response = self.client.generic('PUT', '/todolist/10/', json.dumps({ + "members_to_delete": 1 + })) + self.assertEqual(response.status_code, 400) + + def test_put_members_to_delete_fail(self): + response = self.client.generic('PUT', '/todolist/10/', json.dumps({ + "members_to_delete": "1a" + })) + self.assertEqual(response.status_code, 400) + + # Testing DELETE method + + def test_delete_missing_todo_list_pk(self): + response = self.client.generic('DELETE', '/todolist/') + self.assertEqual(response.status_code, 404) + + def test_delete_not_existing_todo_list_pk(self): + response = self.client.generic('DELETE', '/todolist/23/') + self.assertEqual(response.status_code, 404) + + def test_delete_wrong_todo_list_pk(self): + response = self.client.generic('DELETE', '/todolist/w/') + self.assertEqual(response.status_code, 404) + + def test_delete_pass(self): + response = self.client.generic('DELETE', '/todolist/10/') + self.assertEqual(response.status_code, 200) + + +class ToDoListCRUDTest(TestCase): + def setUp(self) -> None: + self.user = CustomUser.objects.create(id=1, first_name="TestUser1", + last_name="UserLastName1", email="test1@gmail.com", + password="adminpassword1") + self.user2 = CustomUser.objects.create(id=2, first_name="TestUser2", + last_name="UserLastName2", email="test2@gmail.com", + password="adminpassword2") + + self.todo_list = ToDoList.objects.create(name="TestList", description="Test description") + self.todo_list.members.add(self.user.id) + + def test_create(self): + todo_list1 = ToDoList.create('test list name 1') + todo_list2 = ToDoList.create(name='test list name 2', description='test list description 2') + todo_list3 = ToDoList.create(name='test list name 3', description='test list description 3', + members=[self.user, self.user2]) + + first_to_dict_expected = {'id': todo_list1.id, 'name': 'test list name 1', 'description': '', 'members': []} + second_to_dict_expected = {'id': todo_list2.id, 'name': 'test list name 2', + 'description': 'test list description 2', 'members': []} + third_to_dict_expected = {'id': todo_list3.id, 'name': 'test list name 3', + 'description': 'test list description 3', 'members': [1, 2]} + + self.assertEqual(first_to_dict_expected, todo_list1.to_dict()) + self.assertEqual(second_to_dict_expected, todo_list2.to_dict()) + self.assertEqual(third_to_dict_expected, todo_list3.to_dict()) + + def test_update(self): + new_name = 'new list name' + self.todo_list.update(name=new_name) + self.assertEqual(new_name, self.todo_list.name) + + new_description = 'new list description' + self.todo_list.update(description=new_description) + self.assertEqual(new_description, self.todo_list.description) + + new_name, new_description = 'absolutely new list name', 'absolutely new list description' + self.todo_list.update(name=new_name, description=new_description) + self.assertEqual(new_name, self.todo_list.name) + self.assertEqual(new_description, self.todo_list.description) + + def test_get_by_id(self): + todo_list = ToDoList.get_by_id(self.todo_list.id) + expected_to_dict = {'id': self.todo_list.id, 'name': 'TestList', + 'description': 'Test description', 'members': [1]} + self.assertEqual(expected_to_dict, todo_list.to_dict()) + + def test_delete_by_id(self): + list_del = ToDoList.remove(self.todo_list.id) + self.assertEqual(True, list_del) + + def test_str(self): + self.assertEqual(self.todo_list.name, self.todo_list.__str__()) + + def test_get_list_members(self): + self.assertEqual(list(self.todo_list.members.all()), list(self.todo_list.get_list_members())) diff --git a/todolist/__init__.py b/todolist/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/todolist/apps.py b/todolist/apps.py new file mode 100644 index 0000000..3495959 --- /dev/null +++ b/todolist/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class ToDoListConfig(AppConfig): + name = 'todolist' diff --git a/todolist/migrations/0001_initial.py b/todolist/migrations/0001_initial.py new file mode 100644 index 0000000..5c4ac40 --- /dev/null +++ b/todolist/migrations/0001_initial.py @@ -0,0 +1,22 @@ +# Generated by Django 3.1.7 on 2021-03-11 10:42 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='ToDoList', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=50)), + ('description', models.CharField(default='No description for now.', max_length=500)), + ], + ), + ] diff --git a/todolist/migrations/0002_todolist_members.py b/todolist/migrations/0002_todolist_members.py new file mode 100644 index 0000000..c0bef16 --- /dev/null +++ b/todolist/migrations/0002_todolist_members.py @@ -0,0 +1,20 @@ +# Generated by Django 3.1.7 on 2021-03-11 10:42 + +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('todolist', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='todolist', + name='members', + field=models.ManyToManyField(related_name='todo_lists', to=settings.AUTH_USER_MODEL), + ), + ] diff --git a/todolist/migrations/__init__.py b/todolist/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/todolist/models.py b/todolist/models.py new file mode 100644 index 0000000..c8dcf26 --- /dev/null +++ b/todolist/models.py @@ -0,0 +1,56 @@ +from django.db import models, IntegrityError, DatabaseError + +from utils.abstract_model import AbstractModel +from custom_user.models import CustomUser + + +class ToDoList(AbstractModel): + name = models.CharField(max_length=50) + description = models.CharField(max_length=500, default='No description for now.') + members = models.ManyToManyField(CustomUser, related_name='todo_lists') + + def __str__(self): + return self.name + + def to_dict(self): + return {'id': self.id, + 'name': self.name, + 'description': self.description, + 'members': sorted([member.id for member in self.members.all()])} + + def update(self, name=None, description=None): + try: + if name: + self.name = name + if description: + self.description = description + self.save() + return self + except (ValueError, IntegrityError, DatabaseError): + return None + + def update_members(self, members_to_add=None, members_to_delete=None): + try: + if members_to_add: + self.members.add(*members_to_add) + if members_to_delete: + self.members.remove(*members_to_delete) + return self + except (TypeError, ValueError): + return None + + def get_list_members(self): + members = self.members.all() + return members + + @classmethod + def create(cls, name, description='', members=None): + try: + todo_list = ToDoList(name=name, description=description) + todo_list.save() + if members: + todo_list.members.add(*members) + return todo_list + except (ValueError, IntegrityError, DatabaseError): + # log error + return None diff --git a/todolist/urls.py b/todolist/urls.py new file mode 100644 index 0000000..edb2feb --- /dev/null +++ b/todolist/urls.py @@ -0,0 +1,8 @@ +from django.urls import path + +from .views import ToDoListView + +urlpatterns = [ + path('', ToDoListView.as_view()), + path('/', ToDoListView.as_view()), +] diff --git a/todolist/views.py b/todolist/views.py new file mode 100644 index 0000000..5944e97 --- /dev/null +++ b/todolist/views.py @@ -0,0 +1,69 @@ +import json + +from django.http import JsonResponse, HttpResponse +from rest_framework.views import APIView +from utils.validators import is_integer +from .models import CustomUser, ToDoList + + +class ToDoListView(APIView): + + def get(self, request, todo_list_pk=None): + if todo_list_pk: + if not is_integer(todo_list_pk): + return HttpResponse(status=404) + todo_list = ToDoList.get_by_id(todo_list_pk) + if not todo_list: + return HttpResponse(status=404) + return JsonResponse(todo_list.to_dict(), status=200) + + todo_lists = ToDoList.get_all() + todo_lists = json.dumps([todo_list.to_dict() for todo_list in todo_lists]) + return HttpResponse(todo_lists, status=200, content_type="application/json") + + def post(self, request): + data = request.body + + data = { + 'name': data.get('name'), + 'description': data.get('description') if data.get('description') else '', + 'members': [CustomUser.get_by_id(pk=user_id) for user_id in data.get('members')] + if data.get('members') else None + } + + todo_list = ToDoList.create(**data) + if todo_list: + return JsonResponse(todo_list.to_dict(), status=201) + return HttpResponse(status=400) + + def put(self, request, todo_list_pk=None): + if todo_list_pk and not is_integer(todo_list_pk): + return HttpResponse(status=404) + todo_list = ToDoList.get_by_id(todo_list_pk) + if not todo_list: + return HttpResponse(status=404) + data = request.body + + members_to_add = data.get('members_to_add') + members_to_delete = data.get('members_to_delete') + if members_to_add or members_to_delete: + todo_list = todo_list.update_members(members_to_add, members_to_delete) + if not todo_list: + return HttpResponse(status=400) + data = {'name': data.get('name') if data.get('name') else None, + 'description': data.get('description') if data.get('description') else None} + + todo_list = todo_list.update(**data) + if not todo_list: + return HttpResponse(status=400) + return HttpResponse(status=200) + + def delete(self, request, todo_list_pk=None): + if todo_list_pk and not is_integer(todo_list_pk): + return HttpResponse(status=404) + todo_list = ToDoList.get_by_id(todo_list_pk) + if not todo_list: + return HttpResponse(status=404) + + ToDoList.remove(pk=todo_list_pk) + return HttpResponse(status=200) diff --git a/utils/__init__.py b/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/utils/abstract_model.py b/utils/abstract_model.py new file mode 100644 index 0000000..ac9b38e --- /dev/null +++ b/utils/abstract_model.py @@ -0,0 +1,41 @@ +from abc import abstractmethod + +from django.db import models + + +class AbstractModel(models.Model): + objects = models.Manager() + + class Meta: + abstract = True + + @classmethod + def get_by_id(cls, pk: int): # pylint: disable=C0103 + try: + entity = cls.objects.get(pk=pk) + return entity + except cls.DoesNotExist: + return None + + @classmethod + def get_all(cls): + task = cls.objects.all() + return task + + @classmethod + def remove(cls, pk): # pylint: disable=C0103 + try: + task = cls.objects.get(id=pk) + task.delete() + except cls.DoesNotExist: + return False + return True + + @abstractmethod + def update(self, *args, **kwargs): + raise NotImplementedError + + @classmethod + @abstractmethod + def create(cls, *args, **kwargs): + raise NotImplementedError diff --git a/utils/middleware/__init__.py b/utils/middleware/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/utils/middleware/middleware.py b/utils/middleware/middleware.py new file mode 100644 index 0000000..dbdf6c0 --- /dev/null +++ b/utils/middleware/middleware.py @@ -0,0 +1,23 @@ +from django.http import HttpResponse + +import json + + +class JSONMiddleware: + """ + Process requests data from PUT and POST requests. + """ + + def __init__(self, get_response): + self.get_response = get_response + + def __call__(self, request): + if request.method == 'POST' or request.method == 'PUT': + try: + request._body = json.loads(request.body) + return self.get_response(request) + except json.JSONDecodeError: + return HttpResponse("Invalid data.", status=400) + else: + response = self.get_response(request) + return response diff --git a/utils/validators.py b/utils/validators.py new file mode 100644 index 0000000..45903ef --- /dev/null +++ b/utils/validators.py @@ -0,0 +1,7 @@ +def is_integer(number): + try: + float(number) + except ValueError: + return False + else: + return float(number).is_integer()