繁体   English   中英

通过Python中的方法调用模拟属性

[英]Mock property by method call in Python

嗨,首先,一些代码片段:
模块A:

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

模块B:

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

应该工作正常。 现在,我尝试测试convert方法。 但是由于最后一个价格在变化,因此我想到了模拟last_price属性以检查转换是否有效。

我找到了一些有关补丁和Magic Mocks的知识,但我不知道如何模拟类方法的输出,这些方法不会返回任何东西,而只会改变内部属性。

有人知道该怎么做吗? 也许还有其他建议?

我考虑过只返回last_price,但是其他一些方法也正在使用它,因此我不需要每次都调用该函数。

提前致谢!

使用可以直接使用curr.last_price,因为curr是Foo类的对象

我的代码段:模块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

模块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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM