aboutsummaryrefslogtreecommitdiffstats
path: root/vid-automation/src/test/java/org/onap/vid/api/InstantiationTemplatesApiTest.java
blob: bc47ad8344614f77921cf94014c4bdf41a371095 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
package org.onap.vid.api;

import static java.util.Arrays.stream;
import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.arrayWithSize;
import static org.hamcrest.Matchers.greaterThan;
import static org.onap.vid.api.TestUtils.convertRequest;
import static vid.automation.test.services.SimulatorApi.registerExpectationFromPreset;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.ImmutableMap;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.onap.sdc.ci.tests.datatypes.UserCredentials;
import org.onap.simulator.presetGenerator.presets.aai.PresetAAIGetSubscribersGet;
import org.onap.vid.model.mso.MsoResponseWrapper2;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import vid.automation.test.Constants.Users;
import vid.automation.test.infra.FeatureTogglingTest;
import vid.automation.test.infra.Features;
import vid.automation.test.model.User;
import vid.automation.test.services.AsyncJobsService;
import vid.automation.test.services.SimulatorApi.RegistrationStrategy;

public class InstantiationTemplatesApiTest extends AsyncInstantiationBase {

    /*
    Testing the Template Topology API should be very thin, given the following
    assumptions:

      - Template topology API is relying on Retry's logic.

      - The templates themselves are an actual representation of the initial
        state in VID's backend. This is all the knowledge that used to create
        a service in the first time. So if API is fed with same state, it already
        should be able to reiterate another instance.


    The tests below will verify that:

      - A request resulting from Cypress test on "instantiation-templates.e2e.ts"
        is accepted by API endpoint

      - A valid "regular" (not from template) request, yields a template that a
        Cypress is able to deploy.

      These two tests are, technically,  cyclic.

      Currently the only test below is shortcutting the both tests, by checking
      that feeding a Cypress input yields a Template that is the same. This is
      not perfect, but currently what we have.

     */

    @Override
    public UserCredentials getUserCredentials() {
        User user = usersService.getUser(Users.SILVIA_ROBBINS_TYLER_SILVIA);
        return new UserCredentials(user.credentials.userId, user.credentials.password, Users.SILVIA_ROBBINS_TYLER_SILVIA, "", "");
    }

    @BeforeMethod
    public void setUp() {
        registerExpectationFromPreset(new PresetAAIGetSubscribersGet(), RegistrationStrategy.CLEAR_THEN_SET);
    }

    @AfterMethod
    protected void dropAllFromNameCounter() {
        AsyncJobsService asyncJobsService = new AsyncJobsService();
        asyncJobsService.muteAllAsyncJobs();
        asyncJobsService.dropAllFromNameCounter();
    }

    protected String templateTopologyUri(String jobId) {
        return uri.toASCIIString() + "/instantiationTemplates/templateTopology/" + jobId;
    }

    @Test
    public void templateTopology_givenDeployFromCypressE2E_getTemplateTopologyDataIsEquivalent() throws IOException {
        templateTopology_givenDeploy_templateTopologyIsEquivalentToBody(
            fileAsJsonNode("asyncInstantiation/templates__instance_template.json"));
    }

    @Test
    public void templateTopology_givenDeployFromEditedTemplateCypressE2E_getTemplateTopologyDataIsEquivalentToOriginalTemplate() throws IOException {
        templateTopology_givenDeploy_templateTopologyIsEquivalent(
            fileAsJsonNode("asyncInstantiation/templates__instance_from_template__set_without_modify1.json"),
            fileAsJsonNode("asyncInstantiation/templates__instance_template.json"));
    }

    @Test
    public void templateTopology_givenDeploy_OriginalTemplateNotChanged() throws IOException {
        String uuidOriginTemplate = postAsyncInstanceRequest(fileAsJsonNode("asyncInstantiation/templates__instance_template.json"));
        JsonNode originTemplateBeforeDeploy = restTemplate.getForObject(templateTopologyUri(uuidOriginTemplate), JsonNode.class);

        ObjectNode changedNode = originTemplateBeforeDeploy.deepCopy();
        changedNode.put("instanceName", "Cloned_Node_Instance_Name");
        postAsyncInstanceRequest(changedNode);

        JsonNode originTemplateAfterDeploy = restTemplate.getForObject(templateTopologyUri(uuidOriginTemplate), JsonNode.class);
        assertThat(cleanupTemplate(originTemplateBeforeDeploy), jsonEquals(cleanupTemplate(originTemplateAfterDeploy)));

    }

    @Test
    @FeatureTogglingTest(Features.FLAG_2004_CREATE_ANOTHER_INSTANCE_FROM_TEMPLATE)
    public void templateTopology_givenDeploy_getServiceInfoHoldsRequestSummary() throws IOException {
        ObjectNode request =
            fileAsJsonNode(CREATE_BULK_OF_MACRO_REQUEST)
                .put("bulkSize", 1)
                .put("pause", false);

        postAsyncInstanceRequest(request);

        assertThat(fetchRequestSummary(request.at("/modelInfo/modelVersionId").asText()),
            jsonEquals(ImmutableMap.of(
                "vnf", 1L,
                "vfModule", 2L,
                "volumeGroup", 1L
            )));
    }

    private JsonNode fetchRequestSummary(String serviceModelId) {
        return stream(restTemplate.getForObject(getTemplateInfoUrl(serviceModelId), JsonNode[].class))
            .map(it -> it.at("/requestSummary"))
            .findFirst()
            .orElseGet(() -> {
                throw new AssertionError(getTemplateInfoUrl(serviceModelId) + " returned zero results");
            });
    }

    private ObjectNode fileAsJsonNode(String fileName) throws IOException {
        return objectMapper.readValue(
            convertRequest(objectMapper, fileName),
            ObjectNode.class);
    }

    public void templateTopology_givenDeploy_templateTopologyIsEquivalentToBody(JsonNode body) {
        templateTopology_givenDeploy_templateTopologyIsEquivalent(body, body);
    }

    public void templateTopology_givenDeploy_templateTopologyIsEquivalent(JsonNode body, JsonNode expectedTemplateTopology) {
        String uuid1 = postAsyncInstanceRequest(body);
        JsonNode templateTopology1 = restTemplate.getForObject(templateTopologyUri(uuid1), JsonNode.class);

        assertThat(cleanupTemplate(templateTopology1), jsonEquals(cleanupTemplate(expectedTemplateTopology)));
    }

    private JsonNode cleanupTemplate(JsonNode templateTopology) {
        return Stream.of(templateTopology)
            .map(this::removeTrackById)
            .map(this::removeNullValues)
            .findAny().get();
    }

    private JsonNode removeTrackById(JsonNode node) {
        return removeAny(node, it -> it.getKey().equals("trackById"));
    }

    private JsonNode removeNullValues(JsonNode node) {
        return removeAny(node, it -> it.getValue().isNull());
    }

    private JsonNode removeAny(JsonNode node, Predicate<Entry<String, JsonNode>> entryPredicate) {
        if (node.isObject()) {
            ((ObjectNode) node).remove(
                Streams.fromIterator(node.fields())
                    .filter(entryPredicate)
                    .map(Entry::getKey)
                    .collect(Collectors.toList())
            );

            for (JsonNode child : node) {
                removeAny(child, entryPredicate);
            }
        }

        return node;
    }

    private <T> String postAsyncInstanceRequest(T body) {
        String[] jobsUuids = (String[]) restTemplate.exchange(
            getCreateBulkUri(),
            HttpMethod.POST,
            new HttpEntity<>(body),
            new ParameterizedTypeReference<MsoResponseWrapper2<String[]>>() {
            })
            .getBody().getEntity();

        assertThat(jobsUuids, arrayWithSize(greaterThan(0)));
        return jobsUuids[0];
    }

}