【问题标题】:How to write unit tests for a function using dbus to get information from Spotify?如何使用 dbus 为函数编写单元测试以从 Spotify 获取信息?
【发布时间】:2018-11-18 15:37:48
【问题描述】:

我有这个功能

def get_info_linux():
    import dbus

    session_bus = dbus.SessionBus()
    spotify_bus = session_bus.get_object("org.mpris.MediaPlayer2.spotify",
                                         "/org/mpris/MediaPlayer2")
    spotify_properties = dbus.Interface(spotify_bus,
                                        "org.freedesktop.DBus.Properties")
    metadata = spotify_properties.Get("org.mpris.MediaPlayer2.Player", "Metadata")
    track = str(metadata['xesam:title'])
    artist = str(metadata['xesam:artist'][0])
    return artist, track

这会使用 dbus 从 spotify 获取信息。如何为它编写单元测试?

【问题讨论】:

    标签: python linux unit-testing dbus


    【解决方案1】:

    测试这种 D-Bus 服务客户端的最常见方法是针对假的 D-Bus 会话总线运行它,该总线上运行着 Spotify 服务的模拟实现(由您的测试代码控制)。

    您可以使用GTestDBus 创建模拟会话总线,然后使用普通的 GDBus API 在其上公开一个 D-Bus 对象。创建一个Gio.DBusConnection 连接到g_test_dbus_get_bus_address() 返回的地址,然后在D-Bus 对象路径/org/mpris/MediaPlayer2 上公开一个对象,至少实现org.freedesktop.DBus.Properties 属性,并为您的代码的属性返回模拟数据- 正在测试的查询。

    您的被测代码在测试工具下运行时应使用模拟会话总线,因为GTestDBus 覆盖了DBUS_SESSION_BUS_ADDRESS 环境变量,GIO 使用(默认情况下)查找真实会话总线的地址.

    【讨论】:

      【解决方案2】:

      直接为依赖于网络的东西编写单元测试不是一个好主意,也不能确保您的测试始终具有相同的行为。

      但是您可以通过添加抽象干扰来规避这一点。此接口可以通过您当前在代码中使用的方法来实现,并且您可以实现在测试中使用的存根。这将返回您喜欢的任何内容。

      【讨论】:

      • 一个通用的答案。
      • Dbus 与网络实际上没有任何关系,它是当前系统本地的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-13
      • 1970-01-01
      • 2021-06-12
      • 2019-01-12
      • 1970-01-01
      相关资源
      最近更新 更多