1

Am trying to set a decorator on a unit test, the purpose of the decorator is to ensure that a user logins in before accessing other endpoints.

Below is the decorator for logging in :

def login_decorator(*args, **kwargs):
    def login_user():
        kwargs['self'].client.login(
            username=kwargs['email'],
            password=kwargs['password'],
        )

Then am trying to utilize it on the unit test function as below :

@login_decorator(self=self, email=self.email, password=self.password)
    def test_customer_profile_add(self):
        response = super().create_customer_profile(self.customer_data)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

however self is underlines with an error Unresolved reference , how can I achieve passing of the params through the decorator with self.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Lutaaya Huzaifah Idris
  • 3,596
  • 8
  • 38
  • 77
  • 2
    There are many problems here. I think you would do well to start by reviewing a [general guide to writing decorators with arguments](https://stackoverflow.com/a/1594484) (link is to one of the "classic" highly-rated Stack Overflow answers). – Karl Knechtel Mar 18 '21 at 21:58

1 Answers1

1

You should pass your params to login_user function:


def login_decorator(func):
    def login_user(self, *args, **kwargs):
        # function args
        print(self.username, self.password)
        self.client.login(
            username=self.username,
            password=self.password,
        )
        func(self, *args, **kwargs)

and your test function:

@login_decorator
def test_customer_profile_add(self):
    response = super().create_customer_profile(self.customer_data)
    self.assertEqual(response.status_code, status.HTTP_201_CREATED)
Phoenix
  • 3,996
  • 4
  • 29
  • 40