1

Hi first some code snippets:
module A:

    class Foo:
      def __init__(symbol):
        self.last_price = None
      def get_last_price(self):
        x = do_some_query_requests()
        self.last_price = x

module B:

    class Bar:
      def convert(symbol, amount):
        curr = Foo(symbol)
        curr.get_last_price()
        #do some conversion with last_price
        return converted_stuff

Should work fine. Now I try to test the convert method. But due the last price is changing, I thought about mocking the last_price property to check if the conversion works.

I found something about patches and Magic Mocks, but I don't know how to mock the output of a method of a class, which do not return something but only change internal properties.

Do somebody know how to do that? Maybe some other suggestions?

I thought about simply return the last_price, but some other methods are using it as well, so I don't need to call the function every time.

Thanks in Advance!

sawrz
  • 31
  • 3

1 Answers1

0

Use can directly use the curr.last_price as curr is the object of the class Foo

my code snippets: module A:

class Foo:
  def __init__(self,symbol):
    self.last_price = None
  def get_last_price(self):
    x = do_some_query_requests()
    self.last_price = x

module B:

class Bar:
  def convert(symbol, amount):
    curr = Foo(symbol)
    curr.get_last_price()
    print(curr.last_price)  //get_last_price updates the last_price 
                            //You can use that directly
    #do some conversion with last_price
    return converted_stuff
Hariom Singh
  • 3,308
  • 5
  • 26
  • 50
  • Yes that's true but while unit testing that stuff I have no access to that object, because it's called in that method. So how can I mock then last_price in the way, that I can check that the conversion works right? I mean I need to know last price, which changes. Last price is called in convert. But to know if the conversion works right I need to know last_price, do the conversion by hand and assert if both values are equal. Maybe I'm thinking to complicated... – sawrz Jun 21 '17 at 12:11
  • This May be helpful https://stackoverflow.com/questions/23909692/how-to-unittest-local-variable-in-python – Hariom Singh Jun 21 '17 at 12:56
  • This is also true, but it do not fix my problem. I don't want to check a local variable. I'm only interested in the output. But the output varies with the changing variable of last price. I need to fix this variable somehow, to get a predictable result. This is like I would use a random number for some calculations. This is pretty unpredictable, but I can check if the calculations are doing right, by fix this "random" number. Mock can do that. The problem is, that this is a function returning some value and not manipulating some object attributes. – sawrz Jun 21 '17 at 13:06