我们有一个 ETL 数据 API 存储库。我们在其中进行所有 etl 处理,然后将数据吐出到 API 中。这些 API 从将资源类传递到服务器以构建 API 的单个命令一次运行一个。资源类位于 __init__.py.
这是一个很棒的约定并且使用起来非常简单,但我遇到的问题是试图让 3 个可用的 API 之一启动以进行测试。我们的目录结构是这样的(调用项目'tomato')
tomato
- category_api
- web
- etl
- test
- here is where we are writing some tests (test_category_api.py)
- data
- article_api
- web
- etl
- test
- data
- recommendation_api
- web
- etl
- test
- data
- common
- common shit
在此测试中,我有以下测试类。从下往上第七行,
你会看到它在哪里中断的评论。它是 import_module
方法。
import unittest
import sys
import os
import sys
import json
from importlib import import_module
from flask import Flask
from flask_restful import Api, abort, wraps
from flask_restful.utils import cors
from flask.ext.testing import TestCase
#dir_above_top_level = os.path.join(os.path.abspath(__file__), '../../.. /')
#sys.path.append(os.path.abspath(dir_above_top_level))
_CATEGORY_ENDPOINT = '/v1/category/'
_PACKAGE_NAME = os.environ['RECO_API_PACKAGE_NAME']
_CORS = cors.crossdomain(origin='*',
headers=['Origin', 'X-Requested-With',
'Content-Type', 'Accept'],
methods=['GET', 'HEAD', 'OPTIONS'],
max_age=3600)
class CategoryTests(TestCase):
def __init__(self):
self.app = Flask(__name__)
self._configure_app()
for resource in self.resource_classes:
self.api.add_resource(self.resource,
self.resource.URI_TEMPLATE)
def test_status_code(self):
self.response = self.client.post(_CATEGORY_ENDPOINT,
data=json.dumps(
{'title': 'Enjoy this delicious food'}),
headers=json.dumps(
{'content-type':'application/json'}))
self.assertEqual(self.response.status_code, 200)
def test_version(self):
self.response = self.client.post(_CATEGORY_ENDPOINT,
data=json.dumps(
{"title": "eat some delicious stuff"}),
headers=json.dumps(
{'content-type':'application/json'}))
self.assertEqual(json.dumps(self.response['version']), '1')
def _configure_app(self):
self.app = Flask(__name__)
self.app.config['TESTING'] = True
self.app.debug = True
self.decorators = [_CORS]
self.app.Threaded = True
self.web_package = 'tomato.category.web'
self.package = import_module('.__init__', self.web_package) # WE BREAK HERE
self.resources = package.RESOURCE_NAMES
self.resource_classes = [ getattr(package, resource) for resource in resources ]
self.api = Api(self.app, catch_all_404s=True, decorators=self.decorators)
if __name__ == '__main__':
unittest.main()
运行这些测试时出现异常:
ImportError: 没有名为 tomato.category.web.__init__ 的模块
但 cd 进入主顶层目录,ls tomato/category/web
得到我们 __init__.py
并且它就在资源类中。
如何导入此类以便实例化 API 以运行此类中的测试? 或者,如果我完全走错了路,我应该怎么做?
最佳答案
您不需要导入 __init__
,就像您可能不会执行 from tomato.category.web import __init__
一样。您应该能够直接导入 web
包。
self.web_package = 'tomato.category.web'
self.package = import_module(self.web_package)
关于python - Python 中的 Flask 测试——在 repo 中构建一个 API,通过 import_module 对其进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27553028/