view tests/test_uniques.py @ 18:56596902e9ae default tip

add some setup + tests
author Jeff Hammel <k0scist@gmail.com>
date Sun, 10 Dec 2017 17:57:03 -0800
parents
children
line wrap: on
line source

#!/usr/bin/env python

"""
test CSV file uniques counter
"""

import csv
import os
import shutil
import tempfile
import unittest
from lemuriformes.uniques import uniques
from StringIO import StringIO


class TestUniques(unittest.TestCase):

    header = ['a', 'b', 'c']
    dataset = [[1,2,3],
               [1,1,2],
               [1,2,4]]

    def write_dataset(self, fp):

        writer = csv.writer(fp)
        writer.writerow(self.header)
        writer.writerows(self.dataset)
        fp.flush()

    def validate(self, uniq):
        """validate `uniq` for object dataset"""

        # count them
        counts = {key: len(value)
                  for key, value in uniq.items()}
        assert counts['a'] == 1
        assert counts['b'] == 2
        assert counts['c'] == 3


    def test_file(self):
        """test reading uniques from a file"""

        tmpdir = tempfile.mkdtemp()
        try:
            # write test data
            dst = os.path.join(tmpdir, 'test.csv')
            with open(dst, 'w') as fp:
                self.write_dataset(fp)

            # determine uniques
            self.validate(uniques(dst))

        finally:
            shutil.rmtree(tmpdir, ignore_errors=True)

    def test_buffer(self):
        """test using a StringIO buffer object"""

        # write test data to buffer
        buffer = StringIO()
        self.write_dataset(buffer)
        buffer.seek(0)

        # determine uniques
        self.validate(uniques(buffer))

if __name__ == '__main__':
    unittest.main()