Initial OpenECOMP policy/engine commit
[policy/engine.git] / ECOMP-TEST / src / test / java / org / openecomp / policy / pdp / test / std / json / RequestConformanceTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP-TEST
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.policy.pdp.test.std.json;
22
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.fail;
25
26 import java.io.File;
27 import java.io.StringWriter;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.Iterator;
31 import java.util.List;
32
33 import javax.xml.transform.Transformer;
34 import javax.xml.transform.TransformerFactory;
35 import javax.xml.transform.dom.DOMSource;
36 import javax.xml.transform.stream.StreamResult;
37
38 import org.junit.Test;
39
40 import com.att.research.xacml.api.Request;
41 import com.att.research.xacml.api.RequestAttributes;
42 import com.att.research.xacml.api.RequestReference;
43 import com.att.research.xacml.std.dom.DOMRequest;
44 import com.att.research.xacml.std.json.JSONRequest;
45 import com.att.research.xacml.std.json.JSONStructureException;
46 /**
47  * Test JSON Request convert to object - Conformance tests
48  * 
49  * TO RUN - use jUnit
50  * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test
51  * 
52  * NOTE:
53  * The "correct" way to verify that each JSON string gets translated into our internal Objects correctly is to look explicitly at each of the child objects
54  * and verify that they are correct.  This would involve a lot of coding to get child of child of child and individually verify each property of each element.
55  * To simplify testing we assume that request.toString() correctly includes a complete text representation of every sub-component of the Request object
56  * and we compare the resulting String to our expected String.
57  * This has two possible sources of error:
58  *      - toString might not include some sub-component, and
59  *      - the initial verification of the resulting string is done by hand and may have been incorrect.
60  * 
61  *
62  */
63 public class RequestConformanceTest {
64         
65         // where to find the conformance test XML files
66         private final String CONFORMANCE_DIRECTORY_PATH = "testsets/conformance/xacml3.0-ct-v.0.4";
67         
68         // The request object output from each test conversion from JSON string
69         Request request;
70
71
72         
73         
74         
75         // test just one of each top-level element.
76         // For simple elements also test for incorrect type
77         @Test
78         public void testConformanceRequests() {
79                 
80                 List<File> filesInDirectory = null;
81                 
82                 File conformanceDirectory = null;
83                 
84                 File currentFile = null;
85                 
86                 try {
87                         conformanceDirectory = new File(CONFORMANCE_DIRECTORY_PATH);
88                         filesInDirectory = getRequestsInDirectory(conformanceDirectory);
89                 } catch (Exception e) {
90                         fail("Unable to set up Conformance tests for dir '" + conformanceDirectory.getAbsolutePath()+"' e="+ e);
91                 }
92                 
93                 // run through each XML file
94                 //      - load the file from XML into an internal Request object
95                 //      - generate the JSON representation of that Request object
96                 //      - load that JSON representation into a new Request object
97                 //      - compare the 2 Request objects
98                 Request xmlRequest = null;
99                 Request jsonRequest = null;
100                 try {
101                         for (File f : filesInDirectory) {
102                                 currentFile = f;
103
104 //// This is a simple way to select just one file for debugging - comment out when not being used
105 //if ( ! f.getName().equals("IIA023Request.xml")) {   continue;  }
106
107 // during debugging it is helpful to know what file it is starting to work on
108 //                              System.out.println("starting file="+currentFile.getName());
109                                 
110                                 try {
111                                         // load XML into a Request object
112                                         xmlRequest = DOMRequest.load(f);
113                                         xmlRequest.getStatus();
114                                 } catch (Exception e) {
115                                         // if XML does not load, just note it and continue with next file
116                                         System.out.println("XML file did not load: '" + f.getName() + "  e=" + e);
117                                         continue;
118                                 }
119                                 
120
121
122                                 // generate JSON from the Request
123                                 String jsonString = JSONRequest.toString(xmlRequest, false);
124
125                                         
126                                 
127                                 // load JSON into a Request
128                                 jsonRequest = JSONRequest.load(jsonString);
129                                 
130                                 // compare the two Request objects
131                                 
132                                 // check simple things first
133                                 assertEquals("File '" + currentFile.getName() + "' CombinedDecision", xmlRequest.getCombinedDecision(), jsonRequest.getCombinedDecision());
134                                 assertEquals("File '" + currentFile.getName() + "' getReturnPolicyIdList", xmlRequest.getReturnPolicyIdList(), jsonRequest.getReturnPolicyIdList());
135                                 assertEquals("File '" + currentFile.getName() + "' requestDefaults", xmlRequest.getRequestDefaults(), jsonRequest.getRequestDefaults());
136
137                                 // multiRequests (guaranteed to not be null)
138                                 // We do NOT care about ordering, so compare the two collections inefficiently
139                                 Collection<RequestReference> xmlCollection = xmlRequest.getMultiRequests();
140                                 Collection<RequestReference> jsonCollection = jsonRequest.getMultiRequests();
141                                 String errorMessage = null;
142                                 if (jsonCollection.size() != xmlCollection.size()) {
143                                         errorMessage = "File '" + currentFile.getName() + "' MultiRequests not same size.  ";
144                                 } else if (! jsonCollection.containsAll(xmlCollection)) {
145                                         errorMessage = "File '" + currentFile.getName() + "' MultiRequests have different contents.  ";
146                                 }
147                                 if (errorMessage != null) {
148                                         String xmlContents = "";
149                                         String jsonContents = "";
150                                         Iterator<RequestReference> rrIt = xmlCollection.iterator();
151                                         while (rrIt.hasNext()) {
152                                                 xmlContents += "\n   " + rrIt.next().toString(); 
153                                         }
154                                         rrIt = jsonCollection.iterator();
155                                         while (rrIt.hasNext()) { 
156                                                 jsonContents += "\n  " + rrIt.next().toString(); 
157                                         }
158                                         fail(errorMessage + "\nXML(" + xmlCollection.size() + ")='" + xmlContents + 
159                                                         "'  \nJSON(" + jsonCollection.size() + ")='" + jsonContents +
160                                                         "'" +
161                                                         "\njson='" + jsonString + "'");
162                                 }
163                                 
164                                 // attributes (guaranteed to not be null)
165                                 // We do NOT care about ordering, so compare the two collections inefficiently
166                                 Collection<RequestAttributes> xmlAttrCollection = xmlRequest.getRequestAttributes();
167                                 Collection<RequestAttributes> jsonAttrCollection = jsonRequest.getRequestAttributes();
168                                 errorMessage = null;
169                                 if (jsonAttrCollection.size() != xmlAttrCollection.size()) {
170                                         errorMessage = "File '" + currentFile.getName() + "' RequestAttributes not same size.  ";
171                                 } else if (! jsonAttrCollection.containsAll(xmlAttrCollection)) {
172                                         String attrName = "";
173                                         Iterator<RequestAttributes> rait = xmlAttrCollection.iterator();
174                                         while (rait.hasNext()) {
175                                                 RequestAttributes ra = rait.next();
176                                                 if (jsonAttrCollection.contains(ra) == false) {
177                                                         attrName = ra.toString();
178                                                 }
179                                         }
180                                         errorMessage = "File '" + currentFile.getName() + "' RequestAttributes have different contents.  JSON is missing attr=" + attrName;
181                                 }
182                                 if (errorMessage != null) {
183                                         String xmlContents = "";
184                                         String jsonContents = "";
185                                         Iterator<RequestAttributes> rrIt = xmlAttrCollection.iterator();
186                                         while (rrIt.hasNext()) {
187                                                 RequestAttributes ras = rrIt.next();
188                                                 xmlContents += "\n   " + ras.toString();
189                                                 if (ras.getContentRoot() != null) {
190                                                         StringWriter writer = new StringWriter();
191                                                         Transformer transformer = null;
192                                                         try {
193                                                                 transformer = TransformerFactory.newInstance().newTransformer();
194                                                                 transformer.transform(new DOMSource(ras.getContentRoot()), new StreamResult(writer));
195                                                         } catch (Exception e) {
196                                                                 throw new JSONStructureException("Unable to Content node to string; e="+e);
197                                                         }
198
199                                                         xmlContents += "\n        Content: " + writer.toString();
200                                                 }
201                                         }
202                                         rrIt = jsonAttrCollection.iterator();
203                                         while (rrIt.hasNext()) { 
204                                                 RequestAttributes ras = rrIt.next();
205                                                 jsonContents += "\n   " + ras.toString();       
206                                                 if (ras.getContentRoot() != null) {
207                                                         StringWriter writer = new StringWriter();
208                                                         Transformer transformer = null;
209                                                         try {
210                                                                 transformer = TransformerFactory.newInstance().newTransformer();
211                                                                 transformer.transform(new DOMSource(ras.getContentRoot()), new StreamResult(writer));
212                                                         } catch (Exception e) {
213                                                                 throw new JSONStructureException("Unable to Content node to string; e="+e);
214                                                         }
215
216                                                         jsonContents += "\n        Content: " + writer.toString();
217                                                 }
218                                         }
219                                         fail(errorMessage + "\nXML(" + xmlAttrCollection.size() + ")='" + xmlContents + 
220                                                         "'  \nJSON(" + jsonAttrCollection.size() + ")='" + jsonContents +
221                                                         "\njson='" + jsonString + "'");
222                                 }
223                                 
224
225                         }                       
226
227                 } catch (Exception e) {
228                         fail ("Failed test with '" + currentFile.getName() + "', e=" + e);
229                 }
230
231                 
232         }
233         
234         //
235         // HELPER to get list of all Request files in the given directory
236         //
237         
238         private List<File> getRequestsInDirectory(File directory) {
239                 List<File> fileList = new ArrayList<File>();
240                 
241                 File[] fileArray = directory.listFiles();
242                 for (File f : fileArray) {
243                         if (f.isDirectory()) {
244                                 List<File> subDirList = getRequestsInDirectory(f);
245                                 fileList.addAll(subDirList);
246                         }
247                         if (f.getName().endsWith("Request.xml")) {
248                                 fileList.add(f);
249                         }
250                 }
251                 return fileList;
252                 
253         }
254         
255 }