前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >如何在 Django 中测试模型表单

如何在 Django 中测试模型表单

原创
作者头像
用户11021319
发布2024-03-13 09:32:26
1180
发布2024-03-13 09:32:26

1. 问题背景

在编写测试用例来测试 FilterForm 时,遇到了以下问题:

代码语言:javascript
复制
class MyTestCreateFilter(TestCase):

  def test_createfilter(self):
    self.client = Client()     
    self.user = User.objects.create_superuser(username='bizi111',email='test5@example.com',password='bizi111')
    self.user = authenticate(username='bizi111', password='bizi111')
    #print self.user
    self.factory = RequestFactory()
    request = self.factory.get('/filter/new')
    request.user = self.user
    response = create_or_edit_filter(request)
    self.assertEqual(response.status_code, 200)
    

    filterform = FilterForm()
    #print filterform.is_valid()
    # http://jshk.com.cn/mb/reg.asp?kefu=zhangyajie
    form_data = {'keyword': 'it','industry':'it','zip_code':'50005','distance':30}

    filteform = FilterForm(form_data)

    self.assertEqual(filteform.is_valid(), True)

其中 FilterForm 有一个 clean 方法:

代码语言:javascript
复制
    def clean(self):
        #print self.instance.user_profile
        user_profile = self.instance.user_profile
        keyword = self.cleaned_data.get("keyword")
        if Filter.objects.filter(user_profile=user_profile, keyword=keyword).exclude(id=self.instance.id).count() > 0:
            msg = u"A filter with that keyword already exists!"
            self._errors["keyword"] = self.error_class([msg])

        return self.cleaned_data

在运行测试时,出现错误:

代码语言:javascript
复制
File "/home/suma/workspace2/bizintro/bizintro/forms.py", line 80, in
  clean
      user_profile = self.instance.user_profile   File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py",
  line 343, in get
      raise self.field.rel.to.DoesNotExist DoesNotExist

2. 解决方案

根据错误信息,可以发现问题是 FilterForm 是一个绑定表单,需要有一个模型实例作为上下文。在测试用例中,没有为 FilterForm 设置模型实例。

为了解决这个问题,可以在测试用例中添加以下代码:

代码语言:javascript
复制
filterform = FilterForm()
#print filterform.is_valid()
form_data = {'keyword': 'it','industry':'it','zip_code':'50005','distance':30}

filterform = FilterForm(form_data)

filterform.instance = # Some object here...


self.assertEqual(filterform.is_valid(), True)

其中,需要将 # Some object here... 替换为一个有效的模型实例。


代码例子:

代码语言:javascript
复制
class MyTestCreateFilter(TestCase):

  def test_createfilter(self):
    self.client = Client()     
    self.user = User.objects.create_superuser(username='bizi111',email='test5@example.com',password='bizi111')
    self.user = authenticate(username='bizi111', password='bizi111')
    #print self.user
    self.factory = RequestFactory()
    request = self.factory.get('/filter/new')
    request.user = self.user
    response = create_or_edit_filter(request)
    self.assertEqual(response.status_code, 200)

    filterform = FilterForm()
    #print filterform.is_valid()
    form_data = {'keyword': 'it','industry':'it','zip_code':'50005','distance':30}

    filterform = FilterForm(form_data)

    filterform.instance = Filter()  # 创建一个 Filter 模型实例

    self.assertEqual(filterform.is_valid(), True)

按照上述代码,就可以成功运行测试用例,并不会出现 DoesNotExist 的错误。

标题: 线段交点检测及其解决方案

  1. 问题背景 给定两个列表,我们希望找出它们在相同索引处相交的点。例如,如果我们提供两个列表 [9, 8, 7, 6, 5] 和 [3, 4, 5, 6, 7],目标是找到它们在索引 3 处相交的点。常见的解决方案涉及遍历并比较两个列表中的每个元素,但我们希望探索更具数学性、高效的方法。
  2. 解决方案
    • 集合交集法:一种常用方法是使用集合的交集运算。我们可以将每个列表的坐标视为一个集合,计算它们的交集。例如,我们计算 (9, 0), (8, 1), (7, 2), (6, 3), (5, 4) 和 (3, 0), (4, 1), (5, 2), (6, 3), (7, 4) 的交集,发现 (6, 3) 和 (7, 4) 同时出现在两个列表中。因此,我们找到这两个列表在索引 3 和 4 处相交。
    • 线性方程法:另一种方法是将列表中的元素视为线段,使用线性方程求解线段相交点。我们可以构造一个线性方程组,其中每个方程代表列表中的一条线段。求解该方程组,可以得到两个线段的交点。例如,我们构造方程组 y = 9 - x、y = 3 + x。求解得 x = 6,y = 3。因此,这两个列表在点 (6, 3) 处相交。

代码例子:

代码语言:javascript
复制
# 集合交集法
def find_intersection_by_set(list1, list2):
    """
    Find the intersection points of two lists using set intersection.

    Args:
        list1: The first list of coordinates.
        list2: The second list of coordinates.

    Returns:
        A list of tuples representing the intersection points.
    """
    intersecting_points = set(enumerate(list1)).intersection(set(enumerate(list2)))
    return [(index, value) for index, value in intersecting_points]


# 线性方程法
def find_intersection_by_linear_equation(list1, list2):
    """
    Find the intersection points of two lists using linear equation.

    Args:
        list1: The first list of coordinates.
        list2: The second list of coordinates.

    Returns:
        A list of tuples representing the intersection points.
    """
    intersecting_points = []
    for i, (A0, B0, A1, B1) in enumerate(zip(list1, list2, list1[1:], list2[1:])):
        # Check integer intersections
        if A0 == B0:
            intersecting_points.append((i, A0))
        if A1 == B1:
            intersecting_points.append((i + 1, A1))

        # Check for intersection between points
        if (A0 > B0 and A1 < B1) or (A0 < B0 and A1 > B1):
            intersection_index = solve_linear_equation(A0, A1, B0, B1)
            intersecting_points.append((i + intersection_index, (A1 - A0) * intersection_index + A0))

    return intersecting_points


def solve_linear_equation(A0, A1, B0, B1):
    """
    Solve the linear equation (A0, A1) and (B0, B1) and return the intersection index.

    Args:
        A0: The y-coordinate of the first point of the first line.
        A1: The y-coordinate of the second point of the first line.
        B0: The y-coordinate of the first point of the second line.
        B1: The y-coordinate of the second point of the second line.

    Returns:
        The intersection index.
    """
    return (B0 - A0) / (A1 - A0)

最后,根据问题的情况,我们可以使用任一方法来找到列表 [9, 8, 7, 6, 5] 和 [3, 4, 5, 6, 7] 在索引 3 处的交点。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 问题背景
  • 2. 解决方案
  • 标题: 线段交点检测及其解决方案
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档