Completed
Pull Request — master (#2842)
by Edward
05:40
created

DownloadGitRepoActionTestCase.side_effect()   A

Complexity

Conditions 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
c 2
b 0
f 0
dl 0
loc 6
rs 9.4285
1
#!/usr/bin/env python
2
3
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
4
# contributor license agreements.  See the NOTICE file distributed with
5
# this work for additional information regarding copyright ownership.
6
# The ASF licenses this file to You under the Apache License, Version 2.0
7
# (the "License"); you may not use this file except in compliance with
8
# the License.  You may obtain a copy of the License at
9
#
10
#     http://www.apache.org/licenses/LICENSE-2.0
11
#
12
# Unless required by applicable law or agreed to in writing, software
13
# distributed under the License is distributed on an "AS IS" BASIS,
14
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
# See the License for the specific language governing permissions and
16
# limitations under the License.
17
18
import mock
19
import os
20
import shutil
21
import tempfile
22
import hashlib
23
24
from git.repo import Repo
25
from gitdb.exc import BadName
26
from st2common.services import packs as pack_service
27
from st2tests.base import BaseActionTestCase
28
29
from pack_mgmt.download import DownloadGitRepoAction
30
31
PACK_INDEX = {
32
    "test": {
33
        "version": "0.4",
34
        "name": "test",
35
        "repo_url": "https://github.com/StackStorm-Exchange/stackstorm-test",
36
        "author": "st2-dev",
37
        "keywords": ["some", "search", "another", "terms"],
38
        "email": "[email protected]",
39
        "description": "st2 pack to test package management pipeline"
40
    },
41
    "test2": {
42
        "version": "0.5",
43
        "name": "test2",
44
        "repo_url": "https://github.com/StackStorm-Exchange/stackstorm-test2",
45
        "author": "stanley",
46
        "keywords": ["some", "special", "terms"],
47
        "email": "[email protected]",
48
        "description": "another st2 pack to test package management pipeline"
49
    }
50
}
51
52
53
@mock.patch.object(pack_service, 'fetch_pack_index', mock.MagicMock(return_value=(PACK_INDEX, {})))
54
class DownloadGitRepoActionTestCase(BaseActionTestCase):
55
    action_cls = DownloadGitRepoAction
56
57
    def setUp(self):
58
        super(DownloadGitRepoActionTestCase, self).setUp()
59
60
        clone_from = mock.patch.object(Repo, 'clone_from')
61
62
        self.addCleanup(clone_from.stop)
63
        self.clone_from = clone_from.start()
64
65
        expand_user = mock.patch.object(os.path, 'expanduser',
66
                                        mock.MagicMock(return_value=tempfile.mkdtemp()))
67
68
        self.addCleanup(expand_user.stop)
69
        self.expand_user = expand_user.start()
70
71
        self.repo_base = tempfile.mkdtemp()
72
73
        self.repo_instance = mock.MagicMock()
74
75
        def side_effect(url, to_path, **kwargs):
76
            # Since we have no way to pass pack name here, we would have to derive it from repo url
77
            fixture_name = url.split('/')[-1]
78
            fixture_path = os.path.join(self._get_base_pack_path(), 'tests/fixtures', fixture_name)
79
            shutil.copytree(fixture_path, to_path)
80
            return self.repo_instance
81
82
        self.clone_from.side_effect = side_effect
83
84
    def tearDown(self):
85
        shutil.rmtree(self.repo_base)
86
        shutil.rmtree(self.expand_user())
87
88
    def test_run_pack_download(self):
89
        action = self.get_action_instance()
90
        result = action.run(packs=['test'], abs_repo_base=self.repo_base)
91
        temp_dir = hashlib.md5(PACK_INDEX['test']['repo_url']).hexdigest()
92
93
94
        self.assertEqual(result, {'test': 'Success.'})
95
        self.clone_from.assert_called_once_with(PACK_INDEX['test']['repo_url'],
96
                                           os.path.join(os.path.expanduser('~'), temp_dir),
97
                                           branch='master')
98
        self.assertTrue(os.path.isfile(os.path.join(self.repo_base, 'test/pack.yaml')))
99
100
    def test_run_pack_download_existing_pack(self):
101
        action = self.get_action_instance()
102
        action.run(packs=['test'], abs_repo_base=self.repo_base)
103
        self.assertTrue(os.path.isfile(os.path.join(self.repo_base, 'test/pack.yaml')))
104
105
        result = action.run(packs=['test'], abs_repo_base=self.repo_base)
106
107
        self.assertEqual(result, {'test': 'Success.'})
108
109
    def test_run_pack_download_multiple_packs(self):
110
        action = self.get_action_instance()
111
        result = action.run(packs=['test', 'test2'], abs_repo_base=self.repo_base)
112
        temp_dirs = [
113
            hashlib.md5(PACK_INDEX['test']['repo_url']).hexdigest(),
114
            hashlib.md5(PACK_INDEX['test2']['repo_url']).hexdigest()
115
        ]
116
117
        self.assertEqual(result, {'test': 'Success.', 'test2': 'Success.'})
118
        self.clone_from.assert_any_call(PACK_INDEX['test']['repo_url'],
119
                                        os.path.join(os.path.expanduser('~'), temp_dirs[0]),
120
                                        branch='master')
121
        self.clone_from.assert_any_call(PACK_INDEX['test2']['repo_url'],
122
                                        os.path.join(os.path.expanduser('~'), temp_dirs[1]),
123
                                        branch='master')
124
        self.assertEqual(self.clone_from.call_count, 2)
125
        self.assertTrue(os.path.isfile(os.path.join(self.repo_base, 'test/pack.yaml')))
126
        self.assertTrue(os.path.isfile(os.path.join(self.repo_base, 'test2/pack.yaml')))
127
128
    @mock.patch.object(Repo, 'clone_from')
129
    def test_run_pack_download_error(self, clone_from):
130
        clone_from.side_effect = Exception('Something went terribly wrong during the clone')
131
132
        action = self.get_action_instance()
133
        self.assertRaises(Exception, action.run, packs=['test'], abs_repo_base=self.repo_base)
134
135
    def test_run_pack_download_no_tag(self):
136
        self.repo_instance.commit.side_effect = BadName
137
138
        action = self.get_action_instance()
139
        self.assertRaises(ValueError, action.run, packs=['test#1.2.3'],
140
                          abs_repo_base=self.repo_base)
141
142
    def test_run_pack_download_v_tag(self):
143
        def side_effect(ref):
144
            if ref[0] != 'v':
145
                raise BadName()
146
147
        self.repo_instance.commit.side_effect = side_effect
148
149
        action = self.get_action_instance()
150
        result = action.run(packs=['test#1.2.3'], abs_repo_base=self.repo_base)
151
152
        self.assertEqual(result, {'test': 'Success.'})
153