1

In django testing I have a Imagefield which is used in many test cases, In order to avoid the repetition I have assigned the Imagefile obj to the global variable

file = open(os.path.join(settings.BASE_DIR, 'logged_out.jpg'), 'rb')
image = {'image':SimpleUploadedFile(name=file.name, content=file.read(), content_type='image/jpeg')}

class FeedFormTest(TestCase):

    def setUp(self):
        self.user = baker.make(SnetUser)
        self.data = {
            'post_info':'Test_data',
        }

    def test_feed_form_is_valid(self):
        #Option 1 Not working
        #self.data.update(image)
        #form = FeedForm(self.data)
        #Option 2 Not working
        #form = FeedForm(self.data, image)
        #Option 3 Working
        form = FeedForm(self.data, image) #locally defined image in SetUp method instead globally
        print(form.errors)
        self.assertTrue(form.is_valid())

When I execute the test it's working only for the image which is defined inside the setUp method of test class. Can you suggest or guide me the method in using the variables effectively without defining it multiple times. As I have other variables too like user credentials

ivardu
  • 179
  • 2
  • 15
  • Is there a reason why you don't want to set `self.image` in `setUp`? – schillingt Mar 31 '20 at 15:05
  • Yes, I have couple of other tests which uses the same image so I don't want to set every time in every test class. In general avoiding duplicate variable assignation – ivardu Apr 01 '20 at 15:12
  • You could subclass `TestCase`, then inherit from that in all of your tests. – schillingt Apr 01 '20 at 15:16
  • Yes, I'm using for one of the Test Cases by inheriting for example login. I'm looking for why global is not working and it's best practice or not.. – ivardu Apr 02 '20 at 12:08

0 Answers0