unitbench / src / tests / test_unitbench.py

'''
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_stddev, 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_stddev, 3.32, places=2)

class TestFunctionProfiler(TestCase):
        
    def test_track_parameters(self):
        fp = FunctionProfiler(track_parameters=True)
        
        @fp
        def sum23():
            return 2 + 3
        
        @fp
        def plus2(x):
            return x + 2
        
        @fp
        def adder(x, y):
            return x + y
        
        eq_(plus2(5), 7)
        eq_(plus2(8), 10)
        eq_(sum23(), 5)
        eq_(adder(7, 9), 16)
        eq_(adder(1, 1), 2)
        eq_(len(fp.results), 5)
        
    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 0
            
            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")
        eq_("Values,Sample1,Sample2", lines[0])
        eq_("10", lines[1].split(',')[0])
        eq_("100", lines[2].split(',')[0])
        eq_("1000", lines[3].split(',')[0])
        
        
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.