-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEasyExcelF.cs
More file actions
494 lines (436 loc) · 18.1 KB
/
EasyExcelF.cs
File metadata and controls
494 lines (436 loc) · 18.1 KB
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
using ExcelDataReader;
using System.Collections;
using System.Data;
namespace EasyExcelFramework
{
public class EasyExcelF
{
public EasyExcelF parent;
//Dictionary of Worksheets
private Dictionary<string, DataTable>? worksheets;
public Dictionary<string, DataTable>? Worksheets { get => worksheets; }
public InterpreterClass Interpreter;
//worksheet property
private string worksheet;
public string Worksheet { get => worksheet; }
//Dictionary of variables
public Dictionary<string, dynamic>? Locals;
//Dictionary of Globals
public Dictionary<string, dynamic>? Globals;
public IDictionary? Environ;
//First worksheet where the framework begins executing
//RegisteredActions
private Dictionary<string, Func<EasyExcelF, dynamic[], bool>> registeredactions;
private string firstworksheet;
//Current indent the framework is operating at
private int currentindent;
public int CurrentIndent { get => currentindent; }
private string[] currentdatarow;
public string[] Currentdatarow { get => currentdatarow; }
public int Currentrownumber { get => currentrownumber; }
private int currentrownumber;
public dynamic[] passedparams;
public List<TestStepsLogEntry> StepHistory;
public List<TestLog> TestHistory;
public bool loopactive;
public bool breakoutofloop;
public Func<string, string> Screenshot { get => screenshot; set => screenshot = value; }
private Func<string, string> screenshot;
private Func<EasyExcelF, string> report;
private string defaultpath;
private bool ignoreerrors;
public void finish()
{
Console.WriteLine("Passed: " + TestHistory.Count(n => n.Outcome));
Console.WriteLine("Failed: " + TestHistory.Count(n => !n.Outcome));
Console.WriteLine();
bool failed = false;
foreach (var t in TestHistory)
{
Console.WriteLine(string.Format("Test {0,-20} {1,4} {2} {3} {4}",
t.Test,
t.Outcome ? "Pass" : "Fail",
t.Started,
t.End - t.Started,
string.Join(", ", t.parameters)
));
if (!t.Outcome)
failed = true;
}
if (failed)
{
Console.WriteLine();
Console.WriteLine("Detail:");
Console.WriteLine();
foreach (var t in TestHistory)
{
if (!t.Outcome)
{
Console.WriteLine(string.Format("Test: {0,-20} {1,4} {2} {3} {4}",
t.Test,
t.Outcome ? "Pass" : "Fail",
t.Started,
t.End - t.Started,
string.Join(", ", t.parameters)
));
foreach (var s in t.StepHistory)
{
if (s.Outcome)
Console.ForegroundColor = ConsoleColor.Green;
else
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(string.Format("\tStep: {0} {1} {2,-20} {3} {4}",
s.Started,
s.End - s.Started,
s.Action,
string.Join(", ", s.parameters),
s.Outcome ? "Pass" : "Fail"
));
Console.ResetColor();
if (!s.Outcome)
Console.WriteLine("\t\t"+s.Ex);
}
}
}
}
}
public EasyExcelF(string filename = null, string defaultpath = null)
{
//Add core
EECore eec = new EECore(this);
EELogic eel = new EELogic(this);
EEAssert eea = new EEAssert(this);
//Instanciate Interpreter
Interpreter = new InterpreterClass();
//Instanciate worksheets
worksheets = new Dictionary<string, DataTable>(StringComparer.OrdinalIgnoreCase);
//get environment variables
Environ = Environment.GetEnvironmentVariables();
//set indent level
currentindent = 0;
//Instanciate variables
Locals = new Dictionary<string, dynamic>(StringComparer.OrdinalIgnoreCase);
if (Globals == null)
Globals = new Dictionary<string, dynamic>(StringComparer.OrdinalIgnoreCase);
if (filename != null)
Populateworksheets(filename);
if (string.IsNullOrEmpty(firstworksheet) & filename != null)
throw (new Exception("First worksheet not found: " + filename));
TestHistory = new List<TestLog>();
if (defaultpath == null)
{
this.defaultpath = Directory.GetCurrentDirectory();
}
else
{
this.defaultpath = defaultpath;
}
Console.WriteLine("Easy Excel Framework");
Console.WriteLine("====================");
Console.WriteLine("\nTest Initialised: " + DateTime.Now);
if (filename !=null)
Console.WriteLine(string.Format("File: {0}\n",filename));
}
public EasyExcelF()
{
//Add core
EECore eec = new EECore(this);
EELogic eel = new EELogic(this);
EEAssert eea = new EEAssert(this);
//Instanciate Interpreter
Interpreter = new InterpreterClass();
//Instanciate worksheets
worksheets = new Dictionary<string, DataTable>(StringComparer.OrdinalIgnoreCase);
currentindent = 0;
//get environment variables
Environ = Environment.GetEnvironmentVariables();
//Instanciate variables
Locals = new Dictionary<string, dynamic>(StringComparer.OrdinalIgnoreCase);
if (Globals == null)
Globals = new Dictionary<string, dynamic>(StringComparer.OrdinalIgnoreCase);
//Populateworksheets("Default.xlsx");
//if (string.IsNullOrEmpty(firstworksheet))
// throw (new Exception("First worksheet not found: Default.xslx"));
TestHistory = new List<TestLog>();
this.defaultpath = Directory.GetCurrentDirectory();
Console.WriteLine("Easy Excel Framework");
Console.WriteLine("====================");
Console.WriteLine("\nTest Initialised: " + DateTime.Now);
//Console.WriteLine("File: Default.xlsx\n");
}
public EasyExcelF(EasyExcelF parent)
{
this.parent = parent;
registeredactions = parent.registeredactions;
//Instanciate Interpreter
Interpreter = new InterpreterClass();
//Instanciate worksheets
worksheets = parent.worksheets;
currentindent = 0;
Globals = parent.Globals;
Environ = parent.Environ;
//Instanciate variables
Locals = new Dictionary<string, dynamic>(StringComparer.OrdinalIgnoreCase);
TestHistory = new List<TestLog>();
this.defaultpath = Directory.GetCurrentDirectory();
}
public void Execute(string worksheet = null, dynamic[] passedparameters = null)
{
//handle null parameter
if (worksheet is null)
{
worksheet = firstworksheet;
}
if (string.IsNullOrEmpty(worksheet))
throw new InvalidDataException("Cannot call blank worksheet");
if (passedparameters is null)
{
passedparameters = new string[1];
}
passedparams = passedparameters;
//handle null worksheets
if (worksheets == null)
{
throw new ArgumentNullException(nameof(worksheets));
}
if (Globals == null)
Globals = new Dictionary<string, dynamic>(StringComparer.OrdinalIgnoreCase);
this.worksheet = worksheet;
this.currentrownumber = 0;
//loop through specified worksheet
foreach (DataRow execrow in worksheets[worksheet].Rows)
{
TestStepsLogEntry steplog = new TestStepsLogEntry();
this.currentrownumber++;
if (execrow[currentindent] == null)
throw new ArgumentNullException(nameof(execrow));
//Convert ItemArray into string array
this.currentdatarow = Array.ConvertAll(execrow.ItemArray, x => x.ToString());
int ind = this.currentindent + 1;
string[] parms = this.currentdatarow[ind..];
string[] processedparams = new string[parms.Length];
steplog.Started = DateTime.Now;
steplog.Outcome = false;
steplog.Action = execrow[currentindent].ToString();
steplog.parameters = parms;
steplog.worksheet = worksheet;
steplog.Rownumber = Currentrownumber;
// if (ignoreerrors is null)
// ignoreerrors = false;
if (StepHistory != null)
StepHistory.Add(steplog);
for (int i = 0; i < parms.Length; i++)
{
if (parms[i].StartsWith("="))
{
try
{
processedparams[i] = Interpreter.EvalToString(this, parms[i][1..], passedparameters);
}
catch
{
processedparams[i] = parms[i];
}
}
else
{
processedparams[i] = parms[i];
}
}
try
{
bool result = Command(steplog.Action, processedparams);
steplog.End = DateTime.Now;
steplog.Outcome = true;
}
catch (Exception ex)
{
steplog.End = DateTime.Now;
steplog.Ex = ex;
steplog.Outcome = false;
if (ex.InnerException != null)
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
if (!ignoreerrors)
throw;
}
}
}
public bool Command(string cleanaction, string[] processedparams)
{
if (cleanaction.StartsWith("*"))
{
ignoreerrors = true;
cleanaction = cleanaction[1..];
this.currentdatarow[currentindent] = this.currentdatarow[currentindent][1..];
}
if (registeredactions.ContainsKey(cleanaction))
{
return registeredactions[cleanaction](this, processedparams);
}
else
{
//If it's a worksheet
if (worksheets is not null)
{
if (worksheets.ContainsKey(cleanaction) ||
cleanaction.ToUpper() == "CALL" ||
cleanaction.ToUpper() == "TEST")
{
calltestcase(this.currentdatarow);
return true;
}
else
{
if (!ignoreerrors)
throw new InvalidOperationException("Unrecognised Action: " + cleanaction);
}
}
else
{
if (!ignoreerrors)
throw new InvalidOperationException("Unrecognised Action: " + cleanaction);
}
}
return false;
}
public void Populateworksheets(string filename, string defaultsheetname = "Unknown")
{
//open the file > create a stream
FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read);
Conditions condition = new Conditions();
//create excel object
IExcelDataReader excelReader;
// Fix codepage issues
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
switch (condition.excelextension(filename))
{
case (int)Conditions.FileFormats.XLS:
//1.1 Reading from a binary Excel file ('97-2003 format; *.xls)
excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
break;
case (int)Conditions.FileFormats.CSV:
//Handle CSV Files
excelReader = ExcelReaderFactory.CreateCsvReader(stream);
break;
case (int)Conditions.FileFormats.XLSX:
//1.2 Reading from a OpenXml Excel file (2007 format; *.xlsx)
excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
break;
default:
throw new Exception("Unsupported extension: " + filename);
}
DataSet ds = excelReader.AsDataSet();
//If table name is default (Normal for csv files)
if (ds.Tables[0].TableName == "Table1")
{
ds.Tables[0].TableName = defaultsheetname;
}
//If it's the first time around populate first worksheet
if (string.IsNullOrEmpty(firstworksheet))
{
//populate firstworksheet if it's null or blank
firstworksheet = ds.Tables[0].TableName;
}
//Loop through the worksheets
foreach (DataTable table in ds.Tables)
{
//First Worksheet with a given name take pre-emininence
if (!worksheets.ContainsKey(table.TableName))
worksheets[table.TableName] = table;
}
}
//register addon
public void RegisterMethod(string action, Func<EasyExcelF, dynamic[], bool> passedfunction)
{
//if null assign dict
registeredactions ??= new Dictionary<string, Func<EasyExcelF, dynamic[], bool>>(StringComparer.OrdinalIgnoreCase);
registeredactions[action] = passedfunction;
}
public void calltestcase(dynamic[] parms)
{
switch (parms[0].ToUpper())
{
case "CALL":
//call testcase in new scope
callnewtestcase(parms[1..]);
break;
case "TEST":
//call testcase in new scope
test(parms[1..]);
break;
default:
//call testcase in same scope
switch (parms.Length)
{
case 0:
throw new ArgumentOutOfRangeException("Expected Worksheet");
case 1:
this.Execute(parms[0]);
break;
default:
this.Execute(parms[0], parms[1..]);
break;
}
break;
}
}
private void callnewtestcase(dynamic[] parms)
{
EasyExcelF CalledTestcase = new EasyExcelF(this);
switch (parms.Length)
{
case 0:
throw new ArgumentOutOfRangeException("Expected Worksheet");
case 1:
CalledTestcase.Execute(parms[0]);
break;
default:
CalledTestcase.Execute(parms[0], parms[1..]);
break;
}
}
private void test(dynamic[] parms)
{
if (StepHistory != null)
throw new InvalidOperationException("Cannot Test within a test");
EasyExcelF CalledTestcase = new EasyExcelF(this);
CalledTestcase.StepHistory = new List<TestStepsLogEntry>();
TestLog tl = new TestLog();
tl.Started = DateTime.Now;
tl.Test = parms[0];
tl.parameters = parms;
tl.Outcome = true;
tl.StepHistory = CalledTestcase.StepHistory;
try
{
switch (parms.Length)
{
case 0:
throw new ArgumentOutOfRangeException("Expected Worksheet");
case 1:
CalledTestcase.Execute(parms[0]);
break;
default:
CalledTestcase.Execute(parms[0], parms[0..]);
break;
}
}
catch (Exception ex)
{
tl.Outcome = false;
tl.End = DateTime.Now;
if (this.Screenshot != null)
{
tl.StepHistory[tl.StepHistory.Count-1].screenshot = this.Screenshot(defaultpath);
}
tl.StepHistory[tl.StepHistory.Count - 1].Ex = ex;
//this.TestHistory.Add(tl);
//throw;
}
tl.End = DateTime.Now;
this.TestHistory.Add(tl);
}
public void RegisterScreenShot(Func<string, string> sshot) => Screenshot = sshot;
public void RegisterReport(Func<EasyExcelF, string> Report) => this.report = Report;
}
}