settings.py 中的 mongoengine connect() 测试问题
我希望能够根据我是否在测试模式下启动 django 来执行条件 connect() 。
在我的settings.py中,我使用mongoengine connect()方法连接到我的数据库,但问题是,如果我运行manage.py test,我不想这样做,
有什么方法可以检查settings.py是否正在运行是否从测试导入,可能有一些标志。
类似的东西 如果不是 IN_TESTS: 连接()
I want to be able to do conditional connect() based on either I started django in testing mode or not.
in my settings.py I use mongoengine connect() method to connect to my database but the problem is that I don't want to do that if I ran manage.py test
Is there any way I can check if settings.py is being imported from tests or not, some flag maybe.
something like
if not IN_TESTS:
connect()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我正在使用自定义测试运行程序来解决这个问题。这是我基于解决方案的示例: https:// github.com/xintron/django-mongorunner/blob/master/mongorunner/testrunner.py
这样做的优点是为每个单元测试提供新数据库。
I'm solving this with a custom test runner. Here is an example I based my solution off of: https://github.com/xintron/django-mongorunner/blob/master/mongorunner/testrunner.py
This has the advantage of providing a fresh database for each of your unit tests.
虽然可以这样做,但拥有 2 个设置文件是更容易且常见的做法。一种可能的配置可能是:
您有 2 个设置文件,
lsettings.py
无法连接,settings.py
可以连接因此,在本地测试时您可以
:无法连接。
tl;dr:通过有条件地相互导入多个配置文件,而不是尝试在同一设置文件中包含条件参数,可以更轻松地管理配置差异。 YMMV。
While it is possible to do that, it is easier and common practice to have 2 settings files. One possible configuration could be:
You have 2 settings files,
lsettings.py
that doesn't connect andsettings.py
that doesSo, while locally testing you can:
And it doesn't connect.
tl;dr: It is easier to manage configuration differences by having multiple configuration files that import each other conditionally rather than trying to have conditional parameters within the same settings file. YMMV.
我不确定它是否完全万无一失,但我使用这样一个事实:在测试中,您可能会使用
./manage.py test
从命令行启动它,因此“test”是其中之一命令行参数。所以这有效:I'm not sure it's completely foolproof, but I use the fact that in a test, you will have probably started it from the command line with
./manage.py test
, so 'test' is one of the command-line args. So this works:我所做的是使用
register_connection
,然后在测试时模拟连接。在我定义 Mongo 文档的文件中,我有以下内容:
然后在测试中我使用 mock 库 更改连接的行为(也可以模拟
connection
子模块上的函数之一,如get_db
),如下所示:What I do is use
register_connection
, and then mock the connections on test.In the file that I define the Mongo Documents I have this:
Then in the tests I use the mock library to change the behave of connections (it would be possible too to mock one of the functions on the
connection
sub module likeget_db
) like this: