我正在尝试编写基于py.test的测试用例。我的test.py是
!flask/bin/python
import pytest
import config
@pytest.fixture
def app(request):
SQLALCHEMY_DATABASE_URI = 'postgresql://sanjeev:sanjeev@localhost:5432/app'
config[SQLALCHEMY_DATABASE_URI]
db.create_all()
def fin():
db.session.remove()
db.drop_all()
request.addfinalizer(fin)
def test_foo(app):
pass
我的config.py文件看起来像
import os
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
basedir = os.path.abspath(os.path.dirname(__file__))
CSRF_ENABLED = True
SECRET_KEY = 'you-will-never-guess'
SQLALCHEMY_DATABASE_URI = 'postgresql://sanjeev:sanjeev@localhost:5432/app'
SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository')
但我收到错误TypeError:'module'对象没有属性' getitem '
下面是错误日志跟踪
ERROR at setup of test_foo
request = <SubRequest 'app' for <Function 'test_foo'>>
@pytest.fixture
def app(request):
SQLALCHEMY_DATABASE_URI = 'postgresql://sanjeev:sanjeev@localhost:5432/app'
config[SQLALCHEMY_DATABASE_URI]
TypeError: 'module' object has no attribute '__getitem__'
test.py:20: TypeError
答案 0 :(得分:4)
导入模块config
。因此,您无法像列表一样访问它:
>>> import math
>>> math[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object has no attribute '__getitem__'
>>>
相反,如果你想从shell运行它,你可以使用sys.argv
,或者将它作为函数传递:
<强> sys.argv
强>:
myfile.py
:
import sys
print sys.argv[1:]
<强>运行:强>
bash-3.2$ python myfile.py Hello World!
['Hello', 'World!']
bash-3.2$
传入:
myfile.py
:
def test(variable):
print variable
<强>运行:强>
>>> import myfile
>>> myfile[56]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object has no attribute '__getitem__'
>>> myfile.test(56)
56
>>>
您的更新文件 test.py
:
!flask/bin/python
import pytest
import config
@pytest.fixture
def app(request):
SQLALCHEMY_DATABASE_URI = 'postgresql://sanjeev:sanjeev@localhost:5432/app'
config.take(SQLALCHEMY_DATABASE_URI)
db.create_all()
def fin():
db.session.remove()
db.drop_all()
request.addfinalizer(fin)
def test_foo(app):
pass
<强> config.py
强>
import os
from sqlalchemy.ext.declarative import declarative_base
global myvar
def take(variable):
global myvar
myvar = variable
print myvar #Just a test to see if it works
Base = declarative_base()
basedir = os.path.abspath(os.path.dirname(__file__))
CSRF_ENABLED = True
SECRET_KEY = 'you-will-never-guess'
SQLALCHEMY_DATABASE_URI = 'postgresql://sanjeev:sanjeev@localhost:5432/app'
SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository')
我的虚拟文件config.py
:
global myvar
def take(variable):
global myvar
myvar = variable
def show():
global myvar
print myvar
我的虚拟文件test.py
:
import config
variable = [6, 7, 8]
config.take(variable)
config.show()
正在运行: 这应打印[6, 7, 8]
bash-3.2$ python test.py
[6, 7, 8]
bash-3.2$