﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
31221	HStoreField returns str instead of dict during tests.	Michael Mulholland		"It appears that while running tests on my app, the behavior of HStoreField is not consistent. The TestCase I am trying to run is to test a script (which normally runs fine as a management command) that crashes upon trying to use metadata in an HStoreField. Model instances for testing are loaded from a fixture.

While debugging the test, I've found that accessing an HStoreField on a model instance will return a str type instead of the expected dict. What's stranger is that this doesn't occur when the test database already exists and --keepdb is used (the first run with --keepdb will fail, but the second doesn't). This leads me to believe that the way fixtures are loaded during testing is breaking HStoreField's to_python conversion or something.

I found a similar issue #25454, where the same problem was solved, but it looks like the problem is either occurring under different circumstances or has been reintroduced.

My test runner is from this gist, where the test db is created with hstore extension installed: [https://gist.github.com/smcoll/bb2533e4b53ae570e11eb2ab011b887b]

Currently my knowledge of the django code base isn't extensive enough to suggest a fix, but I have been able to reproduce this problem with the following models/tests:

{{{
# models.py
class MyModel(models.Model):
    name = models.CharField(max_length=66)
    metadata = HStoreField(blank=True)
}}}

{{{
# tests.py
class TestMyApp(TestCase):
    fixtures = ['i_myapp']
    def test_mymodel(self):
        for mymodel_instance in MyModel.objects.all():
            self.assertEqual(type(mymodel_instance.metadata), dict)
}}}

{{{
# i_myapp.json
[
    {
        ""model"": ""myapp.mymodel"",
        ""pk"": 4,
        ""fields"": {
            ""name"": ""First"",
            ""metadata"": ""{}""
        }
    },
    {
        ""model"": ""myapp.mymodel"",
        ""pk"": 5,
        ""fields"": {
            ""name"": ""Second"",
            ""metadata"": ""{\""details\"": \""this one isn't blank\""}""
        }
    }
]
}}}

The test test_mymodel fails with:
{{{
AssertionError: <class 'str'> != <class 'dict'>
}}}
"	Bug	closed	contrib.postgres	dev	Normal	invalid	hstore		Unreviewed	0	0	0	0	0	0
