Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我应该在哪里放置单元测试的辅助函数?_Python_Unit Testing - Fatal编程技术网

Python 我应该在哪里放置单元测试的辅助函数?

Python 我应该在哪里放置单元测试的辅助函数?,python,unit-testing,Python,Unit Testing,在我的单元测试中,我有一些代码为投资组合中的每个股票代码生成随机余额和所需分配: import random import unittest class TestPortfolio(unittest.TestCase): def setUp(self): self.portfolio = ["AAPL", "AMZN", "GOOG"] allocations = [] balances = [] for i in ra

在我的单元测试中,我有一些代码为
投资组合中的每个股票代码生成随机余额和所需分配:

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)

将它移动到一个可以从需要的地方调用的函数。我想得太多了。