编写修补对象的上下文管理器

时间:2018-01-17 11:04:02

标签: python mocking contextmanager

在我的Python 3测试代码中,我有很多这样的陈述:

from unittest.mock import patch

user = User(...)
with patch.object(MyAuthenticationClass, 'authenticate', return_value=(user, 'token'):
    # do something

现在我想把它写成:

with request_user(user):
    # do something

如何将方法request_user编写为上下文管理器,以便以这种方式修补身份验证,并在with阻止后删除补丁?

1 个答案:

答案 0 :(得分:2)

您可以编写一个这样的简单包装器:

// StreamingJob.scala

...

val filteredEvents = content
      .map(x => Event.toCaseClass(x))
      .filter(x => x.value == true)

...

// Event.scala

case class Event(
                  id: String,
                  value: Int,
                )
object Event {
  implicit val formats = DefaultFormats

  def toCaseClass(str: String) =
    parse(str).extract[Event]
}

并使用它:

def request_user(user):
    return patch.object(MyAuthenticationClass, 'authenticate', return_value=(user, 'token')