Decorator to facilitate config changes in tests
- Dominant language
- Python
- Stars
- 15.7k
- Forks
- 2.1k
- Avg merge
- 4d 21h
- Merged PRs (30d)
- 31
Description
While modifying some of `fetchart`'s tests I came across the problem that test methods of one class need to apply different configurations each. To make this work, `fetchart` currently reads parts of the config not in `__init__` but when acutally searching for artwork. This is because the `UseThePlugin` subclass of `TestCase` that all tests use in order not to duplicate the plugin loading code otherwise would initialize the plugin (and read the config) before it can be changed in the method
It would probably be nicer to have all the config reading and validation in `__init__`, though. I don't know how much this affects other parts of beets, but I'd assume the problem to be global. One solution I came up with is the following decorator (which I did not test, maybe it doesn't even work!). The only catch might be that it makes use of `unittest.TestCase._testMethodName`, which is undocumented:
The decorator
``` python
def with_config(self, func, config, before_setup=True):
func.__beets_config = config
func.__beets_config_before_setup = before_setup
@wraps(func)
def apply_config(*args, **kwargs):
if not func.__beets_config_before_setup:
beets.config.add(config)
func(*args, **kwargs)
return apply_config
```
Additions to `setUp`
``` python
def setUp(self):
...
func = getattr(self, self._testMethodName)
if hasattr(func, '__beets_config') and func.__beets_config_before_setup:
beets.config.add(func.__beets_config)
...
```
Using it
``` python
class UseThePlugin(_common.TestCase):
def setUp(self):
super(UseThePlugin, self).setUp()
# The config is now updated!
self.plugin = fetchart.FetchArtPlugin()
```
``` python
class MyTest(UseThePlugin):
@with_config({u'fetchart': {u'somekey': 42}})
test_it(self)
pass
```
If the undocumented attribute is not a showstopper, would this be worth including in `_common.TestCase`?
On a side-note; is there anyone working on https://github.com/beetbox/beets/issues/735#issuecomment-153418759 ? If not, I might take over joining `test._common`/`test.helper`.
Contributor guide
Assessment
This issue has not been assessed yet.