如何使用pytest进行单元测试?

huangapple go评论52阅读模式
英文:

How would I go about unit testing this using pytest?

问题

I'm trying to unit test the below code using pytest but I'm completely unsure link a list value with the function I'm testing.

def already_exists(self, name) -> bool:
        for storm in self.storm_list:
            if storm.name == name:
                return True
        return False

这是我从中提取的函数的完整代码:

class Storm(ABC):
    def __init__(self, name, wind_speed):
        self.name = name
        self.wind_speed = wind_speed
        super().__init__()

class control_Centre:
    def __init__(self):
        self.storm_list = []

    def already_exists(self, name) -> bool:
        for storm in self.storm_list:
            if storm.name == name:
                return True
        return False
英文:

I'm trying to unit test the below code using pytest but I'm completely unsure link a list value with the function I'm testing.

def already_exists(self, name) -> bool:
        for storm in self.storm_list:
            if storm.name == name:
                return True
        return False

This is the complete code from where I got the function from:

class Storm(ABC):
    def __init__(self, name, wind_speed):
        self.name = name
        self.wind_speed = wind_speed
        super().__init__()

class control_Centre:
    def __init__(self):
        self.storm_list = []

    def already_exists(self, name) -> bool:
        for storm in self.storm_list:
            if storm.name == name:
                return True
        return False

答案1

得分: 1

def test_already_exists():
    s1 = Storm('Jeff', 10)
    c1 = control_Centre()
    c1.storm_list.append(s1)
    assert(c1.already_exists('Jeff') == True)
    assert(c1.already_exists('Dave') == False)

注意,你的函数实际上并不检查两个风暴是否相同,只是检查在你的“控制中心”对象中是否存在具有给定名称的风暴。

英文:
def test_already_exists():
    s1 = Storm('Jeff', 10)
    c1 = control_Centre()
    c1.storm_list.append(s1)
    assert(c1.already_exists('Jeff') == True)
    assert(c1.already_exists('Dave') == False)

Bear in mind, your function doesn't actually check that two storms are the same, just that a storm with a given name exists in your 'control centre' object.

huangapple
  • 本文由 发表于 2023年5月24日 23:35:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76325228.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定