Merge pull request #26 from OhBonsai/master

test: add basic test code and attribute create api test case
This commit is contained in:
pycook 2020-01-17 15:34:02 +08:00 committed by GitHub
commit 28ff27c019
5 changed files with 160 additions and 1 deletions

16
cmdb-api/Makefile Normal file
View File

@ -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}'

17
cmdb-api/local_test.py Normal file
View File

@ -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)

View File

@ -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

View File

@ -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."""

View File

@ -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 == "区域"