1import os
2from click.testing import CliRunner
3
4from gandi.cli.core.base import GandiModule
5from ..compat import unittest, mock
6from ..fixtures.api import Api
7from ..fixtures.mocks import MockObject
8
9
10class CommandTestCase(unittest.TestCase):
11
12    base_mocks = [
13        ('gandi.cli.core.base.GandiModule.save', MockObject.blank_func),
14        ('gandi.cli.core.base.GandiModule.execute', MockObject.execute),
15        ('gandi.cli.core.base.GandiModule.deprecated', MockObject.deprecated),
16    ]
17    mocks = []
18
19    def setUp(self):
20        self.runner = CliRunner()
21
22        self.mocks = self.mocks + self.base_mocks
23        self.mocks = [mock.patch(*mock_args) for mock_args in self.mocks]
24        for dummy in self.mocks:
25            dummy.start()
26
27        GandiModule._api = Api()
28        GandiModule._api._calls = {}
29        GandiModule._conffiles = {'global': {'api': {'env': 'test',
30                                                     'key': 'apikey0001'},
31                                             'apirest': {'key': 'apikey002'}}}
32        GandiModule._poll_freq = 0.1
33
34        self.api_calls = GandiModule._api._calls
35
36    def tearDown(self):
37        GandiModule._api = None
38        GandiModule._conffiles = {}
39
40        for dummy in reversed(self.mocks):
41            dummy.stop()
42
43    def invoke_with_exceptions(self, cli, args, catch_exceptions=False,
44                               **kwargs):
45        return self.runner.invoke(cli, args, catch_exceptions=catch_exceptions,
46                                  **kwargs)
47
48    def isolated_invoke_with_exceptions(self, cli, args,
49                                        catch_exceptions=False,
50                                        temp_dir=None,
51                                        temp_name=None,
52                                        temp_content=None,
53                                        **kwargs):
54
55        temp_dir = temp_dir or 'sandbox'
56        temp_name = temp_name or 'example.txt'
57        with self.runner.isolated_filesystem():
58            os.mkdir(temp_dir)
59
60            with open('%s/%s' % (temp_dir, temp_name), 'w') as f:
61                f.write(temp_content)
62
63            return self.runner.invoke(cli, args,
64                                      catch_exceptions=catch_exceptions,
65                                      **kwargs)
66