2017-10-08 6 views
0

Python에서 단위 테스트를 이해하는 데 문제가 있습니다. 다른 객체 인 deal을 생성하는 객체 인 retailer이 있습니다. dealretailer에서 생성 된 속성을 참조, 그래서 나는 그것을 참조를 전달 해요 :Python 단위 테스트에서 다른 개체에서 개체를 만드는 방법

class deal(): 
    def __init__(self, deal_container, parent): 

deal_container 속성은 또한 자신의 방법을 만들 호출 retailer에서 온다. 그렇다면 쉽게 deal 개체를 만드는 데 필요한 모든 것을 어떻게 만들 수 있습니까?

단위 테스트에서 retailer의 인스턴스를 만든 다음 deal을 만드는 해당 개체에서 메서드를 호출해야합니까?

FactoryBoy를 사용하여 retailer의 인스턴스를 만들 수 있으며 해당 개체에 deal이라는 메서드를 포함시키는 방법은 무엇입니까?

어떻게 접근하면 좋을까요?

다음은 단위 테스트입니다. dealscandeal 클래스의 해당 비트를

class TestExtractString(TestCase): 
    fixtures = ['deals_test_data.json'] 

    def setUp(self): 
     with open('/home/danny/PycharmProjects/askarby/deals/tests/BestBuyTest.html', 'r') as myfile: 
      text = myfile.read().replace('\n', '') 
     self.soup_obj = bs4.BeautifulSoup(text,"html.parser") 
     self.deal = self.soup_obj.find_all('div',attrs={'class':'list-item'})[0] 

    def test_extracts_title(self): 
     z = Retailer.objects.get(pk=1) 
     s = dealscan.retailer(z) 
     d = dealscan.deal(self.deal,s) 
     result = d.extract_string(self.deal,'title') 

을하고 여기에 : 나는 거래를 제공하는 데 필요한 soup_obj를 설정하고있다. deal을 만드는 retailer 클래스가 있지만 아직 deal을 만드는 retailer의 비트를 작성하지 않았습니다. 나는 deal을 위해 내가 필요로하는 비트를 모의 할 수 있기를 바라고 있는데, retailer을 전혀 호출하지 않아도된다. 그렇다면 어떻게하면 deal을 참조하여 retailer을 참조 할 수 있을까?

class deal(): 
    def __init__(self, deal_container, parent): 
     ''' 
     Initializes deal object 
     Precondition: 0 > price 
     Precondition: 0 > old_price 
     Precondition: len(currency) = 3 

     :param deal_container: obj 
     ''' 
     self.css = self.parent.css 

     self.deal_container = deal_container 
     self.parent = parent 
     self.title = self.extract_string('title') 
     self.currency = self.parent.currency 
     self.price = self.extract_price('price') 
     self.old_price = self.extract_price('old_price') 
     self.brand = self.extract_string('brand') 
     self.image = self.extract_image('image') 
     self.description = self.extract_string('description') 

     #define amazon category as clearance_url 
     #define all marketplace deals 

    def __str__(self): 
     return self.title 

    def extract_string(self, element, deal): 
     ''' 

     :param object deal: deal object to extract title from 
     :param string element: element to look for in CSS 
     :return string result: result of string extract from CSS 
     ''' 
     tag = self.css[element]['tag'] 
     attr = self.css[element]['attr'] 
     name = self.css[element]['name'] 
     result = deal.find(tag, attrs={attr: name}) 
     if result: 
      if element == 'title': 
       return result.text 
      elif element == 'price': 
       result = self.extract_price(result).text 
       if result: 
        return result 
      elif element == 'image': 
       result = self.extract_image(result) 

     return False 
+1

이러한 개체가 어떻게 생성되는지는 중요하지 않습니다. 단위 테스트는'deal '이하는 일, 그 행동이 무엇인지에 초점을 맞추어야한다. 따라서 실제 객체, 모의 객체 또는 스텁 (stub)과 같이 거래가 올바르게 작동하는지 여부를 테스트가 결정할 수 있다면 원하는 것을 전달할 수 있습니다. – quamrana

+0

시험하고자하는 "단위"코드의 코드를 보여주고 시험의 목표를 설명하십시오. –

+0

그래. 그러나 거래가 어떤 것인지 테스트하기 위해서는 거래를 만들어야하며 부모가 가지고있는 속성을 참조하기 때문에 부모가 필요합니다. 따라서 부모 개체 외부에서 거래를 만들려고하면 다음과 같이 나타납니다. AttributeError : '거래'개체에 '부모'속성이 없습니다. '거래'를 작성하여 오류가 발생하지 않도록해야합니다. 즉, 부모 개체를 만들어야합니다. – RubyNoob

답변

0

문제는 deal 객체가 self.parent 속성을 설정하기 전에 부모를 참조한다는 점입니다. 사용 :

self.parent = parent   
self.css = self.parent.css 
self.deal_container = deal_container 

AttributeError이 사라집니다.

단위 테스트에서 다른 개체를 만드는 데 개체를 사용하는 것이 좋은지 여부에 대한 질문은 사용자가 모의를 사용할 수 있다는 것입니다.하지만 이렇게하는 것이 좋습니다. 도우미 메서드를 사용하여 setUp에서 한 번 부모 개체를 설정하면 코드를 읽기 쉽게 만들 수 있으며 테스트 성능이 약간 향상 될 수 있습니다.