1

私はフォローを持っていますclass

class PlaylistManager(models.Manager):
    def add_playlist(self, name):
        playlist = Playlist(name=name)
        playlist.save()
        return playlist

class Playlist(models.Model):
    name = models.CharField(max_length=30)
    date_created = models.DateTimeField(auto_now_add=True)
    date_modified = models.DateTimeField(auto_now=True)
    deleted = models.BooleanField(default=False)
    objects = PlaylistManager() # is a customer manager

    class Meta:
        db_table = 'playlists'

そして私testはフォロー しています

PLAYLIST = 'playlist' # 8 characters
class PlaylistTest(TestCase):
    def insert_playlist(playlist=PLAYLIST):
        Playlist.objects.add_playlist(playlist)

    def test_add_one_video_to_playlist(self):
        self.insert_playlist()
        self.assertEqual(Playlist.objects.count(), 1, msg='playlist count is not 1, it is ' + str(Playlist.objects.count()))

これをテストすると、次のエラーが表示されます

DatabaseError: value too long for type character varying(30)


----------------------------------------------------------------------
Ran 1 test in 0.004s

FAILED (errors=1)
Destroying test database for alias 'default'...

質問
- 失敗するのはなぜですか?
-max_length=300テストを行って実行すると、問題はありませんが、それは望ましくありません。

アップデート

PostgreSQLバックエンドとして使用しています


UPDATE 1
これはテストで起こっていることです:

PLAYLIST='playlist'
class PlaylistTest(TestCase):
    def insert_playlist(playlist=PLAYLIST):
        Playlist.objects.add_playlist(playlist)

PlaylistManagerデバッグするためにしばらく 変更しました

class PlaylistManager(models.Manager):
    def add_playlist(self, name):
        logging.warn('type ' + str(type(name)))
        logging.warn('adding ' + str(dir(name)))
        playlist = Playlist(name=name)
        playlist.save()
        return playlist

ケース-1:私が言うならplaylist=PLAYLIST
の中に 入るadd_playlistPlaylistManagerPlaylistTestオブジェクトです

Creating test database for alias 'default'...
WARNING:root:type <class 'vlists.apps.playlists.tests.PlaylistTest'>
WARNING:root:adding ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_addSkip', '_baseAssertEqual', '_classSetupFailed', '_cleanups', '_deprecate', '_fixture_setup', '_fixture_teardown', '_formatMessage', '_getAssertEqualityFunc', '_post_teardown', '_pre_setup', '_resultForDoCleanups', '_testMethodDoc', '_testMethodName', '_truncateMessage', '_type_equality_funcs', '_urlconf_setup', '_urlconf_teardown', 'addCleanup', 'addTypeEqualityFunc', 'assertAlmostEqual', 'assertAlmostEquals', 'assertContains', 'assertDictContainsSubset', 'assertDictEqual', 'assertEqual', 'assertEquals', 'assertFalse', 'assertFieldOutput', 'assertFormError', 'assertGreater', 'assertGreaterEqual', 'assertHTMLEqual', 'assertHTMLNotEqual', 'assertIn', 'assertIs', 'assertIsInstance', 'assertIsNone', 'assertIsNot', 'assertIsNotNone', 'assertItemsEqual', 'assertLess', 'assertLessEqual', 'assertListEqual', 'assertMultiLineEqual', 'assertNotAlmostEqual', 'assertNotAlmostEquals', 'assertNotContains', 'assertNotEqual', 'assertNotEquals', 'assertNotIn', 'assertNotIsInstance', 'assertNotRegexpMatches', 'assertNumQueries', 'assertQuerysetEqual', 'assertRaises', 'assertRaisesMessage', 'assertRaisesRegexp', 'assertRedirects', 'assertRegexpMatches', 'assertSequenceEqual', 'assertSetEqual', 'assertTemplateNotUsed', 'assertTemplateUsed', 'assertTrue', 'assertTupleEqual', 'assert_', 'client', 'client_class', 'countTestCases', 'debug', 'defaultTestResult', 'doCleanups', 'fail', 'failIf', 'failIfAlmostEqual', 'failIfEqual', 'failUnless', 'failUnlessAlmostEqual', 'failUnlessEqual', 'failUnlessRaises', 'failureException', 'id', 'insert_playlist', 'longMessage', 'maxDiff', 'restore_warnings_state', 'run', 'save_warnings_state', 'setUp', 'setUpClass', 'settings', 'shortDescription', 'skipTest', 'tearDown', 'tearDownClass', 'test_add_one_video_to_playlist']

そしてそれは失敗します

**Case -2 : if I say `Playlist.objects.add_playlist('name')`**  
PLAYLIST = 'playlist'
class PlaylistTest(TestCase):
    def insert_playlist(playlist=PLAYLIST):
        Playlist.objects.add_playlist('name') # this line has changed

    def test_add_one_video_to_playlist(self):
        self.insert_playlist()
        self.assertEqual(Playlist.objects.count(), 1, msg='playlist count is not 1, it is ' + str(Playlist.objects.count()))  

すべてが良さそうです!

Creating test database for alias 'default'...
WARNING:root:type <type 'str'>
WARNING:root:adding ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
.
----------------------------------------------------------------------
Ran 1 test in 0.007s

OK
Destroying test database for alias 'default'...

より大きな質問

  • 生の文字列を渡す必要があるのはなぜですか?

私はここで混乱しています

4

1 に答える 1

2

これは私の側では惨事でした、私はそれを間違ってやっていました

私が書いた不正確で実際の

PLAYLIST = 'playlist'
class PlaylistTest(TestCase):
    def insert_playlist(playlist_name=PLAYLIST):
        Playlist.objects.add_playlist(playlist_name)

    def test_add_one_video_to_playlist(self):
        self.insert_playlist()
        self.assertEqual(Playlist.objects.count(), 1, msg='playlist count is not 1, it is ' + str(Playlist.objects.count()))

クラスメソッドに追加するのを忘れていたselfので、クラスインスタンスが常に渡されていました

正しい実装

PLAYLIST = 'playlist'
class PlaylistTest(TestCase):
    def insert_playlist(self, playlist_name=PLAYLIST): # added self as first parameter here
        Playlist.objects.add_playlist(playlist_name)

    def test_add_one_video_to_playlist(self):
        self.insert_playlist()
        self.assertEqual(Playlist.objects.count(), 1, msg='playlist count is not 1, it is ' + str(Playlist.objects.count()))

そして、物事はうまくいき始めました!問題に答えて考えてくれたすべての人に感謝します

于 2012-07-18T17:20:36.877 に答える