-2

Given that I have the below test:

class VideoGamesTest:


    def test_create_a_new_videoGame(self):

        protocol = 'http://'
        domain = 'localhost:'
        port = '8080'
        path = '/app/videogames'
        self.url = protocol+domain+port+path

        response = requests.get(self.url,headers={'Accept': 'application/json'})

        payload = {
                "id": 16,
                "name": "I am my Hero",
                "releaseDate": "2020-02-21T16:54:03.200Z",
                "reviewScore": 9.0,
                "category": "Biography",
                "rating": "9.0"
            }


        response = requests.post(self.url,data=json.dumps(payload),headers={'Content-Type': 'application/json'} )
        response = json.loads(response.text)
        assert 'status' in response.keys()


    def test_get_all_videoGames(self):

        protocol = 'http://'
        domain = 'localhost:'
        port = '8080'
        path = '/app/videogames'
        self.url = protocol+domain+port+path
        response = requests.get(self.url,headers={'Accept': 'application/json'})

        response = json.loads(response.text)[0]

        print(response)

        assert 'id' in response.keys()

As you can see, the below part is repetitive:

    protocol = 'http://'
    domain = 'localhost:'
    port = '8080'
    path = '/app/videogames'
    self.url = protocol+domain+port+path

I don't know, how to refactor the this class so that i can have the url as the attribute of the class. But, given that, i cannot use __init__ in my pytest class, then it is not doable.

Question is:

How can i omit the repetitive part of the tests?

Jeff
  • 7,767
  • 28
  • 85
  • 138
  • 1
    Make them class attributes? – jordanm Feb 21 '20 at 20:59
  • https://docs.python.org/3.8/tutorial/classes.html#class-and-instance-variables – jordanm Feb 21 '20 at 21:00
  • Yes, but inorder to make them the class atribute, i should have the costructor `__init__` but i am not allowed to do that in `pytest` normally. – Jeff Feb 21 '20 at 21:08
  • 1
    Assigning via `__init__` would make it an instance attribute, not a class attribute. The link I posted explains the difference. – jordanm Feb 21 '20 at 21:12

1 Answers1

0

You can use the unittest.TestCase class from the standard library as base class of your testing class and use the setUpClass(cls) to attach attributes to the cls to have them available during the runtime of your testing methods.

import unittest

class MyTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
       """ put your setup code here, attach the attributes to the passed cls object """
marscher
  • 800
  • 1
  • 5
  • 22