对于单元测试,我应该在哪里放置帮助程序函数?



在我的单元测试中,我有一些代码可以为列表中的每个股票代码生成随机余额和所需的分配portfolio

import random
import unittest
class TestPortfolio(unittest.TestCase):
def setUp(self):
self.portfolio = ["AAPL", "AMZN", "GOOG"]
allocations = []
balances = []
for i in range(len(self.portfolio)):
a = random.random()
b = round(random.uniform(1.0, 10000.00), 2)
allocations.append(a)
balances.append(b)
allocations = [round(i / sum(allocations), 4) for i in allocations]

如果我想在其他单元测试中重用该段代码,我应该将函数放在哪里?

您可以将逻辑移动到可以从所需的任何测试中调用的函数

def get_allocations(portfolio):
allocations = []
balances = []
for i in range(len(portfolio)):
a = random.random()
b = round(random.uniform(1.0, 10000.00), 2)
allocations.append(a)
balances.append(b)
return round(i / sum(allocations), 4) for i in allocations]

class TestPortfolio(unittest.TestCase):
def setUp(self):
self.portfolio = ["AAPL", "AMZN", "GOOG"]
self.allocations =  get_allocations(self.portfolio)

相关内容

最新更新