Объектно-ориентированное тестирование на Python
Предварительное условие: объектно-ориентированное тестирование
Автоматизированное объектно-ориентированное тестирование может выполняться в Python с помощью инструмента тестирования Pytest. В этой статье мы проводим объектно-ориентированное тестирование, выполняя тестовые примеры для классов. Мы пишем программу, у которой есть один родительский класс под названием Product и три дочерних класса - Snack, Beverage и Staples. Мы реализуем все классы и сохраняем их в файле с именем product.py . У классов есть следующие функции:
- Закуска - printDetails () и getExpDate ()
- Напиток - printDetails () и getExpDate ()
- Скобы - printDetails () и getExpDate ()
Важно отметить, что getExpDate () в этом случае является замещаемой функцией.
Code in product.py file:
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() |
Выход:
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 тестовых примеров, по два тестовых примера для каждого из дочерних классов.
Code in test_product.py file:
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 ) |
Примечание. Имя функции и имя тестового файла всегда должны начинаться со слова « test ».
Чтобы выполнить вышеуказанные тестовые примеры, создайте два отдельных файла, product.py и test_product.py в одной папке. Для выполнения напишите следующую команду:
pytest
ИЛИ
pytest -v
pytest -v показывает подробный вывод.
Результат показан ниже:
Если мы изменим значение в одном из утверждений тестового примера, это приведет к сбою тестового примера. См. Результат, показанный ниже:
В выходных данных, показанных выше, тестовый пример test_expDate () в классе TestBeverage завершился неудачно, поскольку оператор утверждения привел к выражению False.
Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.