在我的 Django 项目下有一些应用程序,它们都有单元测试。我现在正在工作的其中之一应该只包含在开发/阶段环境中,因此我使用环境变量来启用它。
当此变量存在时,它会被添加到 INSTALLED_APPS 并且工作正常,问题是 Django 正在执行此应用程序的测试,即使它不在 INSTALLED_APPS 中,并且失败并显示以下消息:
ImportError:无法导入测试模块:debug.tests.unit.test_services`
...(追溯信息)...
RuntimeError:模型类 debug.models.Email 未声明显式 app_label 并且不在 INSTALLED_APPS 中的应用程序中。
app_label当我在这个应用程序中定义class Meta模型时,错误是不同的,它说它找不到表,我认为这是因为该应用程序不在 INSTALLED_APPS 中,所以它的迁移没有执行。
操作错误:没有这样的表:debug_email
我不确定为什么 Django 对所有应用程序执行测试,但不是迁移。
我是否缺少 Django 测试配置中的某些内容?
我有一堂课
class PlaylistManager(models.Manager):
def add_playlist(self, name):
playlist = Playlist(name=name)
playlist.save()
return playlist
def get_playlist_with_id(self, id):
return super(PlaylistManager, self).get_query_set().filter(pk=id)
class Playlist(models.Model):
name = models.CharField(max_length=30)
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
deleted = models.BooleanField(default=False)
objects = PlaylistManager() # is a customer manager
def __repr__(self):
return '<Playlist name:%s, date_created:%s, date_modified:%s, deleted:%s>' % \
(self.name, self.date_created, self.date_modified, self.deleted)
class Meta:
db_table = 'playlists'
Run Code Online (Sandbox Code Playgroud)
和我test一样
def test_get_playlist(self):
playlist = Utility.add_playlist()
self.assertEqual(Playlist.objects.get_playlist_with_id(playlist.id), playlist)
class Utility():
@staticmethod
def add_playlist(playlist_name=PLAYLIST):
return Playlist.objects.add_playlist(playlist_name)
Run Code Online (Sandbox Code Playgroud)
当我运行测试时,我发现错误为
AssertionError: [<Playlist name:playlist, …Run Code Online (Sandbox Code Playgroud) 对于长方法的名称,PEP8的正确方法是什么?我有一个自我描述方法的单元测试:
def success_if_buying_price_item_when_participating_and_progression_is_100_percent(self):
Run Code Online (Sandbox Code Playgroud)
但不幸的是,这个(太长?)方法达到了80个字符的行限制.
我应该重命名它并在代码中添加描述还是有另一种方式?
通过将选项附加到Tox,如何将选项附加到Tox运行命令?具体来说,您如何使用Tox运行特定的Django单元测试?
我正在尝试将Tox包装在一些Django单元测试中,并且可以使用运行所有的单元tox测试django-admin.py test --settings=myapp.tests.settings myapp.tests.Tests。
但是,我想myapp.tests.Tests.test_somespecificthing在进行特定的测试,这意味着告诉Tox将“ .test_somespecificthing”附加到它运行的命令的末尾,但是我不知道该怎么做。
文档说使用“-”将其他参数传递给基础命令,但这似乎不起作用。
我们使用 django 迁移 (django v1.7+) 更改了我们的数据库。数据库中存在的数据不再有效。
基本上我想通过在单元测试中测试迁移,构建迁移前数据库,添加一些数据,应用迁移,然后确认一切顺利。
怎么做:
加载单元测试时阻止新的迁移
我找到了一些关于覆盖的东西,settings.MIGRATION_MODULES但不知道如何使用它。当我检查时,executor.loader.applied_migrations它仍然列出了所有内容。我可以阻止新迁移的唯一方法是实际删除文件;不是我可以使用的解决方案。
在 unittest 数据库中创建一条记录(使用旧模型)
如果我们可以阻止迁移,那么这应该非常简单。 myModel.object.create(...)
应用迁移
我想我现在可能可以解决这个问题,因为我已经找到了test_executor:设置一个指向迁移文件的计划并执行它?嗯,对吗?有任何代码:-D
确认数据库中的旧数据现在与新模型匹配
同样,我希望这应该很简单:只需获取迁移前创建的实例并确认它已以所有正确的方式更改。
所以挑战真的只是解决如何防止单元测试应用最新的迁移脚本,然后在我们准备好时应用它?
也许我有错误的方法?我是否应该创建装置,并在最后确认它们都很好?是在应用迁移之前还是在它们全部完成之后加载夹具?
通过使用MigrationExecutor和挑选特定的迁移,.migrate我已经能够,也许?,将它回滚到特定状态,然后一个一个地向前滚动。但这令人怀疑;由于缺乏实际的 ALTER TABLE 指令,目前正在追逐 sqlite 捏造。陪审团还在外面。
在单元测试视图时,我似乎无法模拟表单的行为。
我的表单是一个简单的 ModelForm 并驻留在profiles.forms. 该视图(再次)是一个简单的视图,它检查表单是否有效然后重定向。
视图.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from profiles.forms import ProfileForm
def home(request):
form = ProfileForm()
if request.method == 'POST':
form = ProfileForm(request.POST)
if form.is_valid():
profile = form.save()
return HttpResponseRedirect(reverse("thanks"))
Run Code Online (Sandbox Code Playgroud)
我的测试是这样的:
class TestViewHomePost(TestCase):
def setUp(self):
self.factory = RequestFactory()
def test_form(self):
with mock.patch('profiles.views.ProfileForm') as mock_profile_form:
mock_profile_form.is_valid.return_value = True
request = self.factory.post(reverse("home"), data={})
response = home(request)
logger.debug(mock_profile_form.is_valid.call_count) # "0"
Run Code Online (Sandbox Code Playgroud)
is_valid 没有在模拟上被调用,这意味着 ProfileForm 没有被修补。
我在哪里做错了?
我正在尝试编写一些单元测试并使用它们运行它们,manage.py test但由于django_migrations某种原因脚本无法创建表。
这是完整的错误:
Creating test database for alias 'default'...
Traceback (most recent call last):
File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\utils.py", line 83, in _execute
return self.cursor.execute(sql)
psycopg2.ProgrammingError: no schema has been selected to create in
LINE 1: CREATE TABLE "django_migrations" ("id" serial NOT NULL PRIMA...
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\migrations\recorder.py", line 55, in ensure_schema
editor.create_model(self.Migration)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\base\schema.py", line 298, in …Run Code Online (Sandbox Code Playgroud) 我正在为一个用 Python3.6/Django 2.0 制作的 web 应用程序编写测试,我有以下情况:
class TestFoo(TestCase):
def test_a(self):
obj = Foo.objects.create(a = "bar")
expectation = {"a" : "bar"}
self.assertEquals(obj.method_x(), expectation)
def test_b(self):
obj = Foo.objects.create(a = "baz")
expectation = {"a" : "baz"}
self.assertEquals(obj.method_x(), expectation)
def test_c(self):
obj = Foo.objects.create(a = "bar")
obj2 = Foo.objects.create(a = "baz")
obj.b.add(obj2)
expectation = {"a" : "bar", "b" : {"a": "baz"}}
self.assertEquals(obj.method_x(), expectation)
Run Code Online (Sandbox Code Playgroud)
据我了解,每个测试都是单独运行的,但是当我与测试 a 或 b 一起运行 test_c 时,所有测试都会失败。基本上是这样的:
我正在用oauth2_provider我的rest_framework。我正在尝试为我的api编写测试用例。我已经获得了访问令牌。但是我无法在使用access token中验证用户使用的APIClient
curl命令APIClient。
curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/api/v1/users/current/
Run Code Online (Sandbox Code Playgroud)
我试过了
client.get('/api/v1/users/current/', headers={'Authorization': 'Bearer {}'.format(self.access_token)})
Run Code Online (Sandbox Code Playgroud)
和
client.credentials(HTTP_AUTHORIZATION='Token ' + self.access_token)
Run Code Online (Sandbox Code Playgroud)
这是片段的一部分
from rest_framework.test import APIClient
from rest_framework.test import APITestCase
....
class APITest(APITestCase):
def setUp(self):
...
self.client = APIClient()
...
response = self.client.post('/api/v1/oauth2/token/', post_data)
self.access_token = response.json()['access_token']
def test_get_current_user(self):
client.get('/api/v1/users/current/', headers={'Authorization': 'Bearer {}'.format(self.access_token)})
Run Code Online (Sandbox Code Playgroud)
我正在回应
<HttpResponseForbidden status_code=403, "text/html; charset=utf-8">
Run Code Online (Sandbox Code Playgroud) django django-testing oauth-provider django-unittest django-rest-framework
我刚刚开始学习单元测试并遇到了这个问题。
\n\n我得到这样的项目结构(现在是 it\xe2\x80\x99s Django 1.6.2):
\n\n./manage.py\n./myproject\n./myproject/urls.py\n./myproject/myapp/\n./myproject/myapp/urls.py\n./myproject/myapp/views.py\n./tests/\n./test/test_example.py\nRun Code Online (Sandbox Code Playgroud)\n\n在 ./myproject/urls.py 我有:
\n\nfrom django.conf.urls import patterns, include, url\nurlpatterns = patterns('',\n url(r'^myapp/', include('myproject.myapp.urls')),\n)\nRun Code Online (Sandbox Code Playgroud)\n\n在 ./myproject/myapp/urls.py 我有:
\n\nfrom django.conf.urls import patterns, url\n\nurlpatterns = patterns('myproject.myapp.views',\n url(r'^example1/$', 'itemlist'), \n url(r'^example1/(?P<item_id>\\w+)/$', 'item'),\n)\nRun Code Online (Sandbox Code Playgroud)\n\n我编写了基本测试并将其放入./test/test_example.py
\n\nimport unittest\nfrom django.test import Client\n\nclass PagesTestCase(unittest.TestCase): \n def setUp(self):\n self.client = Client()\n\n def test_itemlist(self): \n response = self.client.get('/myapp/example1/')\n self.assertEqual(response.status_code, 200)\n\n def test_item(self): \n response = self.client.get('/myapp/example1/100100/')\n self.assertEqual(response.status_code, 200)\nRun Code Online (Sandbox Code Playgroud)\n\n我从 shell 运行这个测试,如下所示:
\n\ncd ./tests\npython manage.py test\n …Run Code Online (Sandbox Code Playgroud) django-unittest ×10
django ×9
python ×4
unit-testing ×4
django-apps ×1
django-forms ×1
mocking ×1
pep8 ×1
postgresql ×1
python-3.x ×1
tox ×1