StaticLiveServerTestCase 服务器错误 500

时间:2021-04-27 20:20:36

标签: django django-testing django-tests

主 urls.py 文件:

urlpatterns = [

    path(
        'admin/',
        admin.site.urls
    ),

    path(
        '',
        include(
            'employee.urls'
        )
    ),

    path(
        '',
        include(
            'epos.urls'
        )
    ),

    path(
        '',
        include(
            'supplier.urls'
        )
    ),

]

epos.urls:

urlpatterns = [
    path(
        '',
        home_view,
        name='home'
    ),

home_view:

@login_required
def home_view(request):
    # Get all categories
    categories = Category.objects.all()

    # Get the first category which will be selected by default
    selected_category = categories.first()

    # Get the order_items for the selected category (first category)
    products = Product.objects.filter(
        category=selected_category.id
    )

    user = request.user

    tax = Tax.objects.latest('id')

    context = {
        'categories': categories,
        'user': user,
        'title': "EPOS",
        'products': products,
        'selected_category': selected_category,
        'tax': tax
    }

    return render(request, 'epos/epos.html', context)

测试用例:

class LoginTests(StaticLiveServerTestCase):

    fixtures = ['fixtures/employee/employee_data.json']

    def setUp(self):

        self.browser = webdriver.Chrome()
        self.browser.get(self.live_server_url)
        self.browser.maximize_window()

    def tearDown(self):
        self.browser.quit()

    def test_login_when_clocked_in(self):
        import ipdb;ipdb.set_trace()
        login_button = self.browser.find_element_by_xpath(
            '//button[normalize-space()="Login"]'
        )

        clock_in_out_button = self.browser.find_element_by_xpath(
            '//button[normalize-space()="Clock In/Out"]'
        )

        pin_input = self.browser.find_element_by_id(
            'pin'
        )

        pin_code = 'some pin'
        employee_name = 'some name'

        pin_input.send_keys(pin_code)
        
        clock_in_out_button.click()

        time.sleep(10)
        login_button.click()

settings.py


ROOT_URLCONF = 'allPOS.urls'
LOGIN_URL = '/login/'

当测试登录时,我被重定向到 localhost:46497/ 的主网页,但我收到的是服务器错误 500,而不是该页面。 此错误仅在测试时发生。此外,如果我添加另一个路径,例如localhost:46497/analytics 它按预期打开网页。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

经过 4 个小时的调试,我发现问题与数据库为空有关。

我想要渲染的网页期望通过一些模型,由于数据库为空,这些模型没有通过,因此崩溃。在正常情况下( ./manage.py runserver )如果 DEBUG=True 它会告诉你什么是错的,但由于某种原因 StaticLiveServerTestCase 没有这个选项,或者至少我不知道。如果有人知道如何为 StaticLiveServerTestCase 启用一些调试器,请随时添加到此线程。

所以我做了什么: ./manage.py dumpdata order.tax > data.json - 我将需要的数据转储到 json 文件中,并在测试用例的开头将该数据添加到 fixture

希望这对有同样问题的人有所帮助!

相关问题