Skip to content
This repository has been archived by the owner on Nov 9, 2023. It is now read-only.

Commit

Permalink
Add unittests for API endpoints (#4)
Browse files Browse the repository at this point in the history
* Add unittests for API endpoints

Signed-off-by: starry69 <[email protected]>

* Add black/flake8 GH action

and add pytest in python-app action

Signed-off-by: starry69 <[email protected]>

* Fix deepsrc confing

Signed-off-by: starry69 <[email protected]>
  • Loading branch information
starry-shivam authored Feb 2, 2021
1 parent 0361c67 commit d113d45
Show file tree
Hide file tree
Showing 15 changed files with 196 additions and 9 deletions.
7 changes: 6 additions & 1 deletion .deepsource.toml
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
version = 1

test_patterns = [
"tests/**",
"test_*.py"
]

[[analyzers]]
name = "python"
enabled = true

[analyzers.meta]
runtime_version = "3.x.x"
runtime_version = "3.x.x"
5 changes: 5 additions & 0 deletions .flake8
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[flake8]
ignore = E203, E266, E501, W503, F403, F401
max-line-length = 79
max-complexity = 18
select = B,C,E,F,W,T4,B9
11 changes: 11 additions & 0 deletions .github/workflows/black.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
name: Lint

on: [push, pull_request]

jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
- uses: psf/black@stable
15 changes: 15 additions & 0 deletions .github/workflows/pre-commit.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
name: pre-commit

on:
pull_request:
push:
branches: [master]

jobs:
pre-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
- uses: pre-commit/[email protected]

6 changes: 4 additions & 2 deletions .github/workflows/python-app.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,13 @@ jobs:
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install flake8 pytest
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
if [ -f requirements-dev.txt ]; then pip install -r requirements-dev.txt; fi
- name: Lint with flake8
run: |
# stop the build if there are Python syntax errors or undefined names
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
# exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
- name: Test with pytest
run: |
pytest -v
31 changes: 31 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
exclude: '.github/'
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.3.0
hooks:
- id: check-added-large-files
- id: check-ast
- id: check-builtin-literals
- id: check-case-conflict
- id: check-docstring-first
- id: check-json
- id: check-merge-conflict
- id: check-yaml
- id: debug-statements
- id: detect-private-key
- id: end-of-file-fixer
- id: fix-byte-order-marker
- id: fix-encoding-pragma
- id: pretty-format-json
- id: requirements-txt-fixer
- id: trailing-whitespace

- repo: https://github.com/ambv/black
rev: stable
hooks:
- id: black
language_version: python3
- repo: https://gitlab.com/pycqa/flake8
rev: 3.8.4
hooks:
- id: flake8
4 changes: 3 additions & 1 deletion QuotesAPI/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@
from QuotesAPI.database import quot
from QuotesAPI import ACCESS_KEY

app = Flask(__name__, template_folder="../templates", static_folder="../static")
app = Flask(
__name__, template_folder="../templates", static_folder="../static"
)
api = Api(app)


Expand Down
16 changes: 16 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[tool.black]
line-length = 79
include = '\.pyi?$'
exclude = '''
/(
\.git
| \.hg
| \.mypy_cache
| \.tox
| \.venv
| _build
| buck-out
| build
| dist
)/
'''
5 changes: 5 additions & 0 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
black
flake8
pre-commit
pytest
requests
4 changes: 2 additions & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Flask
Flask-RESTful
sqlalchemy
gunicorn
psycopg2
shortuuid
gunicorn
sqlalchemy
4 changes: 2 additions & 2 deletions static/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ a {
padding-bottom: 5px;
padding-left: 5px;
padding-right: 5px;

}

ul {
Expand Down Expand Up @@ -128,4 +128,4 @@ li {
ul {
padding-inline-start: 0px;
}
}
}
2 changes: 1 addition & 1 deletion templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -101,4 +101,4 @@ <h4>Example Response:</h4>
</div>
<p class="made_by">Made with &#10084;&#65039; by <a href="https://www.github.com/imudayveer" target="_blank">imudayveer</a> at Kontol Labs.</p>
</body>
</html>
</html>
Empty file added tests/__init__.py
Empty file.
94 changes: 94 additions & 0 deletions tests/test_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# MIT License
# Copyright (C) 2020-2021 Stɑrry Shivɑm.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# 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.
"""Includes unittests for public API endpoints."""


import pytest
import requests as r


BASE_URL = "https://superhero-quotes.herokuapp.com"


@pytest.mark.parametrize(
["banner", "expected_banner", "total"],
[
("mcu", "Marvel Cinematic Universe (MCU)", 5),
("dcu", "DC Universe (DCU)", 10),
],
)
def test_grab_endpoint(banner, expected_banner, total):
# make request to the API
res = r.get(f"{BASE_URL}/grab?banner={banner}&size={total}")
# check status code
assert res.status_code == 200
# check total quotes
json_data = res.json()
assert json_data["TotalQuotes"] == total
assert len(json_data["Items"]) == total
# finally check banner
assert json_data["Banner"] == expected_banner


def test_default_grab_endpoint_size():
# make request to the API without passing size parameter
banners = ["dcu", "mcu"]
for b in banners:
res = r.get(f"{BASE_URL}/grab?banner={b}")
# by default it should return 10 quotes
assert res.json()["TotalQuotes"] == 10


def test_invalid_grab_banner():
# make request to API by passing 'pizza' in banner parameter
res = r.get(f"{BASE_URL}/grab?banner=pizza")
# status 404: not found
assert res.status_code == 404
assert res.json()["message"].startswith("Not found")


def test_random_endpoint():
# make request to /random endpoint.
res = r.get(f"{BASE_URL}/random")
# check status code
assert res.status_code == 200
json_data = res.json()
assert json_data["Banner"] in {
"DC Universe (DCU)",
"Marvel Cinematic Universe (MCU)",
}


def test_quoteid_endpoint():
# make request with specific quoteId
quote_id = "k3fhzAKsvCeuFhXPHPQcnT"
res = r.get(f"{BASE_URL}/quoteId/{quote_id}")
# check status code
assert res.status_code == 200
json_data = res.json()
# check if id & quote matches
quote_text = "The pen, is truly mightier than the sword! "
assert json_data["Stuff"]["id"] == quote_id
assert json_data["Stuff"]["data"]["quote"] == quote_text


def test_invalid_quoteid():
# make request with invalid quoteid
invalid_id = "1234abcd"
res = r.get(f"{BASE_URL}/quoteId/{invalid_id}")
# status 404: not found
assert res.status_code == 404
# check error message
err_msg = "Can't find any quote for this id."
assert res.json()["message"] == err_msg
1 change: 1 addition & 0 deletions wsgi.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
# Hack for herokowowo
from QuotesAPI.__main__ import app

Expand Down

0 comments on commit d113d45

Please sign in to comment.