comparison gwt-client/src/test/java/test/AbstractModuleRunner.java @ 9148:48d87af1243e

Unit testing flowdepthdevelopment added
author gernotbelger
date Tue, 12 Jun 2018 15:04:40 +0200
parents gwt-client/src/test/java/test/ModuleRunner.java@af73fdd96920
children de55d9a94796
comparison
equal deleted inserted replaced
9147:28fe5e654495 9148:48d87af1243e
1 package test;
2
3 /** Copyright (C) 2017 by Bundesanstalt für Gewässerkunde
4 * Software engineering by
5 * Björnsen Beratende Ingenieure GmbH
6 * Dr. Schumacher Ingenieurbüro für Wasser und Umwelt
7 *
8 * This file is Free Software under the GNU AGPL (>=v3)
9 * and comes with ABSOLUTELY NO WARRANTY! Check out the
10 * documentation coming with Dive4Elements River for details.
11 */
12
13 import java.io.File;
14 import java.io.FileNotFoundException;
15 import java.io.FileOutputStream;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.io.InputStreamReader;
19 import java.net.URL;
20 import java.util.ArrayList;
21 import java.util.List;
22
23 import org.apache.commons.io.FileUtils;
24 import org.apache.commons.io.IOUtils;
25 import org.dive4elements.artifacts.common.ArtifactNamespaceContext;
26 import org.dive4elements.artifacts.common.utils.ClientProtocolUtils;
27 import org.dive4elements.artifacts.httpclient.exceptions.ConnectionException;
28 import org.dive4elements.artifacts.httpclient.http.HttpClient;
29 import org.dive4elements.artifacts.httpclient.http.HttpClientImpl;
30 import org.dive4elements.artifacts.httpclient.http.response.DocumentResponseHandler;
31 import org.dive4elements.artifacts.httpclient.utils.XMLUtils;
32 import org.dive4elements.river.client.server.AdvanceServiceImpl;
33 import org.dive4elements.river.client.server.ArtifactHelper;
34 import org.dive4elements.river.client.server.CollectionHelper;
35 import org.dive4elements.river.client.server.CreateCollectionServiceImpl;
36 import org.dive4elements.river.client.server.FLYSArtifactCreator;
37 import org.dive4elements.river.client.server.FeedServiceImpl;
38 import org.dive4elements.river.client.server.auth.DefaultUser;
39 import org.dive4elements.river.client.server.auth.User;
40 import org.dive4elements.river.client.server.auth.UserClient;
41 import org.dive4elements.river.client.shared.exceptions.ServerException;
42 import org.dive4elements.river.client.shared.model.Artifact;
43 import org.dive4elements.river.client.shared.model.Collection;
44 import org.dive4elements.river.client.shared.model.Data;
45 import org.dive4elements.river.client.shared.model.DataItem;
46 import org.dive4elements.river.client.shared.model.DefaultCollection;
47 import org.dive4elements.river.client.shared.model.DefaultDataItem;
48 import org.dive4elements.river.client.shared.model.OutputMode;
49 import org.dive4elements.river.client.shared.model.StringOptionsData;
50 import org.junit.Assert;
51 import org.w3c.dom.Document;
52 import org.w3c.dom.Element;
53
54 import test.BerechnungsartenTester.CalcMode;
55 import test.BerechnungsartenTester.FilenameMapper;
56 import test.BerechnungsartenTester.River;
57
58 /**
59 * @author Domenico Nardi Tironi
60 *
61 */
62 public abstract class AbstractModuleRunner {
63
64 public enum Infotype {
65 sinfo
66 }
67
68 private final String serverUrl = "http://localhost:8181";
69 private final String locale = "de";
70 private final HttpClient client;
71
72 private static final String exportFileDir = "D:" + File.separator;
73 private static final String IGNORE_ERSTELLDATUM = "# Datum der Erstellung";
74 private static final String IGNORE_FLYS_VERSION = "# FLYS-Version:";
75 private static final String IGNORE_BEARBEITER = "# Bearbeiter:";
76
77 private final String username;
78 private final String password;
79 private final Infotype infotype;
80 private final String userUuid;
81 private Collection collection;
82 private Artifact artifact;
83 private final FilenameMapper fileName;
84
85 // common attributes
86 private final CalcMode calcMode;
87 private final double from;
88 private final double to;
89 private final River river;
90
91 public AbstractModuleRunner(final String username, final String password, final Infotype infotype, final CalcMode sinfoCalcFlowDepth,
92 final FilenameMapper helloWorldFile, final double from, final double to, final River beispielfluss) throws ConnectionException, ServerException {
93 // common attributes (evtl. doch in subklassen, evtl. Zwischenhierarchiestufe einführen
94
95 this.calcMode = sinfoCalcFlowDepth;
96 this.river = beispielfluss;
97 this.from = from;
98 this.to = to;
99
100 this.username = username;
101 this.password = password;
102 this.infotype = infotype;
103 this.fileName = helloWorldFile;
104
105 // init
106 this.client = new HttpClientImpl(this.serverUrl, this.locale);
107 this.userUuid = makeUserUuid();
108 this.collection = getCollection();
109 this.artifact = getArtifact();
110 }
111
112 private String makeUserUuid() throws ConnectionException {
113 final User user = new DefaultUser(this.username, this.password, null, false, new ArrayList<String>(), new ArrayList<String>());
114 final UserClient userClient = new UserClient(this.serverUrl);
115 Element userElement;
116
117 userElement = userClient.findUser(user);
118 return userElement.getAttributeNS(ArtifactNamespaceContext.NAMESPACE_URI, "uuid");
119
120 }
121
122 protected final Artifact getArtifact() throws ServerException, ConnectionException {
123 if (this.artifact == null) {
124 this.artifact = ArtifactHelper.createArtifact(this.serverUrl, this.locale, this.infotype.name(), null);
125 setCollection(CollectionHelper.addArtifact(getCollection(), this.artifact, this.serverUrl, this.locale)); // wichtig; sorgt für Persistenz
126 }
127 return this.artifact;
128 }
129
130 protected Collection getCollection() throws ConnectionException {
131
132 if (this.collection == null) {
133 // lazy-Loading
134 final Document create = ClientProtocolUtils.newCreateCollectionDocument(null);
135 final Document doc = (Document) this.client.createCollection(create, this.userUuid, new DocumentResponseHandler());
136 final String uuid = XMLUtils.xpathString(doc, CreateCollectionServiceImpl.XPATH_COLLECTION_UUID, ArtifactNamespaceContext.INSTANCE);
137 final String ttlStr = XMLUtils.xpathString(doc, CreateCollectionServiceImpl.XPATH_COLLECTION_TTL, ArtifactNamespaceContext.INSTANCE);
138 this.collection = new DefaultCollection(uuid, Long.valueOf(ttlStr), uuid);
139 }
140 return this.collection;
141
142 }
143
144 private final void setCollection(final Collection collection) {
145 this.collection = collection;
146 }
147
148 private final void setArtifact(final Artifact artifact) {
149 this.artifact = artifact;
150 }
151
152 public abstract void runTest(final boolean exportToFile) throws ConnectionException, ServerException, IOException;
153
154 protected final void describeCollection() throws ConnectionException {
155
156 final String uuid = getCollection().identifier();
157 final Document describe = ClientProtocolUtils.newDescribeCollectionDocument(uuid);
158 final Document response = (Document) this.client.doCollectionAction(describe, uuid, new DocumentResponseHandler());
159 final Collection c = CollectionHelper.parseCollection(response);
160 setCollection(c);
161
162 }
163
164 protected final void feedAndGo(final Data[] data, final int reachableStateIndex) throws ConnectionException, ServerException {
165 feed(data);
166 advance(getReachableStateByIndex(getArtifact(), reachableStateIndex)); // reachablestate könnte auch String sein.
167
168 }
169
170 private final String getReachableStateByIndex(final Artifact artifact, final int index) {
171
172 final String[] states = artifact.getArtifactDescription().getReachableStates();
173 if (states != null) {
174 if (states.length > index) {
175 return states[index];
176 } else {
177 return states[0];
178 }
179 } else {
180 return "";
181 }
182 }
183
184 private final void feed(final Data[] data) throws ServerException, ConnectionException {
185 final Document feed = ClientProtocolUtils.newFeedDocument(getArtifact().getUuid(), getArtifact().getHash(), createKVP(data));
186 final Document description = (Document) this.client.feed(
187 new org.dive4elements.artifacts.httpclient.objects.Artifact(getArtifact().getUuid(), getArtifact().getHash()), feed,
188 new DocumentResponseHandler());
189
190 final String result = XMLUtils.xpathString(description, FeedServiceImpl.XPATH_RESULT, ArtifactNamespaceContext.INSTANCE);
191
192 if (result == null || !result.equals(FeedServiceImpl.OPERATION_FAILURE)) {
193 setArtifact((Artifact) new FLYSArtifactCreator().create(description));
194 } else if (result != null && result.equals(FeedServiceImpl.OPERATION_FAILURE)) {
195 final String msg = XMLUtils.xpathString(description, FeedServiceImpl.XPATH_RESULT_MSG, ArtifactNamespaceContext.INSTANCE);
196 throw new ServerException(msg);
197 }
198 }
199
200 protected final Data[] extractPairData(final List<String> pairIds, final String dataName) {
201 final Data[] data = new Data[pairIds.size()];
202 int i = 0;
203 for (final String pairId : pairIds) {
204 final Data pair = new StringOptionsData(dataName, dataName, new DataItem[] { new DefaultDataItem(pairId, pairId, pairId) });
205 data[i] = pair;
206 i++;
207 }
208 return data;
209 }
210
211 private final String[][] createKVP(final Data[] data) {
212 if (data != null) {
213 final String[][] kvp = new String[data.length][];
214
215 int i = 0;
216
217 for (final Data d : data) {
218 final String key = d.getLabel();
219 final String value = d.getStringValue();
220
221 kvp[i++] = new String[] { key, value };
222 }
223
224 return kvp;
225 }
226 return null;
227 }
228
229 private final void advance(final String target) throws ConnectionException, ServerException {
230 final Document advance = ClientProtocolUtils.newAdvanceDocument(getArtifact().getUuid(), getArtifact().getHash(), target);
231 final Document description = (Document) this.client.advance(
232 new org.dive4elements.artifacts.httpclient.objects.Artifact(getArtifact().getUuid(), getArtifact().getHash()), advance,
233 new DocumentResponseHandler());
234
235 if (description == null) {
236 throw new ServerException(AdvanceServiceImpl.ERROR_ADVANCE_ARTIFACT);
237 }
238
239 final String result = XMLUtils.xpathString(description, AdvanceServiceImpl.XPATH_RESULT, ArtifactNamespaceContext.INSTANCE);
240
241 if (result == null || !result.equals(AdvanceServiceImpl.OPERATION_FAILURE)) {
242 setArtifact((Artifact) new FLYSArtifactCreator().create(description));
243 }
244 }
245
246 /// ExportServiceImpl
247 protected final void assertAndWriteToFile(final String mode, final boolean exportToFile) throws IOException {
248
249 final String type = "csv";
250
251 final String enc = "windows-1252";// req.getParameter("encoding");
252
253 final URL expectedResource = getClass().getResource(this.fileName.getFilename());
254 final Document attr = null;
255 final Document request = ClientProtocolUtils.newOutCollectionDocument(getCollection().identifier(), mode, type, attr);
256
257 final InputStream response = this.client.collectionOut(request, getCollection().identifier(), mode);
258
259 final String actual = deleteErstelldatum(IOUtils.toString(response, "UTF-8"));
260
261 final String expected = deleteErstelldatum(FileUtils.readFileToString(new File(expectedResource.getFile()), enc));
262
263 // if (!actual.equals(expected)) {
264 if (exportToFile) {
265 doGetWriteToDisk(mode); // TODO: WENN der Test negativ ausfällt, Datei abspeichern -> Diskussion
266 }
267
268 Assert.assertEquals(expected, actual);
269 }
270
271 private final String deleteErstelldatum(final String input) {
272 String result = "";
273 final String[] lines = input.split(System.lineSeparator());
274 for (final String line : lines) {
275 if (!line.contains(AbstractModuleRunner.IGNORE_ERSTELLDATUM) && !line.contains(AbstractModuleRunner.IGNORE_FLYS_VERSION)
276 && !line.contains(AbstractModuleRunner.IGNORE_BEARBEITER)) {
277 result = result + line + System.lineSeparator();
278 }
279 }
280 return result;
281 }
282
283 public final void doGetWriteToDisk(final String mode) throws FileNotFoundException, IOException {
284
285 final String name = mode;
286 final String type = "csv";
287
288 final String fn = name + System.currentTimeMillis() + "." + type;
289 final String enc = "windows-1252";
290
291 final String filepath = exportFileDir + fn;
292
293 final Document attr = null;
294 final Document request = ClientProtocolUtils.newOutCollectionDocument(getCollection().identifier(), mode, type, attr);
295
296 final InputStream response = this.client.collectionOut(request, getCollection().identifier(), mode);
297 final InputStreamReader in = new InputStreamReader(response, "UTF-8");
298
299 IOUtils.copy(in, new FileOutputStream(filepath), enc);
300
301 }
302
303 protected final void selectCalcMode() throws ConnectionException, ServerException {
304
305 /* Select CalcMode */
306 final String calcmodeStr = this.calcMode.name();
307 final Data dataCalcMode = new StringOptionsData("calculation_mode", "calculation_mode",
308 new DataItem[] { new DefaultDataItem(calcmodeStr, calcmodeStr, calcmodeStr) });
309 feedAndGo(new Data[] { dataCalcMode }, 0);
310 }
311
312 protected final void selectRange() throws ConnectionException, ServerException {
313 final String fromStr = String.valueOf(this.from);
314 final String toStr = String.valueOf(this.to);
315 final Data dataFrom = new StringOptionsData("ld_from", "ld_from", new DataItem[] { new DefaultDataItem(fromStr, fromStr, fromStr) });
316 final Data dataTo = new StringOptionsData("ld_to", "ld_to", new DataItem[] { new DefaultDataItem(toStr, toStr, toStr) });
317 final Data[] rangeFromToDetermined = new Data[] { dataFrom, dataTo };
318
319 feedAndGo(rangeFromToDetermined, 0);
320 }
321
322 protected final void selectRiver() throws ConnectionException, ServerException {
323 final String riverStr = this.river.name();
324 final Data data = new StringOptionsData("river", "river", new DataItem[] { new DefaultDataItem(riverStr, riverStr, riverStr) });
325 feedAndGo(new Data[] { data }, 0);
326 }
327
328 protected final void export(final boolean exportToFile) throws IOException, ServerException {
329 final OutputMode[] modes = getArtifact().getArtifactDescription().getOutputModes();
330 if (modes != null) {
331 for (final OutputMode mode : modes) {
332 if (mode.getDescription().contains("_export"))
333 assertAndWriteToFile(mode.getName(), exportToFile);
334 }
335 }
336 }
337
338 protected final String getRecommendationPairString(final SimpleRecommendation rec1, final SimpleRecommendation rec2)
339 throws ConnectionException, ServerException {
340
341 return rec1.getRecommendationPairString(rec2, getCollection(), this.serverUrl, this.locale);
342 }
343
344 }

http://dive4elements.wald.intevation.org