python unit testing methods inside of classes

2020-08-25 04:57发布

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)

2条回答
乱世女痞
2楼-- · 2020-08-25 05:50

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")
查看更多
Rolldiameter
3楼-- · 2020-08-25 05:57

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.

查看更多
登录 后发表回答