Source

lspec / lspec.inc

  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
/*
   Copyright 2011 Bradley Lindsay

   Licensed 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.
*/
/*
* Terminology:
*   expectation => each [expect] style statement
*   test        => each [it] statement
*   test group  => each [describe] statement
*   test suite  => Compilation of all the test groups [lspec->suite]
*/
define error_code_missingGivenBlock => 10
define error_msg_missingGivenBlock  => 'This method requires a block'

define error_code_lspecNotInTestGroup => 100
define error_msg_lspecNotInTestGroup  => 'The test block is not encompassed in a test group block'

define error_code_lspecNotInTest => 101
define error_msg_lspecNotInTest  => "The test case is not encompassed in a test block"
    
define error_code_lspecTestGroupInTest => 102
define error_msg_lspecTestGroupInTest  => "The test group is in a test block"

define error_code_lspecStopInTestGroup => 103
define error_msg_lspecStopInTestGroup  => "Can not stop while in a test group"
    
define error_code_lspecInvalidResultFormat => 104
define error_msg_lspecInvalidResultFormat  => "You have specified an invalid result format"

define error_code_lspecTestGroupHasBeforeEach => 105
define error_msg_lspecTestGroupHasBeforeEach  => "You have already specified a [beforeEach] block"

define error_code_lspecTestGroupHasAfterEach => 106
define error_msg_lspecTestGroupHasAfterEach  => "You have already specified an [afterEach] block"

define error_code_lspecTestGroupHasBeforeAll => 107
define error_msg_lspecTestGroupHasBeforeAll  => "You have already specified a [beforeAll] block"

define error_code_lspecTestGroupHasAfterAll => 108
define error_msg_lspecTestGroupHasAfterAll  => "You have already specified a [afterAll] block"


define lspec_testSuite => type {
    // Tallying up the test suite
    data private suite    = array,
         private result   = string,
         private failures = '',
         private pendings = ''
    // Tally Getters
    public suite    => .'suite',
           result   => .'result',
           failures => .'failures',
           pendings => .'pendings'
         
    // Flow status
    data private inTestGroup  = false,
         private inTest       = false,
         private currentDepth = 0,
         private done         = false
    // Flow "Setters"
    public enterTestGroup => { .inTestGroup = true  },
           leaveTestGroup => { .inTestGroup = false },
           enterTest      => { .inTest = true  },
           leaveTest      => { .inTest = false },
           incGroupDepth  => .currentDepth++,
           decGroupDepth  => .currentDepth--,
           isStopped      => .done
    public stop => {
        fail_if(.inTestGroup,
            error_code_lspecStopInTestGroup, error_msg_lspecStopInTestGroup)
        .done = true
        .outputPendings
        .outputFailures
        .outputSummary
    }
         
    // Stats
    data private numTests     = 0,
         private numTestCases = 0,
         private numSuccesses = 0,
         private numFailures  = 0,
         private numPending   = 0,
         private runTime      = 0
    // Stats Getters and Setters
     public numTests     => .'numTests',
            numTestCases => .'numTestCases',
            numSuccesses => .'numSuccesses',
            numFailures  => .'numFailures',
            numPending   => .'numPending',
            runTime      => .'runTime',
            runTimeSec   => .'runTime' / 1000000.0,
            runTime(time::integer) => { .'runTime' += #time }
         
    // Configuration Options
    data private validFormats = (:'p', 'd'),
                            // p => Progress, default
                            // d => Documentation
         private options      = map(
                    'resultsFormat'  = "p",
                    'indentor'       = "    ",
                    'suppressOutput' = false,
         )
    // Configuration Options Setters & Getters
    public options => .'options'
    public setOptions(new::map) => {
        with key in .'options'->keys 
        do {
            #new->contains(#key)? .'options'->find(#key) = #new->find(#key)
        }
    }
    public indentor => .options->find('indentor'),
           indentor(new::string) => { .options->find('indentor') = #new }
       
    public isOutputSuppressed =>   .options->find('suppressOutput'),
           suppressOutput     => { .options->find('suppressOutput') = true  },
           showOutput         => { .options->find('suppressOutput') = false }
           
    public resultsFormat => .options->find('resultsFormat')
    public formatResults(new::string) => {
        fail_if(not .validFormats->contains(#new), 
            error_code_lspecInvalidResultFormat, error_msg_lspecInvalidResultFormat)
        .options->find('resultsFormat') = #new
    }
    
    
    // Code to add test stuff to lspec test suite
    public addTestGroup(tg::lspec_testGroup) => {
        fail_if(.inTest, error_code_lspecTestGroupInTest, error_msg_lspecTestGroupInTest)
        
        if(.inTestGroup) => {
            .getCurrentTestGroup->groups->insert(#tg)
        else
            .suite->insert(#tg)
            #tg->run
        }
    }
    public addTest(test::lspec_test) => {
        fail_if(not .inTestGroup, error_code_lspecNotInTestGroup, error_msg_lspecNotInTestGroup)
        .getCurrentTestGroup->tests->insert(#test)
        .numTests++
    }
    public addTestCase => {
        fail_if(not .inTest, error_code_lspecNotInTest, error_msg_lspecNotInTest)
        .numTestCases++
    }
    public addBeforeAll(block::capture) => {
        fail_if(not .inTestGroup, error_code_lspecNotInTestGroup, error_msg_lspecNotInTestGroup)
        .getCurrentTestGroup->beforeAll(#block)
    }
    public addBeforeEach(block::capture) => {
        fail_if(not .inTestGroup, error_code_lspecNotInTestGroup, error_msg_lspecNotInTestGroup)
        
        .getCurrentTestGroup->beforeEach(#block)
    }
    public addAfterAll(block::capture) => {
        fail_if(not .inTestGroup, error_code_lspecNotInTestGroup, error_msg_lspecNotInTestGroup)
        .getCurrentTestGroup->afterAll(#block)
    }
    public addAfterEach(block::capture) => {
        fail_if(not .inTestGroup, error_code_lspecNotInTestGroup, error_msg_lspecNotInTestGroup)
        
        .getCurrentTestGroup->afterEach(#block)
    }
    
    
    // Test suite location methods
    public getCurrentTestGroup => {
        local(ret_val) = .suite->last
        loop(.currentDepth) => {
            #ret_val = #ret_val->groups->get(#ret_val->currentGroup)
        }
        return #ret_val
    }
    private currentTGroupLabels => {
        local(test_group) = .suite->last
        local(ret_val)    = ''
        loop(.currentDepth) => {
            #ret_val   += #test_group->label + ' '
            #test_group = #test_group->groups->get(#test_group->currentGroup)
        }
        #ret_val += #test_group->label
        return #ret_val
    }
    public getCurrentTest => {
        return .getCurrentTestGroup->tests->get(.getCurrentTestGroup->currentTest)
    }
    public runCurrentBeforeEach => {
        local(test_group) = .suite->last
        loop(.currentDepth) => {
            #test_group->beforeEach->invoke
            #test_group = #test_group->groups->get(#test_group->currentGroup)
        }
        #test_group->beforeEach->invoke
    }
    
    
    // Completed test status code
    public testPending(test::lspec_test) => {
        .numPending++
        
        local(spacer)    = ' ' * (.numPending->asString->size + 2)
        
        .pendings == ''? .pendings += '\n\nPending:'
        
        .pendings += '\n\n' + .indentor + .numPending + ') ' + .getCurrentTestGroup->label + ' ' + #test->label
        .pendings += '\n' + .indentor + #spacer + .indentor + '# ' + #test->location->first + ' ' + #test->location->second
    }
    
    public testSucceeded => .numSuccesses++
    
    public testFailed(test::lspec_test, error=null) => {
        .numFailures++
        
        local(spacer)    = ' ' * (.numFailures->asString->size + 2)
        local(location)  = (not #error ? #test->failedTestCase->location | #test->location)
        local(line_num)  = integer(#location->first->split(':')->first)
        local(col_num)   = integer(#location->first->split(':')->second)
        local(code)
        
        if(#error) => {
            #code = 'Unexpcted Error!'
        else
            local(f) = file(#location->second, file_openRead, file_modeLine)
            #f->doWithClose => {
                loop(#line_num - 1) => {#f->get}
                #code = #f->get->sub(#col_num)
            }
        }
        
        .failures == ''? .failures += '\n\nFailures:'
        
        .failures += '\n\n' + .indentor + .numFailures + ') ' + .currentTGroupLabels + ' ' + #test->label
        .failures += '\n' + .indentor + #spacer + 'Failure/Error: ' + #code
        if(#error) => {
            .failures += '\n' + .indentor + #spacer + .indentor + 'Error Code: ' + #error->first
            .failures += '\n' + .indentor + #spacer + .indentor + ' Error Msg: ' + #error->second
        else
            .failures += '\n' + .indentor + #spacer + .indentor + 'expected: ' + #test->failedTestCase->val_expected
            .failures += '\n' + .indentor + #spacer + .indentor + '     got: ' + #test->failedTestCase->val_actual
        }
        .failures += '\n' + .indentor + #spacer + '# ' + #location->first + ' ' + #location->second
    }
    
    
    // Test suite output code
    public output(value::string) => {
        .result += #value
        not .isOutputSuppressed? stdout(#value)
    }
    public output(tg::lspec_testGroup) => {
        'p' == .resultsFormat? return
        
        local(out) = (.indentor * .currentDepth) + #tg->label
        .result != '' ? #out = '\n' + #out
        .output(#out)
    }
    public output(test::lspec_test) => {
        'p' == .resultsFormat? return
        
        local(out) = '\n' + (.indentor * .currentDepth) + .indentor + #test->label
        .output(#out)
    }
    
    public outputStatus(status::string) => {
        match(.resultsFormat) => {
        case('d')
            #status != 'fail'? return
            .output(' (FAILED - ' + .numFailures + ')')
        case('p')
            match(#status) => {
            case('pending') .output('*')
            case('success') .output('.')
            case('fail')    .output('F')
            }
        }
    }
    
    public outputSummary => {
        local(summary) = '\n\nFinished in ' + .runTimeSec + ' seconds\n'
        #summary += .numTests + ' test' + (.numTests == 1 ? '' | 's')
        #summary += ', ' + .numFailures + ' failure' + (.numFailures == 1 ? '' | 's')
        .numPending > 0?
            #summary += ', ' + .numPending + ' pending'
        .output(#summary)
    }
    public outputPendings => .output(.pendings)
    public outputFailures => .output(.failures)
}

/*
* Wrapper for the test suite.
* This allows us to create one universal test suite object per thread. All
* subsequent methods use this object, and so should users when necessary
*/
define lspec => var(_lspec) || $_lspec := lspec_testSuite

/*
* Method used to clear out the [lspec] test suite but leave formatting options in place.
*/
define lspec_clearSuite => {
    local(options) = lspec->options
    var(_lspec)    = lspec_testSuite
    $_lspec->setOptions(#options)
}


/*
* The test group type
*/
define lspec_testGroup => type {
    data private label::string,
         private block::capture,
         private suite::lspec_testSuite,
         private tests  = array,
         private groups = array,
         private beforeAll::capture,
         private beforeEach::capture,
         private afterAll::capture,
         private afterEach::capture,
         private parentGroup  = null,
         private currentTest  = 0,
         private currentGroup = 0
     // Getters
     public label        => .'label',
            parentSuite  => .'suite',
            tests        => .'tests',
            groups       => .'groups',
            beforeEach   => .'beforeEach',
            afterEach    => .'afterEach',
            currentTest  => .'currentTest',
            currentGroup => .'currentGroup'
    
    public onCreate(label, gb::capture, ts::lspec_testSuite=lspec) => {
        .label = #label->asString
        .block = #gb->asCopyDeep
        .suite = #ts
    }
    
    public numTests => .tests->size
    
    public beforeAll(block::capture) => {
        fail_if(.beforeAll,
            error_code_lspecTestGroupHasBeforeAll, error_msg_lspecTestGroupHasBeforeAll
        )
        .beforeAll = #block
        #block->invoke
    }
    
    public beforeEach(block::capture) => {
        fail_if(.beforeEach,
            error_code_lspecTestGroupHasBeforeEach, error_msg_lspecTestGroupHasBeforeEach
        )
        .beforeEach = #block
    }
    
    public afterAll(block::capture) => {
        fail_if(.afterAll,
            error_code_lspecTestGroupHasAfterAll, error_msg_lspecTestGroupHasAfterAll
        )
        .afterAll = #block
    }
    
    public afterEach(block::capture) => {
        fail_if(.afterEach,
            error_code_lspecTestGroupHasAfterEach, error_msg_lspecTestGroupHasAfterEach
        )
        .afterEach = #block
    }
    
    public runAfterEaches => {
        .afterEach->invoke
        .parentGroup? .parentGroup->runAfterEaches
    }
    
    public run => {
        local(start) = micros
        .parentSuite->enterTestGroup
        handle => {
            .afterAll->invoke
            .parentSuite->leaveTestGroup
            not .parentGroup? .parentSuite->runTime(micros - #start)
        }
        
        .parentSuite->output(self)
        .block->invoke
        .currentTest = 0
        .tests->forEach => {
            .currentTest++
            
            .parentSuite->runCurrentBeforeEach
            #1->run
            .runAfterEaches
        }
        .currentGroup = 0
        .groups->forEach => {
            .currentGroup++
            .parentSuite->incGroupDepth
            #1->parentGroup = self
            #1->run 
            .parentSuite->decGroupDepth
        }
    }
}

/*
* The test type
*/
define lspec_test => type {
    data private label::string,
         private block::capture,
         private suite::lspec_testSuite,
         private status::string,
         private location::pair,
         private failedTestCase::expect
    // Getters
    public label          => .'label',
           parentSuite    => .'suite',
           status         => .'status',
           location       => .'location',
           failedTestCase => .'failedTestCase'
    // Setters
    public failed(test_case::expect)   => {
        .status = 'fail'
        .failedTestCase = #test_case
    }
    
    public onCreate(label, gb::capture, ts::lspec_testSuite=lspec) => {
        .label = #label->asString
        .block = #gb
        .suite = #ts
        
        // We need to know where the test came from in case of errors
        // (Trying to get the error_stack in the handle method doesn't give us what we need)
        iterate(currentCapture->callStack->split('\n')) => {
            local(line_col)  = loop_value->sub(1,loop_value->find(' ') - 1)
            local(file_path) = loop_value->sub(1+loop_value->find(' '))
            if(currentCapture->callsite_file != #file_path) => {
                .location = pair(#line_col, #file_path)
                loop_abort
            }
        }
    }
    
    public run => {
        local(cur_failures) = .parentSuite->numFailures
        local(cur_cases)    = .parentSuite->numTestCases

        .parentSuite->output(self)

        .parentSuite->enterTest
        handle => { .parentSuite->leaveTest }
        local(gb_error) = pair(0='No error')
        protect => {
            handle_error => { #gb_error = pair(error_code=error_msg) }
            .block->invoke
        }

        if(#gb_error->first != 0) => {
            failure_clear
            error_reset
            .status = 'fail'
            .parentSuite->testFailed(self, #gb_error)
        else(.parentSuite->numTestCases == #cur_cases)
            .status = 'pending'
            .parentSuite->testPending(self)
        else(not .status)
            .status = 'success'
            .parentSuite->testSucceeded
        else
            .parentSuite->testFailed(self)
        }
        
        .parentSuite->outputStatus(.status)
    }
}


/*
* Wrapper for getting a test group into the test suite
*/
define describe(label) => {
    lspec->isStopped? lspec_clearSuite
    lspec->addTestGroup(lspec_testGroup(#label, givenBlock))
}
define context(label) =>  {
    lspec->isStopped? lspec_clearSuite
    lspec->addTestGroup(lspec_testGroup(#label, givenBlock))
}


/*
* Wrapper for getting a test into the test suite
*/
define it(label) => {
    lspec->addTest(lspec_test(#label, givenBlock))
}


/*
* Before and after hooks
*/
define beforeAll => {
    lspec->addBeforeAll(givenBlock)
}
define beforeEach => {
    lspec->addBeforeEach(givenBlock)
}
define afterAll => {
    lspec->addAfterAll(givenBlock)
}
define afterEach => {
    lspec->addAfterEach(givenBlock)
}


/*
* The base expect type that can be extended for test cases
* The base onCreate sets up everything that is needed before the test case runs
* The onCreate that takes a boolean is the simplest test case - asserting true
*/
define expect => type {
    data private suite::lspec_testSuite,
         private location,
         private val_expected,
         private val_actual
    // Want getters but not setters
    public parentSuite  => .'suite',
           location     => .'location',
           val_expected => .'val_expected',
           val_actual   => .'val_actual'
    
    public onCreate(ts::lspec_testSuite=lspec) => {
        .suite = #ts
        .parentSuite->addTestCase
        
        // We need to know where the expect came from
        iterate(currentCapture->callStack->split('\n')) => {
            local(line_col)  = loop_value->sub(1,loop_value->find(' ') - 1)
            local(file_path) = loop_value->sub(1+loop_value->find(' '))
            if(currentCapture->callsite_file != #file_path) => {
                .location = pair(#line_col, #file_path)
                loop_abort
            }
        }
    }
    public onCreate(test_case::boolean, expected::string='true', got::string='false') => {
        .onCreate
        not #test_case? .fail(#expected, #got)
    }
    public onCreate(expected, got) => {
        .onCreate(#expected == #got, #expected->asString, #got->asString)
    }
    
    private fail(expected::string='', got::string='') => {
        .val_expected = #expected
        .val_actual   = #got
        .parentSuite->getCurrentTest->failed(self)
    }
}

/*
* This expect statement expects a null value to be passed into it
*/
define expect->null(value) => {
    not #value->isA(::null)?
        .fail('null', '"' + #value + '"')
}

/*
* This expect statement catches any errors sent to its block and then
* compares the error with the given expected error.
*/
define expect->error(code::integer, msg::string) => {
    fail_if(not givenBlock,
        error_code_missingGivenBlock, error_msg_missingGivenBlock)
    
    local(my_error) = pair(error_code_noerror=error_msg_noerror)
    protect => {
        handle_error => { #my_error = pair(error_code=error_msg) }
        givenBlock()
    }
    
    failure_clear
    error_reset
    
    if(#my_error->first != #code or #my_error->second != #msg) => {
        .fail(#code + ': ' + #msg,
              #my_error->first + ': ' + #my_error->second)
    }
}

/*
* This expect statement passes if there is any error in the
* givenBlock and fails there is no error.
*/
define expect->error => {
    fail_if(not givenBlock,
    error_code_missingGivenBlock, error_msg_missingGivenBlock)

    local(my_error) = pair(error_code_noerror=error_msg_noerror)
    protect => {
        handle_error => { #my_error = pair(error_code=error_msg) }
        givenBlock()
    }

    failure_clear
    error_reset
    
    if(#my_error->first == error_code_noerror and #my_error->second == error_msg_noerror) => {
        .fail('Any Error', #my_error->first + ': ' + #my_error->second)
    }
}

/*
* This expect statement catches whatever is sent to stdout in its block and
* compares that with the given expected result.
*/
define expect->stdout(expected::string) => {
    fail_if(not givenBlock,
        error_code_missingGivenBlock, error_msg_missingGivenBlock)
    
    // save stdout using ->dup
    // create a local conduit
    // close real stdout, reopen it on our write pipe using dup2 system call
    // make a file object here which we read stdout from
    local(save_stdout)     = file_stdout->fd->dup
    local(readFd, writeFd) = io_file_pipe
    #writeFd->dup2(file_stdout->fd)
    local(read_test) = file(#readFd)
    // set stdout back using our save
    handle => { #save_stdout->dup2(file_stdout->fd) }
    
    givenBlock()
    
    local(did_read) = #read_test->readString
    
    #did_read != #expected? .fail(#expected, #did_read)
}