📜  Python中的面向对象测试

📅  最后修改于: 2022-05-13 01:54:35.574000             🧑  作者: Mango

Python中的面向对象测试

先决条件:面向对象的测试

可以使用Pytest测试工具在Python中执行自动化的面向对象测试。在本文中,我们通过为类执行测试用例来执行面向对象的测试。我们编写了一个程序,其中有一个名为 Product 的父类三个子类——Snack、Beverage 和 Staples。我们实现所有类并将它们保存在一个名为product.py的文件中。这些类具有以下功能:

  • 小吃——printDetails( )getExpDate()
  • 饮料 – printDetails()getExpDate()
  • 订书钉——printDetails( )getExpDate()

重要的是要注意getExpDate()在这种情况下是一个被覆盖的函数。

product.py文件中的代码:

Python3
# importing the modules
from datetime import date
from dateutil.relativedelta import relativedelta
  
# base class
  
  
class Product:
  
    name = ""
  
    # printing the class in the constructor
    def __init__(self):
        print("super class Product")
  
# getExpDate() returns the expiry date of product
# since every product has different expiry date
# therefore this method is overridden by child classes
    def getExpDate():
  
        # gives exp date
        print("Expiry date")
        pass
  
  
# derived class 1
class Snack(Product):
  
    # months
    shelfLife = 6
    price = 0
  
    # constructor - initializing variables
    def __init__(self, name, price):
        self.name = name
        self.price = price
  
    # prints the Snack product details
    def printDetails(self):
        print("name : " + self.name)
        print("price : " + str(self.price))
        print("shelf life : " + str(self.shelfLife) + " months")
  
    # calculates the expiry date using relativedelta library and returns
    def getExpDate(self, pkdDate):
        expDate = pkdDate + relativedelta(months=self.shelfLife)
        return expDate
  
# derived class 2
class Beverage(Product):
  
    # 2 years
    shelfLife = 2
    price = 0
  
    # constructor - initializing variables
    def __init__(self, name, price):
        self.name = name
        self.price = price
  
    # prints the Beverage product details
    def printDetails(self):
        print("name : " + self.name)
        print("price : " + str(self.price))
        print("shelf life : " + str(self.shelfLife) + " years")
  
    # calculates the expiry date using relativedelta 
    # library and returns
    def getExpDate(self, pkdDate):
        expDate = pkdDate + relativedelta(years=self.shelfLife)
        return expDate
  
  
# derived class 3
class Staples(Product):
  
    # 1 year
    shelfLife = 1
    price = 0
  
    # constructor - initializing variables
    def __init__(self, name, price):
        self.name = name
        self.price = price
  
    # prints the Staples product details
    def printDetails(self):
        print("name : " + self.name)
        print("price : " + str(self.price))
        print("shelf life : " + str(self.shelfLife) + " year")
  
    # calculates the expiry date using relativedelta
    # library and returns
    def getExpDate(self, pkdDate):
        expDate = pkdDate + relativedelta(years=self.shelfLife)
        return expDate
  
  
def main():
    s = Snack('cookies', 60)
    s.printDetails()
    print(s.name + " will expire on " +
          str(s.getExpDate(date(2019, 10, 3))) + "months")
    # yyyy-mm-dd
  
    p = Product()
  
    st = Staples('rice', 300)
    st.printDetails()
    print(st.name + " will expire on " + str(st.getExpDate(date(2020, 1, 23))))
  
    b = Beverage('coffee', 250)
    b.printDetails()
    print(b.name + " will expire on " + str(b.getExpDate(date(2018, 12, 17))))
  
    print("done till here")
  
  
if __name__ == '__main__':
    main()


Python3
# importing the modules
import pytest
from product import Snack, Staples, Beverage
from datetime import date
  
  
class TestSnack:
  
      # test case for print details of Snack
    def test_details(self):
        s = Snack('chips' , 50)
        print("testing details : snack")
        assert ('chips' , 50, 6)  == (s.name, s.price, s.shelfLife)
  
    # test case for calculating exiry date of Snack
    def test_expDate(self):
        s = Snack('wafers', 40)
        print("testing expiry date : snack")
        expdate = s.getExpDate(date(2019, 10, 3))
        assert expdate == date(2020, 4, 3)
  
  
class TestStaple:
  
      # test case for print details of Staples
    def test_details(self):
        st = Staples('rice' , 300)
        print("testing details : staples")
        assert ('rice' , 300, 1)  == (st.name, st.price, st.shelfLife)
  
    # test case for calculating exiry date of Staples
    def test_expDate(self):
        st = Staples('wheat flour', 400)
        print("testing expiry date : staples")
        expdate = st.getExpDate(date(2020, 1, 23))
        assert expdate == date(2021, 1, 23)
  
  
  
class TestBeverage:
  
      # test case for print details of Beverage
    def test_details(self):
        b = Beverage('coffee' , 250)
        print("testing details : beverage")
        assert ('coffee' , 250, 2)  == (b.name, b.price, b.shelfLife)
  
    # test case for calculating exiry date of Beverage
    def test_expDate(self):
        b = Beverage('green tea', 400)
        print("testing expiry date : beverage")
        expdate = b.getExpDate(date(2018, 12, 17))
        assert expdate == date(2020, 12, 17)


输出:

name : cookies
price : 60
shelf life : 6 months
cookies will expire on 2020-04-03months
super class Product
name : rice
price : 300
shelf life : 1 year
rice will expire on 2021-01-23
name : coffee
price : 250
shelf life : 2 years
coffee will expire on 2020-12-17
done till here

为了执行面向对象的测试,我们为每个类编写测试用例。在编写这些测试用例时,应牢记以下几点:

  • 创建一个单独的测试类来测试每个类的功能,例如TestSnack , TestStaple , TestBeverage
  • 为类的每个函数编写一个测试用例
  • 使用assert关键字在测试用例中添加断言。如果测试用例通过,assert 语句将返回True ,如果测试用例失败则返回False

我们为product.py文件的所有类中存在的每个函数编写了测试用例,除了 Product 类(父类)。这是因为 Product 类只有一个函数,而且它也被子类覆盖了,所以编写测试用例没有任何区别。因此,我们总共编写了 6 个测试用例,其中为每个子类编写了两个测试用例。

test_product.py文件中的代码:

蟒蛇3

# importing the modules
import pytest
from product import Snack, Staples, Beverage
from datetime import date
  
  
class TestSnack:
  
      # test case for print details of Snack
    def test_details(self):
        s = Snack('chips' , 50)
        print("testing details : snack")
        assert ('chips' , 50, 6)  == (s.name, s.price, s.shelfLife)
  
    # test case for calculating exiry date of Snack
    def test_expDate(self):
        s = Snack('wafers', 40)
        print("testing expiry date : snack")
        expdate = s.getExpDate(date(2019, 10, 3))
        assert expdate == date(2020, 4, 3)
  
  
class TestStaple:
  
      # test case for print details of Staples
    def test_details(self):
        st = Staples('rice' , 300)
        print("testing details : staples")
        assert ('rice' , 300, 1)  == (st.name, st.price, st.shelfLife)
  
    # test case for calculating exiry date of Staples
    def test_expDate(self):
        st = Staples('wheat flour', 400)
        print("testing expiry date : staples")
        expdate = st.getExpDate(date(2020, 1, 23))
        assert expdate == date(2021, 1, 23)
  
  
  
class TestBeverage:
  
      # test case for print details of Beverage
    def test_details(self):
        b = Beverage('coffee' , 250)
        print("testing details : beverage")
        assert ('coffee' , 250, 2)  == (b.name, b.price, b.shelfLife)
  
    # test case for calculating exiry date of Beverage
    def test_expDate(self):
        b = Beverage('green tea', 400)
        print("testing expiry date : beverage")
        expdate = b.getExpDate(date(2018, 12, 17))
        assert expdate == date(2020, 12, 17)

注意:函数名和测试文件名应始终以单词“ test ”开头。

要执行上述测试用例,请在单个文件夹中创建两个单独的文件product.pytest_product.py 。要执行写入以下命令:

pytest

或者

pytest -v

pytest -v显示详细输出。

输出如下所示:

如果我们更改测试用例的断言语句之一中的值,则会导致测试用例失败。请参阅下图所示的输出:

在上面显示的输出中,TestBeverage 类中的test_expDate ()测试用例失败,因为断言语句导致False表达式。