/
AutomatedTestBase.java
1926 lines (1696 loc) · 62.7 KB
/
AutomatedTestBase.java
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sysds.test;
import static java.lang.Thread.sleep;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.SparkSession.Builder;
import org.apache.sysds.api.DMLScript;
import org.apache.sysds.common.Types.DataType;
import org.apache.sysds.common.Types.ExecMode;
import org.apache.sysds.common.Types.FileFormat;
import org.apache.sysds.common.Types.ValueType;
import org.apache.sysds.conf.ConfigurationManager;
import org.apache.sysds.conf.DMLConfig;
import org.apache.sysds.hops.OptimizerUtils;
import org.apache.sysds.lops.Lop;
import org.apache.sysds.lops.LopProperties.ExecType;
import org.apache.sysds.parser.DataExpression;
import org.apache.sysds.parser.ParseException;
import org.apache.sysds.runtime.DMLRuntimeException;
import org.apache.sysds.runtime.DMLScriptException;
import org.apache.sysds.runtime.controlprogram.context.SparkExecutionContext;
import org.apache.sysds.runtime.io.FileFormatPropertiesCSV;
import org.apache.sysds.runtime.io.FrameReader;
import org.apache.sysds.runtime.io.FrameReaderFactory;
import org.apache.sysds.runtime.matrix.data.FrameBlock;
import org.apache.sysds.runtime.matrix.data.MatrixBlock;
import org.apache.sysds.runtime.matrix.data.MatrixValue.CellIndex;
import org.apache.sysds.runtime.meta.MatrixCharacteristics;
import org.apache.sysds.runtime.privacy.CheckedConstraintsLog;
import org.apache.sysds.runtime.privacy.PrivacyConstraint;
import org.apache.sysds.runtime.privacy.PrivacyConstraint.PrivacyLevel;
import org.apache.sysds.runtime.util.DataConverter;
import org.apache.sysds.runtime.util.HDFSTool;
import org.apache.sysds.utils.ParameterBuilder;
import org.apache.sysds.utils.Statistics;
import org.apache.wink.json4j.JSONException;
import org.apache.wink.json4j.JSONObject;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
/**
* <p>
* Extend this class to easily
* </p>
* <ul>
* <li>set up an environment for DML script execution</li>
* <li>use multiple test cases</li>
* <li>generate test data></li>
* <li>check results</li>
* <li>clean up after test run</li>
* </ul>
*
*/
@SuppressWarnings("deprecation")
public abstract class AutomatedTestBase {
private static final Log LOG = LogFactory.getLog(AutomatedTestBase.class.getName());
public static final boolean EXCEPTION_EXPECTED = true;
public static final boolean EXCEPTION_NOT_EXPECTED = false;
// By default: TEST_GPU is set to false to allow developers without Nvidia GPU to run integration test suite
public static boolean TEST_GPU = false;
public static final double GPU_TOLERANCE = 1e-9;
public static final int FED_WORKER_WAIT = 1000; // in ms
// With OpenJDK 8u242 on Windows, the new changes in JDK are not allowing
// to set the native library paths internally thus breaking the code.
// That is why, these static assignments to java.library.path and hadoop.home.dir
// (for native winutils) have been removed.
/**
* Script source directory for .dml and .r files only (TEST_DATA_DIR for generated test data artifacts).
*/
protected static final String SCRIPT_DIR = "./src/test/scripts/";
protected static final String INPUT_DIR = "in/";
protected static final String OUTPUT_DIR = "out/";
protected static final String EXPECTED_DIR = "expected/";
/** Location where this class writes files for inspection if DEBUG is set to true. */
private static final String DEBUG_TEMP_DIR = "./tmp/";
/** Directory under which config files shared across tests are located. */
private static final String CONFIG_DIR = "./src/test/config/";
/**
* Location of the SystemDS config file that we use as a template when generating the configs for each test case.
*/
private static final File CONFIG_TEMPLATE_FILE = new File(CONFIG_DIR, "SystemDS-config.xml");
protected enum CodegenTestType {
DEFAULT, FUSE_ALL, FUSE_NO_REDUNDANCY;
public String getCodgenConfig() {
switch(this) {
case DEFAULT:
return "SystemDS-config-codegen.xml";
case FUSE_ALL:
return "SystemDS-config-codegen-fuse-all.xml";
case FUSE_NO_REDUNDANCY:
return "SystemDS-config-codegen-fuse-no-redundancy.xml";
default:
throw new RuntimeException("Unsupported codegen test config: " + this.name());
}
}
}
/**
* Location under which we create local temporary directories for test cases. To adjust where testTemp is located,
* use -Dsystemds.testTemp.root.dir=<new location>. This is necessary if any parent directories are
* public-protected.
*/
private static final String LOCAL_TEMP_ROOT_DIR = System.getProperty("systemds.testTemp.root.dir",
"target/testTemp");
private static final File LOCAL_TEMP_ROOT = new File(LOCAL_TEMP_ROOT_DIR);
/** Base directory for generated IN, OUT, EXPECTED test data artifacts instead of SCRIPT_DIR. */
protected static final String TEST_DATA_DIR = LOCAL_TEMP_ROOT_DIR + "/";
protected static final boolean TEST_CACHE_ENABLED = true;
/** Optional sub-directory under EXPECTED_DIR for reusing R script test results */
private String cacheDir = "";
/**
* Runtime backend to use for all integration tests. Some individual tests override this value, but the rest will
* use whatever is the default here.
* <p>
* Also set DMLScript.USE_LOCAL_SPARK_CONFIG to true for running the test suite in spark mode
*/
protected static ExecMode rtplatform = ExecMode.HYBRID;
protected static final boolean DEBUG = false;
public static boolean VERBOSE_STATS = false;
protected String fullDMLScriptName; // utilize for both DML and PyDML, should probably be renamed.
// protected String fullPYDMLScriptName;
protected String fullRScriptName;
protected static String baseDirectory;
protected static String sourceDirectory;
protected HashMap<String, TestConfiguration> availableTestConfigurations;
/* For testing in the old way */
protected HashMap<String, String> testVariables; /* variables and their values */
/* For testing in the new way */
// protected String[] dmlArgs; /* program-independent arguments to SystemDS (e.g., debug, execution mode) */
protected String[] programArgs; /* program-specific arguments, which are passed to SystemDS via -args option */
protected String rCmd; /* Rscript foo.R arg1, arg2 ... */
protected String selectedTest;
protected String[] outputDirectories;
protected String[] comparisonFiles;
protected ArrayList<String> inputDirectories;
protected ArrayList<String> inputRFiles;
protected ArrayList<String> expectedFiles;
private File curLocalTempDir = null;
private boolean isOutAndExpectedDeletionDisabled = false;
private static boolean outputBuffering = false;
static {
java.io.InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("my.properties");
java.util.Properties properties = new Properties();
try {
properties.load(inputStream);
}
catch(IOException e) {
e.printStackTrace();
}
outputBuffering = Boolean.parseBoolean(properties.getProperty("automatedtestbase.outputbuffering"));
TEST_GPU = Boolean.parseBoolean(properties.getProperty("enableGPU"));
VERBOSE_STATS = Boolean.parseBoolean(properties.getProperty("enableStats"));
}
// Timestamp before test start.
private long lTimeBeforeTest;
@Before
public abstract void setUp();
/**
* <p>
* Adds a test configuration to the list of available test configurations.
* </p>
*
* @param testName test name
* @param config test configuration
*/
protected void addTestConfiguration(String testName, TestConfiguration config) {
availableTestConfigurations.put(testName, config);
}
protected void addTestConfiguration(TestConfiguration config) {
availableTestConfigurations.put(config.getTestScript(), config);
}
/**
* <p>
* Adds a test configuration to the list of available test configurations based on the test directory and the test
* name.
* </p>
*
* @param testDirectory test directory
* @param testName test name
*/
protected void addTestConfiguration(String testDirectory, String testName) {
TestConfiguration config = new TestConfiguration(testDirectory, testName);
availableTestConfigurations.put(testName, config);
}
@Before
public final void setUpBase() {
availableTestConfigurations = new HashMap<>();
testVariables = new HashMap<>();
inputDirectories = new ArrayList<>();
inputRFiles = new ArrayList<>();
expectedFiles = new ArrayList<>();
outputDirectories = new String[0];
setOutAndExpectedDeletionDisabled(false);
lTimeBeforeTest = System.currentTimeMillis();
TestUtils.clearAssertionInformation();
}
protected void setOutputBuffering(boolean value) {
outputBuffering = value;
}
/**
* <p>
* Returns a test configuration from the list of available configurations. If no configuration is added for the
* specified name, the test will fail.
* </p>
*
* @param testName test name
* @return test configuration
*/
protected TestConfiguration getTestConfiguration(String testName) {
if(!availableTestConfigurations.containsKey(testName))
fail("unable to load test configuration");
return availableTestConfigurations.get(testName);
}
/**
* <p>
* Gets a test configuration from the list of available configurations and loads it if it's available. It is then
* returned. If no configuration exists for the specified name, the test will fail.
*
* </p>
*
* @param testName test name
* @return test configuration
*/
protected TestConfiguration getAndLoadTestConfiguration(String testName) {
TestConfiguration testConfiguration = getTestConfiguration(testName);
loadTestConfiguration(testConfiguration);
return testConfiguration;
}
/**
* Subclasses must call {@link #loadTestConfiguration(TestConfiguration)} before calling this method.
*
* @return the directory where the current test case should write temp files. This directory also contains the
* current test's customized SystemDS config file.
*/
protected File getCurLocalTempDir() {
if(null == curLocalTempDir) {
throw new RuntimeException("Called getCurLocalTempDir() before calling loadTestConfiguration()");
}
return curLocalTempDir;
}
/**
* Subclasses must call {@link #loadTestConfiguration(TestConfiguration)} before calling this method.
*
* @return the location of the current test case's SystemDS config file
*/
protected File getCurConfigFile() {
return new File(getCurLocalTempDir(), "SystemDS-config.xml");
}
/**
* <p>
* Tests that use custom SystemDS configuration should override to ensure scratch space and local temporary
* directory locations are also updated.
* </p>
*/
protected File getConfigTemplateFile() {
return CONFIG_TEMPLATE_FILE;
}
protected File getCodegenConfigFile(String parent, CodegenTestType type) {
// Instrumentation in this test's output log to show custom configuration file used for template.
File tmp = new File(parent, type.getCodgenConfig());
if( LOG.isInfoEnabled() )
LOG.info("This test case overrides default configuration with " + tmp.getPath());
return tmp;
}
protected ExecMode setExecMode(ExecType instType) {
switch(instType) {
case SPARK:
return setExecMode(ExecMode.SPARK);
default:
return setExecMode(ExecMode.HYBRID);
}
}
protected ExecMode setExecMode(ExecMode execMode) {
ExecMode platformOld = rtplatform;
rtplatform = execMode;
if(rtplatform != ExecMode.SINGLE_NODE)
DMLScript.USE_LOCAL_SPARK_CONFIG = true;
return platformOld;
}
protected void resetExecMode(ExecMode execModeOld) {
rtplatform = execModeOld;
DMLScript.USE_LOCAL_SPARK_CONFIG = false;
}
/**
* <p>
* Generates a random matrix with the specified characteristics and returns it as a two dimensional array.
* </p>
*
* @param rows number of rows
* @param cols number of columns
* @param min minimum value
* @param max maximum value
* @param sparsity sparsity
* @param seed seed
* @return two dimensional array containing random matrix
*/
protected double[][] getRandomMatrix(int rows, int cols, double min, double max, double sparsity, long seed) {
return TestUtils.generateTestMatrix(rows, cols, min, max, sparsity, seed);
}
/**
* <p>
* Generates a random matrix with the specified characteristics which does not contain any zero values and returns
* it as a two dimensional array.
* </p>
*
* @param rows number of rows
* @param cols number of columns
* @param min minimum value
* @param max maximum value
* @param seed seed
* @return two dimensional array containing random matrix
*/
protected double[][] getNonZeroRandomMatrix(int rows, int cols, double min, double max, long seed) {
return TestUtils.generateNonZeroTestMatrix(rows, cols, min, max, seed);
}
/**
* <p>
* Generates a random matrix with the specified characteristics and writes it to a file.
* </p>
*
* @param name directory name
* @param rows number of rows
* @param cols number of columns
* @param min minimum value
* @param max maximum value
* @param sparsity sparsity
* @param seed seed
*/
protected double[][] createRandomMatrix(String name, int rows, int cols, double min, double max, double sparsity,
long seed) {
return createRandomMatrix(name, rows, cols, min, max, sparsity, seed, false);
}
/**
* <p>
* Generates a random matrix with the specified characteristics and writes it to a file.
* </p>
*
* @param name directory name
* @param rows number of rows
* @param cols number of columns
* @param min minimum value
* @param max maximum value
* @param sparsity sparsity
* @param seed seed
* @param bIncludeR If true, writes also a R matrix to disk
*/
protected double[][] createRandomMatrix(String name, int rows, int cols, double min, double max, double sparsity,
long seed, boolean bIncludeR) {
double[][] matrix = TestUtils.generateTestMatrix(rows, cols, min, max, sparsity, seed);
String completePath = baseDirectory + INPUT_DIR + name + "/in";
TestUtils.writeTestMatrix(completePath, matrix, bIncludeR);
if(DEBUG)
TestUtils.writeTestMatrix(DEBUG_TEMP_DIR + completePath, matrix);
inputDirectories.add(baseDirectory + INPUT_DIR + name);
return matrix;
}
private static void cleanupExistingData(String fname, boolean cleanupRData) throws IOException {
HDFSTool.deleteFileIfExistOnHDFS(fname);
HDFSTool.deleteFileIfExistOnHDFS(fname + ".mtd");
if(cleanupRData)
HDFSTool.deleteFileIfExistOnHDFS(fname + ".mtx");
}
/**
* <p>
* Adds a matrix to the input path and writes it to a file.
* </p>
*
* @param name directory name
* @param matrix two dimensional matrix
* @param bIncludeR generates also the corresponding R matrix
*/
protected double[][] writeInputMatrix(String name, double[][] matrix, boolean bIncludeR) {
String completePath = baseDirectory + INPUT_DIR + name + "/in";
String completeRPath = baseDirectory + INPUT_DIR + name + ".mtx";
try {
cleanupExistingData(baseDirectory + INPUT_DIR + name, bIncludeR);
}
catch(IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
TestUtils.writeTestMatrix(completePath, matrix);
if(bIncludeR) {
TestUtils.writeTestMatrix(completeRPath, matrix, true);
inputRFiles.add(completeRPath);
}
if(DEBUG)
TestUtils.writeTestMatrix(DEBUG_TEMP_DIR + completePath, matrix);
inputDirectories.add(baseDirectory + INPUT_DIR + name);
return matrix;
}
protected double[][] writeInputMatrixWithMTD(String name, MatrixBlock matrix, boolean bIncludeR) {
double[][] data = DataConverter.convertToDoubleMatrix(matrix);
return writeInputMatrixWithMTD(name, data, bIncludeR);
}
protected double[][] writeInputMatrixWithMTD(String name, double[][] matrix, boolean bIncludeR) {
MatrixCharacteristics mc = new MatrixCharacteristics(matrix.length, matrix[0].length,
OptimizerUtils.DEFAULT_BLOCKSIZE, -1);
return writeInputMatrixWithMTD(name, matrix, bIncludeR, mc);
}
protected double[][] writeInputMatrixWithMTD(String name, double[][] matrix, long nnz, boolean bIncludeR) {
MatrixCharacteristics mc = new MatrixCharacteristics(matrix.length, matrix[0].length,
OptimizerUtils.DEFAULT_BLOCKSIZE, nnz);
return writeInputMatrixWithMTD(name, matrix, bIncludeR, mc, null);
}
protected double[][] writeInputMatrixWithMTD(String name, double[][] matrix, boolean bIncludeR,
MatrixCharacteristics mc) {
return writeInputMatrixWithMTD(name, matrix, bIncludeR, mc, null);
}
protected double[][] writeInputMatrixWithMTD(String name, double[][] matrix, PrivacyConstraint privacyConstraint) {
return writeInputMatrixWithMTD(name, matrix, false, null, privacyConstraint);
}
protected double[][] writeInputMatrixWithMTD(String name, double[][] matrix, boolean bIncludeR,
PrivacyConstraint privacyConstraint) {
MatrixCharacteristics mc = new MatrixCharacteristics(matrix.length, matrix[0].length,
OptimizerUtils.DEFAULT_BLOCKSIZE, -1);
return writeInputMatrixWithMTD(name, matrix, bIncludeR, mc, privacyConstraint);
}
protected double[][] writeInputMatrixWithMTD(String name, double[][] matrix, boolean bIncludeR,
MatrixCharacteristics mc, PrivacyConstraint privacyConstraint) {
writeInputMatrix(name, matrix, bIncludeR);
// write metadata file
try {
String completeMTDPath = baseDirectory + INPUT_DIR + name + ".mtd";
HDFSTool.writeMetaDataFile(completeMTDPath, ValueType.FP64, mc, FileFormat.TEXT, privacyConstraint);
}
catch(IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return matrix;
}
/**
* <p>
* Adds a matrix to the input path and writes it to a file.
* </p>
*
* @param name directory name
* @param matrix two dimensional matrix
*/
protected double[][] writeInputMatrix(String name, double[][] matrix) {
return writeInputMatrix(name, matrix, false);
}
/**
* <p>
* Adds a matrix to the input path and writes it to a file in binary format.
* </p>
*
* @param name directory name
* @param matrix two dimensional matrix
* @param rowsInBlock rows in block
* @param colsInBlock columns in block
* @param sparseFormat sparse format
*/
protected void writeInputBinaryMatrix(String name, double[][] matrix, int rowsInBlock, int colsInBlock,
boolean sparseFormat) {
String completePath = baseDirectory + INPUT_DIR + name + "/in";
try {
cleanupExistingData(baseDirectory + INPUT_DIR + name, false);
}
catch(IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
if(rowsInBlock == 1 && colsInBlock == 1) {
TestUtils.writeBinaryTestMatrixCells(completePath, matrix);
if(DEBUG)
TestUtils.writeBinaryTestMatrixCells(DEBUG_TEMP_DIR + completePath, matrix);
}
else {
TestUtils.writeBinaryTestMatrixBlocks(completePath, matrix, rowsInBlock, colsInBlock, sparseFormat);
if(DEBUG)
TestUtils.writeBinaryTestMatrixBlocks(DEBUG_TEMP_DIR +
completePath, matrix, rowsInBlock, colsInBlock, sparseFormat);
}
inputDirectories.add(baseDirectory + INPUT_DIR + name);
}
/**
* Writes the given matrix to input path, and writes the associated metadata file.
*
* @param name
* @param matrix
* @param rowsInBlock
* @param colsInBlock
* @param sparseFormat
* @param mc
* @throws IOException
*/
protected void writeInputBinaryMatrixWithMTD(String name, double[][] matrix, int rowsInBlock, int colsInBlock,
boolean sparseFormat, MatrixCharacteristics mc) throws IOException {
writeInputBinaryMatrix(name, matrix, rowsInBlock, colsInBlock, sparseFormat);
// write metadata file
String completeMTDPath = baseDirectory + INPUT_DIR + name + ".mtd";
HDFSTool.writeMetaDataFile(completeMTDPath, ValueType.FP64, mc, FileFormat.BINARY);
}
/**
* <p>
* Adds a matrix to the expectation path and writes it to a file.
* </p>
*
* @param name directory name
* @param matrix two dimensional matrix
*/
protected void writeExpectedMatrix(String name, double[][] matrix) {
TestUtils.writeTestMatrix(baseDirectory + EXPECTED_DIR + cacheDir + name, matrix);
expectedFiles.add(baseDirectory + EXPECTED_DIR + cacheDir + name);
}
/**
* <p>
* Adds a matrix to the expectation path and writes it to a file.
* </p>
*
* @param name directory name
* @param matrix two dimensional matrix
*/
protected void writeExpectedMatrixMarket(String name, double[][] matrix) {
File path = new File(baseDirectory, EXPECTED_DIR + cacheDir);
path.mkdirs();
TestUtils.writeTestMatrix(baseDirectory + EXPECTED_DIR + cacheDir + name, matrix, true);
expectedFiles.add(baseDirectory + EXPECTED_DIR + cacheDir + name);
}
/**
* <p>
* Adds a matrix to the expectation path and writes it to a file in binary format.
* </p>
*
* @param name directory name
* @param matrix two dimensional matrix
* @param rowsInBlock rows in block
* @param colsInBlock columns in block
* @param sparseFormat sparse format
*/
protected void writeExpectedBinaryMatrix(String name, double[][] matrix, int rowsInBlock, int colsInBlock,
boolean sparseFormat) {
if(rowsInBlock == 1 && colsInBlock == 1) {
TestUtils.writeBinaryTestMatrixCells(baseDirectory + EXPECTED_DIR + name + "/in", matrix);
}
else {
TestUtils.writeBinaryTestMatrixBlocks(baseDirectory + EXPECTED_DIR + name
+ "/in", matrix, rowsInBlock, colsInBlock, sparseFormat);
}
inputDirectories.add(baseDirectory + EXPECTED_DIR + name);
}
/**
* <p>
* Creates a helper matrix which can be used for writing scalars to a file.
* </p>
*/
protected void createHelperMatrix() {
TestUtils.writeTestMatrix(baseDirectory + INPUT_DIR + "helper/in", new double[][] {{1, 1}});
inputDirectories.add(baseDirectory + INPUT_DIR + "helper");
}
/**
* <p>
* Creates a expectation helper matrix which can be used to compare scalars.
* </p>
*
* @param name file name
* @param value scalar value
*/
protected void writeExpectedHelperMatrix(String name, double value) {
TestUtils.writeTestMatrix(baseDirectory + EXPECTED_DIR + cacheDir + name, new double[][] {{value, value}});
expectedFiles.add(baseDirectory + EXPECTED_DIR + cacheDir + name);
}
protected void writeExpectedScalar(String name, double value) {
File path = new File(baseDirectory, EXPECTED_DIR + cacheDir);
path.mkdirs();
TestUtils.writeTestScalar(baseDirectory + EXPECTED_DIR + cacheDir + name, value);
expectedFiles.add(baseDirectory + EXPECTED_DIR + cacheDir + name);
}
protected void writeExpectedScalar(String name, long value) {
File path = new File(baseDirectory, EXPECTED_DIR + cacheDir);
path.mkdirs();
TestUtils.writeTestScalar(baseDirectory + EXPECTED_DIR + cacheDir + name, value);
expectedFiles.add(baseDirectory + EXPECTED_DIR + cacheDir + name);
}
protected static HashMap<CellIndex, Double> readDMLMatrixFromHDFS(String fileName) {
return TestUtils.readDMLMatrixFromHDFS(baseDirectory + OUTPUT_DIR + fileName);
}
public HashMap<CellIndex, Double> readRMatrixFromFS(String fileName) {
if( LOG.isInfoEnabled() )
LOG.info("R script out: " + baseDirectory + EXPECTED_DIR + cacheDir + fileName);
return TestUtils.readRMatrixFromFS(baseDirectory + EXPECTED_DIR + cacheDir + fileName);
}
protected static HashMap<CellIndex, Double> readDMLScalarFromHDFS(String fileName) {
return TestUtils.readDMLScalarFromHDFS(baseDirectory + OUTPUT_DIR + fileName);
}
protected static String readDMLLineageFromHDFS(String fileName) {
return TestUtils.readDMLString(baseDirectory + OUTPUT_DIR + fileName + ".lineage");
}
protected static String readDMLLineageDedupFromHDFS(String fileName) {
return TestUtils.readDMLString(baseDirectory + OUTPUT_DIR + fileName + ".lineage.dedup");
}
protected static FrameBlock readDMLFrameFromHDFS(String fileName, FileFormat fmt) throws IOException {
// read frame data from hdfs
String strFrameFileName = baseDirectory + OUTPUT_DIR + fileName;
FrameReader reader = FrameReaderFactory.createFrameReader(fmt);
MatrixCharacteristics md = readDMLMetaDataFile(fileName);
return reader.readFrameFromHDFS(strFrameFileName, md.getRows(), md.getCols());
}
protected static FrameBlock readDMLFrameFromHDFS(String fileName, FileFormat fmt, MatrixCharacteristics md)
throws IOException {
// read frame data from hdfs
String strFrameFileName = baseDirectory + OUTPUT_DIR + fileName;
FrameReader reader = FrameReaderFactory.createFrameReader(fmt);
return reader.readFrameFromHDFS(strFrameFileName, md.getRows(), md.getCols());
}
protected static FrameBlock readRFrameFromHDFS(String fileName, FileFormat fmt, MatrixCharacteristics md)
throws IOException {
// read frame data from hdfs
String strFrameFileName = baseDirectory + EXPECTED_DIR + fileName;
FileFormatPropertiesCSV fprop = new FileFormatPropertiesCSV();
fprop.setHeader(true);
FrameReader reader = FrameReaderFactory.createFrameReader(fmt, fprop);
return reader.readFrameFromHDFS(strFrameFileName, md.getRows(), md.getCols());
}
public HashMap<CellIndex, Double> readRScalarFromFS(String fileName) {
if( LOG.isInfoEnabled() )
LOG.info("R script out: " + baseDirectory + EXPECTED_DIR + cacheDir + fileName);
return TestUtils.readRScalarFromFS(baseDirectory + EXPECTED_DIR + cacheDir + fileName);
}
public static void checkDMLMetaDataFile(String fileName, MatrixCharacteristics mc) {
MatrixCharacteristics rmc = readDMLMetaDataFile(fileName);
Assert.assertEquals(mc.getRows(), rmc.getRows());
Assert.assertEquals(mc.getCols(), rmc.getCols());
}
public static MatrixCharacteristics readDMLMetaDataFile(String fileName) {
try {
JSONObject meta = getMetaDataJSON(fileName);
long rlen = Long.parseLong(meta.get(DataExpression.READROWPARAM).toString());
long clen = Long.parseLong(meta.get(DataExpression.READCOLPARAM).toString());
return new MatrixCharacteristics(rlen, clen, -1, -1);
}
catch(Exception ex) {
throw new RuntimeException(ex);
}
}
public static JSONObject getMetaDataJSON(String fileName) {
return getMetaDataJSON(fileName, OUTPUT_DIR);
}
public static JSONObject getMetaDataJSON(String fileName, String outputDir) {
String fname = baseDirectory + outputDir + fileName + ".mtd";
return new DataExpression().readMetadataFile(fname, false);
}
public static String readDMLMetaDataValue(String fileName, String outputDir, String key) throws JSONException {
JSONObject meta = getMetaDataJSON(fileName, outputDir);
return meta.get(key).toString();
}
/**
* Call readDMLMetaDataValue but fail test in case of JSONException or NullPointerException.
* @param fileName of metadata file
* @param outputDir directory of metadata file
* @param key key to find in metadata
* @return value retrieved from metadata for the given key
*/
public static String readDMLMetaDataValueCatchException(String fileName, String outputDir, String key){
try {
return readDMLMetaDataValue(fileName, outputDir, key);
} catch (JSONException | NullPointerException e){
fail("Privacy constraint not written to output metadata file:\n" + e);
return null;
}
}
public static ValueType readDMLMetaDataValueType(String fileName) {
try {
JSONObject meta = getMetaDataJSON(fileName);
return ValueType.fromExternalString(meta.get(DataExpression.VALUETYPEPARAM).toString());
}
catch(Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* <p>
* Loads a test configuration with its parameters. Adds the output directories to the output list as well as to the
* list of possible comparison files.
* </p>
*
* @param config test configuration name
*
*/
protected void loadTestConfiguration(TestConfiguration config) {
loadTestConfiguration(config, null);
}
/**
* <p>
* Loads a test configuration with its parameters. Adds the output directories to the output list as well as to the
* list of possible comparison files.
* </p>
*
* @param config test configuration name
* @param cacheDirectory subdirectory for reusing R script expected results if null, defaults to empty string (i.e.,
* no cache)
*/
protected void loadTestConfiguration(TestConfiguration config, String cacheDirectory) {
if(!availableTestConfigurations.containsValue(config))
fail("test configuration not available: " + config.getTestScript());
String testDirectory = config.getTestDirectory();
if(testDirectory != null) {
if(isTargetTestDirectory(testDirectory)) {
baseDirectory = TEST_DATA_DIR + testDirectory;
sourceDirectory = SCRIPT_DIR + getSourceDirectory(testDirectory);
}
else {
baseDirectory = SCRIPT_DIR + testDirectory;
sourceDirectory = baseDirectory;
}
}
setCacheDirectory(cacheDirectory);
selectedTest = config.getTestScript();
String[] outputFiles = config.getOutputFiles();
if(outputFiles != null) {
outputDirectories = new String[outputFiles.length];
comparisonFiles = new String[outputFiles.length];
for(int i = 0; i < outputFiles.length; i++) {
outputDirectories[i] = baseDirectory + OUTPUT_DIR + outputFiles[i];
comparisonFiles[i] = baseDirectory + EXPECTED_DIR + cacheDir + outputFiles[i];
}
}
testVariables = config.getVariables();
testVariables.put("basedir", baseDirectory);
testVariables.put("indir", baseDirectory + INPUT_DIR);
testVariables.put("outdir", baseDirectory + OUTPUT_DIR);
testVariables.put("readhelper",
"Helper = read(\"" + baseDirectory + INPUT_DIR + "helper/in\", " + "rows=1, cols=2, format=\"text\");");
testVariables.put("Routdir", baseDirectory + EXPECTED_DIR + cacheDir);
// Create a temporary directory for this test case.
// Eventually all files written by the tests should go under here, but making
// that change will take quite a bit of effort.
try {
if(null == testDirectory) {
System.err.printf("Warning: Test configuration did not specify a test directory.\n");
curLocalTempDir = new File(LOCAL_TEMP_ROOT, String.format("unknownTest/%s", selectedTest));
}
else {
curLocalTempDir = new File(LOCAL_TEMP_ROOT, String.format("%s/%s", testDirectory, selectedTest));
}
curLocalTempDir.mkdirs();
TestUtils.clearDirectory(curLocalTempDir.getPath());
// Create a SystemDS config file for this test case based on default template
// from src/test/config or derive from custom configuration provided by test.
String configTemplate = FileUtils.readFileToString(getConfigTemplateFile(), "UTF-8");
String localTemp = curLocalTempDir.getPath();
String configContents = configTemplate
.replace(createXMLElement(DMLConfig.SCRATCH_SPACE, "scratch_space"),
createXMLElement(DMLConfig.SCRATCH_SPACE, localTemp + "/scratch_space"))
.replace(createXMLElement(DMLConfig.LOCAL_TMP_DIR, "/tmp/systemds"),
createXMLElement(DMLConfig.LOCAL_TMP_DIR, localTemp + "/localtmp"));
FileUtils.write(getCurConfigFile(), configContents, "UTF-8");
if( LOG.isDebugEnabled() )
LOG.debug("This test case will use SystemDS config file %s\n" + getCurConfigFile());
}
catch(IOException e) {
throw new RuntimeException(e);
}
if(DEBUG)
TestUtils.clearDirectory(DEBUG_TEMP_DIR + baseDirectory + INPUT_DIR);
}
public String createXMLElement(String tagName, String value) {
return String.format("<%s>%s</%s>", tagName, value, tagName);
}
/**
* <p>
* Loads a test configuration with its parameters. Adds the output directories to the output list as well as to the
* list of possible comparison files.
* </p>
*
* @param configurationName test configuration name
*
*/
@Deprecated
protected void loadTestConfiguration(String configurationName) {
if(!availableTestConfigurations.containsKey(configurationName))
fail("test configuration not available: " + configurationName);
TestConfiguration config = availableTestConfigurations.get(configurationName);
loadTestConfiguration(config);
}
/**
* Runs an R script, default to the old way
*/
protected void runRScript() {
runRScript(false);
}
/**
* Runs an R script in the old or the new way
*/
protected void runRScript(boolean newWay) {
String executionFile = sourceDirectory + selectedTest + ".R";;
if(fullRScriptName != null)
executionFile = fullRScriptName;
// *** HACK ALERT *** HACK ALERT *** HACK ALERT ***
// Some of the R scripts will fail if the "expected" directory doesn't exist.
// Make sure the directory exists.
File expectedDir = new File(baseDirectory, "expected" + "/" + cacheDir);
expectedDir.mkdirs();
// *** END HACK ***
String cmd;
if(!newWay) {
executionFile = executionFile + "t";
cmd = "R -f " + executionFile;
}
else {
// *** HACK ALERT *** HACK ALERT *** HACK ALERT ***
// Rscript does *not* load the "methods" package by default
// to save on start time. The "Matrix" package used in the
// tests requires the "methods" package and should still
// load and attach it, but in R 3.2 with the latest version
// of the "Matrix" package, "methods" is loaded *but not
// attached* when run with Rscript. Therefore, we need to
// explicitly load it with Rscript.
cmd = rCmd.replaceFirst("Rscript",
"Rscript --default-packages=methods,datasets,graphics,grDevices,stats,utils");
// *** END HACK ***
}
if(System.getProperty("os.name").contains("Windows")) {
cmd = cmd.replace('/', '\\');
executionFile = executionFile.replace('/', '\\');
}
if(DEBUG) {
if(!newWay) { // not sure why have this condition
TestUtils.printRScript(executionFile);
}
}
if(!newWay) {
ParameterBuilder.setVariablesInScript(sourceDirectory, selectedTest + ".R", testVariables);
}
if(cacheDir.length() > 0) {
File expectedFile = null;
String[] outputFiles = null;
TestConfiguration testConfig = getTestConfiguration(selectedTest);
if(testConfig != null) {
outputFiles = testConfig.getOutputFiles();
}
if(outputFiles != null && outputFiles.length > 0) {
expectedFile = new File(expectedDir.getPath() + "/" + outputFiles[0]);
if(expectedFile.canRead()) {
if( LOG.isInfoEnabled() )
LOG.info("Skipping R script cmd: " + cmd);
return;
}