Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python unit testing methods inside of classes

Very new to unit testing so this could be something very easy but I am not sure how to mimic self argument in functions.

Function I want to test:

class dataFeed:
    def generateURL(self, ticker, days, period):
        return "https://www.google.com/finance/getprices?i=" + str(period) + "&p=" + str(days) + "d&f=d,o,h,l,c,v&df=cpct&q=" + ticker

test class:

import unittest
from dataFeed import dataFeed as df

class TestCases(unittest.TestCase):
    def test(self):
        self.assertEqual(df.generateURL("AAPL", 2, 5), "https://www.google.com/finance/getprices?i=5&p=2d&f=d,o,h,l,c,v&df=cpct&q=AAPL")

if __name__ == '__main__':
    unittest.main()

the output I get is this:

ERROR: test (__main__.TestCases)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\ian\Documents\Capstone\Components\testing.py", line 9, in test
    self.assertEqual(df.generateURL("AAPL", 2, 5), "https://www.google.com/finance/getprices?i=5&p=2d&f=d,o,h,l,c,v&df=cpct&q=AAPL")
TypeError: unbound method generateURL() must be called with dataFeed instance as first argument (got str instance instead)
like image 522
user2327814 Avatar asked Apr 29 '14 15:04

user2327814


People also ask

How do you unit test a method in a class?

First, you arrange the objects under test the way you need them (instantiate a consumer). Then you act on the objects under test (invoking the method in question) Finally, you make assertions on the resulting state you expect the objects to be in.

How do we define unit tests within a test file Python?

Unit tests are usually written as a separate code in a different file, and there could be different naming conventions that you could follow. You could either write the name of the unit test file as the name of the code/unit + test separated by an underscore or test + name of the code/unit separated by an underscore.

What are the 4 types of testing in Python 3?

There are 4 types of testing available in Python – Unit Testing, Feature Testing, Integration Testing & Performance Testing.


2 Answers

You'll want to create an instance of the dataFeed object and use it for testing.

ex.

class TestCases(unittest.TestCase):
    def test(self):
        data_feed = dataFeed()
        self.assertEqual(data_feed.generateURL("AAPL", 2, 5), "https://www.google.com/finance/getprices?i=5&p=2d&f=d,o,h,l,c,v&df=cpct&q=AAPL")
like image 148
VirusBloom Avatar answered Sep 21 '22 06:09

VirusBloom


Looks like your class method can be made static as it does not use self argument in its implementation. So just make the method static and you can use your TestCase class as it is.

In case your class method is not static, look at virusbloom’s answer.

like image 20
ketan goyal Avatar answered Sep 19 '22 06:09

ketan goyal