标签: model-mommy

模范妈妈:多个食谱与单个食谱有外键关系

我对 ModelMommy 的这种烦恼已经有一段时间了,但我不知道如何正确地做到这一点。

让我们假设一个简单的关系:

class Organization(models.Model):
    label = models.CharField(unique=True)

class Asset(models.Model):
    organization = models.ForeignKey(Organization)
    label = models.CharField(unique=True)
Run Code Online (Sandbox Code Playgroud)

和食谱:

from model_mommy.recipe import Recipe, foreign_key


organization_recipe = Recipe(Organization, label='My Organization') 
asset1_recipe = Recipe(Asset,
                      organization=foreign_key(organization_recipe),
                      label='asset 1')
asset2_recipe = Recipe(Asset,
                      organization=foreign_key(organization_recipe),
                      label='asset 2')
Run Code Online (Sandbox Code Playgroud)

现在,当我制作这些资产配方时,我收到错误:

>> asset1 = asset1_recipe.make()
>> asset2 = asset2_recipe.make()
IntegrityError: duplicate key value violates unique constraint "organizations_organization_label_key"
DETAIL:  Key (label)=(My Organization) already exists.
Run Code Online (Sandbox Code Playgroud)

这可以通过将 asset1 的组织作为参数提供给 asset2 的 make 方法来解决:

>> asset1 = asset1_recipe.make()
>> asset2 = asset2_recipe.make(organization=asset1.organization)
Run Code Online (Sandbox Code Playgroud)

但必须有一种更简单、更干净的方法来做到这一点。

编辑 …

testing django model-mommy

5
推荐指数
1
解决办法
1634
查看次数

使用Model Mommy测试登录

我在功能测试中测试登录时遇到问题.我正在使用模型妈妈用密码创建一个用户调用Megan但是我的测试仍然没有通过,因为当发送信息时它会抛出并在html页面上输入错误"请输入正确的用户名和密码.请注意两者字段可能区分大小写." 所以我怀疑测试用户没有被创建或类似的东西.

功能测试:

from django.test import LiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from model_mommy import mommy
from django.contrib.auth.models import User


class NewUserTest(LiveServerTestCase):

    def setUp(self):
        self.user = mommy.make('User', 
        username='Megan',
        password = 'password',
        is_active = True)

        self.browser = webdriver.Firefox()
        self.browser.implicitly_wait(15)

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

    def test_user_can_start_a_new_movement(self):
        #some code
        self.browser.get(self.live_server_url)
        self.assertIn('P2', self.browser.title)

        #Megan first logs in 
        login_link = self.browser.find_element_by_link_text('Log In')
        login_link.click()
        #Megan then puts in her user information
        username = self.browser.find_element_by_id('id_username')
        password = self.browser.find_element_by_id('id_password')
        submit = self.browser.find_element_by_id('id_submit')
        username.send_keys('Megan')
        password.send_keys('password')
        submit.click()
Run Code Online (Sandbox Code Playgroud)

的login.html …

django django-testing django-tests model-mommy

1
推荐指数
1
解决办法
1066
查看次数