From 1fa9bf8880d300dd8cda40803cbf5504e372f289 Mon Sep 17 00:00:00 2001 From: penzai Date: Fri, 17 Jan 2020 15:08:46 +0800 Subject: [PATCH] test: add basic test code and attribute create api test case --- cmdb-api/Makefile | 16 +++++ cmdb-api/local_test.py | 17 +++++ cmdb-api/requirements-test.txt | 7 ++ cmdb-api/tests/conftest.py | 96 ++++++++++++++++++++++++++- cmdb-api/tests/test_cmdb_attribute.py | 25 +++++++ 5 files changed, 160 insertions(+), 1 deletion(-) create mode 100644 cmdb-api/Makefile create mode 100644 cmdb-api/local_test.py create mode 100644 cmdb-api/requirements-test.txt diff --git a/cmdb-api/Makefile b/cmdb-api/Makefile new file mode 100644 index 0000000..a289b86 --- /dev/null +++ b/cmdb-api/Makefile @@ -0,0 +1,16 @@ +default: help + +test: ## test in local environment + pytest -s --html=test-output/test/index.html --cov-report html:test-output/coverage --cov=api tests + +clean_test: ## clean test output + rm -f .coverage + rm -rf .pytest_cache + rm -rf test-output + + +docker_test: ## test all case in docker container + @echo "TODO" + +help: + @grep -E '^[a-zA-Z_-]+:.*?## .*$$' ./Makefile | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' diff --git a/cmdb-api/local_test.py b/cmdb-api/local_test.py new file mode 100644 index 0000000..fdcccf0 --- /dev/null +++ b/cmdb-api/local_test.py @@ -0,0 +1,17 @@ +# -*- coding: utf-8 -*- +"""For debugging in ide""" + +from tests.conftest import * +from pytest_mock import mocker +from _pytest.config import _prepareconfig + +from tests.test_cmdb_attribute import test_create_attribute + + +for a in app(): + for d in database(a): + for s in session(d, a): + for c in client(a): + for m in mocker(_prepareconfig()): + clean_db() + test_create_attribute(s, c) diff --git a/cmdb-api/requirements-test.txt b/cmdb-api/requirements-test.txt new file mode 100644 index 0000000..9629698 --- /dev/null +++ b/cmdb-api/requirements-test.txt @@ -0,0 +1,7 @@ +-i https://mirrors.aliyun.com/pypi/simple +pytest==4.0.2 +attrs==19.1.0 +coverage==4.4.2 +pytest-cov==2.5.1 +pytest-html==1.16.1 +pytest-mock==1.10.0 \ No newline at end of file diff --git a/cmdb-api/tests/conftest.py b/cmdb-api/tests/conftest.py index 003c8fc..fee9d8f 100644 --- a/cmdb-api/tests/conftest.py +++ b/cmdb-api/tests/conftest.py @@ -1,16 +1,54 @@ # -*- coding: utf-8 -*- """Defines fixtures available to all tests.""" +import jwt import pytest from webtest import TestApp +from flask import Response, json +from flask.testing import FlaskClient +from werkzeug.datastructures import Headers from api.app import create_app +from api.extensions import db +from api.models.acl import User -@pytest.fixture +class CMDBTestClient(FlaskClient): + TEST_APP_SECRET = "test" + + def open(self, *args, **kwargs): + headers = kwargs.pop("headers", Headers()) + headers.setdefault("User-Agent", "py.test") + kwargs["headers"] = headers + + json_data = kwargs.pop("json") + if json_data is not None: + kwargs["data"] = json.dumps(json_data) + if not kwargs.get("content_type"): + kwargs["content_type"] = "application/json" + + auth = kwargs.pop("auth", ( + "Access-Token", + jwt.encode({"sub": "test@xx.com"}, key=self.TEST_APP_SECRET) + )) + kwargs["headers"][auth[0]] = auth[1] + + return super(CMDBTestClient, self).open(*args, **kwargs) + + +class CMDBTestResponse(Response): + @property + def json(self): + return json.loads(self.data) + + +@pytest.fixture(scope="session") def app(): """Create application for the tests.""" _app = create_app("tests.settings") + _app.config['SECRET_KEY'] = CMDBTestClient.TEST_APP_SECRET + _app.test_client_class = CMDBTestClient + _app.response_class = CMDBTestResponse ctx = _app.test_request_context() ctx.push() yield _app @@ -18,6 +56,62 @@ def app(): ctx.pop() +@pytest.fixture(scope="session") +def client(app): + with app.test_client(use_cookies=False) as c: + yield c + + +@pytest.fixture(scope="session") +def database(app): + """Clean database after each case finished""" + setup_db() + yield db + teardown_db() + + +@pytest.fixture(scope="function") +def session(database, app): + with app.app_context(): + clean_db() + yield database.session + database.session.rollback() + + +def setup_db(): + teardown_db() + db.create_all() + # create test user + + +def teardown_db(): + db.session.remove() + db.drop_all() + db.session.bind.dispose() + + +def clean_db(): + """clean all data but not drop table""" + for table in reversed(db.metadata.sorted_tables): + if table.fullname in ["users"]: + continue + db.session.execute(table.delete()) + db.session.commit() + + if not User.get_by(email="test@xx.com"): + print("hello world xxxxx") + u = User.create( + flush=True, + username="test", + nickname="测试", + email="test@xx.com", + key="", + secret="" + ) + u._set_password("123456") + u.save() + + @pytest.fixture def testapp(app): """Create Webtest app.""" diff --git a/cmdb-api/tests/test_cmdb_attribute.py b/cmdb-api/tests/test_cmdb_attribute.py index 40a96af..fc754d9 100644 --- a/cmdb-api/tests/test_cmdb_attribute.py +++ b/cmdb-api/tests/test_cmdb_attribute.py @@ -1 +1,26 @@ # -*- coding: utf-8 -*- +from api.models.cmdb import Attribute + + +def test_create_attribute(session, client): + url = "/api/v0.1/attributes" + payload = { + "name": "region", + "alias": "区域", + "value_type": "2" + } + + resp = client.post(url, json=payload) + + # check resp status code and content + assert resp.status_code == 200 + assert resp.json["attr_id"] + + # check there is a ci_types in database + attr_id = resp.json["attr_id"] + attr_ins = Attribute.get_by_id(attr_id) + assert attr_ins.id == attr_id + assert attr_ins.name == "region" + assert attr_ins.alias == "区域" + +