diff --git a/.gitignore b/.gitignore index b694934..21670a3 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,71 @@ -.venv \ No newline at end of file +# Arquivos e diretórios específicos do Flask +/__pycache__/ +/*.pyc +/*.pyo +/*.pyd + +# Banco de dados SQLite (substitua o nome do arquivo pelo seu, se necessário) +/db.sqlite +/db_testing.sqlite +data* +/data + +# Diretório virtualenv (se estiver usando um ambiente virtual) +/venv/ +venv* + +# Arquivos e diretórios específicos do Visual Studio Code +.vscode/ +*.code-workspace +*.code-workspace-stored +.idea/ +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw* +*.suo +*.user +*.sln.docstates + +# Logs e arquivos temporários +*.log +*.pot +*.bak +*.tmp + +# Arquivos gerados automaticamente +*.pyc +__pycache__/ +*.db + +# Ambiente virtual Python (se você usa um ambiente virtual) +/.env + +# Dependências Python (exclui o diretório, mas inclui o arquivo de requisitos) +__pycache__/ +*.pyc +*.pyo +__pycache__/ +*.egg-info/ +dist/ +build/ +*.egg +*.egg-info +*.egg-info/ +MANIFEST + +# Arquivos de configuração sensíveis, como .env, .env.local, etc. +.env +.env.local +.env.*.local +.secrets.toml +.tool-versions + +# Diretórios específicos do Flask a serem excluídos +instance/ +migrations/ + +# Arquivo de cobertura de código +.coverage +.pytest_cache/ \ No newline at end of file diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000..a7bfa31 --- /dev/null +++ b/.pylintrc @@ -0,0 +1,634 @@ +[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=yes + +# Clear in-memory caches upon conclusion of linting. Useful if running pylint +# in a server-like mode. +clear-cache-post-run=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.11 + +# Discover python modules and packages in the file system subtree. +recursive=no + +# Add paths to the list of the source roots. Supports globbing patterns. The +# source root is an absolute path or a path relative to the current working +# directory used to determine a package namespace for modules located under the +# source root. +source-roots= + +# 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= + + +[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 alias names. If left empty, type +# alias names will be checked with the set naming style. +#typealias-rgx= + +# 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= + + +[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, + asyncSetUp, + __post_init__ + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict,_fields,_replace,_source,_make,os._exit + +# 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=mcs + + +[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 + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when caught. +overgeneral-exceptions=builtins.BaseException,builtins.Exception + + +[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 explicit reexports by alias from a package __init__. +allow-reexport-from-package=no + +# 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= + + +[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 + + +[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, + use-implicit-booleaness-not-comparison-to-string, + use-implicit-booleaness-not-comparison-to-zero + +# 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= + + +[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 + + +[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= + + +[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 + + +[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, +# json2 (improved json format), json (old json format) and msvs (visual +# studio). You can also give a reporter class, e.g. +# mypackage.mymodule.MyReporterClass. +output-format=colorized + +# Tells whether to display a full report or only the messages. +reports=no + +# Activate the evaluation score. +score=yes + + +[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 + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. No available dictionaries : You need to install +# both the python package and the system dependency for enchant to work. +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 + + +[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 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= + + +[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 \ No newline at end of file diff --git a/.secrets-example.toml b/.secrets-example.toml new file mode 100644 index 0000000..6a8ab7e --- /dev/null +++ b/.secrets-example.toml @@ -0,0 +1,33 @@ +[default] +APP_NAME = "app_name" +DATABASE = "sqlite" +DEBUG = true +SECRET_KEY = "***" +DATABASE_URL = "sqlite:///db.sqlite" + +[development] +APP_NAME = "project" +DATABASE = "postgresql" +DEBUG = true +SECRET_KEY = "***" +POSTGRES_USER = "user" +POSTGRES_PASSWORD = "***" +POSTGRES_HOST = "['127.0.0.1', 'localhost']" +POSTGRES_DB = "db" + +[testing] +APP_NAME = "project" +DATABASE = "sqlite" +DEBUG = true +SECRET_KEY = "***" +DATABASE_URL = "sqlite:///db" + +[production] +APP_NAME = "project" +DATABASE = "postgresql" +DEBUG = false +SECRET_KEY = "***" +POSTGRES_USER = "user" +POSTGRES_PASSWORD = "***" +POSTGRES_HOST = "['127.0.0.1', 'localhost']" +POSTGRES_DB = "db" \ No newline at end of file diff --git a/LICENSE b/LICENSE index 7d3b216..13a408a 100644 --- a/LICENSE +++ b/LICENSE @@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index e8d1675..1798034 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,110 @@ -# delivery-app-backend -BackEnd do projeto DeliveryAPP +

+ Delivery Back-end API +

+ +

+ Requisitos   |    + Tecnologias   |    + Como Usar   |    + Usar com Make +

+ +## :memo: Requisitos + +| Ferramenta | Versão | Descrição | +| -------------------------------------------------- | ------- | ------------------------------------------- | +| [Python](https://www.python.org/) | 3.11.* | Ambiente de execução Python | +| [pip](https://pypi.org/project/pip/) | ^24.1.1 | Gerenciador de pacotes Python | +| [Git](https://git-scm.com) | - | Controle de versões | +| [PostgreSQL](https://www.postgresql.org/) | - | Sistema de gerenciamento de banco de dados | +| [Docker](https://www.docker.com/) | - | Motor de container | +| [Docker-compose](https://docs.docker.com/compose/) | - | Orquestrador de containers Docker | + +## :rocket: Tecnologias + +Este projeto está sendo desenvolvido pela equipe [Hamper](https://hamper.com) com as seguintes tecnologias: + +- Linguagem e ambiente: [Python](https://www.python.org/) +- Object-Relational Mapper (ORM): [SQLAlchemy](https://www.sqlalchemy.org/) +- Banco de dados: [PostgreSQL](https://www.postgresql.org/) +- Migrações de banco de dados: [Alembic](https://alembic.sqlalchemy.org/) + +## :information_source: Como Usar + +```bash +# Clonar este repositório +$ git clone https://github.com/DeliveryAPP-Project/delivery-app-backend.git + +# Ir para o diretório do repositório +$ cd delivery-app-backend + +# Criar um ambiente virtual +$ python3 -m venv venv + +# Ativar o ambiente virtual +$ source venv/bin/activate + +# Instalar as dependências +$ pip install -r requirements.txt +``` + +### Configuração do Projeto + +```bash +# Renomear o arquivo de exemplo de variáveis de ambiente +$ cp .secrets-example.toml .secrets.toml + +# Definir as variáveis de ambiente para o Flask +$ export FLASK_APP=project +$ export FLASK_ENV=development # ou outro ambiente: testing, production +``` + +### Configuração do Banco de Dados + +```bash +# Iniciar o banco de dados com Docker +$ docker compose up + +# Iniciar o banco de dados com Docker Compose em segundo plano +$ docker-compose up -d + +# Parar o banco de dados com Docker Compose +$ docker-compose down + +# Inicializar o banco de dados +$ flask db init # Executar apenas uma vez para inicializar a conexão +$ flask db migrate # Criar a instância do SQLAlchemy +$ flask db upgrade # Criar as tabelas no banco de dados +``` + +### Executando o Projeto + +```bash +# Inicializar a aplicação +$ python -m project run +``` + +## :blue_book: Documentação da API + +A documentação da API pode ser acessada em [http://127.0.0.1:5000/api/v1](http://127.0.0.1:5000/api/v1), onde a versão do Swagger estará disponível. + +
+ +## Alembic + +Para gerenciar models, migrations e seeders, utilize o Alembic: + +```bash +# Aplicar a última migração ao banco de dados +$ alembic upgrade head + +# Gerar uma nova revisão (com base em modificações ou novos models) +$ alembic revision --autogenerate -m "nome_da_modificacao" +``` + +Mais comandos úteis podem ser encontrados na [documentação do Alembic](https://alembic.sqlalchemy.org/en/latest/api/commands.html). + +## :information_source: Usar com Make + +Veja como usar a aplicação através do Make no arquivo [Make.init](make.md). + diff --git a/docker-compose.yml b/docker-compose.yml index cfb6abc..00ae0f5 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -9,9 +9,15 @@ services: POSTGRES_USER: myuser POSTGRES_PASSWORD: mypassword1 ports: - - "5432:5432" + - "5433:5432" volumes: - pgdata:/var/lib/postgresql/data + redis: + image: redis:latest + container_name: redis + ports: + - "6379:6379" + volumes: pgdata: \ No newline at end of file diff --git a/main.py b/main.py deleted file mode 100644 index 970c826..0000000 --- a/main.py +++ /dev/null @@ -1,10 +0,0 @@ -from flask import Flask - -app = Flask(__name__) - -@app.route("/") -def hello_world(): - return "

Hello, World {name}!

".format(name=__name__) - -if __name__ == "__main__": - app.run(debug=True) \ No newline at end of file diff --git a/make.md b/make.md new file mode 100644 index 0000000..cc56c5e --- /dev/null +++ b/make.md @@ -0,0 +1,109 @@ +# Guia de Comandos Make + +Este guia fornece instruções para usar comandos Make para testar, inicializar e gerenciar a API hamper. + +## Comandos de Formatação e Teste + +Para testar os endpoints da aplicação e formatar o código: + +```sh +# Formatar o código de acordo com o ruff e o pylint +$ make format + +# Iniciar os testes com pytest +$ make test +``` + +## Comandos Make e Atalhos na Aplicação + +### Informações Gerais + +- Todos os comandos devem ser executados na raiz da aplicação. +- Sempre ative o ambiente virtual antes de usar os comandos. + +### Definindo o Ambiente e Nome da Aplicação + +Antes de inicializar a aplicação, defina o tipo de ambiente e o nome da aplicação (APP_NAME) no terminal. Exemplo: + +```sh +export FLASK_APP=project +export FLASK_ENV=development +``` + +### Inicializar a Aplicação + +- **Comando:** `make up` + - Executa: `python -m project run` para inicializar a aplicação. + +## Gerenciamento do Banco de Dados com flask-migrate + +### Inicializar o Banco de Dados + +1. **Comando:** `make db-init` + - Executa: `flask db init` (Inicializa a instância SQLAlchemy) + +2. **Comando:** `make migrate` + - Executa: `flask db migrate` (Executa as migrações das tabelas no banco de dados) + +3. **Comando:** `make upgrade` + - Executa: `flask db upgrade` (Cria as tabelas no banco de dados) + +## Configuração dos Ambientes (ENV e APP) + +### Ambiente Padrão + +- **Comando:** `make env-default` + - Executa: + ```sh + export FLASK_APP=project + export FLASK_ENV=default + python -m project run + ``` + +### Ambiente de Desenvolvimento + +- **Comando:** `make env-development` + - Executa: + ```sh + export FLASK_APP=project + export FLASK_ENV=development + python -m project run + ``` + +### Ambiente de Teste + +- **Comando:** `make env-testing` + - Executa: + ```sh + export FLASK_APP=project + export FLASK_ENV=testing + python -m project run + ``` + +### Ambiente de Produção + +- **Comando:** `make env-production` + - Executa: + ```sh + export FLASK_APP=project + export FLASK_ENV=production + python -m project run + ``` + +- **Comando:** `make up-prod` + - Executa: + ```sh + export FLASK_APP=project + export FLASK_ENV=production + gunicorn -w 4 -b 0.0.0.0:5000 "project:create_app()" + ``` + +### Ambiente de Homologação + +- **Comando:** `make up-homologacao` + - Executa: + ```sh + export FLASK_APP=project + export FLASK_ENV=homologacao + python -m project run + ``` \ No newline at end of file diff --git a/makefile b/makefile new file mode 100644 index 0000000..5bb3ed6 --- /dev/null +++ b/makefile @@ -0,0 +1,36 @@ +#bash/sh +up: + python -m project run + +up-prod: + export FLASK_ENV=production && export FLASK_ENV=production && gunicorn -w 4 -b 0.0.0.0:5000 "project:create_app()" + +up-homologacao: + export FLASK_APP=project && export FLASK_ENV=homologacao && python -m project run + +db-init: + flask db init + +migrate: + flask db migrate + +upgrade: + flask db upgrade + +env-default: + export FLASK_ENV=default && export FLASK_APP=project && python -m project run + +env-development: + export FLASK_APP=project && export FLASK_ENV=development && python -m project run + +env-production: + export FLASK_APP=project && export FLASK_ENV=production && python -m project run + +env-testing: + export FLASK_APP=project && export FLASK_ENV=testing && python -m project run + +test: + coverage run -m pytest && coverage report && coverage html + +format: + pylint project && ruff check && ruff format \ No newline at end of file diff --git a/project/__init__.py b/project/__init__.py new file mode 100644 index 0000000..eb6b243 --- /dev/null +++ b/project/__init__.py @@ -0,0 +1,9 @@ +""" +Inicialização do app + +""" + +from .base import create_app, create_app_wsgi + + +__all__ = ["create_app", "create_app_wsgi"] diff --git a/project/__main__.py b/project/__main__.py new file mode 100644 index 0000000..ade909f --- /dev/null +++ b/project/__main__.py @@ -0,0 +1,18 @@ +""" +Script de Gerenciamento do Flask + +""" + +import click +from flask.cli import FlaskGroup + +from . import create_app_wsgi + + +@click.group(cls=FlaskGroup, create_app=create_app_wsgi) +def main(): + """Management script for the project_name application.""" + + +if __name__ == "__main__": # pragma: no cover + main() diff --git a/project/base.py b/project/base.py new file mode 100644 index 0000000..ac3d132 --- /dev/null +++ b/project/base.py @@ -0,0 +1,36 @@ +""" +Inicialização do app + +""" + +from dynaconf import FlaskDynaconf +from flask import Flask +from flask_cors import CORS + + +def create_app(**config) -> Flask: + """ + Configuração do CORS e carregamento das extensões + + """ + app = Flask(__name__) + FlaskDynaconf(app, envvar_prefix="FLASK", settings_files=["settings.toml"]) + # pylint: disable=E1101 + app.config.load_extensions("EXTENSIONS") + app.config.update(config) + CORS(app) + + print(f"Ambiente atual: {app.config.env}") + print(f"Banco de dados atual: {app.config.get('SQLALCHEMY_DATABASE_URI')}") + print("Aplicação inicializada com sucesso!") + + return app + + +def create_app_wsgi() -> create_app: + """ + Método que inicializa o app + + """ + + return create_app() diff --git a/project/controller/client_controller.py b/project/controller/client_controller.py new file mode 100644 index 0000000..b3bac9b --- /dev/null +++ b/project/controller/client_controller.py @@ -0,0 +1,76 @@ +import json +from flask import request +from flask_restx import Resource +from project.ext.serializer import ClientSchema + +from project.service.client_service import ( + delete_client, + get_all_clients, + get_one_client, + post_client, + update_client, +) +from project.utils.redis_utils import ( + delete_redis_value, + get_redis_value, + set_redis_value, +) +from typing import Tuple, Any, List, Dict + +client_schema_list = ClientSchema(many=True) +client_schema = ClientSchema(many=False) + + +class ClientResource(Resource): + def get(self) -> Tuple[List[Dict[str, Any]], int]: + key_redis = "clients" + clients = get_redis_value(key_redis) + if clients: + return clients + clients = get_all_clients() + clients = client_schema_list.dump(clients) + set_redis_value(key_redis, json.dumps(clients)) + return clients, 200 + + def post(self) -> Tuple[Dict[str, str], int]: + try: + client_data = request.json + post_client(client_data) + delete_redis_value("clients") + return {"message": "Cliente cadastrado com sucesso!"}, 201 + + except Exception as e: + return {"error": str(e)}, 400 + + +class ClientResourceID(Resource): + def get(self, id) -> Tuple[Dict[str, Any], int]: + if client := get_one_client(id): + return client_schema.dump(client), 200 + else: + return {"error": f"Cliente com ID {id} não encontrado."}, 404 + + def patch(self, id) -> Tuple[Dict[str, str], int]: + try: + client_data = request.json + result = update_client(id, client_data) + + if "error" in result: + return {"error": result["error"]}, 404 + delete_redis_value("clients") + return {"message": result["message"]}, 200 + + except Exception as e: + return {"error": str(e)}, 500 + + def delete(self, id) -> Tuple[Dict[str, str], int]: + try: + result = delete_client(id) + + if "error" in result: + return {"error": result["error"]}, 404 + delete_redis_value("clients") + return {"message": result["message"]}, 200 + + except Exception as e: + return {"error": str(e)}, 500 diff --git a/project/controller/order_controller.py b/project/controller/order_controller.py new file mode 100644 index 0000000..9b2e2fc --- /dev/null +++ b/project/controller/order_controller.py @@ -0,0 +1,75 @@ +import json + +from flask import request +from flask_restx import Resource +from project.ext.serializer import OrderSchema +from project.service.order_service import ( + delete_one_order, + get_all_orders, + get_one_order, + post_order, + update_order, +) +from typing import Tuple, Dict, List, Any +from project.utils.redis_utils import ( + delete_redis_value, + get_redis_value, + set_redis_value, +) + +order_schema_list = OrderSchema(many=True) +order_schema = OrderSchema(many=False) + + +class OrderResource(Resource): + def get(self) -> Tuple[List[Dict[str, Any]], int]: + key_redis = "orders" + orders = get_redis_value(key_redis) + if orders: + return orders + orders = get_all_orders() + orders = order_schema_list.dump(orders) + set_redis_value(key_redis, json.dumps(orders)) + return orders, 200 + + def post(self) -> Tuple[Dict[str, str], int]: + try: + order_data = request.json + post_order(order_data) + delete_redis_value("orders") + return {"message": "Pedido criado com sucesso!"}, 201 + + except Exception as e: + return {"error": str(e)}, 400 + + +class OrderResourceID(Resource): + def get(self, id) -> Tuple[Dict[str, Any], int]: + if order := get_one_order(id): + return order_schema.dump(order), 200 # type: ignore + else: + return {"error": f"Ordem com ID {id} não encontrado."}, 404 + + def patch(self, id) -> Tuple[Dict[str, str], int]: + try: + order_data = request.json + result = update_order(id, order_data) + if "error" in result: + return {"error": result["error"]}, 404 + delete_redis_value("clients") + return {"message": result["message"]}, 200 + + except Exception as e: + return {"error": str(e)}, 500 + + def delete(self, id) -> Tuple[Dict[str, str], int]: + try: + result = delete_one_order(id) + + if "error" in result: + return {"error": result["error"]}, 404 + delete_redis_value("orders") + return {"message": result["message"]}, 200 + + except Exception as e: + return {"error": str(e)}, 500 diff --git a/project/controller/product_controller.py b/project/controller/product_controller.py new file mode 100644 index 0000000..608fb92 --- /dev/null +++ b/project/controller/product_controller.py @@ -0,0 +1,76 @@ +import json +from flask import request +from flask_restx import Resource +from project.ext.serializer import ProductSchema + +from project.service.product_service import ( + delete_product, + get_all_products, + get_one_product, + post_product, + update_product, +) +from typing import Tuple, Dict, Any, List +from project.utils.redis_utils import ( + delete_redis_value, + get_redis_value, + set_redis_value, +) + +product_schema_list = ProductSchema(many=True) +product_schema = ProductSchema(many=False) + + +class ProductResource(Resource): + def get(self) -> Tuple[List[Dict[str, Any]], int]: + key_redis = "products" + products = get_redis_value(key_redis) + if products: + return products + products = get_all_products() + products = product_schema_list.dump(products) + set_redis_value(key_redis, json.dumps(products)) + return products, 200 + + def post(self) -> Tuple[Dict[str, str], int]: + try: + product_data = request.json + post_product(product_data) + delete_redis_value("products") + return {"message": "Produto cadastrado com sucesso!"}, 201 + + except Exception as e: + return {"error": str(e)}, 400 + + +class ProductResourceID(Resource): + def get(self, id) -> Tuple[Dict[str, Any], int]: + if product := get_one_product(id): + return product_schema.dump(product), 200 # type: ignore + else: + return {"error": f"Produto com ID {id} não encontrado."}, 404 + + def patch(self, id) -> Tuple[Dict[str, str], int]: + try: + product_data = request.json + result = update_product(id, product_data) + + if "error" in result: + return {"error": result["error"]}, 404 + delete_redis_value("clients") + return {"message": result["message"]}, 200 + + except Exception as e: + return {"error": str(e)}, 500 + + def delete(self, id) -> Tuple[Dict[str, str], int]: + try: + result = delete_product(id) + + if "error" in result: + return {"error": result["error"]}, 404 + delete_redis_value("products") + return {"message": result["message"]}, 200 + + except Exception as e: + return {"error": str(e)}, 500 diff --git a/project/controller/restaurant_controller.py b/project/controller/restaurant_controller.py new file mode 100644 index 0000000..95e69d4 --- /dev/null +++ b/project/controller/restaurant_controller.py @@ -0,0 +1,77 @@ +import json +from flask import request +from flask_restx import Resource +from project.ext.serializer import RestaurantSchema + +from project.service.restaurant_service import ( + delete_restaurant, + get_all_restaurants, + get_one_restaurant, + post_restaurant, + update_restaurant, +) +from typing import Tuple, Dict, Any, List, Optional +from project.utils.redis_utils import ( + delete_redis_value, + get_redis_value, + set_redis_value, +) + +restaurant_schema_list = RestaurantSchema(many=True) +restaurant_schema = RestaurantSchema(many=False) + + +class RestaurantResource(Resource): + def get(self) -> Tuple[List[Dict[str, Any]], int]: + key_redis = "restaurants" + restaurants = get_redis_value(key_redis) + if restaurants: + return restaurants + restaurants = get_all_restaurants() + restaurants = restaurant_schema_list.dump(restaurants) + set_redis_value(key_redis, json.dumps(restaurants)) + return restaurants, 200 + + def post(self) -> Tuple[Dict[str, str], int]: + try: + restaurant_data = request.json + post_restaurant(restaurant_data) + delete_redis_value("restaurants") + return {"message": "Restaurante cadastrado com sucesso!"}, 201 + + except Exception as e: + return {"error": str(e)}, 400 + + +class RestaurantResourceID(Resource): + def get(self, id) -> Tuple[Optional[Dict[str, Any]], int]: + print("a") + if restaurant := get_one_restaurant(id): + return restaurant # type: ignore + else: + return {"error": f"Restaurante com ID {id} não encontrado."}, 404 + + def patch(self, id) -> Tuple[Dict[str, str], int]: + try: + restaurant_data = request.json + result = update_restaurant(id, restaurant_data) + + if "error" in result: + return {"error": result["error"]}, 404 + delete_redis_value("clients") + return {"message": result["message"]}, 200 + + except Exception as e: + return {"error": str(e)}, 500 + + def delete(self, id) -> Tuple[Dict[str, str], int]: + try: + result = delete_restaurant(id) + + if "error" in result: + return {"error": result["error"]}, 404 + delete_redis_value("restaurants") + return {"message": result["message"]}, 200 + + except Exception as e: + return {"error": str(e)}, 500 diff --git a/project/controller/user_controller.py b/project/controller/user_controller.py new file mode 100644 index 0000000..681cbb0 --- /dev/null +++ b/project/controller/user_controller.py @@ -0,0 +1,76 @@ +import json +from flask import abort, request +from flask_restx import Resource +from project.ext.serializer import UserSchema + +from project.service.user_service import ( + delete_user, + get_all_users, + get_one_user, + post_user, + update_user, +) +from typing import Tuple, Dict, Any, List +from project.utils.redis_utils import ( + delete_redis_value, + get_redis_value, + set_redis_value, +) + +user_schema_list = UserSchema(many=True) +user_schema = UserSchema(many=False) + + +class UserResource(Resource): + def get(self) -> Tuple[List[Dict[str, Any]], int]: + key_redis = "users" + users = get_redis_value(key_redis) + if users: + return users + users = get_all_users() + users = user_schema_list.dump(users) + set_redis_value(key_redis, json.dumps(users)) + return users, 200 + + def post(self) -> Tuple[Dict[str, str], int]: + try: + user_data = request.json + post_user(user_data) + delete_redis_value("users") + return {"message": "Usuário cadastrado com sucesso!"}, 201 + + except Exception as e: + return {"error": str(e)}, 400 + + +class UserResourceID(Resource): + def get(self, id) -> Tuple[Dict[str, Any], int]: + if user := get_one_user(id): + return user_schema.dump(user), 200 # type: ignore + else: + return {"error": f"Usuário com ID {id} não encontrado."}, 404 + + def patch(self, id) -> Tuple[Dict[str, str], int]: + try: + user_data = request.json + result = update_user(id, user_data) + + if "error" in result: + abort(404, message=result["error"]) + delete_redis_value("clients") + return {"message": result["message"]}, 200 + + except Exception as e: + return {"error": str(e)}, 500 + + def delete(self, id) -> Tuple[Dict[str, str], int]: + try: + result = delete_user(id) + + if "error" in result: + return {"error": result["error"]}, 404 + delete_redis_value("users") + return {"message": result["message"]}, 200 + + except Exception as e: + return {"error": str(e)}, 500 diff --git a/project/ext/commands.py b/project/ext/commands.py new file mode 100644 index 0000000..e45a4eb --- /dev/null +++ b/project/ext/commands.py @@ -0,0 +1,39 @@ +from datetime import time +from .database import db +from ..models.client_model import Client +from ..models.product_model import Product +from ..models.restaurant_model import Restaurant + + +def populate_database() -> None: + data = [ + Client( + client_name="João", + client_cellphone="47999999999", + client_address="Rua da Sé", + client_address_number=60, + client_address_complement="Casa", + client_address_neighborhood="Bairro da Sé", + client_zip_code="89898989", + ), + Product( + name="X-Picanha", + value=4, + description="Carne", + url_image="url image", + restaurant_id=1, + ), + Restaurant( + name="Bóde do Nô", + description="Descrição do restaurante", + classification=4.9, + location="Recife-PE", + url_image_logo="url_logo", + url_image_banner="url_banner", + horario_funcionamento=time(8, 0, 0), # 08:00:00 + horario_fechamento=time(22, 0, 0) # 22:00:00 + ), + ] + + db.session.bulk_save_objects(data) + db.session.commit() diff --git a/project/ext/database.py b/project/ext/database.py new file mode 100644 index 0000000..f107d85 --- /dev/null +++ b/project/ext/database.py @@ -0,0 +1,9 @@ +from flask_migrate import Migrate +from flask_sqlalchemy import SQLAlchemy + +db = SQLAlchemy() + + +def init_app(app) -> None: + db.init_app(app) + Migrate(app, db) \ No newline at end of file diff --git a/project/ext/restapi/__init__.py b/project/ext/restapi/__init__.py new file mode 100644 index 0000000..f30825c --- /dev/null +++ b/project/ext/restapi/__init__.py @@ -0,0 +1,146 @@ +from flask import Blueprint +from flask_restx import Api, fields + +from project.controller.user_controller import UserResource, UserResourceID +from project.utils.namespace import ( + client_ns, + order_ns, + product_ns, + restaurant_ns, + user_ns, +) + +from ...controller.client_controller import ClientResource, ClientResourceID +from ...controller.order_controller import OrderResource, OrderResourceID +from ...controller.product_controller import ProductResource, ProductResourceID +from ...controller.restaurant_controller import RestaurantResource, RestaurantResourceID + + +bp = Blueprint("restapi", __name__, url_prefix="/api/v1") +api = Api(bp) + + +restaurant_model = api.model( + "Restaurant", + { + "name": fields.String(required=True, description="Nome do restaurante"), + "description": fields.String( + required=True, description="Descrição do restaurante" + ), + "classification": fields.Float( + required=True, description="Classificação do restaurante" + ), + "location": fields.String( + required=True, description="Localização do restaurante" + ), + "url_image_logo": fields.String( + required=True, description="URL da logo do restaurante" + ), + "url_image_banner": fields.String( + required=True, description="URL do banner do restaurante" + ), + "horario_funcionamento": fields.String( + required=False, description="Horário de funcionamento" + ), + "horario_fechamento": fields.String( + required=False, description="Horário de fechamento" + ), + }, +) + +user_model = api.model( + "User", + { + "firstname": fields.String(required=True, description="Nome de usuário"), + "lastname": fields.String(required=True, description="Sobrenome de usuário"), + "email": fields.String(required=True, description="E-mail"), + }, +) + +product_model = api.model( + "Product", + { + "name": fields.String(required=True, description="Nome do produto"), + "value": fields.Float(required=True, description="Valor do produto"), + "description": fields.String(required=True, description="Descrição do produto"), + "url_image": fields.String( + required=True, description="URL da imagem do produto" + ), + "restaurant_id": fields.Integer(required=True, description="ID do restaurante"), + }, +) + +order_model = api.model( + "Order", + { + "created_at": fields.DateTime(required=True, description="Data de criação"), + "client_id": fields.Integer(required=True, description="ID do cliente"), + "restaurant_id": fields.Integer(required=True, description="ID do restaurante"), + "products": fields.List(fields.Integer, description="ID dos produtos"), + }, +) + +client_model = api.model( + "Client", + { + "client_name": fields.String(required=True, description="Nome do cliente"), + "client_cellphone": fields.String( + required=True, description="Celular do cliente" + ), + "client_address": fields.String( + required=True, description="Endereço do cliente" + ), + "client_address_number": fields.Integer( + required=True, description="Número do endereço do cliente" + ), + "client_address_complement": fields.String( + required=True, description="Complemento do endereço do cliente" + ), + "client_address_neighborhood": fields.String( + required=True, description="Bairro do endereço do cliente" + ), + "client_zip_code": fields.String( + required=True, description="CEP do endereço do cliente" + ), + }, +) + +# Adicionar os modelos aos namespaces +restaurant_ns.models["RestaurantModel"] = restaurant_model +user_ns.models["UserModel"] = user_model +product_ns.models["ProductModel"] = product_model +client_ns.models["ClientModel"] = client_model +order_ns.models["OrderModel"] = order_model + +# # Adicionar os recursos aos namespaces +restaurant_ns.add_resource(RestaurantResource, "/") +restaurant_ns.add_resource(RestaurantResourceID, "//products") + +user_ns.add_resource(UserResource, "/") +user_ns.add_resource(UserResourceID, "/") + +product_ns.add_resource(ProductResource, "/") +product_ns.add_resource(ProductResourceID, "/") + +client_ns.add_resource(ClientResource, "/") +client_ns.add_resource(ClientResourceID, "/") + +order_ns.add_resource(OrderResource, "/") +order_ns.add_resource(OrderResourceID, "/") + + +# Adicionar os namespaces ao API +api.add_namespace(restaurant_ns) +api.add_namespace(user_ns) +api.add_namespace(product_ns) +api.add_namespace(client_ns) +api.add_namespace(order_ns) + + +def init_app(app): + app.register_blueprint(bp) + api.add_namespace(restaurant_ns) + api.add_namespace(user_ns) + api.add_namespace(product_ns) + api.add_namespace(client_ns) + api.add_namespace(order_ns) diff --git a/project/ext/serializer.py b/project/ext/serializer.py new file mode 100644 index 0000000..d63e28c --- /dev/null +++ b/project/ext/serializer.py @@ -0,0 +1,49 @@ +from flask_marshmallow import Marshmallow +from marshmallow import fields + +from project.models.order_model import Order +from project.models.product_model import Product +from project.models.restaurant_model import Restaurant +from project.models.user_model import User +from project.models.client_model import Client + + +ma = Marshmallow() + + +def init_app(app): + ma.init_app(app) + + +class ClientSchema(ma.SQLAlchemyAutoSchema): + class Meta: + model = Client + load_instance = True + + +class OrderSchema(ma.SQLAlchemyAutoSchema): + class Meta: + model = Order + load_instance = True + include_relationships = True + + +class ProductSchema(ma.SQLAlchemyAutoSchema): + class Meta: + model = Product + load_instance = True + + +class RestaurantSchema(ma.SQLAlchemyAutoSchema): + class Meta: + model = Restaurant + load_instance = True + include_relationships = True + + +class UserSchema(ma.SQLAlchemyAutoSchema): + class Meta: + model = User + load_instance = True + orders = fields.Nested(OrderSchema) + include_relationships = True diff --git a/project/models/client_model.py b/project/models/client_model.py new file mode 100644 index 0000000..3a8acff --- /dev/null +++ b/project/models/client_model.py @@ -0,0 +1,12 @@ +from ..ext.database import db + + +class Client(db.Model): + id: int = db.Column(db.Integer, primary_key=True, autoincrement=True) + client_name: str = db.Column(db.String(80), nullable=False) + client_cellphone: str = db.Column(db.String(11), nullable=False) + client_address: str = db.Column(db.String(120), nullable=False) + client_address_number: int = db.Column(db.Integer, nullable=False) + client_address_complement: str = db.Column(db.String(120), nullable=False) + client_address_neighborhood: str = db.Column(db.String(40), nullable=True) + client_zip_code: str = db.Column(db.String(8), nullable=False) diff --git a/project/models/mock_data.py b/project/models/mock_data.py new file mode 100644 index 0000000..12e50bd --- /dev/null +++ b/project/models/mock_data.py @@ -0,0 +1,176 @@ +"""Dados estáticos para uso em desenvolvimento""" + +mock_restaurants = [ + { + "id": 1, + "name": "Bóde do Nô", + "description": "Descrrição do restaurante", + "classification": 4.9, + "location": "Recife-PE", + "url_image_logo": "url_logo", + "url_image_banner": "url_banner", + }, + { + "id": 2, + "name": "Imperador dos camarões", + "description": "Descrrição do restaurante", + "classification": 4.8, + "location": "Maceió-AL", + "url_image_logo": "url_logo", + "url_image_banner": "url_banner", + }, + { + "id": 3, + "name": "Bar da Sogra", + "description": "Descrrição do restaurante", + "classification": 4.1, + "location": "Salvador-BA", + "url_image_logo": "url_logo", + "url_image_banner": "url_banner", + }, + { + "id": 4, + "name": "Raspa Tácho", + "description": "Descrrição do restaurante", + "classification": 4.8, + "location": "Fortaleza-CE", + "url_image_logo": "url_logo", + "url_image_banner": "url_banner", + }, + { + "id": 5, + "name": "Boi na Brasa", + "description": "Descrrição do restaurante", + "classification": 4.9, + "location": "Fortaleza-CE", + "url_image_logo": "url_logo", + "url_image_banner": "url_banner", + }, +] + +mock_products = [ + { + "id": 1, + "name": "X-Bacon", + "value": 20, + "description": "Bacon", + "url_image": "url_image", + "restaurant_id": 1, + }, + { + "id": 2, + "name": "X-Picanha", + "value": 20, + "description": "Picanha", + "url_image": "url_image", + "restaurant_id": 2, + }, + { + "id": 3, + "name": "X-Salada", + "value": 20, + "description": "Salada", + "url_image": "url_image", + "restaurant_id": 3, + }, + { + "id": 4, + "name": "X-Frango", + "value": 20, + "description": "Frango", + "url_image": "url_image", + "restaurant_id": 4, + }, + { + "id": 5, + "name": "X-Batata", + "value": 20, + "description": "Batata", + "url_image": "url_image", + "restaurant_id": 5, + }, +] + +mock_users = [ + {"id": 1, "firstname": "Tony", "lastname": "Stark", "email": "ironman@icloud.com"}, + { + "id": 2, + "firstname": "Peter", + "lastname": "Parker", + "email": "spiderman@icloud.com", + }, + {"id": 3, "firstname": "Bruce", "lastname": "Banner", "email": "hulk@icloud.com"}, + { + "id": 4, + "firstname": "Natasha", + "lastname": "Romanoff", + "email": "blackwidow@icloud.com", + }, + { + "id": 5, + "firstname": "Steve", + "lastname": "Rogers", + "email": "captainamerica@icloud.com", + }, +] + +mock_clients = [ + { + "id": 1, + "client_name": "John Doe", + "client_cellphone": "69999999999", + "client_address": "1600 Amphitheatre Parkway", + "client_address_number": 1600, + "client_address_complement": "", + "client_address_neighborhood": "Mountain View", + "client_zip_code": "94043", + }, + { + "id": 2, + "client_name": "Jane Smith", + "client_cellphone": "69998887777", + "client_address": "One Microsoft Way", + "client_address_number": 1, + "client_address_complement": "", + "client_address_neighborhood": "Redmond", + "client_zip_code": "98052", + }, + { + "id": 3, + "client_name": "Alice Johnson", + "client_cellphone": "69995554444", + "client_address": "1600 Pennsylvania Avenue NW", + "client_address_number": 1600, + "client_address_complement": "", + "client_address_neighborhood": "Washington", + "client_zip_code": "20500", + }, + { + "id": 4, + "client_name": "Bob Brown", + "client_cellphone": "69992221111", + "client_address": "221B Baker Street", + "client_address_number": 221, + "client_address_complement": "", + "client_address_neighborhood": "London", + "client_zip_code": "NW1 6XE", + }, + { + "id": 5, + "client_name": "Eva Green", + "client_cellphone": "69991112222", + "client_address": "1600 Pennsylvania Avenue NW", + "client_address_number": 1600, + "client_address_complement": "", + "client_address_neighborhood": "Washington", + "client_zip_code": "20500", + }, +] + +mock_orders = [ + {"id": 1, "client_id": 1, "restaurant_id": 1, "products": [1]}, + {"id": 2, "client_id": 2, "restaurant_id": 2, "products": [2, 3]}, + {"id": 3, "client_id": 3, "restaurant_id": 1, "products": [4]}, + {"id": 4, "client_id": 4, "restaurant_id": 2, "products": [5]}, + {"id": 5, "client_id": 5, "restaurant_id": 4, "products": [1, 2, 5]}, +] diff --git a/project/models/order_model.py b/project/models/order_model.py new file mode 100644 index 0000000..726798a --- /dev/null +++ b/project/models/order_model.py @@ -0,0 +1,26 @@ +from datetime import datetime + +from project.models.client_model import Client +from project.models.restaurant_model import Restaurant +from ..ext.database import db + +order_product_association = db.Table( + "order_product_association", + db.Column("order_id", db.Integer, db.ForeignKey("order.id")), + db.Column("product_id", db.Integer, db.ForeignKey("product.id")), +) + + +class Order(db.Model): + id: int = db.Column(db.Integer, primary_key=True, autoincrement=True) + created_at: datetime = db.Column(db.DateTime, default=datetime.now) + client_id: int = db.Column(db.Integer, db.ForeignKey(Client.id)) + restaurant_id: int = db.Column(db.Integer, db.ForeignKey(Restaurant.id)) + total_value: float = db.Column(db.Float) + products = db.relationship( + "Product", + secondary=order_product_association, + backref=db.backref("orders", lazy="dynamic"), + ) + client = db.relationship("Client", lazy=True) + restaurant = db.relationship("Restaurant", lazy=True) diff --git a/project/models/product_model.py b/project/models/product_model.py new file mode 100644 index 0000000..2c547b9 --- /dev/null +++ b/project/models/product_model.py @@ -0,0 +1,21 @@ +from ..ext.database import db + +products_restaurants = db.Table( + "products_restaurants", + db.Column("product_id", db.Integer, db.ForeignKey("product.id")), + db.Column("restaurant_id", db.Integer, db.ForeignKey("restaurant.id")), +) + + +class Product(db.Model): + id: int = db.Column(db.Integer, primary_key=True, autoincrement=True) + name: str = db.Column(db.String(40), nullable=False, unique=False) + value: float = db.Column(db.Float(precision=6), nullable=False) + description: str = db.Column(db.String(120), nullable=False) + url_image: str = db.Column(db.String(), nullable=True) + restaurant_id: int = db.Column( + db.Integer, db.ForeignKey("restaurant.id"), nullable=False + ) + associated_restaurants = db.relationship( + "Restaurant", secondary=products_restaurants, backref="associated_products" + ) diff --git a/project/models/restaurant_model.py b/project/models/restaurant_model.py new file mode 100644 index 0000000..2fc4837 --- /dev/null +++ b/project/models/restaurant_model.py @@ -0,0 +1,15 @@ +from ..ext.database import db +from sqlalchemy.types import Time +from datetime import time + +class Restaurant(db.Model): + id: int = db.Column(db.Integer, primary_key=True, autoincrement=True) + name: str = db.Column(db.String(20), unique=True, nullable=False) + description: str = db.Column(db.String(120), nullable=False) + classification: float = db.Column(db.Float(precision=3), nullable=False) + location: str = db.Column(db.String(120), nullable=False) + url_image_logo: str = db.Column(db.String(), nullable=True) + url_image_banner: str = db.Column(db.String(), nullable=True) + horario_funcionamento: time = db.Column(Time(), nullable=True) + horario_fechamento: time = db.Column(Time(), nullable=True) + products = db.relationship("Product", backref="restaurant", lazy=True) \ No newline at end of file diff --git a/project/models/user_model.py b/project/models/user_model.py new file mode 100644 index 0000000..f8440a4 --- /dev/null +++ b/project/models/user_model.py @@ -0,0 +1,8 @@ +from ..ext.database import db + + +class User(db.Model): + id: int = db.Column(db.Integer, primary_key=True, autoincrement=True) + firstname: str = db.Column(db.String(20), nullable=False) + lastname: str = db.Column(db.String(20), nullable=False) + email: str = db.Column(db.String(120), unique=True, nullable=False) diff --git a/project/service/client_service.py b/project/service/client_service.py new file mode 100644 index 0000000..889879d --- /dev/null +++ b/project/service/client_service.py @@ -0,0 +1,54 @@ +from flask import request + +from ..ext.database import db +from ..models.client_model import Client +from typing import Dict, Optional + + +def get_all_clients() -> list[Client]: + return Client.query.all() + + +def post_client(data_client) -> None: + data_client = request.get_json() + client = Client(**data_client) + db.session.add(client) + db.session.commit() + + +def get_one_client(id) -> Optional[Client]: + return client if (client := Client.query.get(id)) else None + + +def update_client(id, updated_data) -> Dict[str, str]: + client = get_one_client(id) + + if client is None: + return {"error": f"Cliente com ID {id} não encontrado"} + + try: + for key, value in updated_data.items(): + setattr(client, key, value) + + db.session.commit() + return {"message": f"Cliente com ID {id} atualizado com sucesso!"} + + except Exception as e: + db.session.rollback() + return {"error": str(e)} + + +def delete_client(id) -> Dict[str, str]: + client = get_one_client(id) + + if client is None: + return {"error": f"Cliente com ID {id} não encontrado"} + + try: + db.session.delete(client) + db.session.commit() + return {"message": f"CLiente com ID {id} deletado com sucesso."} + + except Exception as e: + db.session.rollback() + return {"error": str(e)} diff --git a/project/service/order_service.py b/project/service/order_service.py new file mode 100644 index 0000000..f75dc57 --- /dev/null +++ b/project/service/order_service.py @@ -0,0 +1,98 @@ +from flask import abort +from typing import Dict, Optional +from project.ext.database import db +from project.models.client_model import Client +from project.models.order_model import Order +from project.models.product_model import Product +from project.models.restaurant_model import Restaurant +from datetime import datetime + +from ..utils.twilio_utils import send_whatsapp_message + + +def get_all_orders() -> list[Order]: + return Order.query.all() + +def post_order(order_data: dict, current_time: Optional[datetime.time] = None) -> tuple[dict, int]: + if not Client.query.get(order_data["client_id"]): + abort(404, f"Cliente com ID {order_data['client_id']} não encontrado.") + + restaurant = Restaurant.query.get(order_data["restaurant_id"]) + if not restaurant: + abort(404, f"Restaurante com ID {order_data['restaurant_id']} não encontrado.") + + if "current_time" in order_data: + current_time = datetime.strptime(order_data["current_time"], "%H:%M:%S").time() + elif current_time is None: + current_time = datetime.now().time() + + if restaurant.horario_funcionamento and restaurant.horario_fechamento: + if not (restaurant.horario_funcionamento <= current_time <= restaurant.horario_fechamento): + abort(403, "O restaurante está fora do horário de funcionamento.") + + if not all(Product.query.get(product["product_id"]) for product in order_data["products"]): + abort(404, "Um ou mais produtos não foram encontrados.") + + products = [ + (Product.query.get(product["product_id"]), product["quantity"]) + for product in order_data["products"] + ] + + products_value = [product.value * quantity for product, quantity in products] + + new_order = Order( + client_id=order_data["client_id"], + restaurant_id=order_data["restaurant_id"], + products=[product for product, quantity in products], + total_value=sum(products_value), + ) + db.session.add(new_order) + db.session.commit() + + send_whatsapp_message(new_order) + + return {"message": "Pedido cadastrado com sucesso!"}, 201 + + +def get_one_order(order_id) -> Optional[Order]: + return order if (order := Order.query.get(order_id)) else None + + +def update_order(id, updated_data) -> Dict[str, str]: + order = get_one_order(id) + + if order is None: + return {"error": f"Ordem com ID {id} não encontrado."} + + try: + for key, value in updated_data.items(): + if key == "products": + value = [Product.query.get(product_id) for product_id in value] + setattr(order, key, value) + + db.session.commit() + return {"message": f"Ordem com ID {id} atualizado com sucesso!"} + + except Exception as e: + db.session.rollback() + return {"error": str(e)} + + +def delete_one_order(id) -> Dict[str, str]: + order = get_one_order(id) + + if order is None: + return {"error": f"Ordem com ID {id} não encontrado"} + + try: + db.session.delete(order) + db.session.commit() + return {"message": f"Ordem com ID {id} deletado com sucesso."} + + except Exception as e: + db.session.rollback() + return {"error": str(e)} + + +def total_order_value(order_data): + order_data diff --git a/project/service/product_service.py b/project/service/product_service.py new file mode 100644 index 0000000..a84dee4 --- /dev/null +++ b/project/service/product_service.py @@ -0,0 +1,51 @@ +from flask import request +from ..ext.database import db +from typing import Dict, Optional +from ..models.product_model import Product + + +def get_all_products() -> list[Product]: + return Product.query.all() + + +def post_product(product_data) -> None: + product_data = request.get_json() + product = Product(**product_data) + db.session.add(product) + db.session.commit() + + +def get_one_product(product_id) -> Optional[Product]: + return product if (product := Product.query.get(product_id)) else None + + +def update_product(id, updated_data) -> Dict[str, str]: + product = get_one_product(id) + if product is None: + return {"error": f"Produto com ID {id} não encontrado"} + + try: + for key, value in updated_data.items(): + setattr(product, key, value) + + db.session.commit() + return {"message": f"Produto com ID {id} atualizado com sucesso!"} + + except Exception as e: + db.session.rollback() + return {"error": str(e)} + + +def delete_product(id) -> Dict[str, str]: + product = get_one_product(id) + if product is None: + return {"error": f"Produto com ID {id} não encontrado"} + + try: + db.session.delete(product) + db.session.commit() + return {"message": f"Produto com ID {id} deletado com sucesso."} + + except Exception as e: + db.session.rollback() + return {"error": str(e)} diff --git a/project/service/restaurant_service.py b/project/service/restaurant_service.py new file mode 100644 index 0000000..2068f99 --- /dev/null +++ b/project/service/restaurant_service.py @@ -0,0 +1,85 @@ +from flask import request +from datetime import datetime +from ..ext.database import db +from ..models.restaurant_model import Restaurant +from typing import Dict, Optional + + +def get_all_restaurants() -> list[Restaurant]: + return Restaurant.query.all() + + +def post_restaurant(data_restaurant) -> None: + data_restaurant = request.get_json() + data_restaurant['horario_funcionamento'] = datetime.strptime(data_restaurant['horario_funcionamento'], '%H:%M:%S').time() + data_restaurant['horario_fechamento'] = datetime.strptime(data_restaurant['horario_fechamento'], '%H:%M:%S').time() + restaurant = Restaurant(**data_restaurant) + db.session.add(restaurant) + db.session.commit() + + +def get_one_restaurant(restaurant_id) -> Optional[Dict[str, str]]: + restaurant = Restaurant.query.get(restaurant_id) + + if restaurant: + restaurant_data = { + "id": restaurant.id, + "name": restaurant.name, + "description": restaurant.description, + "classification": restaurant.classification, + "location": restaurant.location, + "url_image_logo": restaurant.url_image_logo, + "url_image_banner": restaurant.url_image_banner, + "horario_funcionamento": restaurant.horario_funcionamento.strftime("%H:%M:%S"), + "horario_fechamento": restaurant.horario_fechamento.strftime("%H:%M:%S"), + "associated_products": [], + } + + for product in restaurant.products: + product_data = { + "id": product.id, + "name": product.name, + "value": product.value, + "description": product.description, + "url_image": product.url_image, + "restaurant_id": product.restaurant_id, + } + restaurant_data["associated_products"].append(product_data) + + return restaurant_data + else: + return None + + +def update_restaurant(id, updated_data) -> Dict[str, str]: + restaurant = get_one_restaurant(id) + + if restaurant is None: + return {"error": f"Restaurante com ID {id} não encontrado"} + + try: + for key, value in updated_data.items(): + restaurant[key] = value + + db.session.commit() + return {"message": f"Restaurante com ID {id} atualizado com sucesso!"} + + except Exception as e: + db.session.rollback() + return {"error": str(e)} + + +def delete_restaurant(id) -> Dict[str, str]: + restaurant = Restaurant.query.get(id) + + if restaurant is None: + return {"error": f"Restaurante com ID {id} não encontrado"} + + try: + db.session.delete(restaurant) + db.session.commit() + return {"message": f"Restaurante com ID {id} deletado com sucesso."} + + except Exception as e: + db.session.rollback() + return {"error": str(e)} diff --git a/project/service/user_service.py b/project/service/user_service.py new file mode 100644 index 0000000..54c31d8 --- /dev/null +++ b/project/service/user_service.py @@ -0,0 +1,53 @@ +from flask import request +from ..ext.database import db +from ..models.user_model import User +from typing import Dict, Optional + + +def get_all_users() -> list[User]: + return User.query.all() + + +def post_user(user_data) -> None: + user_data = request.get_json() + user = User(**user_data) + db.session.add(user) + db.session.commit() + + +def get_one_user(user_id) -> Optional[User]: + return user if (user := User.query.get(user_id)) else None + + +def update_user(user_id, updated_data) -> Dict[str, str]: + user = get_one_user(user_id) + + if user is None: + return {"error": f"Usuário com ID {user_id} não encontrado"} + + try: + for key, value in updated_data.items(): + setattr(user, key, value) + + db.session.commit() + return {"message": f"Usuário com ID {user_id} atualizado com sucesso!"} + + except Exception as e: + db.session.rollback() + return {"error": str(e)} + + +def delete_user(id) -> Dict[str, str]: + user = get_one_user(id) + + if user is None: + return {"error": f"Usuário com ID {id} não encontrado"} + + try: + db.session.delete(user) + db.session.commit() + return {"message": f"Usuário com ID {id} deletado com sucesso."} + + except Exception as e: + db.session.rollback() + return {"error": str(e)} diff --git a/project/utils/namespace.py b/project/utils/namespace.py new file mode 100644 index 0000000..2a6cf2a --- /dev/null +++ b/project/utils/namespace.py @@ -0,0 +1,11 @@ +from flask_restx import Namespace + +restaurant_ns = Namespace( + name="Restaurant", description="Gerenciar restaurante", path="/restaurants" +) +user_ns = Namespace(name="User", description="Gerenciar usuário", path="/users") +product_ns = Namespace( + name="Product", description="Gerenciar produto", path="/products" +) +client_ns = Namespace(name="Client", description="Gerenciar cliente", path="/clients") +order_ns = Namespace(name="Order", description="Gerenciar pedido", path="/orders") diff --git a/project/utils/redis_utils.py b/project/utils/redis_utils.py new file mode 100644 index 0000000..07bae27 --- /dev/null +++ b/project/utils/redis_utils.py @@ -0,0 +1,15 @@ +import redis + +redis_connection = redis.Redis(host="localhost", port=6379) + + +def set_redis_value(key, value): + redis_connection.set(key, value) + + +def delete_redis_value(key): + redis_connection.delete(key) + + +def get_redis_value(key): + redis_connection.get(key) diff --git a/project/utils/twilio_utils.py b/project/utils/twilio_utils.py new file mode 100644 index 0000000..d186f61 --- /dev/null +++ b/project/utils/twilio_utils.py @@ -0,0 +1,38 @@ +from twilio.rest import Client as ClientTwilio +from project.models.client_model import Client +from project.models.restaurant_model import Restaurant + + +def send_whatsapp_message(new_order): + restaurant_query = Restaurant.query.filter(Restaurant.id == new_order.restaurant_id) + client_query = Client.query.filter(Client.id == new_order.client_id) + + restaurant = restaurant_query.first() + client = client_query.first() + + products_info = "" + for product in new_order.products: + products_info += f"\n- {product.name} - R${product.value}" + + formatted_time = new_order.created_at.strftime("%d-%m-%Y - %H:%M:%S") + + body = ( + f"📝 Pedido Recebido! \n" + f"\n👤 Cliente: {client.client_name} \n" + f"🍽️ Restaurante: {restaurant.name} \n" + f"🛒 Produtos: {products_info} \n" + f"\n💸 Valor Total: R${new_order.total_value} \n" + f"📅 Data do Pedido: {formatted_time}" + ) + + try: + account_sid = "AC07bda34115f9e874de261be356af10d4" + auth_token = "6bd237cb8b9e9d4d805922464c96fc1f" + client = ClientTwilio(account_sid, auth_token) + + client.messages.create( + from_="whatsapp:+14155238886", body=body, to="whatsapp:+554799366596" + ) + + except Exception as e: + print(str(e)) diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..adf1e8c --- /dev/null +++ b/pytest.ini @@ -0,0 +1,4 @@ +[pytest] +python_files = test.py tests.py test_*.py tests_*.py *_test.py *_tests.py +filterwarnings = + ignore::DeprecationWarning diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..3ba593b --- /dev/null +++ b/requirements.txt @@ -0,0 +1,43 @@ +alembic==1.12.0 +aniso8601==9.0.1 +attrs==23.1.0 +black==23.9.1 +blinker==1.6.2 +click==8.1.7 +dynaconf==3.2.2 +exceptiongroup==1.2.0 +Flask==2.3.3 +Flask-Cors==4.0.0 +Flask-Migrate==4.0.4 +flask-restx==1.1.0 +Flask-SQLAlchemy==3.0.5 +gunicorn==21.2.0 +iniconfig==2.0.0 +itsdangerous==2.1.2 +Jinja2==3.1.2 +jsonschema==4.21.1 +jsonschema-specifications==2023.7.1 +Mako==1.2.4 +MarkupSafe==2.1.3 +mypy==1.6.0 +mypy-extensions==1.0.0 +packaging==23.2 +pathspec==0.11.2 +platformdirs==3.11.0 +pluggy==1.4.0 +psycopg2-binary==2.9.9 +pytest==8.0.1 +python-dotenv==1.0.0 +pytz==2023.3.post1 +referencing==0.30.2 +SQLAlchemy==2.0.20 +tomli==2.0.1 +typing_extensions==4.7.1 +Werkzeug==2.3.7 +pylint +flask-marshmallow==0.15.0 +marshmallow-sqlalchemy==1.0.0 +twilio +redis +coverage +factory_boy \ No newline at end of file diff --git a/settings.toml b/settings.toml new file mode 100644 index 0000000..75a91ee --- /dev/null +++ b/settings.toml @@ -0,0 +1,33 @@ +[default] +APP_NAME = "project" +DATABASE = "sqlite" +SECRET_KEY = "548JM6@aK!pO|DN:US,xUG6zF52yZXP" +SQLALCHEMY_TRACK_MODIFICATIONS = false +EXTENSIONS = [ + "project.ext.restapi:init_app", + "project.ext.database:init_app" +] +SQLALCHEMY_DATABASE_URI = 'sqlite:///db.default.sqlite' + +[development] +FLASK_ENV = "development" +INCLUDES = ["default"] +TEMPLATES_AUTO_RELOAD = true +DEBUG = true +SQLALCHEMY_DATABASE_URI = 'sqlite:///db.development.dynaconf.sqlite' + +[testing] +FLASK_ENV = "testing" +INCLUDES = ["default"] +SQLALCHEMY_DATABASE_URI = "sqlite:///db.testing.sqlite" +DEBUG = true + +[production] +FLASK_ENV = "production" +INCLUDES = ["default"] +SQLALCHEMY_DATABASE_URI = "postgresql://slj_user:WEUOkN2UVuZzZdTRUcLHrCZA52pNSWPf@dpg-cms2j6821fec73civqtg-a.oregon-postgres.render.com/slj_database" + +[homologacao] +FLASK_ENV = "homologacao" +INCLUDES = ["default"] +SQLALCHEMY_DATABASE_URI = "postgresql://hpnkbpae:k41SHz9huxu3zVgQhvjq7b7MXYv5n8gK@baasu.db.elephantsql.com/hpnkbpae" diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..5b2411d --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,269 @@ +import os + +import pytest + +from project import create_app_wsgi +from project.ext.database import db +from datetime import time +from sqlalchemy import Engine, event +from project.models.user_model import User +from project.models.restaurant_model import Restaurant +from project.models.product_model import Product +from project.models.client_model import Client +from project.models.order_model import Order +from tests.factory.client_factory import ClientFactory +from tests.factory.order_factory import OrderFactory +from tests.factory.product_factory import ProductFactory +from tests.factory.restaurant_factory import RestaurantFactory +from tests.factory.user_factory import UserFactory + + +# TODO: Define o pragma de chaves estrangeiras para conexões de banco de dados SQLite. +@event.listens_for(Engine, "connect") +def set_sqlite_pragma(dbapi_connection, connection_record): + """ + Define o pragma de chaves estrangeiras para conexões de banco de dados SQLite. + + Args: + dbapi_connection: O objeto de conexão com o banco de dados. + connection_record: O objeto de registro de conexão. + """ + cursor = dbapi_connection.cursor() + cursor.execute("PRAGMA foreign_keys=ON") + cursor.close() + + +@pytest.fixture +def app_testing(): + """ + Configura o ambiente de teste para a aplicação. + + Define a variável de ambiente 'FLASK_ENV' como 'testing'. + Cria uma instância da aplicação usando a função 'create_app_wsgi()'. + Cria o banco de dados usando o contexto da aplicação. + Retorna a instância da aplicação. + Ao finalizar o teste, remove o banco de dados. + + Returns: + app: Instância da aplicação configurada para teste. + """ + os.environ["FLASK_ENV"] = "testing" + app = create_app_wsgi() + with app.app_context(): + db.create_all() + yield app + with app.app_context(): + db.drop_all() + + +@pytest.fixture +def user(app_testing): + """ + Cria uma ingessão de User para os testes. + + Args: + session (Session): Uma instância de Session do SQLAlchemy. + + Returns: + User: Uma instância de User do sistema. + """ + app = app_testing + with app.app_context(): + user = User(firstname="Tony", lastname="Stark", email="ironman@icloud.com") + db.session.add(user) + db.session.commit() + db.session.refresh(user) + + return user + + +@pytest.fixture +def User_10(app_testing): + """ + Cria uma lista de 10 objetos usuário para os testes. + """ + UserFactory.reset_sequence() + users = UserFactory.build_batch(10) + + app = app_testing + with app.app_context(): + for user in users: + db.session.add(user) + db.session.commit() + + return users + + +@pytest.fixture +def cliente(app_testing): + """ + Cria uma ingessão de cliente para os testes. + + Returns: + cliente: Uma instância de cliente do sistema. + """ + app = app_testing + with app.app_context(): + cliente = Client( + client_name="John Doe", + client_cellphone="69999999999", + client_address="1600 Amphitheatre Parkway", + client_address_number="1600", + client_address_complement="", + client_address_neighborhood="Mountain View", + client_zip_code="94043", + ) + db.session.add(cliente) + db.session.commit() + db.session.refresh(cliente) + + return cliente + + +@pytest.fixture +def client_10(app_testing): + """ + Cria uma lista de 10 objetos cliente para os testes. + """ + ClientFactory.reset_sequence() + clients = ClientFactory.build_batch(10) + + app = app_testing + with app.app_context(): + for client in clients: + db.session.add(client) + db.session.commit() + + return clients + + +@pytest.fixture +def restaurant(app_testing): + """ + Cria uma ingessão de restaurante para os testes. + + Returns: + restaurant: Uma instância de restaurante do sistema. + """ + app = app_testing + with app.app_context(): + restaurant = Restaurant( + name="Bóde do Nô", + description="Descrição do restaurante", + classification=4.9, + location="Recife-PE", + url_image_logo="url_logo", + url_image_banner="url_banner", + horario_funcionamento=time(8, 0, 0), + horario_fechamento=time(22, 0, 0), + ) + # product = Product( + # name='Produto Exemplo', + # value=10.5, + # description='Descrição do produto exemplo', + # url_image='url_produto', + # restaurant_id=1 + # ) + db.session.add(restaurant) + # db.session.add(product) + db.session.commit() + db.session.refresh(restaurant) + # db.session.refresh(product) + + return restaurant + + +@pytest.fixture +def restaurant_10(app_testing): + """ + Cria uma lista de 10 objetos restaurante para os testes. + """ + RestaurantFactory.reset_sequence() + restaurants = RestaurantFactory.build_batch(10) + + app = app_testing + with app.app_context(): + for restaurant in restaurants: + db.session.add(restaurant) + db.session.commit() + + return restaurants + + +@pytest.fixture +# TODO: Essa fixture precisa ser usada em conjunto com a fixtures (restaurant) +def product(app_testing): + """ + Cria uma ingessão de produtos para os testes. + + Returns: + product: Uma instância de produtos do sistema. + """ + app = app_testing + with app.app_context(): + product = Product( + name="X-Bacon", + value=20, + description="Bacon", + url_image="url_image", + restaurant_id=1, + ) + db.session.add(product) + db.session.commit() + db.session.refresh(product) + + return product + + +@pytest.fixture +def product_10(app_testing): + """ + Cria uma lista de 10 objetos produtos para os testes. + """ + ProductFactory.reset_sequence() + products = ProductFactory.build_batch(10) + + app = app_testing + with app.app_context(): + for product in products: + db.session.add(product) + db.session.commit() + + return products + + +@pytest.fixture +# TODO: essa fixture precisa ser usada em conjunto com as fixtures (cliente, restaurant, product) +def order(app_testing): + """ + Cria uma ingessão de ordem de pedido para os testes. + + Returns: + order: Uma instância de ordem de pedido do sistema. + """ + app = app_testing + with app.app_context(): + product = db.session.query(Product).get(1) + order = Order(client_id=1, restaurant_id=1, products=[product]) + db.session.add(order) + db.session.commit() + db.session.refresh(order) + + return order + + +@pytest.fixture +def order_10(app_testing): + """ + Cria uma lista de 10 objetos ordem de pedido para os testes. + """ + OrderFactory.reset_sequence() + orders = OrderFactory.build_batch(10) + + app = app_testing + with app.app_context(): + for order in orders: + db.session.add(order) + db.session.commit() + + return orders diff --git a/tests/factory/client_factory.py b/tests/factory/client_factory.py new file mode 100644 index 0000000..7b16374 --- /dev/null +++ b/tests/factory/client_factory.py @@ -0,0 +1,21 @@ +import factory +from factory.alchemy import SQLAlchemyModelFactory + + +from project.models.client_model import Client +from project.ext.database import db + + +class ClientFactory(SQLAlchemyModelFactory): + class Meta: + model = Client + sqlalchemy_session = db.session + + id = factory.Sequence(lambda n: n) + client_name = factory.Sequence(lambda n: f"Client{n}") + client_cellphone = factory.Sequence(lambda n: f"123456789{n}") + client_address = factory.Sequence(lambda n: f"Street{n}") + client_address_number = factory.Sequence(lambda n: n) + client_address_complement = factory.Sequence(lambda n: f"Complement{n}") + client_address_neighborhood = factory.Sequence(lambda n: f"Neighborhood{n}") + client_zip_code = factory.Sequence(lambda n: f"Zip{n}") diff --git a/tests/factory/order_factory.py b/tests/factory/order_factory.py new file mode 100644 index 0000000..5abe6a6 --- /dev/null +++ b/tests/factory/order_factory.py @@ -0,0 +1,28 @@ +import factory +from factory.alchemy import SQLAlchemyModelFactory +from datetime import datetime + + +from project.ext.database import db +from project.models.order_model import Order +from tests.factory.client_factory import ClientFactory +from tests.factory.product_factory import ProductFactory +from tests.factory.restaurant_factory import RestaurantFactory + + +class OrderFactory(SQLAlchemyModelFactory): + class Meta: + model = Order + sqlalchemy_session = db.session + + id = factory.Sequence(lambda n: n) + created_at = factory.LazyFunction(datetime.now) + # TODO: o relacionamento com o cliente + client = factory.SubFactory(ClientFactory) + client_id = factory.LazyAttribute(lambda obj: obj.client.id) + # TODO: o relacionamento com o restaurante + restaurant = factory.SubFactory(RestaurantFactory) + restaurant_id = factory.LazyAttribute(lambda obj: obj.restaurant.id) + total_value = factory.Sequence(lambda n: n * 10.0) + # TODO: uma lista de produtos + products = factory.List([factory.SubFactory(ProductFactory) for _ in range(5)]) diff --git a/tests/factory/product_factory.py b/tests/factory/product_factory.py new file mode 100644 index 0000000..47d9803 --- /dev/null +++ b/tests/factory/product_factory.py @@ -0,0 +1,20 @@ +import factory +from factory.alchemy import SQLAlchemyModelFactory +from project.ext.database import db +from project.models.product_model import Product +from tests.factory.restaurant_factory import RestaurantFactory + + +class ProductFactory(SQLAlchemyModelFactory): + class Meta: + model = Product + sqlalchemy_session = db.session + + id = factory.Sequence(lambda n: n) + name = factory.Sequence(lambda n: f"Product{n}") + description = factory.Sequence(lambda n: f"Description{n}") + value = factory.Sequence(lambda n: n) + url_image = factory.Sequence(lambda n: f"Url{n}") + # TODO: o relacionamento com o restaurante + restaurant = factory.SubFactory(RestaurantFactory) + restaurant_id = factory.LazyAttribute(lambda obj: obj.restaurant.id) diff --git a/tests/factory/restaurant_factory.py b/tests/factory/restaurant_factory.py new file mode 100644 index 0000000..6983227 --- /dev/null +++ b/tests/factory/restaurant_factory.py @@ -0,0 +1,22 @@ +from datetime import time, timedelta, datetime +import random +import factory +from factory.alchemy import SQLAlchemyModelFactory +from project.ext.database import db +from project.models.restaurant_model import Restaurant + + +class RestaurantFactory(SQLAlchemyModelFactory): + class Meta: + model = Restaurant + sqlalchemy_session = db.session + + id = factory.Sequence(lambda n: n) + name = factory.Sequence(lambda n: f"Restaurant{n}") + classification = factory.Sequence(lambda n: n) + description = factory.Sequence(lambda n: f"Description{n}") + location = factory.Sequence(lambda n: f"Location{n}") + horario_funcionamento = factory.LazyFunction(lambda: time(9, 0)) # Abre às 9:00 + horario_fechamento = factory.LazyFunction(lambda: time(21, 0)) # Fecha às 21:00 + url_image_logo = factory.Sequence(lambda n: f"Url{n}") + url_image_banner = factory.Sequence(lambda n: f"Url{n}") \ No newline at end of file diff --git a/tests/factory/user_factory.py b/tests/factory/user_factory.py new file mode 100644 index 0000000..d83c75f --- /dev/null +++ b/tests/factory/user_factory.py @@ -0,0 +1,15 @@ +import factory +from factory.alchemy import SQLAlchemyModelFactory +from project.ext.database import db +from project.models.user_model import User + + +class UserFactory(SQLAlchemyModelFactory): + class Meta: + model = User + sqlalchemy_session = db.session + + id = factory.Sequence(lambda n: n) + firstname = factory.Sequence(lambda n: f"Firstname{n}") + lastname = factory.Sequence(lambda n: f"Lastname{n}") + email = factory.Sequence(lambda n: f"email{n}@test.com") diff --git a/tests/test_client.py b/tests/test_client.py new file mode 100644 index 0000000..9e3241c --- /dev/null +++ b/tests/test_client.py @@ -0,0 +1,122 @@ +def test_list_client_return_200(app_testing, client_10): + """ + Teste para verificar se o endpoint da API para listar clientes retorna o código de status 200. + """ + client = app_testing.test_client() + response = client.get("http://127.0.0.1:5000/api/v1/clients/") + # print(response.json) + assert response.status_code == 200 + for client in response.json: + assert "id" in client + assert "client_name" in client + assert "client_cellphone" in client + + +def test_post_client_return_200(app_testing): + """ + Testa se a rota '/api/v1/clients/' retorna o código de status 201 (Created) ao fazer uma requisição POST com dados válidos de cliente. + """ + client = app_testing.test_client() + + client_data = { + "client_name": "Maria Oliveira", + "client_cellphone": "69996666666", + "client_address": "Rua do Teste, 123", + "client_address_number": 123, + "client_address_complement": "Apto 101", + "client_address_neighborhood": "Bairro do Teste", + "client_zip_code": "12345-678", + } + + response = client.post("/api/v1/clients/", json=client_data) + + assert response.status_code == 201 + assert response.json["message"] == "Cliente cadastrado com sucesso!" + + +def test_post_client_return_400(app_testing): + """ + Testa se a rota '/api/v1/clients/' retorna o código de status 400 (Solicitação Incorreta) ao fazer uma requisição POST com dados invalidos de cliente. + """ + client = app_testing.test_client() + + response = client.post("/api/v1/clients/", json={"invalid": "data"}) + + assert response.status_code == 400 + assert ( + response.json["error"] == "'invalid' is an invalid keyword argument for Client" + ) + + +def test_get_one_client_return_200(app_testing, cliente): + """ + Testa se a rota '/api/v1/clients//' retorna o código de status 200 ao fazer uma requisição GET com um ID de cliente válido. + """ + client = app_testing.test_client() + response = client.get("/api/v1/clients/1") + assert response.status_code == 200 + assert response.json["id"] == 1 + assert "client_name" in response.json + assert "client_cellphone" in response.json + + +def test_get_one_client_return_404(app_testing): + """ + Testa se a rota '/api/v1/clients//' retorna o código de status 404 ao fazer uma requisição GET com um ID de cliente invalido. + """ + client = app_testing.test_client() + response = client.get("/api/v1/clients/0") + assert response.status_code == 404 + assert response.json["error"] == "Cliente com ID 0 não encontrado." + + +def test_patch_client_return_200(app_testing, cliente): + """ + Testa se a rota '/api/v1/clients//' retorna o código de status 200 ao fazer uma requisição PATCH com um ID de cliente válido. + """ + client = app_testing.test_client() + + client_data = { + "client_name": "Maria Oliveira", + "client_cellphone": "69996666666", + "client_address": "Rua do Teste, 123", + "client_address_number": 123, + "client_address_complement": "Apto 101", + "client_address_neighborhood": "Bairro do Teste", + "client_zip_code": "12345-678", + } + + response = client.patch("/api/v1/clients/1", json=client_data) + + assert response.status_code == 200 + assert response.json["message"] == "Cliente com ID 1 atualizado com sucesso!" + + +def test_patch_client_return_404(app_testing): + """ + Testa se a rota '/api/v1/clients//' retorna o código de status 500 ao fazer uma requisição PATCH com um ID de cliente invalido. + """ + client = app_testing.test_client() + response = client.patch("/api/v1/clients/0", json={}) + assert response.status_code == 404 + assert response.json["error"] == "Cliente com ID 0 não encontrado" + + +def test_delete_client_return_200(app_testing, cliente): + """ + Testa se a rota '/api/v1/clients//' retorna o código de status 200 ao fazer uma requisição DELETE com um ID de cliente válido. + """ + client = app_testing.test_client() + response = client.delete("/api/v1/clients/1") + assert response.status_code == 200 + assert response.json["message"] == "CLiente com ID 1 deletado com sucesso." + + +def test_delete_client_return_404(app_testing): + """ + Testa se a rota '/api/v1/clients//' retorna o código de status 404 ao fazer uma requisição DELETE com um ID de cliente invalido. + """ + client = app_testing.test_client() + response = client.delete("/api/v1/clients/0") + assert response.status_code == 404 + assert response.json["error"] == "Cliente com ID 0 não encontrado" diff --git a/tests/test_main.py b/tests/test_main.py new file mode 100644 index 0000000..7cb4b46 --- /dev/null +++ b/tests/test_main.py @@ -0,0 +1,17 @@ +import os + +from project import create_app_wsgi + + +def test_app_name(): + """Testa se o nome da aplicação 'project.base'""" + os.environ["FLASK_ENV"] = "testing" + app = create_app_wsgi() + assert app.name == "project.base" + + +def test_route_swagger_status_code_200(app_testing): + """Testa se o endpoint 'localhost:5000/api/v1/' retorna o status code 200""" + client = app_testing.test_client() + response = client.get("http://127.0.0.1:5000/api/v1/") + assert response.status_code == 200 diff --git a/tests/test_order.py b/tests/test_order.py new file mode 100644 index 0000000..782b4a5 --- /dev/null +++ b/tests/test_order.py @@ -0,0 +1,127 @@ +from datetime import time + + +def test_list_order_return_200( + app_testing, client_10, restaurant_10, product_10, order_10 +): + order = app_testing.test_client() + response = order.get("http://127.0.0.1:5000/api/v1/orders/") + assert response.status_code == 200 + for order in response.json: + assert "client" in order + assert "restaurant" in order + assert "products" in order + assert "created_at" in order + + +def test_post_order_return_200(app_testing, client_10, restaurant_10, product_10): + client = app_testing.test_client() + + order_data = { + "client_id": 4, + "restaurant_id": 5, + "products": [{"product_id": 5, "quantity": 1}], + "created_at": "2024-03-11 10:00:00", + "current_time": time(14, 0).strftime("%H:%M:%S"), + } + + response = client.post("/api/v1/orders/", json=order_data) + + print(f"Status Code: {response.status_code}") + print(f"Response JSON: {response.json}") + + assert response.status_code == 201 + assert response.json["message"] == "Pedido criado com sucesso!" + + + +def test_post_order_return_400(app_testing, client_10, restaurant_10, product_10): + client = app_testing.test_client() + + order_data = { + "client_id": 4, + "restaurant_id": 5, + "products": [{"product_id": 5, "quantity": 1}], + "created_at": "2024-03-11 10:00:00", + "current_time": time(22, 0).strftime("%H:%M:%S"), + } + + response = client.post("/api/v1/orders/", json=order_data) + + assert response.status_code == 400 + assert response.json["error"] == "403 Forbidden: O restaurante está fora do horário de funcionamento." + + +def test_post_order_return_400(app_testing, restaurant_10, product_10): + client = app_testing.test_client() + + order_data = { + "client_id": 4, + "restaurant_id": 5, + "products": [5], + "created_at": "2024-03-11 10:00:00", + } + + response = client.post("/api/v1/orders/", json=order_data) + + assert response.status_code == 400 + assert response.json["error"] == "404 Not Found: Cliente com ID 4 não encontrado." + + +def test_get_one_order_return_200(app_testing, cliente, restaurant, product, order): + client = app_testing.test_client() + + response = client.get("/api/v1/orders/1") + assert response.status_code == 200 + assert response.json["client"] == 1 + assert response.json["restaurant"] == 1 + + +def test_get_one_order_return_404(app_testing): + client = app_testing.test_client() + response = client.get("/api/v1/orders/0") + assert response.status_code == 404 + assert response.json["error"] == "Ordem com ID 0 não encontrado." + + +def test_patch_order_return_200(app_testing, cliente, restaurant, product, order): + client = app_testing.test_client() + + order_data = { + "client_id": 1, + "restaurant_id": 1, + "products": [1], + } + + response = client.patch("/api/v1/orders/1", json=order_data) + assert response.status_code == 200 + assert response.json["message"] == "Ordem com ID 1 atualizado com sucesso!" + + +def test_patch_order_return_404(app_testing): + client = app_testing.test_client() + + order_data = { + "client_id": 1, + "restaurant_id": 1, + "products": [1], + } + response = client.patch("/api/v1/orders/0", json=order_data) + assert response.status_code == 404 + assert response.json["error"] == "Ordem com ID 0 não encontrado." + + +def test_delete_order_return_200(app_testing, cliente, restaurant, product, order): + client = app_testing.test_client() + + response = client.delete("/api/v1/orders/1") + assert response.status_code == 200 + assert response.json["message"] == "Ordem com ID 1 deletado com sucesso." + + +def test_delete_order_return_404(app_testing): + client = app_testing.test_client() + + response = client.delete("/api/v1/orders/0") + assert response.status_code == 404 + assert response.json["error"] == "Ordem com ID 0 não encontrado" diff --git a/tests/test_product.py b/tests/test_product.py new file mode 100644 index 0000000..36d1ebd --- /dev/null +++ b/tests/test_product.py @@ -0,0 +1,123 @@ +def test_list_product_return_200(app_testing, restaurant_10, product_10): + """ + Teste para verificar se o endpoint da API para listar produtos e retorna o código de status 200. + """ + product = app_testing.test_client() + response = product.get("http://127.0.0.1:5000/api/v1/products/") + assert response.status_code == 200 + for product in response.json: + assert "name" in product + assert "Description" in product["description"] + + +def test_post_product_return_200(app_testing, restaurant_10): + """ + Testa se a rota '/api/v1/products/' retorna o código de status 201 (Created) ao fazer uma requisição POST com dados válidos de products. + """ + client = app_testing.test_client() + + product_data = { + "name": "X-Teste", + "value": 15, + "description": "Descrição do produto de teste", + "url_image": "url_image_teste", + "restaurant_id": 5, + } + + response = client.post("/api/v1/products/", json=product_data) + + assert response.status_code == 201 + assert response.json["message"] == "Produto cadastrado com sucesso!" + + +def test_post_product_return_400(app_testing): + """ + Testa se a rota '/api/v1/products/' retorna o código de status 400 (Solicitação Incorreta) ao fazer uma requisição POST com dados invalidos de products. + """ + client = app_testing.test_client() + + response = client.post("/api/v1/products/", json={"invalid": "data"}) + + assert response.status_code == 400 + assert ( + response.json["error"] == "'invalid' is an invalid keyword argument for Product" + ) + + +def test_get_one_product_return_200(app_testing, restaurant, product): + """ + Testa se a rota '/api/v1/products//' retorna o código de status 200 ao fazer uma requisição GET com um ID de products válido. + """ + client = app_testing.test_client() + + response = client.get("/api/v1/products/1") + assert response.status_code == 200 + assert response.json["name"] == "X-Bacon" + assert response.json["value"] == 20 + + +def test_get_one_product_return_404(app_testing): + """ + Testa se a rota '/api/v1/products//' retorna o código de status 404 ao fazer uma requisição GET com um ID de products invalido. + """ + client = app_testing.test_client() + response = client.get("/api/v1/products/0") + assert response.status_code == 404 + + +def test_patch_product_return_200(app_testing, restaurant, product): + """ + Testa se a rota '/api/v1/products//' retorna o código de status 200 ao fazer uma requisição PATCH com um ID de products válido. + """ + client = app_testing.test_client() + + product_data = { + "name": "X-Teste", + "value": 15, + "description": "Descrição do produto de teste", + "url_image": "url_image_teste", + "restaurant_id": 1, + } + + response = client.patch("/api/v1/products/1", json=product_data) + assert response.status_code == 200 + assert response.json["message"] == "Produto com ID 1 atualizado com sucesso!" + + +def test_patch_product_return_404(app_testing): + """ + Testa se a rota '/api/v1/products//' retorna o código de status 404 ao fazer uma requisição PATCH com um ID de products invalido. + """ + client = app_testing.test_client() + + product_data = { + "name": "X-Teste", + "value": 15, + "description": "Descrição do produto de teste", + "url_image": "url_image_teste", + "restaurant_id": 5, + } + + response = client.patch("/api/v1/products/0", json=product_data) + assert response.status_code == 404 + assert response.json["error"] == "Produto com ID 0 não encontrado" + + +def test_delete_product_return_200(app_testing, restaurant, product): + """ + Testa se a rota '/api/v1/products//' retorna o código de status 200 ao fazer uma requisição DELETE com um ID de products válido. + """ + client = app_testing.test_client() + response = client.delete("/api/v1/products/1") + assert response.status_code == 200 + assert response.json["message"] == "Produto com ID 1 deletado com sucesso." + + +def test_delete_product_return_404(app_testing): + """ + Testa se a rota '/api/v1/products//' retorna o código de status 404 ao fazer uma requisição DELETE com um ID de products invalido. + """ + client = app_testing.test_client() + response = client.delete("/api/v1/products/0") + assert response.status_code == 404 + assert response.json["error"] == "Produto com ID 0 não encontrado" diff --git a/tests/test_restaurant.py b/tests/test_restaurant.py new file mode 100644 index 0000000..09fe23b --- /dev/null +++ b/tests/test_restaurant.py @@ -0,0 +1,139 @@ +from datetime import time + +def test_list_restaurant_return_200(app_testing, restaurant_10): + """ + Teste para verificar se o endpoint da API para listar restaurante retorna o código de status 200. + """ + restaurant = app_testing.test_client() + response = restaurant.get("http://127.0.0.1:5000/api/v1/restaurants/") + + assert response.status_code == 200 + for restaurant in response.json: + assert "name" in restaurant + assert "description" in restaurant + + +def test_post_restaurant_return_200(app_testing): + """ + Testa se a rota '/api/v1/restaurants/' retorna o código de status 201 (Created) ao fazer uma requisição POST com dados válidos de products. + """ + client = app_testing.test_client() + + restaurant_data = { + "name": "Restaurante Teste", + "description": "Descrição do restaurante de teste", + "classification": 4.5, + "location": "Cidade do Teste", + "url_image_logo": "url_logo_teste", + "url_image_banner": "url_banner_teste", + "horario_funcionamento": time(8, 0, 0).strftime('%H:%M:%S'), + "horario_fechamento": time(22, 0, 0).strftime('%H:%M:%S'), + } + + response = client.post("/api/v1/restaurants/", json=restaurant_data) + + print(response.json) + + assert response.status_code == 201 + assert response.json["message"] == "Restaurante cadastrado com sucesso!" + + +def test_post_restaurant_return_400(app_testing): + """ + Testa se a rota '/api/v1/restaurants/' retorna o código de status 400 (Solicitação Incorreta) ao fazer uma requisição POST com dados invalidos de products. + """ + client = app_testing.test_client() + + response = client.post("/api/v1/restaurants/", json={"invalid": "data"}) + + assert response.status_code == 400 + + +def test_get_one_restaurant_return_200(app_testing, restaurant): + """ + Testa se a rota '/api/v1/restaurants//' retorna o código de status 200 ao fazer uma requisição GET com um ID de restaurante válido. + """ + client = app_testing.test_client() + + response = client.get("/api/v1/restaurants/1/products") + assert response.status_code == 200 + assert response.json["id"] == 1 + assert "name" in response.json + assert "description" in response.json + + +def test_get_one_restaurant_return_404(app_testing): + """ + Testa se a rota '/api/v1/restaurants//' retorna o código de status 404 ao fazer uma requisição GET com um ID de restaurante invalido. + """ + client = app_testing.test_client() + response = client.get("/api/v1/restaurants/0/products") + assert response.status_code == 404 + assert response.json["error"] == "Restaurante com ID 0 não encontrado." + + +def test_patch_restaurant_return_200(app_testing, restaurant): + """ + Testa se a rota '/api/v1/restaurants/{restaurant.id}/products' retorna o código de status 200 ao fazer uma requisição PATCH com um ID de restaurante válido. + """ + client = app_testing.test_client() + + restaurant_data = { + "name": "Restaurante Teste", + "description": "Descrição do restaurante de teste", + "classification": 4.5, + "location": "Cidade do Teste", + "url_image_logo": "url_logo_teste", + "url_image_banner": "url_banner_teste", + "products": [ + { + "id": 1, + "name": "Produto Teste", + "value": 10.5, + "description": "Descrição do produto de teste", + "url_image": "url_produto_teste", + "restaurant_id": restaurant.id, + } + ], + } + + response = client.patch( + f"/api/v1/restaurants/{restaurant.id}/products", json=restaurant_data + ) + assert response.status_code == 200 + assert ( + response.json["message"] + == f"Restaurante com ID {restaurant.id} atualizado com sucesso!" + ) + + +def test_patch_restaurant_return_404(app_testing): + """ + Testa se a rota '/api/v1/restaurants//' retorna o código de status 500 ao fazer uma requisição PATCH com um ID de restaurante invalido. + """ + client = app_testing.test_client() + response = client.patch("/api/v1/restaurants/0/products", json={}) + # print(response.json) + assert response.status_code == 404 + + +def test_delete_restaurant_return_200(app_testing, restaurant): + """ + Testa se a rota '/api/v1/restaurants//' retorna o código de status 200 ao fazer uma requisição DELETE com um ID de restaurante válido. + """ + client = app_testing.test_client() + response = client.delete("/api/v1/restaurants/1/products") + assert response.status_code == 200 + # print(response.json) + assert response.json["message"] == "Restaurante com ID 1 deletado com sucesso." + + +def test_delete_restaurant_return_404(app_testing): + """ + Testa se a rota '/api/v1/restaurants//' retorna o código de status 404 ao fazer uma requisição DELETE com um ID de restaurante invalido. + """ + client = app_testing.test_client() + response = client.delete("/api/v1/restaurants/0/products") + assert response.status_code == 404 + # print(response.json) + assert response.json["error"] == "Restaurante com ID 0 não encontrado" diff --git a/tests/test_user.py b/tests/test_user.py new file mode 100644 index 0000000..b25268e --- /dev/null +++ b/tests/test_user.py @@ -0,0 +1,107 @@ +def test_list_user_return_200(app_testing, User_10): + """ + Testa se a rota '/api/v1/users/' retorna o código de status 200 e os dados contidos em mock_users. + """ + user = app_testing.test_client() + response = user.get("http://127.0.0.1:5000/api/v1/users/") + assert response.status_code == 200 + for user in response.json: + assert "firstname" in user + assert "Firstname" in user["firstname"] + + +def test_post_user_return_200(app_testing): + """ + Testa se a rota '/api/v1/clients/' retorna o código de status 201 (Created) ao fazer uma requisição POST com dados válidos de Usuário. + """ + client = app_testing.test_client() + + user_data = { + "firstname": "João", + "lastname": "Silva", + "email": "joao.silva@example.com", + } + + response = client.post("/api/v1/users/", json=user_data) + + assert response.status_code == 201 + assert response.json["message"] == "Usuário cadastrado com sucesso!" + + +def test_post_user_return_400(app_testing): + """ + Testa se a rota '/api/v1/users/' retorna o código de status 400 (Solicitação Incorreta) ao fazer uma requisição POST com dados invalidos de usuario. + """ + client = app_testing.test_client() + + response = client.post("/api/v1/users/", json={"invalid": "data"}) + + assert response.status_code == 400 + assert response.json["error"] == "'invalid' is an invalid keyword argument for User" + + +def test_get_one_user_return_200(app_testing, user): + """ + Testa se a rota '/api/v1/users//' retorna o código de status 200 ao fazer uma requisição GET com um ID de Usuário válido. + """ + client = app_testing.test_client() + response = client.get("/api/v1/users/1") + assert response.status_code == 200 + assert response.json["firstname"] == "Tony" + + +def test_get_one_user_return_404(app_testing): + """ + Testa se a rota '/api/v1/users//' retorna o código de status 404 ao fazer uma requisição GET com um ID de Usuário invalido. + """ + client = app_testing.test_client() + response = client.get("/api/v1/users/1") + assert response.status_code == 404 + assert response.json["error"] == "Usuário com ID 1 não encontrado." + + +def test_patch_users_return_200(app_testing, user): + """ + Testa se a rota '/api/v1/clients//' retorna o código de status 200 ao fazer uma requisição PATCH com um ID de Usuario válido. + """ + client = app_testing.test_client() + + user_data = { + "firstname": "João", + "lastname": "Silva", + "email": "joao.silva@example.com", + } + + response = client.patch("/api/v1/users/1", json=user_data) + + assert response.status_code == 200 + assert response.json["message"] == "Usuário com ID 1 atualizado com sucesso!" + + +def test_patch_users_return_500(app_testing): + """ + Testa se a rota '/api/v1/users//' retorna o código de status 500 ao fazer uma requisição PATCH com um ID de Usuario invalido. + """ + client = app_testing.test_client() + response = client.patch("/api/v1/users/1", json={}) + assert response.status_code == 500 + + +def test_delete_client_return_200(app_testing, user): + """ + Testa se a rota '/api/v1/users//' retorna o código de status 200 ao fazer uma requisição DELETE com um ID de cliente válido. + """ + client = app_testing.test_client() + response = client.delete("/api/v1/users/1") + assert response.status_code == 200 + assert response.json["message"] == "Usuário com ID 1 deletado com sucesso." + + +def test_delete_client_return_404(app_testing): + """ + Testa se a rota '/api/v1/users//' retorna o código de status 404 ao fazer uma requisição DELETE com um ID de cliente invalido. + """ + client = app_testing.test_client() + response = client.delete("/api/v1/users/1") + assert response.status_code == 404 + assert response.json["error"] == "Usuário com ID 1 não encontrado"