如何在测试用例中使用数据库视图 [英] How to use database view in test cases

查看:66
本文介绍了如何在测试用例中使用数据库视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在测试案例中,我无法使用数据库视图.另一方面,我能够在前端功能中使用这些数据库视图.但是当我尝试从视图中获取数据时,在测试用例中返回null.

I am unable to use database view in test cases. other hand i am able to use those database view in front end function . but when i try to get data from view in it return null in test case.

请给我建议在测试用例中使用数据库视图

Please give me suggestion for use database views in test cases

推荐答案

通过数据库视图,您是说您使用的是代表基础数据库视图的非托管模型(如

By database view do you mean you are using an unmanaged model which represents an underlying database view (as described here)?

如果是这样,我发现在单元测试期间,Django会忽略模型元数据中的 managed = False 设置,并创建一个实际表.除非您在 setUp 中明确填充此字段,否则它将为空.

If so, I have found that, during unit testing, Django ignores the managed = False setting in the model meta and creates an actual table. Unless you explicitly populate this in your setUp this will be empty.

解决这个问题的一种快捷方法是显式删除表并在测试用例的 setUp 方法中创建视图,如下所示:

A quick-and-dirty way of getting around this is to explicitly drop the table and create the view in your test case's setUp method, like this:

# Imports
from django.db import connection
from django.core.files import File

...

        # Inside your test case setUp method
        # Drop the table
        cursor = connection.cursor()
        # See note 1
        cursor.execute("SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0; DROP TABLE IF EXISTS myproject_myview; SET SQL_NOTES=@OLD_SQL_NOTES;")
        cursor.close()

        # Create the view
        # See note 2
        file_handle=open('/full/path/to/myproject/sql/create_myview.sql','r+')
        sql_file=File(file_handle)
        sql = sql_file.read()
        cursor = connection.cursor()
        cursor.execute(sql) 
        cursor.close()

注意:

  1. 这是为了解决MySQL问题,因此可能不适用于您的情况.该表仅在第一次运行 setUp 时存在.如果您尝试在随后的传递中将表删除,MySQL将生成警告-此代码禁止显示警告.

  1. This is to get around a MySQL problem so might not apply to your case. The table will only exist the first time setUp is run. If you try to drop the table on a subsequent pass MySQL will generate warnings - this code suppresses them.

此文件包含单个视图的创建代码,格式为创建或替换视图myproject_myview AS ... .我发现尝试用同一光标执行包含多个命令的文件也会导致问题.

This file contains creation code for a single view in the format CREATE OR REPLACE VIEW myproject_myview AS.... I've found that trying to execute a file containing multiple commands with the same cursor also causes problems.

这篇关于如何在测试用例中使用数据库视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆