diff --git a/.github/workflows/pylint.yml b/.github/workflows/pylint.yml index 20ed9f6b8..c2c5f3b9e 100644 --- a/.github/workflows/pylint.yml +++ b/.github/workflows/pylint.yml @@ -23,3 +23,4 @@ jobs: - name: Analysing the code with pylint run: | pylint $(git ls-files '*.py') + working-directory: src/backend diff --git a/.github/workflows/pytest-coverage.yml b/.github/workflows/pytest-coverage.yml index 7a4de4fff..50402a7c6 100644 --- a/.github/workflows/pytest-coverage.yml +++ b/.github/workflows/pytest-coverage.yml @@ -9,6 +9,16 @@ jobs: steps: - uses: actions/checkout@v3 + - run: wget https://sqlite.org/2022/sqlite-autoconf-3380500.tar.gz + - run: tar -xvf sqlite-autoconf-3380500.tar.gz + - run: ./configure + working-directory: sqlite-autoconf-3380500 + - run: make + working-directory: sqlite-autoconf-3380500 + - run: sudo make install + working-directory: sqlite-autoconf-3380500 + - run: export PATH="/usr/local/lib:$PATH" + - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v3 with: @@ -23,7 +33,9 @@ jobs: - name: Build coverage file run: | - pytest --junitxml=pytest.xml --cov-report=term-missing:skip-covered --cov=. | tee pytest-coverage.txt + pytest --junitxml=pytest.xml --cov-report=term-missing --cov=. | tee pytest-coverage.txt + env: + LD_LIBRARY_PATH: /usr/local/lib working-directory: src/backend - name: Pytest coverage comment diff --git a/.github/workflows/python-app.yml b/.github/workflows/python-app.yml index cbcbb35e5..033c740b3 100644 --- a/.github/workflows/python-app.yml +++ b/.github/workflows/python-app.yml @@ -19,6 +19,17 @@ jobs: steps: - uses: actions/checkout@v3 + + - run: wget https://sqlite.org/2022/sqlite-autoconf-3380500.tar.gz + - run: tar -xvf sqlite-autoconf-3380500.tar.gz + - run: ./configure + working-directory: sqlite-autoconf-3380500 + - run: make + working-directory: sqlite-autoconf-3380500 + - run: sudo make install + working-directory: sqlite-autoconf-3380500 + - run: export PATH="/usr/local/lib:$PATH" + - name: Set up Python 3.10 uses: actions/setup-python@v3 with: @@ -39,4 +50,6 @@ jobs: - name: Test with pytest run: | pytest + env: + LD_LIBRARY_PATH: /usr/local/lib working-directory: src/backend diff --git a/src/backend/.coveragerc b/src/backend/.coveragerc index 1cb8c51ca..c3fbb1154 100644 --- a/src/backend/.coveragerc +++ b/src/backend/.coveragerc @@ -1,2 +1,4 @@ [run] -omit = *tests* \ No newline at end of file +omit = *tests* + *init* + *decorators* \ No newline at end of file diff --git a/src/backend/.pylintrc b/src/backend/.pylintrc new file mode 100644 index 000000000..cbc3a3759 --- /dev/null +++ b/src/backend/.pylintrc @@ -0,0 +1,619 @@ +[MAIN] + +# 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 + +# Load and enable all available extensions. Use --list-extensions to see a list +# all available extensions. +#enable-all-extensions= + +# In error mode, messages with a category besides ERROR or FATAL are +# suppressed, and no reports are done by default. Error mode is compatible with +# disabling specific errors. +#errors-only= + +# Always return a 0 (non-error) status code, even if lint errors are found. +# This is primarily useful in continuous integration scripts. +#exit-zero= + +# 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-allow-list= + +# 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. (This is an alternative name to extension-pkg-allow-list +# for backward compatibility.) +extension-pkg-whitelist= + +# Return non-zero exit code if any of these messages/categories are detected, +# even if score is above --fail-under value. Syntax same as enable. Messages +# specified are enabled, while categories only check already-enabled messages. +fail-on= + +# Specify a score threshold under which the program will exit with error. +fail-under=10 + +# Interpret the stdin as a python script, whose filename needs to be passed as +# the module_or_package argument. +#from-stdin= + +# Files or directories to be skipped. They should be base names, not paths. +ignore=CVS + +# Add files or directories matching the regular expressions patterns to the +# ignore-list. The regex matches against paths and can be in Posix or Windows +# format. Because '\' represents the directory delimiter on Windows systems, it +# can't be used as an escape character. +ignore-paths= + +# Files or directories matching the regular expression patterns are skipped. +# The regex matches against base names, not paths. The default value ignores +# Emacs file locks +ignore-patterns=^\.# + +# 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= + +# 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, and will cap the count on Windows to +# avoid hangs. +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= + +# Pickle collected data for later comparisons. +persistent=yes + +# Minimum Python version to use for version dependent checks. Will default to +# the version used to run pylint. +py-version=3.8 + +# Discover python modules and packages in the file system subtree. +recursive=no + +# 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 + +# In verbose mode, extra non-checker-related info will be displayed. +#verbose= + + +[REPORTS] + +# Python expression which should return a score less than or equal to 10. You +# have access to the variables 'fatal', 'error', 'warning', 'refactor', +# 'convention', and 'info' 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=max(0, 0 if fatal else 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= + +# Tells whether to display a full report or only the messages. +reports=no + +# Activate the evaluation score. +score=yes + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE, +# UNDEFINED. +confidence=HIGH, + CONTROL_FLOW, + INFERENCE, + INFERENCE_FAILURE, + UNDEFINED + +# 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 re-enable 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=raw-checker-failed, + bad-inline-option, + locally-disabled, + file-ignored, + suppressed-message, + useless-suppression, + deprecated-pragma, + use-symbolic-message-instead, + no-member + +# 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 + + +[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 + + +[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 be considered directives if they +# appear at the beginning of a comment and should not be checked. +spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy: + +# 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 + + +[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= + + +[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 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 symbolic message names to ignore for Mixin members. +ignored-checks-for-mixins=no-member, + not-async-context-manager, + not-context-manager, + attribute-defined-outside-init + +# 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,argparse.Namespace + +# 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 + +# Regex pattern to define which classes are considered mixins. +mixin-class-rgx=.*[Mm]ixin + +# List of decorators that change the signature of a decorated function. +signature-mutators= + + +[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 + + +[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 names allowed to shadow builtins +allowed-redefined-builtins= + +# 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. +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 + + +[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 + + +[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 + +# Deprecated modules which should not be used, separated by a comma. +deprecated-modules= + +# Output a graph (.gv or any supported image format) of external dependencies +# to the given file (report RP0402 must not be disabled). +ext-import-graph= + +# Output a graph (.gv or any supported image format) of all (i.e. internal and +# external) dependencies to the given file (report RP0402 must not be +# disabled). +import-graph= + +# Output a graph (.gv or any supported image format) of internal dependencies +# to 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= + + +[METHOD_ARGS] + +# List of qualified names (i.e., library.method) which require a timeout +# parameter e.g. 'requests.api.get,requests.api.post' +timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when caught. +overgeneral-exceptions=BaseException, + Exception + + +[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,argparse.parse_error + + +[SIMILARITIES] + +# Comments are removed from the similarity computation +ignore-comments=yes + +# Docstrings are removed from the similarity computation +ignore-docstrings=yes + +# Imports are removed from the similarity computation +ignore-imports=yes + +# Signatures are removed from the similarity computation +ignore-signatures=yes + +# Minimum lines number of a similarity. +min-similarity-lines=4 + + +[DESIGN] + +# List of regular expressions of class ancestor names to ignore when counting +# public methods (see R0903) +exclude-too-few-public-methods= + +# List of qualified class names to ignore when counting class parents (see +# R0901) +ignored-parents= + +# 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 (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 + + +[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 + + +[BASIC] + +# Naming style matching correct argument names. +argument-naming-style=snake_case + +# Regular expression matching correct argument names. Overrides argument- +# naming-style. If left empty, argument names will be checked with the set +# 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. If left empty, attribute names will be checked with the set 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. If left empty, class attribute names will be checked +# with the set naming style. +#class-attribute-rgx= + +# Naming style matching correct class constant names. +class-const-naming-style=UPPER_CASE + +# Regular expression matching correct class constant names. Overrides class- +# const-naming-style. If left empty, class constant names will be checked with +# the set naming style. +#class-const-rgx= + +# Naming style matching correct class names. +class-naming-style=PascalCase + +# Regular expression matching correct class names. Overrides class-naming- +# style. If left empty, class names will be checked with the set 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. If left empty, constant names will be checked with the set 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. If left empty, function names will be checked with the set +# 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. If left empty, inline iteration names will be checked +# with the set 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. If left empty, method names will be checked with the set 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. If left empty, module names will be checked with the set 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 + +# Regular expression matching correct type variable names. If left empty, type +# variable names will be checked with the set naming style. +#typevar-rgx= + +# Naming style matching correct variable names. +variable-naming-style=snake_case + +# Regular expression matching correct variable names. Overrides variable- +# naming-style. If left empty, variable names will be checked with the set +# naming style. +#variable-rgx= diff --git a/src/backend/app.py b/src/backend/app.py index 9739cbe4e..5c720aa21 100644 --- a/src/backend/app.py +++ b/src/backend/app.py @@ -1,6 +1,11 @@ """ This is a module docstring """ +import json +import dataclasses +from collections import namedtuple +from werkzeug.datastructures import MultiDict from flask import Flask, request -from login import Login +from pages.login import Login +from pages.mainpage import MainPage # from logging import FileHandler, WARNING @@ -11,25 +16,134 @@ def login(): """Handles login routing""" user_login = Login() - user = request.json["user"] - password = request.json["password"] - if user_login.login(user, password): - return f"welcome {user}", 200 - return "User not found, please try again", 404 + json_form = request.get_json(force=True) + + if isinstance(json_form, dict): + user = json_form.get("user", "") + password = json_form.get("password", "") + if user_login.login(user, password): + return f"welcome {user}", 200 + return "User not found, please try again", 401 + return "", 400 @app.route("/register", methods=["POST", "GET"]) def register(): """Handles register routing""" user_login = Login() - username = request.json["username"] - email = request.json["email"] - password = request.json["password"] - phone = request.json["phone"] - result = user_login.register(username, email, password, phone) - if not result.status: - return result.message, 400 - return result.message, 200 + json_form = request.get_json(force=True) + + if isinstance(json_form, dict): + username = json_form.get("username", "") + email = json_form.get("email", "") + password = json_form.get("password", "") + phone = json_form.get("phone", "") + result = user_login.register(username, email, password, phone) + if not result.status: + return result.message, 400 + return result.message, 201 + return "", 400 + + +@app.route("/", methods=["POST", "GET"]) +@app.route("/main", methods=["POST", "GET"]) +def mainpage(): + """Handle mainpage requests""" + mainpage_obj = MainPage() + if request.method == "POST": + return mainpage_post(mainpage_obj) + + args = request.args + return mainpage_get(mainpage_obj, args) + + +def mainpage_get(mainpage_obj: MainPage, args: MultiDict): + """ + Helper for mainpage get requests + Actions that use get requests: + - Searching apartments + - Populating the mainpage with apartments + - Getting reviews of an apartment + - Getting pictures of an apartment + """ + action_type = namedtuple( + "action_type", ["is_search", "is_populate", "is_review", "is_pictures"] + ) + action = action_type( + args.get("search", default=False, type=bool), + args.get("populate", default=False, type=bool), + args.get("review", default=False, type=bool), + args.get("pictures", default=False, type=bool), + ) + + params = namedtuple( + "params", ["num_apts", "apt_id", "search_query", "price_sort", "rating_sort"] + ) + param = params( + args.get("numApts", type=int), + args.get("aptId", type=int), + args.get("searchQuery", type=str), + args.get("priceSort", type=int), + args.get("ratingSort", type=int), + ) + + query_result = "" + if action.is_search is True and param.search_query is not None: + apts = mainpage_obj.search_apartments(param.search_query) + apts_dict = [dataclasses.asdict(apt) for apt in apts] + query_result = json.dumps(apts_dict) + + elif action.is_populate is True and param.num_apts is not None: + apts = [] + if param.price_sort is not None and param.rating_sort is not None: + apts = mainpage_obj.apartments_sorted( + param.num_apts, param.price_sort, param.rating_sort + ) + else: + apts = mainpage_obj.apartments_default(param.num_apts) + apts_dict = [dataclasses.asdict(apt) for apt in apts] + query_result = json.dumps(apts_dict) + + elif action.is_review is True and param.apt_id is not None: + reviews = mainpage_obj.get_apartments_reviews(param.apt_id) + reviews_dict = [dataclasses.asdict(review) for review in reviews] + query_result = json.dumps(reviews_dict) + + elif action.is_pictures is True and param.apt_id is not None: + query_result = json.dumps(mainpage_obj.get_apartments_pictures(param.apt_id)) + + if len(query_result) != 0: + return query_result, 200 + return "", 400 + + +def mainpage_post(mainpage_obj: MainPage): + """ + Helper for mainpage post requests + Actions that use post request: + - Writing a review to an apartment + """ + json_form = request.get_json(force=True) + + if isinstance(json_form, dict): + apt_id = json_form.get("apt_id") + username = json_form.get("username") + comment = json_form.get("comment") + vote = json_form.get("vote") + if ( + apt_id is not None + and username is not None + and comment is not None + and vote is not None + ): + query_result = "" + reviews = mainpage_obj.write_apartment_review( + apt_id, username, comment, vote + ) + reviews_dict = [dataclasses.asdict(review) for review in reviews] + query_result = json.dumps(reviews_dict) + return query_result, 201 + return "", 400 if __name__ == "__main__": diff --git a/src/backend/database/database.db b/src/backend/database/database.db index cc50ec210..83eda088f 100644 Binary files a/src/backend/database/database.db and b/src/backend/database/database.db differ diff --git a/src/backend/database/schema.sql b/src/backend/database/schema.sql index 2145dbf2a..ab8861de8 100644 --- a/src/backend/database/schema.sql +++ b/src/backend/database/schema.sql @@ -31,7 +31,8 @@ CREATE TABLE Reviews ( user_id INTEGER NOT NULL, date_of_rating DATE NOT NULL, comment TEXT, - vote INTEGER CHECK(vote = 1 OR vote = 0 OR vote = -1) + vote INTEGER CHECK(vote = 1 OR vote = 0 OR vote = -1), + UNIQUE(apt_id, user_id) ); -- TEST diff --git a/src/backend/dataholders/__init__.py b/src/backend/dataholders/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/src/backend/apt.py b/src/backend/dataholders/apt.py similarity index 100% rename from src/backend/apt.py rename to src/backend/dataholders/apt.py diff --git a/src/backend/review.py b/src/backend/dataholders/review.py similarity index 100% rename from src/backend/review.py rename to src/backend/dataholders/review.py diff --git a/src/backend/decorators.py b/src/backend/decorators.py new file mode 100644 index 000000000..129a40bdd --- /dev/null +++ b/src/backend/decorators.py @@ -0,0 +1,27 @@ +"""Stores decorators for common functionalities""" +import sqlite3 +import functools + + +def use_database(func): + """Decorator to utilize DB connections""" + + @functools.wraps(func) + def wrapped(*args): + """Wrapper about the actual function""" + connection = sqlite3.connect("database/database.db") + cursor = connection.cursor() + wrapped.cursor = cursor + wrapped.connection = connection + try: + caller = func(*args) + except Exception: + connection.rollback() + raise + else: + connection.commit() + finally: + connection.close() + return caller + + return wrapped diff --git a/src/backend/pages/__init__.py b/src/backend/pages/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/src/backend/login.py b/src/backend/pages/login.py similarity index 83% rename from src/backend/login.py rename to src/backend/pages/login.py index 5228cec77..b2ea9d32b 100644 --- a/src/backend/login.py +++ b/src/backend/pages/login.py @@ -1,7 +1,7 @@ """ Contains Login class """ from dataclasses import dataclass import re -import sqlite3 +from decorators import use_database @dataclass(frozen=True) @@ -19,6 +19,7 @@ class Login: def __init__(self) -> None: """Constructor""" + @use_database def register( self, username: str, email: str, password: str, phone: str ) -> RegisterResult: @@ -40,33 +41,27 @@ def register( if len(password) < 8: return RegisterResult("Password is too short, please try again", False) - connection = sqlite3.connect("database/database.db") - cursor = connection.cursor() - check = cursor.execute( + + check = self.register.cursor.execute( "SELECT username FROM Users WHERE username = ?", (username,) ).fetchone() if check is None: # valid - cursor.execute( + self.register.cursor.execute( "INSERT INTO Users (username, email, password, phone, apt_id) \ VALUES (?, ?, ?, ?, 0)", (username, email, password, phone), ) - connection.commit() - connection.close() return RegisterResult(f"Register successful, welcome {username}", True) - connection.close() return RegisterResult(f"{username} already registered, please try again", False) + @use_database def login(self, user_id: str, password: str) -> bool: """Login function, returns false if combination not found""" - connection = sqlite3.connect("database/database.db") - cursor = connection.cursor() - user = cursor.execute( + user = self.login.cursor.execute( "SELECT username, email, password FROM Users WHERE (username = ? OR email = ?) \ AND password = ?", (user_id, user_id, password), ).fetchall() - connection.close() return len(user) > 0 def logout(self) -> None: diff --git a/src/backend/mainpage.py b/src/backend/pages/mainpage.py similarity index 65% rename from src/backend/mainpage.py rename to src/backend/pages/mainpage.py index 314f6a828..e2ecba294 100644 --- a/src/backend/mainpage.py +++ b/src/backend/pages/mainpage.py @@ -1,9 +1,11 @@ """Contains Main page class""" import sqlite3 +from datetime import date from typing import List from typing import Tuple -from apt import Apt -from review import Review +from dataholders.apt import Apt +from dataholders.review import Review +from decorators import use_database class MainPage: @@ -12,16 +14,17 @@ class MainPage: def __init__(self) -> None: """Constructor""" + @use_database def search_apartments(self, query: str) -> List[Apt]: """Returns a list of apartments with name matching query""" query_sql = "%" + query.lower() + "%" - connection = sqlite3.connect("database/database.db") - cursor = connection.cursor() - apt_query = cursor.execute( + apt_query = self.search_apartments.cursor.execute( "SELECT Apartments.apt_id, Apartments.apt_name, Apartments.apt_address, \ - COALESCE(SUM(Reviews.vote), 0), Apartments.price_min, Apartments.price_max \ - FROM Apartments, Reviews WHERE LOWER(Apartments.apt_name) LIKE ? \ - AND Apartments.apt_id = Reviews.apt_id", + COALESCE(SUM(Reviews.vote), 0) AS 'total_vote', \ + Apartments.price_min, Apartments.price_max \ + FROM Apartments LEFT JOIN Reviews ON Apartments.apt_id = Reviews.apt_id \ + WHERE LOWER(Apartments.apt_name) LIKE ? \ + GROUP BY Apartments.apt_id", (query_sql,), ).fetchall() apts = [] @@ -30,14 +33,12 @@ def search_apartments(self, query: str) -> List[Apt]: apts.append( Apt(entry[0], entry[1], entry[2], entry[3], entry[4], entry[5]) ) - connection.close() return apts + @use_database def apartments_default(self, num_apts: int) -> List[Apt]: """Returns num_apts apartments to populate the mainpage""" - connection = sqlite3.connect("database/database.db") - cursor = connection.cursor() - apt_query = cursor.execute( + apt_query = self.apartments_default.cursor.execute( "SELECT Apartments.apt_id, Apartments.apt_name, Apartments.apt_address, \ COALESCE(SUM(Reviews.vote), 0) AS 'total_vote', \ Apartments.price_min, Apartments.price_max \ @@ -49,27 +50,29 @@ def apartments_default(self, num_apts: int) -> List[Apt]: apts = [] for entry in apt_query: apts.append(Apt(entry[0], entry[1], entry[2], entry[3], entry[4], entry[5])) - connection.close() return apts + @use_database def apartments_sorted( self, num_apts: int, price_sort: int, rating_sort: int ) -> List[Apt]: """Returns num_apts apartments with sorting criterias""" - connection = sqlite3.connect("database/database.db") - cursor = connection.cursor() apts = [] apt_query = [] if price_sort == 0: - apt_query = self.rating_sort_helper(num_apts, rating_sort, cursor) + apt_query = self.rating_sort_helper( + num_apts, rating_sort, self.apartments_sorted.cursor + ) elif rating_sort == 0 and price_sort != 0: - apt_query = self.price_sort_helper(num_apts, price_sort, cursor) + apt_query = self.price_sort_helper( + num_apts, price_sort, self.apartments_sorted.cursor + ) else: - apt_query = self.both_sort_helper(num_apts, price_sort, rating_sort, cursor) - - connection.close() + apt_query = self.both_sort_helper( + num_apts, price_sort, rating_sort, self.apartments_sorted.cursor + ) for entry in apt_query: apts.append(Apt(entry[0], entry[1], entry[2], entry[3], entry[4], entry[5])) @@ -144,57 +147,66 @@ def both_sort_helper( return apt_query + @use_database def get_apartments_pictures(self, apt_id: int) -> List[str]: """Returns pictures related to an apartment""" - connection = sqlite3.connect("database/database.db") - cursor = connection.cursor() - pic_query = cursor.execute( + pic_query = self.get_apartments_pictures.cursor.execute( "SELECT link FROM AptPics WHERE apt_id = ?", (apt_id,) ).fetchall() res = [] for entry in pic_query: res.append(entry[0]) - cursor.close() return res + @use_database def write_apartment_review( self, apt_id: int, username: str, comment: str, vote: int - ) -> bool: + ) -> List[Review]: """Write a new review for apartment""" - connection = sqlite3.connect("database/database.db") - cursor = connection.cursor() - user_id = cursor.execute( + user_id = self.write_apartment_review.cursor.execute( "SELECT user_id FROM Users WHERE username = ?", (username,) ).fetchone()[0] - current_review = cursor.execute( - "SELECT user_id FROM Reviews WHERE user_id = ?", (user_id,) - ).fetchone() - if current_review is None: - cursor.execute( - "INSERT INTO Reviews (apt_id, user_id, date_of_rating, comment, vote) \ - VALUES (?, ?, date(), ?, ?)", - (apt_id, user_id, comment, vote), - ) - connection.commit() - connection.close() - return True - connection.close() - return False + today = date.today().strftime("%Y-%m-%d") + self.write_apartment_review.cursor.execute( + "INSERT INTO Reviews (apt_id, user_id, date_of_rating, comment, vote) \ + VALUES (?, ?, ?, ?, ?) \ + ON CONFLICT DO UPDATE SET \ + date_of_rating = excluded.date_of_rating, \ + comment = excluded.comment, \ + vote = excluded.vote", + (apt_id, user_id, today, comment, vote), + ) + self.write_apartment_review.connection.commit() + ratings_query = self.write_apartment_review.cursor.execute( + "SELECT Users.username, Reviews.date_of_rating, Reviews.comment, Reviews.vote \ + FROM Users INNER JOIN Reviews \ + ON Users.user_id = Reviews.user_id \ + WHERE Reviews.apt_id = ? \ + ORDER BY Users.username = ? DESC, Reviews.date_of_rating DESC", + (apt_id, username), + ).fetchall() + return self.create_reviews_helper(ratings_query) + @use_database def get_apartments_reviews(self, apt_id: int) -> List[Review]: """Returns a list of apartment reviews""" - connection = sqlite3.connect("database/database.db") - cursor = connection.cursor() - ratings_query = cursor.execute( + ratings_query = self.get_apartments_reviews.cursor.execute( "SELECT Users.username, Reviews.date_of_rating, Reviews.comment, Reviews.vote \ - FROM Users, Reviews WHERE Users.user_id = Reviews.user_id AND Reviews.apt_id = ?", + FROM Users INNER JOIN Reviews \ + ON Users.user_id = Reviews.user_id \ + WHERE Reviews.apt_id = ? \ + ORDER BY Reviews.date_of_rating DESC", (apt_id,), ).fetchall() + return self.create_reviews_helper(ratings_query) + + def create_reviews_helper(self, ratings_query: List[Tuple]) -> List[Review]: + """Create a list of reviews out of a query""" reviews = [] for entry in ratings_query: - vote = False - if entry[3] == 1: - vote = True - reviews.append(Review(entry[0], entry[1], entry[2], vote)) - cursor.close() + if entry[0] is not None: + vote = False + if entry[3] == 1: + vote = True + reviews.append(Review(entry[0], entry[1], entry[2], vote)) return reviews diff --git a/src/backend/tests/test_app.py b/src/backend/tests/test_app.py index c521326a5..8256f940d 100644 --- a/src/backend/tests/test_app.py +++ b/src/backend/tests/test_app.py @@ -2,6 +2,7 @@ import sqlite3 import pytest from app import app +from tests.mainpage_staging import MainPageStaging @pytest.fixture(name="config_app") @@ -18,7 +19,7 @@ def fixture_client(config_app): def test_register_valid(client): - """Test register returns valid (200) network code""" + """Test register handles valid request""" reg_info = { "username": "big_finger", "email": "junk@gmail.com", @@ -31,11 +32,11 @@ def test_register_valid(client): cursor.execute("DELETE FROM Users WHERE username = ?", ("big_finger",)) connection.commit() connection.close() - assert res.status_code == 200 + assert res.status_code == 201 -def test_register_invalid(client): - """Test register returns invalid (400) network code""" +def test_register_invalid_input(client): + """Test register handles invalid register attempt""" reg_info = { "username": "big_finger", "email": "junk@gmail.com", @@ -57,12 +58,19 @@ def test_register_invalid(client): cursor.execute("DELETE FROM Users WHERE username = ?", ("big_finger",)) connection.commit() connection.close() - + assert res_2.text == "big_finger already registered, please try again" assert res_2.status_code == 400 +def test_register_not_json(client): + """Test register handles non-json""" + res = client.post("/register", json="") + assert res.text == "" + assert res.status_code == 400 + + def test_login_valid(client): - """Test login returns valid (200) network code""" + """Test login handles valid request""" connection = sqlite3.connect("database/database.db") cursor = connection.cursor() cursor.execute( @@ -80,8 +88,147 @@ def test_login_valid(client): assert res.status_code == 200 -def test_login_invalid(client): - """Test login returns invalid (404) network code""" +def test_login_invalid_user(client): + """Test handles non-existant user""" log_info = {"user": "big_finger", "password": "123456789"} res = client.post("/login", json=log_info) - assert res.status_code == 404 + assert res.status_code == 401 + + +def test_login_not_json(client): + """Test login handles non-json""" + res = client.post("login", json="") + assert res.status_code == 400 + + +def test_mainpage_get_valid_review(client): + """Test mainpage handles valid reviwew request""" + mainpage = MainPageStaging() + mainpage.initialize_all() + connection = sqlite3.connect("database/database.db") + cursor = connection.cursor() + + far_id = cursor.execute( + "SELECT apt_id FROM Apartments WHERE (apt_name = 'FAR')" + ).fetchone()[0] + query = {"review": "True", "aptId": far_id} + res = client.get("/main", query_string=query) + sample_json = ( + '[{"username": "Big_finger", ' + '"date": "2022-10-10", ' + '"comment": "Decent hall", ' + '"vote": true}]' + ) + + connection.close() + mainpage.clean_all() + assert res.status_code == 200 + assert res.text == sample_json + + +def test_mainpage_get_valid_search(client): + """Test mainpage handles valid search request""" + mainpage = MainPageStaging() + mainpage.initialize_all() + + connection = sqlite3.connect("database/database.db") + cursor = connection.cursor() + + isr_id = cursor.execute( + "SELECT apt_id FROM Apartments WHERE (apt_name = 'ISR')" + ).fetchone()[0] + + query = {"search": "True", "searchQuery": "is"} + res = client.get("/main", query_string=query) + sample_json = ( + f'[{{"apt_id": {isr_id}, ' + '"name": "ISR", ' + '"address": "918 W Illinois", ' + '"rating": 0, ' + '"price_min": 6000, ' + '"price_max": 7000}]' + ) + + connection.close() + mainpage.clean_all() + assert res.status_code == 200 + assert res.text == sample_json + + +def test_mainpage_get_valid_pictures(client): + """Test mainpage handles valid picture query""" + mainpage = MainPageStaging() + mainpage.initialize_all() + + connection = sqlite3.connect("database/database.db") + cursor = connection.cursor() + + sample_id = cursor.execute( + "SELECT apt_id FROM Apartments WHERE (apt_name = 'Sherman')" + ).fetchone()[0] + + query = {"pictures": "True", "aptId": sample_id} + res = client.get("/main", query_string=query) + + sample_json = '["Link1", "Link2", "Link3"]' + + connection.close() + mainpage.clean_all() + + assert res.status_code == 200 + assert res.text == sample_json + + +def test_mainpage_get_valid_populate(client): + """Test mainpage handles valid populate query""" + mainpage = MainPageStaging() + mainpage.initialize_all() + + query_1 = {"populate": "True", "numApts": 1} + query_2 = {"populate": "True", "numApts": 1, "priceSort": 0, "ratingSort": 0} + + res_1 = client.get("/main", query_string=query_1) + res_2 = client.get("/main", query_string=query_2) + mainpage.clean_all() + + assert res_1.status_code == 200 + assert res_2.status_code == 200 + assert res_1.text == res_2.text + + +def test_mainpage_get_invalid_query(client): + """Test mainpage handles invalid get request""" + res = client.get("/main", query_string={"search": "True"}) + assert res.status_code == 400 + + +def test_mainpage_post_valid(client): + """Test mainpage handles valid post request""" + mainpage = MainPageStaging() + mainpage.initialize_all() + connection = sqlite3.connect("database/database.db") + cursor = connection.cursor() + + isr_id = cursor.execute( + "SELECT apt_id FROM Apartments WHERE (apt_name = 'ISR')" + ).fetchone()[0] + sample_review = { + "apt_id": isr_id, + "username": "Minh Phan", + "comment": "Good", + "vote": 1, + } + res = client.post("/main", json=sample_review) + + cursor.execute("DELETE FROM Reviews WHERE apt_id = ?", (isr_id,)) + connection.commit() + connection.close() + mainpage.clean_all() + assert res.status_code == 201 + + +def test_mainpage_post_invalid(client): + """Test mainpage handles invalid post request""" + sample_review = {"username": "User McUserFace", "comment": "Ho ho ho ho"} + res = client.post("/main", json=sample_review) + assert res.status_code == 400 diff --git a/src/backend/tests/test_apt.py b/src/backend/tests/test_apt.py index 2dd06db38..594982082 100644 --- a/src/backend/tests/test_apt.py +++ b/src/backend/tests/test_apt.py @@ -1,5 +1,5 @@ """Test apt.py""" -from apt import Apt +from dataholders.apt import Apt class TestApt: diff --git a/src/backend/tests/test_login.py b/src/backend/tests/test_login.py index 90726e4cb..d9e398bf9 100644 --- a/src/backend/tests/test_login.py +++ b/src/backend/tests/test_login.py @@ -1,6 +1,6 @@ """Test login.py""" import sqlite3 -from login import Login +from pages.login import Login class TestLogin: diff --git a/src/backend/tests/test_mainpage.py b/src/backend/tests/test_mainpage.py index e6aab86c9..825702c89 100644 --- a/src/backend/tests/test_mainpage.py +++ b/src/backend/tests/test_mainpage.py @@ -1,8 +1,9 @@ """Test mainpage.py""" import sqlite3 -from mainpage import MainPage -from apt import Apt -from review import Review +from datetime import date +from pages.mainpage import MainPage +from dataholders.apt import Apt +from dataholders.review import Review from tests.mainpage_staging import MainPageStaging @@ -38,15 +39,15 @@ def test_apartments_default(self): connection = sqlite3.connect("database/database.db") cursor = connection.cursor() - far_id = cursor.execute( - "SELECT apt_id FROM Apartments WHERE (apt_name = 'FAR')" - ).fetchone()[0] sherman_id = cursor.execute( "SELECT apt_id FROM Apartments WHERE (apt_name = 'Sherman')" ).fetchone()[0] isr_id = cursor.execute( "SELECT apt_id FROM Apartments WHERE (apt_name = 'ISR')" ).fetchone()[0] + far_id = cursor.execute( + "SELECT apt_id FROM Apartments WHERE (apt_name = 'FAR')" + ).fetchone()[0] connection.close() sample_apts_default = [] sample_apts_default.append( @@ -269,38 +270,36 @@ def test_write_apartment_review(self): sample_comment = "Bruh this really sucks" connection = sqlite3.connect("database/database.db") cursor = connection.cursor() - fig_binger_id = cursor.execute( - "SELECT user_id FROM Users WHERE (username = 'Fig_binger')" - ).fetchone()[0] sherman_id = cursor.execute( "SELECT apt_id FROM Apartments WHERE (apt_name = 'Sherman')" ).fetchone()[0] + today = date.today().strftime("%Y-%m-%d") connection.close() - can_write = self.main_page.write_apartment_review( + write_result = self.main_page.write_apartment_review( sherman_id, "Fig_binger", sample_comment, -1 ) - - connection = sqlite3.connect("database/database.db") - cursor = connection.cursor() - find_review = cursor.execute( - "SELECT * FROM Reviews WHERE user_id = ?", (fig_binger_id,) - ).fetchall() - cursor.execute("DELETE FROM Reviews WHERE apt_id = ?", (sherman_id,)) - connection.close() + sample_apts_review = [] + sample_apts_review.append(Review("Fig_binger", today, sample_comment, False)) + sample_apts_review.append(Review("Big_finger", "2022-10-09", "Decent", True)) + sample_apts_review.append( + Review("Minh", "2022-10-08", "Bruh this sucks", False) + ) + sample_apts_review.append( + Review("Minh Phan", "2022-10-07", "Pretty good", True) + ) self.main_page_stage.clean_all() - assert can_write - assert find_review is not None + assert write_result == sample_apts_review def test_get_apartments_reviews(self): """Test get_apartments_reviews()""" sample_apts_review = [] + sample_apts_review.append(Review("Big_finger", "2022-10-09", "Decent", True)) sample_apts_review.append( - Review("Minh Phan", "2022-10-07", "Pretty good", True) + Review("Minh", "2022-10-08", "Bruh this sucks", False) ) sample_apts_review.append( - Review("Minh", "2022-10-08", "Bruh this sucks", False) + Review("Minh Phan", "2022-10-07", "Pretty good", True) ) - sample_apts_review.append(Review("Big_finger", "2022-10-09", "Decent", True)) self.main_page_stage.initialize_all() @@ -344,24 +343,6 @@ def test_get_apartments_pictures_invalid(self): self.main_page_stage.clean_all() assert sample_apts_picture == res - def test_write_apartment_review_invalid(self): - """Test write review while having existing review""" - self.main_page_stage.initialize_all() - - connection = sqlite3.connect("database/database.db") - cursor = connection.cursor() - sample_comment = "Bruh this really sucks" - sherman_id = cursor.execute( - "SELECT apt_id FROM Apartments WHERE (apt_name = 'Sherman')" - ).fetchone()[0] - connection.close() - can_write = self.main_page.write_apartment_review( - sherman_id, "Big_finger", sample_comment, -1 - ) - self.main_page_stage.clean_all() - - assert not can_write - def test_get_apartments_reviews_empty(self): """Test get reviews of invalid apartments""" sample_apts_review = [] diff --git a/src/backend/tests/test_review.py b/src/backend/tests/test_review.py index 65a0492b7..1d1578b04 100644 --- a/src/backend/tests/test_review.py +++ b/src/backend/tests/test_review.py @@ -1,5 +1,5 @@ """Test review.py""" -from review import Review +from dataholders.review import Review class TestReview: