我正在尝试掌握Python,但在尝试使用数据类时似乎遇到了瓶颈。但是当我运行测试时,我得到断言错误,因为它似乎没有看到正确的数据类。
我有以下代码:
文件: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']
这是怎么回事?我显然漏掉了一些明显的东西。
感谢像这样更新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)
注意上面代码中的数据类实例化。
并像这样更新您的测试用例:
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()
的输出转换为list。
如果运行该测试,您将得到以下输出:
Ran 1 test in 0.000s
OK