unitbench / src / tests / test_unitbench.py

  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
'''
Copyright (c) 2011, Joseph LaFata
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the unitbench nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
import sys
from nose.tools import assert_almost_equals, assert_raises, eq_
from unitbench import TimeSet, FunctionProfiler, Benchmark
from unitbench import BenchResult, Reporter, ConsoleReporter, CsvReporter
from unittest import TestCase

if sys.version_info < (3, 0):
    from StringIO import StringIO
else:
    from io import StringIO

class NullReporter(Reporter):
    pass

class OneRun(Benchmark):
    def warmup(self):
        return 0
    
    def repeats(self):
        return 1

class TestBenchResult(TestCase):
    
    def test_add_time(self):
        result = BenchResult("bench_sample2", 16)
        
        result.add_time(TimeSet(3, 1, 0))
        eq_(len(result.times), 1)
        
        result.add_time((TimeSet(4, 2, 0), TimeSet(4, 4, 0)))
        eq_(len(result.times), 3)
        
        result.add_time([TimeSet(5, 5, 0), TimeSet(6, 7, 0), TimeSet(8, 11, 0)])
        eq_(len(result.times), 6)
        
        eq_(result.name, "bench_sample2")
        eq_(result.value, "16")
        
        result.calculate_stats()
        
        self.check_stats(result)
    
    def test_stats(self):
        times = []
        times.append(TimeSet(3, 1, 0))
        times.append(TimeSet(4, 2, 0))
        times.append(TimeSet(4, 4, 0))
        times.append(TimeSet(5, 5, 0))
        times.append(TimeSet(6, 7, 0))
        times.append(TimeSet(8, 11, 0))
        
        result = BenchResult("bench_sample1", 10, times)
        eq_(len(times), 6)
        
        result.calculate_stats()
        
        eq_(result.name, "bench_sample1")
        assert result.value == "10"
        
        self.check_stats(result)
        
    def check_stats(self, result):
        
        
        assert result.wall_min == 3
        assert result.wall_max == 8
        assert result.wall_mean == 5
        assert_almost_equals(result.wall_variance, 2.67, places=2)
        assert_almost_equals(result.wall_std_dev, 1.63, places=2)
        
        assert result.user_min == 1
        assert result.user_max == 11
        assert result.user_mean == 5
        assert result.user_variance == 11.0
        assert_almost_equals(result.user_std_dev, 3.32, places=2)

class TestFunctionProfiler(TestCase):
    
    def run_function_profiler(self, repeat, warm, tp):
        fp = FunctionProfiler(repeat, warm, tp)
        
        @fp
        def sum23():
            return 2 + 3
        
        @fp
        def plus2(x):
            return x + 2
        
        @fp
        def adder(x, y):
            return x + y
        
        @fp
        def list_test(x):
            return x[0]
        
        @fp
        def dict_test(x):
            return x['x']
        
        eq_(plus2(5), 7)
        eq_(plus2(8), 10)
        eq_(sum23(), 5)
        eq_(sum23(), 5)
        eq_(adder(7, 9), 16)
        eq_(adder(1, 1), 2)
        eq_(list_test([9, 8, 7, 6]), 9)
        eq_(list_test([6, 7, 8, 9]), 6)
        eq_(dict_test( {'x':11, 'y':9} ), 11)
        
        return fp
    
    def result_check(self, results, function_name, attr, value):
        for r in results:
            if r.name == function_name:
                eq_(getattr(r, attr), value)
                
    def test_track_parameters(self):
        fp = self.run_function_profiler(1, 0, True)
        eq_(len(fp.results), 8)
        results = map(lambda x: x.calculate_stats(), fp.results.values())
        self.result_check(results, 'sum23', 'call_count', 2)
        
    def test_no_parameters(self):
        fp = self.run_function_profiler(1, 0, False)
        eq_(len(fp.results), 5)
        results = map(lambda x: x.calculate_stats(), fp.results.values())
        self.result_check(results, 'sum23', 'call_count', 2)
        
    def test_repeats(self):
        fp = self.run_function_profiler(2, 0, True)
        eq_(len(fp.results), 8)
        results = map(lambda x: x.calculate_stats(), fp.results.values())
        self.result_check(results, 'sum23', 'call_count', 4)
    
    def test_repeats_no_params(self):
        fp = self.run_function_profiler(2, 0, False)
        eq_(len(fp.results), 5)
        results = map(lambda x: x.calculate_stats(), fp.results.values())
        self.result_check(results, 'sum23', 'call_count', 4)
    
    def test_warmup(self):
        fp = self.run_function_profiler(2, 3, True)
        eq_(len(fp.results), 8)
        results = map(lambda x: x.calculate_stats(), fp.results.values())
        self.result_check(results, 'sum23', 'call_count', 4)
        
    def test_warmup_no_params(self):
        fp = self.run_function_profiler(2, 3, False)
        eq_(len(fp.results), 5)
        results = map(lambda x: x.calculate_stats(), fp.results.values())
        self.result_check(results, 'sum23', 'call_count', 4)
        
    def test_args_to_str(self):
        eq_(FunctionProfiler._args_to_str(),
           "None")
        eq_(FunctionProfiler._args_to_str(1),
           "[1]")
        eq_(FunctionProfiler._args_to_str(1, '1'),
           "[1, \"1\"]")
        eq_(FunctionProfiler._args_to_str(1, 2, 3, 4),
           "[1, 2, 3, 4]")
        eq_(FunctionProfiler._args_to_str(1, 2, 3, 4, x=5),
           "[1, 2, 3, 4] {x:5}")
        eq_(FunctionProfiler._args_to_str(x=5),
           "{x:5}")
        eq_(FunctionProfiler._args_to_str(x=5, y=True),
           "{x:5, y:True}")
        eq_(FunctionProfiler._args_to_str(2, x=5, y=True),
           "[2] {x:5, y:True}")
        eq_(FunctionProfiler._args_to_str('', x=5, y=True),
           "[\"\"] {x:5, y:True}")
        eq_(FunctionProfiler._args_to_str('', x=5, y=True, z=eq_),
           "[\"\"] {x:5, y:True, z:eq_}")
        
    def test_wrap_int(self):
        eq_(1, FunctionProfiler._wrap_int(1)())
        eq_(1098, FunctionProfiler._wrap_int(1098)())
        eq_(1257, FunctionProfiler._wrap_int(1257)())
        eq_(-99, FunctionProfiler._wrap_int(-99)())
    
class TestBenchmark(TestCase):
    def test_warmup(self):
        class sample(Benchmark):
            def __init__(self):
                self.count = 0
                self.count2 = 0
                
            def warmup(self):
                return 4
            
            def repeats(self):
                return 0
            
            def bench_count(self):
                self.count += 1
                
            def bench_count2(self, input):
                self.count2 += 1
            
        bm = sample()
        bm.run(NullReporter())
        assert bm.count == 4
        assert bm.count2 == 4
            
    def test_teardown(self):
        """ teardown should be called regardless of errors
        """
        class sample(Benchmark):
            def __init__(self):
                self.setup_count = 0
                
            def warmup(self):
                return 2
            
            def repeats(self):
                return 7
                
            def setup(self):
                self.setup_count += 1
                if self.setup_count > 1:
                    raise ValueError
            
            def teardown(self):
                self.setup_count -= 1
                if self.setup_count < 0:
                    raise ValueError
                
            def bench_works(self):
                pass
        
        bm = sample()
        bm.run()
        assert bm.setup_count == 0
    
    def test_exception(self):
        class sample(OneRun):
            def bench_exception(self, input):
                1/0
                
        bm = sample()
        self.assertRaises(ZeroDivisionError, bm.run)
    
    def test_input(self):
        class SampleBase(OneRun):
            def __init__(self):
                self.passed_in = []
                
            def bench_sample(self, input):
                self.passed_in.append(input)
        
        class InputGen(SampleBase):
            def input(self):
                i = 10
                while i < 1000:
                    yield i
                    i *= 10
                    
        class InputList(SampleBase):
            
            def input(self):
                return [10, 100, 1000, 20]
            
        bm = InputGen()
        bm.run(NullReporter())
        
        assert bm.passed_in == [10, 100]
        
        bm = InputList()
        bm.run(NullReporter())
        
        assert bm.passed_in == [10, 100, 1000, 20]
        
    def test_param_count(self):
        class sample(OneRun):
            def bench_no_params(self):
                self.no_param = True
            
            def bench_one_param(self, input):
                self.one_param = True
                
        bm = sample()
        bm.run(NullReporter())
        
        assert bm.no_param
        assert bm.one_param
        
    def test_findbenchmarks(self):
        class sample(Benchmark):
            
            def benchSample1(self, input):
                pass
            
            def bench_Sample2(self, input):
                pass
            
            def sampleBench3(self, input):
                pass
            
            def bench_sample4(self):
                pass
                
        bms = sample()._find_benchmarks()
        assert "benchSample1" in bms
        assert "bench_Sample2" in bms
        assert not "sampleBench3" in bms
        assert "bench_sample4" in bms
        
    def test_function_name_to_title(self):
        eq_(Benchmark._function_name_to_title("bench_sample1_sample2"), "Sample1 Sample2")
        eq_(Benchmark._function_name_to_title("benchSample1Sample2"), "Sample1 Sample2")
        eq_(Benchmark._function_name_to_title("BENCHsample1_sample2"), "Benchsample1 Sample2")
        eq_(Benchmark._function_name_to_title("Sample1Sample2"), "Sample1 Sample2")
        eq_(Benchmark._function_name_to_title("_sample1_sample2_"), "Sample1 Sample2")
        eq_(Benchmark._function_name_to_title("XMLBenchmark"), "Xml Benchmark")

class TestConsoleReporter(TestCase):
    def test_count_digits(self):
        eq_(ConsoleReporter.count_digits(1), 1)
        eq_(ConsoleReporter.count_digits(5), 1)
        eq_(ConsoleReporter.count_digits(10), 2)
        eq_(ConsoleReporter.count_digits(19), 2)
        eq_(ConsoleReporter.count_digits(99), 2)
        eq_(ConsoleReporter.count_digits(100), 3)
        eq_(ConsoleReporter.count_digits(999), 3)
        eq_(ConsoleReporter.count_digits(1000), 4)
        eq_(ConsoleReporter.count_digits(9999), 4)
        
    def test_make_key(self):
        cr = ConsoleReporter()
        title = "012345678901234567890123456789"
        key = []
        t2 = cr._make_key(title, 30, key)
        eq_(len(key), 1)
        eq_(t2, title[23:] + '...[1]')
        
        key = []
        t2 = cr._make_key(title, 31, key)
        eq_(len(key), 0)
        eq_(t2, title)
        
        key = []
        t2 = cr._make_key(title, 25, key)
        eq_(len(key), 1)
        eq_(t2, title[24-6:] + "...[1]")
        
    def test_write_results(self):
        class sample(OneRun):
            def input(self):
                yield 100
            
            def bench_sample1(self):
                pass
            
            def bench_sample2(self):
                pass
        
        bm = sample()
        
        stream = StringIO()
        bm.run(ConsoleReporter(stream, ConsoleReporter.GroupType.VALUE)) 
        
        output = stream.getvalue()
        stream.close()
        
        lines = output.strip().split("\n")
        
        eq_(len(lines), 4)
        eq_(lines[0].find("100"), 7)
        eq_(lines[2].find("Sample1"), 0)
        eq_(lines[3].find("Sample2"), 0)
        

class TestCsvReporter(TestCase):        
    def test_write_results(self):
        class sample(OneRun):
            def input(self):
                i = 10
                while i < 10000:
                    yield i
                    i *= 10
                    
            def warmup(self):
                return 1
            
            def repeats(self):
                return 3
            
            def bench_sample1(self):
                self.no_param = True
            
            def bench_sample2(self, input):
                self.one_param = True
                
        bm = sample()
        
        stream = StringIO()
        bm.run(CsvReporter(stream))
        
        output = stream.getvalue()
        stream.close()
        
        lines = output.split("\n")
        print lines
        eq_("Name,Value,Call Count,Wall Minimum,Wall Maximum,Wall Average,Wall Standard Deviation,Wall Variance", lines[0])
        eq_("Sample1", lines[1].split(',')[0])
        eq_("10", lines[1].split(',')[1])
        eq_("3", lines[1].split(',')[2])
        eq_(8, len(lines[2].split(',')))
        
        
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.