Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Object oriented testing in Python
Next article icon

Prerequisite:Object-Oriented Testing

Automated Object-Oriented Testing can be performed in Python using Pytesttesting tool. In this article, we perform object-oriented testing by executing test cases for classes. We write a program that hasone parent class called Product andthree child classes- Snack, Beverage, and Staples. We implement all the classes and save them in a file calledproduct.py. The classes have the following functions: 

  • Snack -printDetails()and getExpDate()
  • Beverage -printDetails()and getExpDate()
  • Staples -printDetails()and getExpDate()

It is important to note thatgetExpDate()is an overridden function in this case.

Code inproduct.py file: 

Python3
# importing the modulesfromdatetimeimportdatefromdateutil.relativedeltaimportrelativedelta# base classclassProduct:name=""# printing the class in the constructordef__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 classesdefgetExpDate():# gives exp dateprint("Expiry date")pass# derived class 1classSnack(Product):# monthsshelfLife=6price=0# constructor - initializing variablesdef__init__(self,name,price):self.name=nameself.price=price# prints the Snack product detailsdefprintDetails(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 returnsdefgetExpDate(self,pkdDate):expDate=pkdDate+relativedelta(months=self.shelfLife)returnexpDate# derived class 2classBeverage(Product):# 2 yearsshelfLife=2price=0# constructor - initializing variablesdef__init__(self,name,price):self.name=nameself.price=price# prints the Beverage product detailsdefprintDetails(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 returnsdefgetExpDate(self,pkdDate):expDate=pkdDate+relativedelta(years=self.shelfLife)returnexpDate# derived class 3classStaples(Product):# 1 yearshelfLife=1price=0# constructor - initializing variablesdef__init__(self,name,price):self.name=nameself.price=price# prints the Staples product detailsdefprintDetails(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 returnsdefgetExpDate(self,pkdDate):expDate=pkdDate+relativedelta(years=self.shelfLife)returnexpDatedefmain():s=Snack('cookies',60)s.printDetails()print(s.name+" will expire on "+str(s.getExpDate(date(2019,10,3)))+"months")# yyyy-mm-ddp=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()

Output:

name : cookiesprice : 60shelf life : 6 monthscookies will expire on 2020-04-03monthssuper class Productname : riceprice : 300shelf life : 1 yearrice will expire on 2021-01-23name : coffeeprice : 250shelf life : 2 yearscoffee will expire on 2020-12-17done till here

To perform object-oriented testing, we write test cases for each of the classes. The following things should be kept in mind while writing these test cases: 

  • Create a separate test class for testing the functions of each class, for e.g.TestSnack,TestStaple,TestBeverage
  • Write a test case for each function of a class
  • Useassert keyword to add assertions in the test cases. The assert statement will returnTrue if the test case passes or will returnFalse if the test case fails

We have written test cases for each function present in all classes ofproduct.py file except the Product class (parent class). This is because the Product class has just one function and that too has been overridden by the child classes, so writing a test case would make no difference. Therefore, we write 6 test cases in total where two test cases are written for each of the child classes.

Code intest_product.py file: 

Python3
# importing the modulesimportpytestfromproductimportSnack,Staples,BeveragefromdatetimeimportdateclassTestSnack:# test case for print details of Snackdeftest_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 Snackdeftest_expDate(self):s=Snack('wafers',40)print("testing expiry date : snack")expdate=s.getExpDate(date(2019,10,3))assertexpdate==date(2020,4,3)classTestStaple:# test case for print details of Staplesdeftest_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 Staplesdeftest_expDate(self):st=Staples('wheat flour',400)print("testing expiry date : staples")expdate=st.getExpDate(date(2020,1,23))assertexpdate==date(2021,1,23)classTestBeverage:# test case for print details of Beveragedeftest_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 Beveragedeftest_expDate(self):b=Beverage('green tea',400)print("testing expiry date : beverage")expdate=b.getExpDate(date(2018,12,17))assertexpdate==date(2020,12,17)

Note: The function name and the test file name should always start with the word 'test'.

To execute the above test cases, create two separate files,product.py andtest_product.py in a single folder. To execute write the following command:

pytest

OR

pytest -v

pytest -v  shows the verbose output.

The output is shown below: 

If we change the value in one of the assertion statements of a test case, it will lead the test case to fail. Refer to the output shown below: 

In the output shown above,test_expDate() test case in classTestBeverage failed as the assertion statement resulted in aFalse expression.  


Improve

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp