Skip to content

Commit

Permalink
autorefactoring yappa tests
Browse files Browse the repository at this point in the history
  • Loading branch information
1kovalevskiy committed Jul 15, 2022
1 parent a9746ea commit f154704
Show file tree
Hide file tree
Showing 15 changed files with 223 additions and 177 deletions.
41 changes: 26 additions & 15 deletions tests/config_generation.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,22 @@
import pytest

from yappa.config_generation import inject_function_id
from yappa.utils import get_yc_entrypoint
from yappa.handlers.common import load_yaml
from yappa.utils import get_yc_entrypoint


@pytest.mark.parametrize(
"application_type,expected_entrypoint,initial_entrypoint, is_ok", [
"application_type,expected_entrypoint,initial_entrypoint, is_ok",
[
("wsgi", "handlers.wsgi.handle", "initial.entry_point", True),
("asgi", "handlers.asgi.handle", "initial.entry_point", True),
("raw", "initial.entry_point", "initial.entry_point", True),
("jibber_jabber", "flask", "initial_entrypoint", False),
])
def test_getting_entrypoint(application_type, expected_entrypoint,
initial_entrypoint, is_ok):
],
)
def test_getting_entrypoint(
application_type, expected_entrypoint, initial_entrypoint, is_ok
):
if is_ok:
entrypoint = get_yc_entrypoint(application_type, initial_entrypoint)
assert entrypoint == expected_entrypoint
Expand All @@ -29,15 +32,23 @@ def test_getting_entrypoint(application_type, expected_entrypoint,
OUTPUT_GW_DIR = Path(BASE_GW_DIR, "output")


@pytest.mark.parametrize("input,expected_output", [
(Path(SRC_GW_DIR, "yappa-gw-base.yaml"),
Path(OUTPUT_GW_DIR, "yappa-gw-base.yaml")),
(Path(SRC_GW_DIR, "yappa-gw-pwa.yaml"),
Path(OUTPUT_GW_DIR, "yappa-gw-pwa.yaml")),
])
def test_gw_injection(input, expected_output):
default_config = load_yaml(input)
injected = inject_function_id(default_config, "test_function_id",
"yappa_gateway")
@pytest.mark.parametrize(
"input_,expected_output",
[
(
Path(SRC_GW_DIR, "yappa-gw-base.yaml"),
Path(OUTPUT_GW_DIR, "yappa-gw-base.yaml"),
),
(
Path(SRC_GW_DIR, "yappa-gw-pwa.yaml"),
Path(OUTPUT_GW_DIR, "yappa-gw-pwa.yaml"),
),
],
)
def test_gw_injection(input_, expected_output):
default_config = load_yaml(input_)
injected = inject_function_id(
default_config, "test_function_id", "yappa_gateway"
)
expected_config = load_yaml(expected_output)
assert injected == expected_config
49 changes: 27 additions & 22 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# pylint: disable=redefined-outer-name
import os
from pathlib import Path
from shutil import copy2
Expand All @@ -21,27 +22,26 @@ def yc():
Path(Path(__file__).resolve().parent, "test_apps", "django_wsgi.py"),
Path(Path(__file__).resolve().parent, "test_apps", "django_settings.py"),
Path(Path(__file__).resolve().parent, "test_apps", "flask_app.py"),
Path(Path(__file__).resolve().parent, "test_apps",
"apps_requirements.txt"),
)
Path(Path(__file__).resolve().parent, "test_apps", "apps_requirements.txt"),
)
PACKAGE_FILES = (
Path("package", "utils.py"),
Path("package", "subpackage", "subutils.py"),
Path(".idea"),
Path(".git", "config"),
Path("venv", "flask.py"),
)
)


def create_empty_files(*paths):
for path in paths:
os.makedirs(path.parent, exist_ok=True)
open(path, "w").close()
open(path, "w", encoding="utf-8").close() # pylint: disable=R1732


@pytest.fixture(scope="session")
def apps_dir(tmpdir_factory):
dir_ = tmpdir_factory.mktemp('package')
dir_ = tmpdir_factory.mktemp("package")
os.chdir(dir_)
assert not os.listdir()
create_empty_files(*PACKAGE_FILES)
Expand All @@ -59,12 +59,14 @@ def config_filename():
("flask", "flask_app.app", None, "wsgi"),
("django", "django_wsgi.app", "django_settings", "wsgi"),
("fastapi", "fastapi_app.app", None, "asgi"),
)
)


@pytest.fixture(scope="session",
params=APPS_CONFIGS,
ids=[config[0] for config in APPS_CONFIGS])
@pytest.fixture(
scope="session",
params=APPS_CONFIGS,
ids=[config[0] for config in APPS_CONFIGS],
)
def config(request, apps_dir, config_filename):
config = create_default_config(config_filename)
config.update(
Expand All @@ -79,9 +81,9 @@ def config(request, apps_dir, config_filename):
".idea",
".git",
"venv",
),
),
is_public=True,
)
)
save_yaml(config, config_filename)
return config

Expand All @@ -100,12 +102,13 @@ def function(config, yc):
UPLOAD_STATEGIES = (
"s3",
"direct",
)
)


@pytest.fixture(scope="session", params=UPLOAD_STATEGIES, ids=UPLOAD_STATEGIES)
def function_version(request, yc, function, config, config_filename,
s3_credentials):
def function_version(
request, yc, function, config, config_filename, s3_credentials
):
yield create_function_version(yc, config, request.param, config_filename)
delete_bucket(config["bucket"], **s3_credentials)

Expand All @@ -119,9 +122,7 @@ def s3_credentials(yc):
def sample_event():
return {
"httpMethod": "GET",
"headers": {
"HTTP_HOST": ""
},
"headers": {"HTTP_HOST": ""},
"url": "http://sampleurl.ru/",
"params": {},
"multiValueParams": {},
Expand All @@ -130,11 +131,15 @@ def sample_event():
"queryStringParameters": {},
"multiValueQueryStringParameters": {},
"requestContext": {
"identity": {"sourceIp": "95.170.134.34",
"userAgent": "Mozilla/5.0"},
"identity": {
"sourceIp": "95.170.134.34",
"userAgent": "Mozilla/5.0",
},
"httpMethod": "GET",
"requestId": "0f61048c-2ba9",
"requestTime": "18/Jun/2021:03:56:37 +0000",
"requestTimeEpoch": 1623988597},
"requestTimeEpoch": 1623988597,
},
"body": "",
"isBase64Encoded": False}
"isBase64Encoded": False,
}
33 changes: 18 additions & 15 deletions tests/handlers/asgi.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# pylint: disable=redefined-outer-name
import json
import sys
from copy import copy
Expand All @@ -7,22 +8,26 @@
import pytest

from yappa.handlers.asgi import call_app
from yappa.handlers.wsgi import load_app
from yappa.handlers.common import patch_response
from yappa.handlers.wsgi import load_app

BASE_URL = "http://base-url.com"


@pytest.fixture(params=[
("fastapi_app.app", None),
], ids=[
"fastAPI",
], )
@pytest.fixture(
params=[
("fastapi_app.app", None),
],
ids=[
"fastAPI",
],
)
def app(request):
# TODO сделать зависимой от config, а config - параметризованная фикстура
# чтобы тесты handler, s3, yc_functions вызывались для каждого приложения
sys.path.append(
str(Path(Path(__file__).resolve().parent.parent, "test_apps")))
str(Path(Path(__file__).resolve().parent.parent, "test_apps"))
)
return load_app(*request.param)


Expand All @@ -36,9 +41,9 @@ async def test_sample_call(app, sample_event):
response = await call_app(app, sample_event)
response = patch_response(response)
assert response["statusCode"] == 200
assert response["body"] == 'root url'
assert response["body"] == "root url"
assert isinstance(response["headers"], dict)
assert not isinstance(response['body'], bytes)
assert not isinstance(response["body"], bytes)
assert not response["isBase64Encoded"]


Expand All @@ -57,14 +62,14 @@ async def test_json_response(app, sample_event):
response = patch_response(response)
assert response["statusCode"] == 200
assert response["body"].replace("\n", "") == json.dumps(
{"result": "json", "sub_result": {"sub": "json"}}).replace(" ", "")
{"result": "json", "sub_result": {"sub": "json"}}
).replace(" ", "")
assert not response["isBase64Encoded"]


@pytest.mark.asyncio
async def test_post(app, sample_event):
body = {"test_str": "ok!",
"test_num": 5}
body = {"test_str": "ok!", "test_num": 5}
event = copy(sample_event)
event.update(
url=urljoin(BASE_URL, "post"),
Expand All @@ -82,9 +87,7 @@ async def test_post(app, sample_event):
@pytest.mark.asyncio
async def test_file(app, sample_event):
event = copy(sample_event)
event.update(
url=urljoin(BASE_URL, "file")
)
event.update(url=urljoin(BASE_URL, "file"))
response = await call_app(app, event)
response = patch_response(response)
assert response["statusCode"] == 200
Expand Down
9 changes: 6 additions & 3 deletions tests/handlers/manage.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
def django_settings():
os.environ["DJANGO_SETTINGS_MODULE"] = "django_settings"
sys.path.append(
str(Path(Path(__file__).resolve().parent.parent, "test_apps")))
str(Path(Path(__file__).resolve().parent.parent, "test_apps"))
)


def test_help():
Expand All @@ -24,7 +25,9 @@ def test_help():
def test_arguments():
response = manage({"body": json.dumps({"command": "check", "args": []})})
assert response["body"] == (
'System check identified no issues (0 silenced).\n')
"System check identified no issues (0 silenced).\n"
)
response = manage(
{"body": json.dumps({"command": "check", "args": ["--deploy"]})})
{"body": json.dumps({"command": "check", "args": ["--deploy"]})}
)
assert response["body"].startswith("System check identified some issues")
39 changes: 23 additions & 16 deletions tests/handlers/wsgi.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# pylint: disable=redefined-outer-name
import json
import sys
from copy import copy
Expand All @@ -11,25 +12,29 @@
BASE_URL = "http://base-url.com"


@pytest.fixture(params=[
("flask_app.app", None),
("django_wsgi.app", "django_settings"),
], ids=[
"flask",
"django"
], )
@pytest.fixture(
params=[
("flask_app.app", None),
("django_wsgi.app", "django_settings"),
],
ids=["flask", "django"],
)
def app(request):
# TODO сделать зависимой от config, а config - параметризованная фикстура
# чтобы тесты handler, s3, yc_functions вызывались для каждого приложения
sys.path.append(
str(Path(Path(__file__).resolve().parent.parent, "test_apps")))
str(Path(Path(__file__).resolve().parent.parent, "test_apps"))
)
return load_app(*request.param)


def test_load_from_config(config):
sys.path.append(
str(Path(Path(__file__).resolve().parent.parent, "test_apps")))
app = load_app(config.get("entrypoint"), )
str(Path(Path(__file__).resolve().parent.parent, "test_apps"))
)
app = load_app(
config.get("entrypoint"),
)
assert callable(app)


Expand All @@ -43,7 +48,7 @@ def test_sample_call(app, sample_event):
assert response["statusCode"] == 200
assert response["body"] == "root url"
assert isinstance(response["headers"], dict)
assert not isinstance(response['body'], bytes)
assert not isinstance(response["body"], bytes)


def test_not_found_call(app, sample_event):
Expand All @@ -57,7 +62,8 @@ def test_json_response(app, sample_event):
response = patch_response(call_app(app, sample_event))
assert response["statusCode"] == 200
assert response["body"].replace("\n", "") == json.dumps(
{"result": "json", "sub_result": {"sub": "json"}}).replace(" ", "")
{"result": "json", "sub_result": {"sub": "json"}}
).replace(" ", "")


def test_query_params(app, sample_event):
Expand All @@ -70,7 +76,8 @@ def test_query_params(app, sample_event):
response = patch_response(call_app(app, sample_event))
assert response["statusCode"] == 200, response["body"]
assert response["body"].replace("\n", "").replace(" ", "") == json.dumps(
{"params": params}).replace(" ", "")
{"params": params}
).replace(" ", "")


def test_path_param(app, sample_event):
Expand All @@ -79,12 +86,12 @@ def test_path_param(app, sample_event):
response = patch_response(call_app(app, sample_event))
assert response["statusCode"] == 200
assert response["body"].replace("\n", "") == json.dumps(
{"param": param_value}).replace(" ", "")
{"param": param_value}
).replace(" ", "")


def test_post(app, sample_event):
body = {"test_str": "ok!",
"test_num": 5}
body = {"test_str": "ok!", "test_num": 5}
event = copy(sample_event)
event.update(
url=urljoin(BASE_URL, "post"),
Expand Down
Loading

0 comments on commit f154704

Please sign in to comment.