Background
The Django LiveServerTestCase
class has a live_server_url
method with a @classproperty
decorator. (django.utils.functional.classproperty
.) The class starts its test server before any tests run, and thus knows the test server's URL before any tests run.
I have a similar MyTestCase
class that has a live_server_url
@property
. It starts a new test server before each test, and thus its live_server_url
property can't be a @classproperty
because it doesn't know its port until it is instantiated.
To make the API for both consistent, so that all the test utility functions etc. in the code base can be used with both classes, the tests could be written to never reference live_server_url
in setUpClass()
, before all the tests run. But this would slow down many tests.
Instead, I want MyTestCase.live_server_url
to raise a helpful error if it is referenced from the class object rather than an instance object.
Since MyTestCase.live_server_url
is a @property
, MyTestCase().live_server_url
returns a string, but MyTestCase.live_server_url
returns a property object. This causes cryptic errors like "TypeError: unsupported operand type(s) for +: 'property' and 'str'"
.
Actual question
If I could define a @classproperty
and @property
on the same class, then I would define a MyTestCase.live_server_url
@classproperty
that raises an error with a helpful message like "live_server_url can only be called on an instance of MyTestCase, not on the MyTestCase class".
But when you define 2 methods with the same name in a Python class then the earlier one gets discarded, so I can't do that.
How can I make the behavior of MyTestCase.live_server_url
different depending on whether it is called on the class or on an instance?