使用以下代码,我得到了这个错误的结果:nose.proxy.AssertionError: 302 != 200 : 无法检索重定向页面 '/mes_dossiers/': 响应代码为 302(预期为 200)
我的代码有什么问题?
#test.py
from django.test import TestCase, RequestFactory, Client
from ..models import *
from ..views import *
from django.core.management import call_command
class Cas(TestCase):
def setUp(self):
call_command('loaddata', 'fixture_users.json', verbosity=1)
call_command('loaddata', 'xxxxx_tests_xxxx.yaml',
verbosity=1)
def test_dossier_duplicate(self) :
request = self.factory.get('/dossier/3/copier/', follow = True)
request.user = User.objects.get(id=3)
pk = 3
response = dossier_duplicate(request, pk)
response.client = Client()
self.assertRedirects(response,'/mes_dossiers/',status_code=302,
target_status_code=200)
#urls.py
urlpatterns = [
url(r'^dossier/(?P<pk>[0-9]+)/copier/$',views.dossier_duplicate),
]
#views.py
@login_required(login_url="/accounts/login/")
def dossier_duplicate(request, pk):
dossier = get_object_or_404(Dossier, pk=pk)
groupe …Run Code Online (Sandbox Code Playgroud) 我有一个包含一行的 Dockerfile RUN py.test -vv。
FROM bitnami/python:3.6-prod
#MORE DIRECTIVES
RUN py.test -vv
COPY . /files
WORKDIR /files
EXPOSE 8080
Run Code Online (Sandbox Code Playgroud)
当我运行时docker-compose build,我收到此错误。
Step 16/21 : RUN py.test -vv
---> Running in 5b3f55f10025
============================= test session starts ==============================
platform linux -- Python 3.6.9, pytest-5.2.1, py-1.8.0, pluggy-0.13.0 -- /opt/bitnami/python/bin/python
cachedir: .pytest_cache
rootdir: /
plugins: ordering-0.6, cov-2.8.1, docker-compose-3.1.2, celery-4.3.0
collecting ... collected 0 items / 1 errors
==================================== ERRORS ====================================
________________________ ERROR collecting test session _________________________
opt/bitnami/python/lib/python3.6/site-packages/_pytest/config/__init__.py:456: in _importconftest
return self._conftestpath2mod[key] …Run Code Online (Sandbox Code Playgroud) 我正在尝试用Django/unittest学习单元测试.
这些是我的模型的简单版本:
class Device(models.Model):
name = models.CharField(max_length=100)
def get_ips(self):
return DeviceIP.objects.filter(device=self.id)
class DeviceIP(models.Model):
ip = models.GenericIPAddressField()
device = models.ForeignKey(Device)
Run Code Online (Sandbox Code Playgroud)
这是我提出的测试代码:
from django.test import TestCase
class DeviceTest(TestCase):
def test_get_ips(self):
device = Device()
device.name = 'My Device'
ip1 = DeviceIP()
ip1.ip = '127.0.0.1'
ip1.device = device
ip1.save()
ip2 = DeviceIP()
ip2.ip = '127.0.0.2'
ip2.device = device
ip2.save()
ip3 = DeviceIP()
ip3.ip = '127.0.0.3'
ip3.device = device
ip3.save()
self.assertEqual(device.get_ips(), [ip1, ip2, ip3])
Run Code Online (Sandbox Code Playgroud)
测试结果失败,因为AssertionError即使字符串表示device.get_ips()和[ip1, ip2, ip3]相同.
如果我尝试使用self.assertListEqual …
我有一个基于类的视图
class HomePage(View):
def get(self, request):
return HttpResponse('<p>This is content.</p>')
Run Code Online (Sandbox Code Playgroud)
和url-pattern定义如下:
urlpatterns = patterns('',
url(r'^$', HomePage.as_view()),
)
Run Code Online (Sandbox Code Playgroud)
为了这个模式解析为当前的视图函数,我写了一个这样的测试:
class HomePageTest(TestCase):
def test_root_url_resolves_to_home_page_view(self):
found = resolve('/')
self.assertIsInstance(found.func, HomePage)
Run Code Online (Sandbox Code Playgroud)
通过运行此单元测试,我收到以下错误:
self.assertIsInstance(found.func, HomePage)
AssertionError: <function HomePage at 0x7f85dd2c7840> is not an instance of <class 'web.views.HomePage'>
Run Code Online (Sandbox Code Playgroud)
任何想法如何测试这种情况?
我有一个用于登录 django 项目的设置,我想使用assertLogs 进行测试。
我使用了文档中提供的示例:https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertLogs
with self.assertLogs('foo', level='INFO') as cm:
logging.getLogger('foo').info('first message')
logging.getLogger('foo.bar').error('second message')
self.assertEqual(cm.output, ['INFO:foo:first message',
'ERROR:foo.bar:second message'])
Run Code Online (Sandbox Code Playgroud)
我的 django 设置如下:
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
},
'simple': {
'format': '%(levelname)s %(message)s'
},
'standard': {
'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
},
},
'filters': {
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
},
},
'handlers': {
'console': {
'level': 'INFO',
'filters': ['require_debug_true'],
'class': 'logging.StreamHandler',
},
'default': {
'level':'DEBUG',
'class':'logging.handlers.RotatingFileHandler', …Run Code Online (Sandbox Code Playgroud) 我正在使用Django测试客户端,django.test.client.Client在Django应用程序中测试一些视图.特别是,我正在测试一个视图调用get_object_or_404方法并且该对象不存在的情况,因此应该返回404.
我的测试代码如下所示:
class ViewTests(TestCase):
fixtures=['test.json']
def test_thing_not_there_get(self):
url = '/foo/30afda98-b9d7-4e26-a59a-76ac1b6a001f/'
c = django.test.client.Client()
response = c.get(url)
self.assertEqual(response.status_code, 404)
Run Code Online (Sandbox Code Playgroud)
但是,我得到的是视图代码中未处理的异常错误:
python projects/unittests/manage.py test
Creating test database for alias 'default'...
......ERROR:root:Unhandled Exception on request for http://testserver/foo/30afda98-b9d7-4e26-a59a-76ac1b6a001f/
Traceback (most recent call last):
File "/Users/lorin/.virtualenvs/myvenv/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/Users/lorin/.virtualenvs/myvenv/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 39, in wrapped_view
resp = view_func(*args, **kwargs)
File "/Users/lorin/.virtualenvs/myvenv/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 52, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/lorin/django-myvenv/apps/myvenv_desktop/views.py", line 85, in foo_view
instance …Run Code Online (Sandbox Code Playgroud) 我有一个基于django类的视图,我正在装饰.不幸的是,装饰器进行外部调用以进行状态检查,这超出了单元测试应该做的范围,所以我想覆盖装饰器在单元测试期间什么都不做.这是我的装饰者:
decorators.py
def status_check(func):
@wraps(func)
def wrapped(request, *args, **kwargs):
uri = settings.SERVER_URI
status_code = None
bad_status = [404, 500]
try:
response = requests.head(uri)
except requests.ConnectionError as err:
LOGGER.error('Server is hosed! Oh Noes! Error: %s ' % (err))
raise Http404
except Exception as err:
LOGGER.error('Some crazy stuff is happening. Its Bad. '
'Error: %s' % (err))
raise Http404
status_code = response.status_code
if not status_code or status_code in bad_status:
LOGGER.error('Awww Snap! Server is not happy: %s' % (status_code))
raise Http404
return func(request, …Run Code Online (Sandbox Code Playgroud) 我有一个Django单元测试,我想在其中放置print语句用于调试目的,但显然django正在抑制它们.我怎样才能打印变量的值?我可能能够破解断言等,但想知道人们如何做到这一点.
我有自定义的save_model管理员即
class MyModelAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
# some more question code here
obj.save()
Run Code Online (Sandbox Code Playgroud)
现在,我想测试 MyModelAdminsave_model功能。我尝试发布如下:
class MyModelAdminSaveTestCase(TestCase):
def setUp(self):
# setup code here
def test_save_model(self):
'''Test add employee
'''
my_obj = {
'name': 'Tester',
'address': '12 test Test',
'city': 'New York',
'state': 'NY',
}
self.client.login(username=self.user, password=self.pwd)
response = self.client.post(reverse('admin:mymodel_mymodel_add'), my_obj, follow=True)
self.assertEqual(response.status_code, 200)
self.assertEqual(MyModel.objects.count(), 1)
Run Code Online (Sandbox Code Playgroud)
但是,测试失败:
self.assertEqual(MyModel.objects.count(), 1)
AssertionError: 0 != 1
Run Code Online (Sandbox Code Playgroud) 在我的 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 测试配置中的某些内容?
django-unittest ×10
django ×9
python ×5
python-3.x ×2
debugging ×1
django-apps ×1
django-views ×1
logging ×1
pytest ×1
testing ×1
unit-testing ×1