2017-08-12 104 views
0

我無法正確使用工廠男孩。遞歸錯誤:使用工廠男孩時

這就是我的工廠:

import factory 

from harrispierce.models import Article, Journal, Section 

class JournalFactory(factory.Factory): 
    class Meta: 
     model = Journal 

    name = factory.sequence(lambda n: 'Journal%d'%n) 

    @factory.post_generation 
    def sections(self, create, extracted, **kwargs): 
     if not create: 
      # Simple build, do nothing. 
      return 

     if extracted: 
      # A list of groups were passed in, use them 
      for section in extracted: 
       self.sections.add(section) 


class SectionFactory(factory.Factory): 
    class Meta: 
     model = Section 

    name = factory.sequence(lambda n: 'Section%d'%n) 

和我的測試:

import pytest 
from django.test import TestCase, client 
from harrispierce.factories import JournalFactory, SectionFactory 

@pytest.mark.django_db 
class TestIndex(TestCase): 

    @classmethod 
    def setUpTestData(cls): 
     cls.myclient = client.Client() 

    def test_index_view(self): 
     response = self.myclient.get('/') 
     assert response.status_code == 200 

    def test_index_content(self): 
     section0 = SectionFactory() 
     section1 = SectionFactory() 
     section2 = SectionFactory() 
     print('wijhdjk: ', section0) 
     journal1 = JournalFactory.create(sections=(section0, section1, section2)) 

     response = self.myclient.get('/') 

     print('wijhdjk: ', journal1) 
     self.assertEquals(journal1.name, 'Section0') 
     self.assertContains(response, journal1.name) 

但我得到這個運行時pytest:

journal1 = JournalFactory.create(sections=(section0, section1, section2))

harrispierce_tests/test_index.py:22:

RecursionError: maximum recursion depth exceeded while calling a Python object

!檢測到遞歸(相同的本地人&位置)

回答

1

一個可能的問題是您沒有使用正確的Factory基類:對於Django模型,請使用factory.django.DjangoModelFactory

這不應該導致你有問題,雖然;完整的堆棧跟蹤將會很有用。

嘗試刪除@factory.post_generation部分,並查看您是否得到正確的Journal對象;然後檢查通過哪些參數。

如果這還不足以解決您的代碼,我建議在factory_boy repository上打開一個問題,並帶有可重複的測試用例(已有some branches/commits試圖重現報告的錯誤,可用作模板)。