Initial OpenECOMP policy/engine commit
[policy/engine.git] / ECOMP-XACML / src / test / java / org / openecomp / policy / xacml / test / json / RequestConformanceTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP-XACML
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.xacml.test.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 //System.out.println(JSONRequest.toString(xmlRequest, false));
121
122                                 // generate JSON from the Request
123                                 String jsonString = JSONRequest.toString(xmlRequest, false);            
124                                 
125                                 // load JSON into a Request
126                                 jsonRequest = JSONRequest.load(jsonString);
127                                 
128                                 // compare the two Request objects
129                                 
130                                 // check simple things first
131                                 assertEquals("File '" + currentFile.getName() + "' CombinedDecision", xmlRequest.getCombinedDecision(), jsonRequest.getCombinedDecision());
132                                 assertEquals("File '" + currentFile.getName() + "' getReturnPolicyIdList", xmlRequest.getReturnPolicyIdList(), jsonRequest.getReturnPolicyIdList());
133                                 assertEquals("File '" + currentFile.getName() + "' requestDefaults", xmlRequest.getRequestDefaults(), jsonRequest.getRequestDefaults());
134
135                                 // multiRequests (guaranteed to not be null)
136                                 // We do NOT care about ordering, so compare the two collections inefficiently
137                                 Collection<RequestReference> xmlCollection = xmlRequest.getMultiRequests();
138                                 Collection<RequestReference> jsonCollection = jsonRequest.getMultiRequests();
139                                 String errorMessage = null;
140                                 if (jsonCollection.size() != xmlCollection.size()) {
141                                         errorMessage = "File '" + currentFile.getName() + "' MultiRequests not same size.  ";
142                                 } else if (! jsonCollection.containsAll(xmlCollection)) {
143                                         errorMessage = "File '" + currentFile.getName() + "' MultiRequests have different contents.  ";
144                                 }
145                                 if (errorMessage != null) {
146                                         String xmlContents = "";
147                                         String jsonContents = "";
148                                         Iterator<RequestReference> rrIt = xmlCollection.iterator();
149                                         while (rrIt.hasNext()) {
150                                                 xmlContents += "\n   " + rrIt.next().toString(); 
151                                         }
152                                         rrIt = jsonCollection.iterator();
153                                         while (rrIt.hasNext()) { 
154                                                 jsonContents += "\n  " + rrIt.next().toString(); 
155                                         }
156                                         fail(errorMessage + "\nXML(" + xmlCollection.size() + ")='" + xmlContents + 
157                                                         "'  \nJSON(" + jsonCollection.size() + ")='" + jsonContents +
158                                                         "'" +
159                                                         "\njson='" + jsonString + "'");
160                                 }
161                                 
162                                 // attributes (guaranteed to not be null)
163                                 // We do NOT care about ordering, so compare the two collections inefficiently
164                                 Collection<RequestAttributes> xmlAttrCollection = xmlRequest.getRequestAttributes();
165                                 Collection<RequestAttributes> jsonAttrCollection = jsonRequest.getRequestAttributes();
166                                 errorMessage = null;
167                                 if (jsonAttrCollection.size() != xmlAttrCollection.size()) {
168                                         errorMessage = "File '" + currentFile.getName() + "' RequestAttributes not same size.  ";
169                                 } else if (! jsonAttrCollection.containsAll(xmlAttrCollection)) {
170                                         String attrName = "";
171                                         Iterator<RequestAttributes> rait = xmlAttrCollection.iterator();
172                                         while (rait.hasNext()) {
173                                                 RequestAttributes ra = rait.next();
174                                                 if (jsonAttrCollection.contains(ra) == false) {
175                                                         attrName = ra.toString();
176                                                 }
177                                         }
178                                         errorMessage = "File '" + currentFile.getName() + "' RequestAttributes have different contents.  JSON is missing attr=" + attrName;
179                                 }
180                                 if (errorMessage != null) {
181                                         String xmlContents = "";
182                                         String jsonContents = "";
183                                         Iterator<RequestAttributes> rrIt = xmlAttrCollection.iterator();
184                                         while (rrIt.hasNext()) {
185                                                 RequestAttributes ras = rrIt.next();
186                                                 xmlContents += "\n   " + ras.toString();
187                                                 if (ras.getContentRoot() != null) {
188                                                         StringWriter writer = new StringWriter();
189                                                         Transformer transformer = null;
190                                                         try {
191                                                                 transformer = TransformerFactory.newInstance().newTransformer();
192                                                                 transformer.transform(new DOMSource(ras.getContentRoot()), new StreamResult(writer));
193                                                         } catch (Exception e) {
194                                                                 throw new JSONStructureException("Unable to Content node to string; e="+e);
195                                                         }
196
197                                                         xmlContents += "\n        Content: " + writer.toString();
198                                                 }
199                                         }
200                                         rrIt = jsonAttrCollection.iterator();
201                                         while (rrIt.hasNext()) { 
202                                                 RequestAttributes ras = rrIt.next();
203                                                 jsonContents += "\n   " + ras.toString();       
204                                                 if (ras.getContentRoot() != null) {
205                                                         StringWriter writer = new StringWriter();
206                                                         Transformer transformer = null;
207                                                         try {
208                                                                 transformer = TransformerFactory.newInstance().newTransformer();
209                                                                 transformer.transform(new DOMSource(ras.getContentRoot()), new StreamResult(writer));
210                                                         } catch (Exception e) {
211                                                                 throw new JSONStructureException("Unable to Content node to string; e="+e);
212                                                         }
213
214                                                         jsonContents += "\n        Content: " + writer.toString();
215                                                 }
216                                         }
217                                         fail(errorMessage + "\nXML(" + xmlAttrCollection.size() + ")='" + xmlContents + 
218                                                         "'  \nJSON(" + jsonAttrCollection.size() + ")='" + jsonContents +
219                                                         "\njson='" + jsonString + "'");
220                                 }
221                                 
222
223                         }                       
224
225                 } catch (Exception e) {
226                         fail ("Failed test with '" + currentFile.getName() + "', e=" + e);
227                 }
228
229                 
230         }
231         
232         //
233         // HELPER to get list of all Request files in the given directory
234         //
235         
236         private List<File> getRequestsInDirectory(File directory) {
237                 List<File> fileList = new ArrayList<File>();
238                 
239                 File[] fileArray = directory.listFiles();
240                 for (File f : fileArray) {
241                         if (f.isDirectory()) {
242                                 List<File> subDirList = getRequestsInDirectory(f);
243                                 fileList.addAll(subDirList);
244                         }
245                         if (f.getName().endsWith("Request.xml")) {
246                                 fileList.add(f);
247                         }
248                 }
249                 return fileList;
250                 
251         }
252         
253 }