【问题标题】:How to use a Python Dataclass in another class如何在另一个类中使用 Python 数据类
【发布时间】:2022-11-14 18:13:12
【问题描述】:

我正在尝试掌握 Python,并且在尝试使用 Dataclasses 时似乎遇到了困难。但是当我运行测试时,我得到了断言错误,因为它似乎没有看到正确的数据类。

我有以下代码:

文件:music_library.py

from dataclasses import dataclass

@dataclass
class Track:
    title: str
    artist: str
    file: str

class MusicLibrary:
    def __init__(self):
        self.track = Track

    def all(self):
        return self.track

    def add(self, title, artist, file):
        self.track(title = title, artist = artist, file = file)

正在从测试中调用 add 函数并传递三个参数:

import unittest

from player.music_library import MusicLibrary


class TestMusicLibrary(unittest.TestCase):

    ml = MusicLibrary()

    def test_all(self):
        ml = MusicLibrary()
        ml.add("Track1", "artist1","file1")
        self.assertEqual(ml.all(), ["Track1","artist1","file1" ])

然而测试失败了

Traceback (most recent call last):
  File "/projects/python/python-music-player-challenges/seed/tests/test_music_library.py", line 13, in test_all
    self.assertEqual(ml.all(), ["Track1","artist1","file1" ])
AssertionError: <class 'player.music_library.Track'> != ['Track1', 'artist1', 'file1']

这里发生了什么?我显然错过了一些明显的东西。

谢谢

【问题讨论】:

    标签: python python-3.x unit-testing python-dataclasses


    【解决方案1】:

    像这样更新 music_library.py:

    from dataclasses import dataclass
    
    @dataclass
    class Track:
        title: str
        artist: str
        file: str
    
    
    class MusicLibrary:
        def __init__(self):
            self.track = None
    
        def all(self):
            return self.track
    
        def add(self, title, artist, file):
            self.track = Track(title=title, artist=artist, file=file)
    
    

    注意上面代码中的Dataclass实例化。

    并像这样更新您的测试用例:

    import unittest
    
    from music_library import MusicLibrary
    
    
    class TestMusicLibrary(unittest.TestCase):
    
        def test_all(self):
            ml = MusicLibrary()
            ml.add("Track1", "artist1", "file1")
            self.assertEqual([ml.all().title, ml.all().artist, ml.all().file],
                             ["Track1", "artist1", "file1"])
    

    在您的测试代码中,您正在比较不同的对象类型,您应该首先将ml.all() 的输出转换为列表。

    如果你运行测试,你会得到以下输出:

    Ran 1 test in 0.000s
    
    OK
    

    【讨论】:

      猜你喜欢
      • 2016-12-16
      • 2018-03-19
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-27
      相关资源
      最近更新 更多