Pythonでユニットテストを理解できません。私は別のオブジェクト、deal
を作成するオブジェクトretailer
を持っています。 deal
がretailer
で作成した属性を参照するので、私はそれを参照を渡しています:Pythonユニットテストで別のオブジェクトからオブジェクトを作成する方法
class deal():
def __init__(self, deal_container, parent):
deal_container
属性も、それを作成するために、独自のメソッドを呼び出す、retailer
から来ています。では、簡単にdeal
オブジェクトを作成するために必要なものすべてを作成するにはどうすればよいですか?
ユニットテストでretailer
のインスタンスを作成してから、deal
というオブジェクトを作成する必要がありますか?
FactoryBoyを使用してretailer
のインスタンスを作成できますか?そのオブジェクトにdeal
というメソッドを含めるにはどうすればよいですか?
このアプローチにはどのような方法が最適ですか?
ユニットテストです。私は契約を与える必要がsoup_obj
を設定してい:
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')
、ここではdeal
クラスの該当ビットはdealscan
にあります。そこdeal
作成retailer
クラスは、ですが、私もまだdeal
を作成retailer
のビットを書いていません。私は全くretailer
を起動しなくても、私はdeal
のために必要なビットを模擬することができます願っていたが、その後どのように私はその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
これらのオブジェクトの作成方法は関係ありません。単体テストは、「契約」が何をしているか、その振る舞いが何であるかに焦点を当てるべきです。実際のオブジェクト、模擬オブジェクト、スタブなど、テストが取引が正しく動作するかどうかを判断できるのであれば、あなたが好きなものを渡すことができます。 – quamrana
テストしたい「ユニット」のコードのコードを表示し、テストの対象を説明してください。 –
そうです。しかし、取引が何であるかをテストするには、取引を作成しなければならず、親が持つ属性を参照するため、親が必要です。したがって、親オブジェクトの外で取引を作成しようとすると、次のようになります。 AttributeError: 'deal'オブジェクトに 'parent'属性がありません。 私は 'deal'を作成して、そのエラーを投げないようにする必要があります。つまり、親オブジェクトを作成する必要があります。 – RubyNoob