0

I try to look answer on StackOverflow but I can not find a solution - the most answer is old or not used for my. I have code like this:

#file app.py
#structure of directory
#-words
#--x
#---y
#----z
#------app.py
#-test
#--test.py

def is_connected(f):
    def is_con(self):
        if self.connection:
           print("not work")
        else:
             return False
        f()
        return True
   return is_con

class A():
    /*another code */
    
    @is_connected
    def get_element(self):
        return True

This is the basic logic of my code, for now, I want to test this using unittest.


def lol():
   print(123)

from unittest.mock import patch
from words.x.y.z.app import A
class TestUnit:
    @patch('words.x.y.z.app.is_connected)
    def test_get(self, mocked):
       mocked.return_value = 23
       mocked.side_effect = lol
       a = A()
       assert a.get_element()

But when I run test I see in console

not work

So I guess, this decorator is not mocked. How I can do this properly?

The solutions from stackoverflow which I tried because have sense for me.: Mock authentication decorator in unittesting , Can I patch a Python decorator before it wraps a function?

1 Answers1

0

I found a solution: I added to my decorator @wraps(f) from functools import wraps

def is_connected(f):
    def is_con(self):
        if self.connection:
           print("not work")
        else:
             return False
        f()
        return True
   return is_con

And when I want to test any method with this I just do this:

from unittest.mock import patch
from words.x.y.z.app import A
class TestUnit:

    def test_get(self, ):
       a = A()
       assert a.get_element.__wrapped__(a)

But I don't know how I should use this in this case:

    @is_connected
    def get_element(self, element):
        return element

Should works sth like this:

       assert a.get_element(1).__wrapped__(a)

but no