c5400a3cefc7b69dd23fd58b6403de5d0c1779bc
[dcaegen2/platform.git] / adapter / acumos / tests / test_fed.py
1 # ============LICENSE_START====================================================
2 # org.onap.dcae
3 # =============================================================================
4 # Copyright (c) 2019-2020 AT&T Intellectual Property. All rights reserved.
5 # =============================================================================
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # 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 # ============LICENSE_END======================================================
18
19 import json
20 import requests
21
22 from testing_helpers import get_fixture_path as get_test_file
23
24 from aoconversion import docker_gen as aoc_docker_gen
25 from aoconversion import scanner as aoc_scanner
26
27 #
28 # General mocking
29 #
30
31
32 class _MockModule:
33     """
34     Class to mock packages.
35     Just a quick way to create an object with specified attributes
36     """
37     def __init__(self, **kwargs):
38         for k, v in kwargs.items():
39             setattr(self, k, v)
40
41
42 #
43 # Mocking for package "docker"
44 #
45
46
47 class _MockAPIClient:
48     """
49     Class to mock docker.APIClient class.
50     """
51     def __init__(self, base_url, version=None, user_agent='xxx'):
52         pass
53
54     def build(self, path, rm, tag):
55         return [b'some message', b'another message']
56
57     def push(self, repository, auth_config, stream):
58         return [b'some message', b'another message']
59
60     def images(self, x):
61         return True
62
63
64 def _mock_kwargs_from_env(**kwargs):
65     """
66     Method to mock docker.utils.kwargs_from_env method.
67     """
68     return {'base_url': None}
69
70
71 _mockdocker = _MockModule(
72     APIClient=_MockAPIClient,
73     utils=_MockModule(kwargs_from_env=_mock_kwargs_from_env))
74
75
76 #
77 # Mocking for requests.get
78 #
79
80
81 class _r:
82     """
83     Fake responses for mocking requests.get
84     """
85     def __init__(self, json=None, file=None, data=None):
86         self.jx = json
87         self.fx = file
88         self.dx = data
89         self.status_code = 200
90
91     @property
92     def text(self):
93         return self._raw().decode()
94
95     def raise_for_status(self):
96         pass
97
98     def _raw(self):
99         if self.dx is None:
100             if self.fx is not None:
101                 with open(self.fx, 'rb') as f:
102                     self.dx = f.read()
103             elif self.jx is not None:
104                 self.dx = json.dumps(self.jx, sort_keys=True).encode()
105             else:
106                 self.dx = b''
107         return self.dx
108
109     def iter_content(self, bsize=-1):
110         buf = self._raw()
111         pos = 0
112         lim = len(buf)
113         if bsize <= 0:
114             bsize = lim
115         while pos + bsize < lim:
116             yield buf[pos:pos + bsize]
117             pos = pos + bsize
118         yield buf[pos:]
119
120     def json(self):
121         if self.jx is None:
122             self.jx = json.loads(self._raw().decode())
123         return self.jx
124
125
126 def _mockwww(responses):
127     def _op(path, json=None, auth=None, cert=None, verify=None, stream=False):
128         return responses[path]
129     return _op
130
131
132 _mockpostdata = {
133     'https://onboarding/dataformats': _r({'dataFormatUrl': 'https://onboarding/dataformats/somedfid'}),
134     'https://onboarding/components': _r({'componentUrl': 'https://onboarding/components/somedxid'}),
135 }
136
137 _mockpatchdata = {
138     'https://onboarding/dataformats/somedfid': _r({}),
139     'https://onboarding/components/somedxid': _r({}),
140 }
141
142 _mockwebdata = {
143     'https://acumos/catalogs': _r({'content': [{'catalogId': 'c1'}]}),
144     'https://acumos/solutions?catalogId=c1': _r({'content': [{'solutionId': 's1', 'name': 'example-model', 'ratingAverageTenths': 17}]}),
145     'https://acumos/solutions/s1/revisions': _r({'content': [{'revisionId': 'r1'}]}),
146     'https://acumos/solutions/s1/revisions/r1': _r({'content': {
147         'version': 'v1',
148         'modified': '2019-01-01T00:00:00Z',
149         'artifacts': [
150             {'artifactId': 'a1', 'name': 'xxx.other'},
151             {'artifactId': 'a2', 'name': 'xxx.proto'},
152             {'artifactId': 'a3', 'name': 'xxx.zip'},
153             {'artifactId': 'a4', 'name': 'xxx.json'},
154         ]}
155     }),
156     'https://acumos/artifacts/a2/content': _r(file=get_test_file('models/example-model/model.proto')),
157     'https://acumos/artifacts/a3/content': _r(data=b'dummy zip archive data'),
158     'https://acumos/artifacts/a4/content': _r(file=get_test_file('models/example-model/metadata.json')),
159 }
160
161
162 #
163 # End mocking tools
164 #
165
166
167 def test_aoconversion(mock_schemas, tmpdir, monkeypatch):
168     config = aoc_scanner.Config(dcaeurl='http://dcaeurl', dcaeuser='dcaeuser', onboardingurl='https://onboarding', onboardinguser='obuser', onboardingpass='obpass', acumosurl='https://acumos', certfile=None, dockerregistry='dockerregistry', dockeruser='registryuser', dockerpass='registrypassword')
169     monkeypatch.setattr(aoc_docker_gen, 'APIClient', _mockdocker.APIClient)
170     monkeypatch.setattr(requests, 'get', _mockwww(_mockwebdata))
171     monkeypatch.setattr(requests, 'post', _mockwww(_mockpostdata))
172     monkeypatch.setattr(requests, 'patch', _mockwww(_mockpatchdata))
173     aoc_scanner.scan(config)
174     aoc_scanner.scan(config)
175
176
177 def test__derefconfig():
178     config_path = get_test_file('config.yaml')
179     assert aoc_scanner._derefconfig('@' + config_path) == 'dcaeurl: https://git.onap.org/dcaegen2/platform/plain/mod'