<reponame>alexloser/bace3
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
""" Unit test of bace3/basic.py """
from bace3.basic import PythonVersion, HIGHER_GC_THRESHOLD, LOWER_GC_THRESHOLD, DEFAULT_GC_THRESHOLD
from bace3.basic import NCPU, KB, MB, GB, BEST_IO_BUFFER_SIZE, MAX_FILE_SIZE_32BIT
from bace3.basic import reconfig, get_caller, fmterr
from bace3.basic import to_bytes, utf8, is_iterable, try_unquote
from bace3.basic import recursive_decode, recursive_encode, md5
from bace3.basic import default_release_dirs, search_program, add_sys_path
from bace3.basic import user_dir, home_dir, cur_dir, parent_dir, grand_dir, basename, dirname, is_valid_dir
from bace3.basic import span_wildcard, span_wildcard_recurse, scan_dir, filetime, file_monitor
from bace3.basic import isotime, is_time, time_meter, date_delta, time_delta, datetime_delta
from bace3.basic import urlsplit, urlsplit2, addhttp, addhttp2, trimhttp, trimhttp2, urlpath, urlpath2, urlhost, urlhost2
from bace3.basic import open_as_bytes_stream
from bace3.basic import loadjson, dumpjson


import unittest
from array import array
from random import random
from time import sleep
import sys, _io


class TestBasic(unittest.TestCase):
    def setUp(self):
        pass
    def tearDown(self):
        pass
    
    def test_consts(self):
        self.assertEqual(PythonVersion[0], 3)
        self.assertGreater(NCPU, 1)
        self.assertGreater(HIGHER_GC_THRESHOLD, DEFAULT_GC_THRESHOLD)
        self.assertLess(LOWER_GC_THRESHOLD, DEFAULT_GC_THRESHOLD)
        self.assertGreater(BEST_IO_BUFFER_SIZE, 4096)
        self.assertEqual(0, BEST_IO_BUFFER_SIZE & (BEST_IO_BUFFER_SIZE - 1))
        self.assertEqual(2 * 1024 * 1024 * 1024, MAX_FILE_SIZE_32BIT)
        self.assertEqual(2 * GB, MAX_FILE_SIZE_32BIT)
        self.assertEqual(GB, MB * 1024)
        self.assertEqual(MB, KB * 1024)
        
    def test_system_and_rt(self):
        self.assertEqual("[test_system_and_rt] ", get_caller(0))
        self.assertEqual("[run] ", get_caller(1))
        conf = reconfig()
        self.assertEqual(conf['old gc.threshold'], str(DEFAULT_GC_THRESHOLD))
        self.assertEqual(conf['sys.platform'], 'linux')
        
    def test_debug(self):
        try:
            raise ValueError("test_debug")
        except:
            s = fmterr()
        self.assertTrue(__file__ in s and "ValueError" in s)

    def test_transform(self):
        s = str(self)
        b = to_bytes(s)
        self.assertEqual(b.decode(), s)
        self.assertTrue(to_bytes(b) is b)
        a = [1, 2, 3]
        self.assertTrue(is_iterable(a))
        a = array('i', [int(random() + i) for i in range(100)])
        self.assertEqual(400, len(to_bytes(a)))
        b = b'\xe5\xa3\xb9\xe8\xb4\xb0\xe5\x8f\x81\xe8\x82\x86\xe4\xbc\x8d\xe9\x99\x86\xe6\x9f\x92\xe6\x8d\x8c\xe7\x8e\x96'
        u = utf8(b, errors='strict')
        self.assertEqual(u, "壹贰叁肆伍陆柒捌玖")
        self.assertEqual(try_unquote('%7e/abc+def'), '~/abc def')
        s = "你好" # 7eca689f0d3389d9dea66ae112e5cfd7
        self.assertEqual("7eca689f0d3389d9dea66ae112e5cfd7", md5(s.encode()))
        self.assertEqual(recursive_encode(s, 5), "R!4YOO)^$jV?<h4VpnKbT30c8Pf<NR")
        self.assertEqual(recursive_decode("R!4YOO)^$jV?<h4VpnKbT30c8Pf<NR", 5), s)
        
    def test_path(self):
        drd = default_release_dirs("desktop")
        self.assertGreater(len(drd), 2)
        self.assertTrue(drd[-1], home_dir() + 'desktop')
        self.assertTrue(add_sys_path(drd[-1]))
        self.assertFalse(add_sys_path(drd[-1]))
        self.assertTrue(drd[-1] in sys.path)
        self.assertEqual(user_dir(), home_dir())
        self.assertTrue('bace3' in cur_dir())
        self.assertTrue(grand_dir(__file__) in parent_dir(__file__))
        self.assertTrue(search_program('python3', '/usr/local/bin') or search_program('python3', '/usr/bin'))
        self.assertTrue(is_valid_dir(home_dir()))
        fn = '/home/user/is/me'
        self.assertEqual(basename(fn), "me")
        self.assertEqual(dirname(fn), '/home/user/is/')
        d = parent_dir(__file__)
        self.assertGreater(len(span_wildcard(d, "*")), 2)
        self.assertGreater(len(span_wildcard_recurse(d, "*.py")), 1)
        self.assertEqual(len([f.name for f in scan_dir(d)]), len(span_wildcard(d, "*")))
        self.assertTrue(len(filetime(__file__)) == 3)
        self.assertTrue(file_monitor(__file__))
    
    def test_datetime(self):
        self.assertTrue(is_time(isotime().split()[-1]))
        self.assertFalse(is_time("25:33:18"))
        self.assertEqual(19, len(isotime()))
        @time_meter('do something')
        def do_something():
            sleep(1.2)
        do_something()
        delta = time_delta(15, 16, 17, 22, 59, 59)
        self.assertEqual("7:43:42", str(delta))
        delta = date_delta("1998", "01", "01", "2000", "12", "31")
        self.assertEqual(str(delta).split()[0], "1095")
        delta = datetime_delta(1900, 10, 10, 10, 0, 0, 1900, 10, 10, 10, 0, 0)
        self.assertEqual(str(delta), "0:00:00")
        
    def test_url(self):
        url = "https://www.learning.cn:443/stu/index.html?name=亞歷克斯&age=22#teacher"
        url2 = to_bytes(url)
        self.assertEqual(urlsplit(url)[0], "www.learning.cn:443")
        self.assertEqual(urlhost(url), urlsplit(url)[0])
        self.assertEqual(urlpath(url), "https://www.learning.cn:443/stu/index.html")
        self.assertEqual(addhttp(url), url)
        self.assertTrue(trimhttp(url)[:8] == "www.lear")
        self.assertEqual(urlsplit2(url2)[0], b"www.learning.cn:443")
        self.assertEqual(urlhost2(url2), to_bytes(urlsplit(url)[0]))
        self.assertEqual(urlpath2(url2), to_bytes(urlpath(url)))
        self.assertEqual(addhttp2(url2), url.encode())
        self.assertTrue(trimhttp2(url2)[:8] == to_bytes(trimhttp(url)[:8]))

    def test_json(self):
        j = loadjson(parent_dir(__file__) + "test.json")
        self.assertTrue(len(j))
        self.assertTrue(j['tab_size'] == 4)
        s = dumpjson(j, parent_dir(__file__) + "test.json")
        self.assertTrue(len(s))
        
    def test_io(self):
        f = open_as_bytes_stream(__file__)
        self.assertEqual(str(type(f)), "<class '_io.BytesIO'>")
        self.assertTrue(type(f) is _io.BytesIO)
        

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


#!/usr/bin/env python3
# -*- coding:utf-8 -*-
""" Unit test of bace3/basic.py """
from bace3.basic import PythonVersion, HIGHER_GC_THRESHOLD, LOWER_GC_THRESHOLD, DEFAULT_GC_THRESHOLD
from bace3.basic import NCPU, KB, MB, GB, BEST_IO_BUFFER_SIZE, MAX_FILE_SIZE_32BIT
from bace3.basic import reconfig, get_caller, fmterr
from bace3.basic import to_bytes, utf8, is_iterable, try_unquote
from bace3.basic import recursive_decode, recursive_encode, md5
from bace3.basic import default_release_dirs, search_program, add_sys_path
from bace3.basic import user_dir, home_dir, cur_dir, parent_dir, grand_dir, basename, dirname, is_valid_dir
from bace3.basic import span_wildcard, span_wildcard_recurse, scan_dir, filetime, file_monitor
from bace3.basic import isotime, is_time, time_meter, date_delta, time_delta, datetime_delta
from bace3.basic import urlsplit, urlsplit2, addhttp, addhttp2, trimhttp, trimhttp2, urlpath, urlpath2, urlhost, urlhost2
from bace3.basic import open_as_bytes_stream
from bace3.basic import loadjson, dumpjson


import unittest
from array import array
from random import random
from time import sleep
import sys, _io


class TestBasic(unittest.TestCase):
    def setUp(self):
        pass
    def tearDown(self):
        pass
    
    def test_consts(self):
        self.assertEqual(PythonVersion[0], 3)
        self.assertGreater(NCPU, 1)
        self.assertGreater(HIGHER_GC_THRESHOLD, DEFAULT_GC_THRESHOLD)
        self.assertLess(LOWER_GC_THRESHOLD, DEFAULT_GC_THRESHOLD)
        self.assertGreater(BEST_IO_BUFFER_SIZE, 4096)
        self.assertEqual(0, BEST_IO_BUFFER_SIZE & (BEST_IO_BUFFER_SIZE - 1))
        self.assertEqual(2 * 1024 * 1024 * 1024, MAX_FILE_SIZE_32BIT)
        self.assertEqual(2 * GB, MAX_FILE_SIZE_32BIT)
        self.assertEqual(GB, MB * 1024)
        self.assertEqual(MB, KB * 1024)
        
    def test_system_and_rt(self):
        self.assertEqual("[test_system_and_rt] ", get_caller(0))
        self.assertEqual("[run] ", get_caller(1))
        conf = reconfig()
        self.assertEqual(conf['old gc.threshold'], str(DEFAULT_GC_THRESHOLD))
        self.assertEqual(conf['sys.platform'], 'linux')
        
    def test_debug(self):
        try:
            raise ValueError("test_debug")
        except:
            s = fmterr()
        self.assertTrue(__file__ in s and "ValueError" in s)

    def test_transform(self):
        s = str(self)
        b = to_bytes(s)
        self.assertEqual(b.decode(), s)
        self.assertTrue(to_bytes(b) is b)
        a = [1, 2, 3]
        self.assertTrue(is_iterable(a))
        a = array('i', [int(random() + i) for i in range(100)])
        self.assertEqual(400, len(to_bytes(a)))
        b = b'\xe5\xa3\xb9\xe8\xb4\xb0\xe5\x8f\x81\xe8\x82\x86\xe4\xbc\x8d\xe9\x99\x86\xe6\x9f\x92\xe6\x8d\x8c\xe7\x8e\x96'
        u = utf8(b, errors='strict')
        self.assertEqual(u, "壹贰叁肆伍陆柒捌玖")
        self.assertEqual(try_unquote('%7e/abc+def'), '~/abc def')
        s = "你好" # 7eca689f0d3389d9dea66ae112e5cfd7
        self.assertEqual("7eca689f0d3389d9dea66ae112e5cfd7", md5(s.encode()))
        self.assertEqual(recursive_encode(s, 5), "R!4YOO)^$jV?<h4VpnKbT30c8Pf<NR")
        self.assertEqual(recursive_decode("R!4YOO)^$jV?<h4VpnKbT30c8Pf<NR", 5), s)
        
    def test_path(self):
        drd = default_release_dirs("desktop")
        self.assertGreater(len(drd), 2)
        self.assertTrue(drd[-1], home_dir() + 'desktop')
        self.assertTrue(add_sys_path(drd[-1]))
        self.assertFalse(add_sys_path(drd[-1]))
        self.assertTrue(drd[-1] in sys.path)
        self.assertEqual(user_dir(), home_dir())
        self.assertTrue('bace3' in cur_dir())
        self.assertTrue(grand_dir(__file__) in parent_dir(__file__))
        self.assertTrue(search_program('python3', '/usr/local/bin') or search_program('python3', '/usr/bin'))
        self.assertTrue(is_valid_dir(home_dir()))
        fn = '/home/user/is/me'
        self.assertEqual(basename(fn), "me")
        self.assertEqual(dirname(fn), '/home/user/is/')
        d = parent_dir(__file__)
        self.assertGreater(len(span_wildcard(d, "*")), 2)
        self.assertGreater(len(span_wildcard_recurse(d, "*.py")), 1)
        self.assertEqual(len([f.name for f in scan_dir(d)]), len(span_wildcard(d, "*")))
        self.assertTrue(len(filetime(__file__)) == 3)
        self.assertTrue(file_monitor(__file__))
    
    def test_datetime(self):
        self.assertTrue(is_time(isotime().split()[-1]))
        self.assertFalse(is_time("25:33:18"))
        self.assertEqual(19, len(isotime()))
        @time_meter('do something')
        def do_something():
            sleep(1.2)
        do_something()
        delta = time_delta(15, 16, 17, 22, 59, 59)
        self.assertEqual("7:43:42", str(delta))
        delta = date_delta("1998", "01", "01", "2000", "12", "31")
        self.assertEqual(str(delta).split()[0], "1095")
        delta = datetime_delta(1900, 10, 10, 10, 0, 0, 1900, 10, 10, 10, 0, 0)
        self.assertEqual(str(delta), "0:00:00")
        
    def test_url(self):
        url = "https://www.learning.cn:443/stu/index.html?name=亞歷克斯&age=22#teacher"
        url2 = to_bytes(url)
        self.assertEqual(urlsplit(url)[0], "www.learning.cn:443")
        self.assertEqual(urlhost(url), urlsplit(url)[0])
        self.assertEqual(urlpath(url), "https://www.learning.cn:443/stu/index.html")
        self.assertEqual(addhttp(url), url)
        self.assertTrue(trimhttp(url)[:8] == "www.lear")
        self.assertEqual(urlsplit2(url2)[0], b"www.learning.cn:443")
        self.assertEqual(urlhost2(url2), to_bytes(urlsplit(url)[0]))
        self.assertEqual(urlpath2(url2), to_bytes(urlpath(url)))
        self.assertEqual(addhttp2(url2), url.encode())
        self.assertTrue(trimhttp2(url2)[:8] == to_bytes(trimhttp(url)[:8]))

    def test_json(self):
        j = loadjson(parent_dir(__file__) + "test.json")
        self.assertTrue(len(j))
        self.assertTrue(j['tab_size'] == 4)
        s = dumpjson(j, parent_dir(__file__) + "test.json")
        self.assertTrue(len(s))
        
    def test_io(self):
        f = open_as_bytes_stream(__file__)
        self.assertEqual(str(type(f)), "<class '_io.BytesIO'>")
        self.assertTrue(type(f) is _io.BytesIO)
        

if __name__ == '__main__':
    unittest.main()
#!/usr/bin/env python3 # -*- coding:utf-8 -*- Unit test of bace3/basic.py # 7eca689f0d3389d9dea66ae112e5cfd7 #teacher"