-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRunQueryTests.php
424 lines (358 loc) · 12.3 KB
/
RunQueryTests.php
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
<?php
namespace Slicer\Tests;
date_default_timezone_set('America/Sao_Paulo');
$filename = str_replace("tests_and_examples", "vendor/autoload.php", __DIR__);
require_once $filename;
use Slicer\SlicingDice;
class SlicingDiceTester {
// The Slicing Dice API client
private $client;
// Array for column translation
private $columnTranslation;
// Sleep time in seconds
private $sleepTime;
// Examples path
private $path;
// Examples file extension
private $extension;
public $numSuccess;
public $numFails;
public $failedTests;
private $verbose;
private $perTestInsertion;
private $insertSqlData = false;
function __construct($apiKey, $verboseOption=false) {
$this->client = new SlicingDice(array("masterKey" => $apiKey));
// Translation table for columns with timestamp
$this->columnTranslation = array();
$this->sleepTime = 10;
$this->path = "/examples/";
$this->extension = ".json";
$this->numSuccess = 0;
$this->numFails = 0;
$this->failedTests = array();
$this->verbose = $verboseOption;
$this->updateResults();
}
/**
* Run tests
*
* @param string $queryType the type of the query
*/
public function runTests($queryType){
$testData = $this->loadTestData($queryType);
$numTests = count($testData);
$this->perTestInsertion = array_key_exists('insert', $testData[0]);
if (!$this->perTestInsertion and $this->insertSqlData) {
print 'Running insert for SQL';
$insertionData = $this->loadTestData($queryType, "_insert");
foreach ($insertionData as $insert) {
$this->client->insert($insert);
}
sleep($this->sleepTime);
}
$counter = 0;
foreach($testData as $test){
$queryType_ = $queryType;
$this->emptyColumnTranslation();
$counter += 1;
$name = $test["name"];
print "($counter/$numTests) Executing test $name\n";
if (array_key_exists('description', $test)){
print ' Description: ' . $test["description"];
}
print "\n Query type: $queryType \n";
try{
if ($this->perTestInsertion) {
$this->createColumns($test);
$this->insertData($test);
}
if ($queryType == "update" or $queryType == "delete") {
$result_additionals = $this->runAdditionalOperations($queryType, $test);
if (!$result_additionals) {
continue;
}
$queryType_ = "count_entity";
}
$result = $this->executeQuery($queryType_, $test);
} catch (\Exception $e){
$result = array("result" => array(
"error" => $e->getMessage()
));
}
$this->compareResult($test, $result);
echo "\n";
}
}
/**
* Method used to run delete and update operations, this operations
* are executed before the query and the result comparison
*/
private function runAdditionalOperations($query_type, $test) {
$query_data = $this->translateColumnNames($test['additional_operation']);
if ($query_type == 'delete') {
print " Deleting";
}
else {
print " Updating";
}
if ($this->verbose) {
print_r($query_data);
}
$result = null;
if ($query_type == 'delete') {
$result = $this->client->delete($query_data);
}
else if ($query_type == 'update') {
$result = $this->client->update($query_data);
}
$expected = $this->translateColumnNames($test['result_additional']);
foreach ($expected as $key => $value) {
if ($value == "ignore") {
continue;
}
if (!array_key_exists($key, $result) || array_diff($expected[$key], $result[$key])){
$this->numFails += 1;
array_push($this->failedTests, $test["name"]);
print_r(' Expected: "' . $key . '": ' . json_encode($expected[$key]) . "\n");
print_r(' Result: "' . $key . '": ' . json_encode($result[$key]) . "\n");
echo " Status: Failed\n";
$this->updateResults();
return false;
}
}
$this->numSuccess += 1;
print " Status: Passed";
return true;
}
/**
* Reset column translation
*/
private function emptyColumnTranslation(){
$this->columnTranslation = array();
}
/**
* Load test data from example files
*
* @param string $queryType the type of the query
*/
private function loadTestData($queryType, $suffix="") {
$filename = __DIR__ . $this->path . $queryType . $suffix . $this->extension;
$content = file_get_contents($filename);
return json_decode($content, true);
}
/**
* Create columns on Slicing Dice API
*
* @param array $columnObject the column object to create
*/
private function createColumns($columnObject) {
$isSingular = $this->numFails == 1;
$columnOrColumns = null;
if ($isSingular){
$columnOrColumns = "column";
} else {
$columnOrColumns = "columns";
}
print " Creating " . count($columnObject["columns"]) . " " . $columnOrColumns . "\n";
foreach ($columnObject["columns"] as $column) {
$newColumn = $this->appendTimestampToColumnName($column);
$this->client->createColumn($newColumn);
if ($this->verbose){
echo " - " . $newColumn['api-name'] . "\n";
}
}
}
/**
* Put timestamp to the end of the column name
*
* @param array $column the column to append timestamp
*/
private function appendTimestampToColumnName($column){
$oldName = '"' . $column['api-name'] . '"';
$timestamp = $this->getTimestamp();
$column['name'] = $column['name'] . $timestamp;
$column['api-name'] = $column['api-name'] . $timestamp;
$newName = '"' . $column['api-name'] . '"';
$this->columnTranslation[$oldName] = $newName;
return $column;
}
/**
* Get actual timestamp
*
* @return string with the timestamp
*/
private function getTimestamp(){
$date = new \DateTime();
return strval($date->getTimestamp());
}
/**
* Insert data
*
* @param array $data the data to insert
*/
private function insertData($data){
$isSingular = $this->numFails == 1;
$entityOrEntities = null;
if ($isSingular){
$entityOrEntities = "entity";
} else {
$entityOrEntities = "entities";
}
print " Inserting " . count($data["insert"]) . " " . $entityOrEntities . "\n";
$insertDataArray = $this->translateColumnNames($data["insert"]);
if ($this->verbose) {
print_r($insertDataArray);
}
$this->client->insert($insertDataArray);
sleep($this->sleepTime);
}
/**
* Tranlate column name to use timestamp
*
* @param array $jsonData the json data to translate columns
*/
private function translateColumnNames($jsonData){
$dataString = json_encode($jsonData);
foreach ($this->columnTranslation as $oldName => $newName) {
$dataString = str_replace($oldName, $newName, $dataString);
}
return json_decode($dataString, true);
}
/**
* Execute query on Slicing Dice API
*
* @param string $queryType the query type
* @param array $data the query array
*/
private function executeQuery($queryType, $data){
if ($this->perTestInsertion) {
$queryData = $this->translateColumnNames($data["query"]);
} else {
$queryData = $data['query'];
}
$result = null;
echo " Querying\n";
if ($this->verbose){
print_r($queryData);
}
if ($queryType == "count_entity"){
$result = $this->client->countEntity($queryData);
} else if ($queryType == "count_event"){
$result = $this->client->countEvent($queryData);
} else if ($queryType == "top_values"){
$result = $this->client->topValues($queryData);
} else if ($queryType == "aggregation"){
$result = $this->client->aggregation($queryData);
} else if ($queryType == "result"){
$result = $this->client->result($queryData);
} else if ($queryType == "score") {
$result = $this->client->score($queryData);
} else if ($queryType == "sql") {
$result = $this->client->sql($queryData);
}
return $result;
}
/**
* Compare received result with expected
*
* @param array $expectedArray the expected array
* @param array $result the result array received
*/
private function compareResult($expectedArray, $result){
if ($this->perTestInsertion) {
$expected = $this->translateColumnNames($expectedArray["expected"]);
} else {
$expected = $expectedArray["expected"];
}
foreach ($expectedArray["expected"] as $key => $value) {
if($value == "ignore"){
continue;
}
if (!array_key_exists($key, $result) || array_diff($expected[$key], $result[$key])){
$this->numFails += 1;
array_push($this->failedTests, $expectedArray["name"]);
print_r(' Expected: "' . $key . '": ' . json_encode($expected[$key]) . "\n");
print_r(' Result: "' . $key . '": ' . json_encode($result[$key]) . "\n");
echo " Status: Failed\n";
$this->updateResults();
return;
}
}
$this->numSuccess += 1;
print " Status: Passed\n";
$this->updateResults();
}
/**
* Update tests result on tests result file
*/
private function updateResults() {
if (PHP_OS != "Linux") return;
$finalMessage = null;
$failedTestsStr = null;
foreach ($this->failedTests as $item) {
$failedTestsStr .= " - " . $item . "\n";
}
if ($this->numFails > 0){
$isSingular = $this->numFails == 1;
$testOrTests = null;
if ($isSingular){
$testOrTests = "test has";
} else {
$testOrTests = "tests have";
}
$finalMessage = "FAIL: $this->numFails $testOrTests failed";
} else {
$finalMessage = "SUCCESS: All tests passed";
}
$content = "\nResults:\n" .
" Successes: $this->numSuccess \n" .
" Fails: $this->numFails \n" .
$failedTestsStr . "\n" .
$finalMessage . "\n";
$fp = fopen('testerResult.tmp', 'w');
fwrite($fp, $content);
fclose($fp);
}
}
/**
* Print the content of tests result
*/
function showResult(){
echo file_get_contents("testerResult.tmp");
unlink("testerResult.tmp");
}
function signal_handler(){
showResult();
exit(1);
}
function main(){
$queryTypes = array(
'count_entity',
'count_event',
'top_values',
'aggregation',
'result',
'score',
'sql',
'delete',
'update'
);
$apiKey = $_SERVER["SD_API_KEY"] ? $_SERVER["SD_API_KEY"] : "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfX3NhbHQiOiJkZW1vNzc5NG0iLCJwZXJtaXNzaW9uX2xldmVsIjozLCJwcm9qZWN0X2lkIjoyNzc5NCwiY2xpZW50X2lkIjoxMH0.KvU4-ORIUjie0aApt6gabuDUNeBx0CGo4zYCoTHawyI";
// Use SlicingDiceTester with demo api key
// To get another demo api key visit: http://panel.slicingdice.com/docs/#api-details-api-connection-api-keys-demo-key
$sdTester = new SlicingDiceTester($apiKey);
// run tests for each query type
try{
foreach($queryTypes as $item){
$sdTester->runTests($item);
}
} catch(\Exception $e){
}
showResult();
if ($sdTester->numFails > 0) {
exit(1);
}
}
main();
?>