Django assertRedirects测试由于http:// testserver前缀而失败

时间:2018-06-20 05:34:32

标签: django django-testing django-1.11

我想测试/sitemap.xml/重定向到/sitemap.xml。我正在使用以下代码:

res = self.client.get('/sitemap.xml/')
self.assertRedirects(res, '/sitemap.xml', status_code=301)

并出现以下错误:

AssertionError: Response redirected to 'http://testserver/sitemap.xml', expected '/sitemap.xml'

我应该如何编写此测试以避免testserver冲突?

2 个答案:

答案 0 :(得分:7)

我猜想重定向网址/响应是使用build_absolute_uri或类似的东西通过全路径创建的?只是一个猜测...

首先,从长远来看,使用urlname代替硬编码路径可能会更容易。 url = reverse('sitemap.xml'),url = reverse('sitemap.xml')+'/'给出一些想法...

Django naming url patterns

无论如何,这可以解决您的问题,而不必担心主机。

res = self.client.get('/sitemap.xml/')
expected_url = res.wsgi_request.build_absolute_uri('/sitemap.xml')
self.assertRedirects(res, expected_url, status_code=301)

(在Django 1.10.6上测试)

答案 1 :(得分:3)

我认为您可以使用<Page.Resources> <!-- Default style for CalendarViewDayItem --> <Style TargetType="CalendarViewDayItem"> <Setter Property="MinWidth" Value="40" /> <Setter Property="MinHeight" Value="40" /> <Setter Property="Margin" Value="1" /> <Setter Property="Padding" Value="0, 0, 0,0" /> <Setter Property="UseSystemFocusVisuals" Value="{StaticResource UseSystemFocusVisuals}" /> <Setter Property="FocusVisualMargin" Value="-2" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="CalendarViewDayItem"> <!-- For CalendarViewDayItem, TextBlock visual is created and handled by code and we can't see it from the style. --> <!-- CCalendarViewBaseItemChrome creates and appends a TextBlock in the visual after the ControlTemplate is applied --> <!-- VSM needs a container and that's why Grid is added. But we don't need the rendering of Grid so We set width to 0 --> <Grid x:Name="Root" Width="40" Height="8" Background="Red" VerticalAlignment="Bottom"> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal" /> <VisualState x:Name="PointerOver"> <VisualState.Setters> <Setter Target="Root.(RevealBrush.State)" Value="PointerOver" /> </VisualState.Setters> </VisualState> <VisualState x:Name="Pressed"> <VisualState.Setters> <Setter Target="Root.(RevealBrush.State)" Value="Pressed" /> </VisualState.Setters> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> </Page.Resources>

类似这样的东西:

request.path