id
int64 0
843k
| repository_name
stringlengths 7
55
| file_path
stringlengths 9
332
| class_name
stringlengths 3
290
| human_written_code
stringlengths 12
4.36M
| class_skeleton
stringlengths 19
2.2M
| total_program_units
int64 1
9.57k
| total_doc_str
int64 0
4.2k
| AvgCountLine
float64 0
7.89k
| AvgCountLineBlank
float64 0
300
| AvgCountLineCode
float64 0
7.89k
| AvgCountLineComment
float64 0
7.89k
| AvgCyclomatic
float64 0
130
| CommentToCodeRatio
float64 0
176
| CountClassBase
float64 0
48
| CountClassCoupled
float64 0
589
| CountClassCoupledModified
float64 0
581
| CountClassDerived
float64 0
5.37k
| CountDeclInstanceMethod
float64 0
4.2k
| CountDeclInstanceVariable
float64 0
299
| CountDeclMethod
float64 0
4.2k
| CountDeclMethodAll
float64 0
4.2k
| CountLine
float64 1
115k
| CountLineBlank
float64 0
9.01k
| CountLineCode
float64 0
94.4k
| CountLineCodeDecl
float64 0
46.1k
| CountLineCodeExe
float64 0
91.3k
| CountLineComment
float64 0
27k
| CountStmt
float64 1
93.2k
| CountStmtDecl
float64 0
46.1k
| CountStmtExe
float64 0
90.2k
| MaxCyclomatic
float64 0
759
| MaxInheritanceTree
float64 0
16
| MaxNesting
float64 0
34
| SumCyclomatic
float64 0
6k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,400 |
6809/MC6809
|
6809_MC6809/MC6809/tests/test_base.py
|
MC6809.tests.test_base.BaseCPUTestCase
|
class BaseCPUTestCase(BaseTestCase):
UNITTEST_CFG_DICT = {
"verbosity": None,
"display_cycle": False,
"trace": None,
"bus_socket_host": None,
"bus_socket_port": None,
"ram": None,
"rom": None,
"max_ops": None,
"use_bus": False,
}
def setUp(self):
cfg = TestCfg(self.UNITTEST_CFG_DICT)
memory = Memory(cfg)
self.cpu = CPU(memory, cfg)
def cpu_test_run(self, start, end, mem):
for cell in mem:
self.assertLess(-1, cell, f"${cell:x} < 0")
self.assertGreater(0x100, cell, f"${cell:x} > 0xff")
log.debug("memory load at $%x: %s", start,
", ".join(f"${i:x}" for i in mem)
)
self.cpu.memory.load(start, mem)
if end is None:
end = start + len(mem)
self.cpu.test_run(start, end)
cpu_test_run.__test__ = False # Exclude from nose
def cpu_test_run2(self, start, count, mem):
for cell in mem:
self.assertLess(-1, cell, f"${cell:x} < 0")
self.assertGreater(0x100, cell, f"${cell:x} > 0xff")
self.cpu.memory.load(start, mem)
self.cpu.test_run2(start, count)
cpu_test_run2.__test__ = False # Exclude from nose
def assertMemory(self, start, mem):
for index, should_byte in enumerate(mem):
address = start + index
is_byte = self.cpu.memory.read_byte(address)
msg = f"${is_byte:02x} is not ${should_byte:02x} at address ${address:04x} (index: {index:d})"
self.assertEqual(is_byte, should_byte, msg)
|
class BaseCPUTestCase(BaseTestCase):
def setUp(self):
pass
def cpu_test_run(self, start, end, mem):
pass
def cpu_test_run2(self, start, count, mem):
pass
def assertMemory(self, start, mem):
pass
| 5 | 0 | 7 | 0 | 7 | 0 | 2 | 0.05 | 1 | 4 | 3 | 18 | 4 | 1 | 4 | 83 | 46 | 5 | 41 | 15 | 36 | 2 | 29 | 15 | 24 | 3 | 3 | 1 | 8 |
1,401 |
6809/MC6809
|
6809_MC6809/MC6809/tests/test_base.py
|
MC6809.tests.test_base.BaseStackTestCase
|
class BaseStackTestCase(BaseCPUTestCase):
INITIAL_SYSTEM_STACK_ADDR = 0x1000
INITIAL_USER_STACK_ADDR = 0x2000
def setUp(self):
super().setUp()
self.cpu.system_stack_pointer.set(self.INITIAL_SYSTEM_STACK_ADDR)
self.cpu.user_stack_pointer.set(self.INITIAL_USER_STACK_ADDR)
|
class BaseStackTestCase(BaseCPUTestCase):
def setUp(self):
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 1 | 0 | 5 | 1 | 0 | 1 | 84 | 8 | 1 | 7 | 4 | 5 | 0 | 7 | 4 | 5 | 1 | 4 | 0 | 1 |
1,402 |
6809/MC6809
|
6809_MC6809/MC6809/tests/test_base.py
|
MC6809.tests.test_base.BaseTestCase
|
class BaseTestCase(unittest.TestCase):
"""
Only some special assertments.
"""
maxDiff = 3000
def assertHexList(self, first, second, msg=None):
first = [f"${value:x}" for value in first]
second = [f"${value:x}" for value in second]
self.assertEqual(first, second, msg)
def assertEqualHex(self, hex1, hex2, msg=None):
first = f"${hex1:x}"
second = f"${hex2:x}"
if msg is None:
msg = f"{first} != {second}"
self.assertEqual(first, second, msg)
def assertIsByteRange(self, value):
self.assertTrue(0x0 <= value, f"Value (dez: {value:d} - hex: {value:x}) is negative!")
self.assertTrue(0xff >= value, f"Value (dez: {value:d} - hex: {value:x}) is greater than 0xff!")
def assertIsWordRange(self, value):
self.assertTrue(0x0 <= value, f"Value (dez: {value:d} - hex: {value:x}) is negative!")
self.assertTrue(0xffff >= value, f"Value (dez: {value:d} - hex: {value:x}) is greater than 0xffff!")
def assertEqualHexByte(self, hex1, hex2, msg=None):
self.assertIsByteRange(hex1)
self.assertIsByteRange(hex2)
first = f"${hex1:02x}"
second = f"${hex2:02x}"
if msg is None:
msg = f"{first} != {second}"
self.assertEqual(first, second, msg)
def assertEqualHexWord(self, hex1, hex2, msg=None):
self.assertIsWordRange(hex1)
self.assertIsWordRange(hex2)
first = f"${hex1:04x}"
second = f"${hex2:04x}"
if msg is None:
msg = f"{first} != {second}"
self.assertEqual(first, second, msg)
def assertBinEqual(self, bin1, bin2, msg=None, width=16):
first = bin2hexline(bin1, width=width)
second = bin2hexline(bin2, width=width)
self.assertSequenceEqual(first, second, msg)
|
class BaseTestCase(unittest.TestCase):
'''
Only some special assertments.
'''
def assertHexList(self, first, second, msg=None):
pass
def assertEqualHex(self, hex1, hex2, msg=None):
pass
def assertIsByteRange(self, value):
pass
def assertIsWordRange(self, value):
pass
def assertEqualHexByte(self, hex1, hex2, msg=None):
pass
def assertEqualHexWord(self, hex1, hex2, msg=None):
pass
def assertBinEqual(self, bin1, bin2, msg=None, width=16):
pass
| 8 | 1 | 5 | 0 | 5 | 0 | 1 | 0.08 | 1 | 0 | 0 | 1 | 7 | 0 | 7 | 79 | 48 | 7 | 38 | 17 | 30 | 3 | 38 | 17 | 30 | 2 | 2 | 1 | 10 |
1,403 |
6809/MC6809
|
6809_MC6809/MC6809/tests/test_condition_code_register.py
|
MC6809.tests.test_condition_code_register.CCTestCase
|
class CCTestCase(BaseCPUTestCase):
def test_set_get(self):
for i in range(256):
self.cpu.set_cc(i)
status_byte = self.cpu.get_cc_value()
self.assertEqual(status_byte, i)
def test_HNZVC_8(self):
for i in range(280):
self.cpu.set_cc(0x00)
r = i + 1 # e.g. ADDA 1 loop
self.cpu.update_HNZVC_8(a=i, b=1, r=r)
# print r, self.cpu.get_cc_info()
# test half carry
if r % 16 == 0:
self.assertEqual(self.cpu.H, 1)
else:
self.assertEqual(self.cpu.H, 0)
# test negative
if 128 <= r <= 255:
self.assertEqual(self.cpu.N, 1)
else:
self.assertEqual(self.cpu.N, 0)
# test zero
if signed8(r) == 0:
self.assertEqual(self.cpu.Z, 1)
else:
self.assertEqual(self.cpu.Z, 0)
# test overflow
if r == 128 or r > 256:
self.assertEqual(self.cpu.V, 1)
else:
self.assertEqual(self.cpu.V, 0)
# test carry
if r > 255:
self.assertEqual(self.cpu.C, 1)
else:
self.assertEqual(self.cpu.C, 0)
# Test that CC registers doesn't reset automaticly
self.cpu.set_cc(0xff)
r = i + 1 # e.g. ADDA 1 loop
self.cpu.update_HNZVC_8(a=i, b=1, r=r)
# print "+++", r, self.cpu.get_cc_info()
self.assertEqualHex(self.cpu.get_cc_value(), 0xff)
def test_update_NZ_8_A(self):
self.cpu.update_NZ_8(r=0x12)
self.assertEqual(self.cpu.N, 0)
self.assertEqual(self.cpu.Z, 0)
def test_update_NZ_8_B(self):
self.cpu.update_NZ_8(r=0x0)
self.assertEqual(self.cpu.N, 0)
self.assertEqual(self.cpu.Z, 1)
def test_update_NZ_8_C(self):
self.cpu.update_NZ_8(r=0x80)
self.assertEqual(self.cpu.N, 1)
self.assertEqual(self.cpu.Z, 0)
def test_update_NZ0_16_A(self):
self.cpu.update_NZ0_16(r=0x7fff) # 0x7fff == 32767
self.assertEqual(self.cpu.N, 0)
self.assertEqual(self.cpu.Z, 0)
self.assertEqual(self.cpu.V, 0)
def test_update_NZ0_16_B(self):
self.cpu.update_NZ0_16(r=0x00)
self.assertEqual(self.cpu.N, 0)
self.assertEqual(self.cpu.Z, 1)
self.assertEqual(self.cpu.V, 0)
def test_update_NZ0_16_C(self):
self.cpu.update_NZ0_16(r=0x8000) # signed 0x8000 == -32768
self.assertEqual(self.cpu.N, 1)
self.assertEqual(self.cpu.Z, 0)
self.assertEqual(self.cpu.V, 0)
def test_update_NZ0_8_A(self):
self.cpu.update_NZ0_8(0x7f)
self.assertEqual(self.cpu.N, 0)
self.assertEqual(self.cpu.Z, 0)
self.assertEqual(self.cpu.V, 0)
def test_update_NZ0_8_B(self):
self.cpu.update_NZ0_8(0x100)
self.assertEqual(self.cpu.N, 0)
self.assertEqual(self.cpu.Z, 1)
self.assertEqual(self.cpu.V, 0)
def test_update_NZV_8_B(self):
self.cpu.update_NZ0_8(0x100)
self.assertEqual(self.cpu.N, 0)
self.assertEqual(self.cpu.Z, 1)
self.assertEqual(self.cpu.V, 0)
|
class CCTestCase(BaseCPUTestCase):
def test_set_get(self):
pass
def test_HNZVC_8(self):
pass
def test_update_NZ_8_A(self):
pass
def test_update_NZ_8_B(self):
pass
def test_update_NZ_8_C(self):
pass
def test_update_NZ0_16_A(self):
pass
def test_update_NZ0_16_B(self):
pass
def test_update_NZ0_16_C(self):
pass
def test_update_NZ0_8_A(self):
pass
def test_update_NZ0_8_B(self):
pass
def test_update_NZV_8_B(self):
pass
| 12 | 0 | 8 | 1 | 7 | 1 | 2 | 0.16 | 1 | 1 | 0 | 0 | 11 | 0 | 11 | 94 | 101 | 16 | 77 | 16 | 65 | 12 | 72 | 16 | 60 | 7 | 4 | 2 | 18 |
1,404 |
6809/MC6809
|
6809_MC6809/MC6809/tests/test_config.py
|
MC6809.tests.test_config.TestCfg
|
class TestCfg(BaseConfig):
"""
Default test config
"""
RAM_START = 0x0000
RAM_END = 0x7FFF
ROM_START = 0x8000
ROM_END = 0xFFFF
RESET_VECTOR = 0xFFFE
BUS_ADDR_AREAS = (
(0xFFF2, 0xFFFE, "Interrupt vectors"),
)
DEFAULT_ROMS = None
def __init__(self, cfg_dict):
super().__init__(cfg_dict)
|
class TestCfg(BaseConfig):
'''
Default test config
'''
def __init__(self, cfg_dict):
pass
| 2 | 1 | 3 | 1 | 2 | 0 | 1 | 0.25 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 6 | 21 | 6 | 12 | 9 | 10 | 3 | 10 | 9 | 8 | 1 | 1 | 0 | 1 |
1,405 |
6809/MC6809
|
6809_MC6809/MC6809/tests/test_cpu6809.py
|
MC6809.tests.test_cpu6809.Test6809_Code
|
class Test6809_Code(BaseCPUTestCase):
"""
Test with some small test codes
"""
def test_code01(self):
self.cpu.memory.load(
0x2220, [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]
)
self.cpu_test_run(start=0x4000, end=None, mem=[
0x86, 0x22, # LDA $22 ; Immediate
0x8E, 0x22, 0x22, # LDX $2222 ; Immediate
0x1F, 0x89, # TFR A,B ; Inherent (Register)
0x5A, # DECB ; Inherent (Implied)
0xED, 0x84, # STD ,X ; Indexed (non indirect)
0x4A, # DECA ; Inherent (Implied)
0xA7, 0x94, # STA [,X] ; Indexed (indirect)
])
self.assertEqualHex(self.cpu.accu_a.value, 0x21)
self.assertEqualHex(self.cpu.accu_b.value, 0x21)
self.assertEqualHex(self.cpu.accu_d.value, 0x2121)
self.assertEqualHex(self.cpu.index_x.value, 0x2222)
self.assertEqualHex(self.cpu.index_y.value, 0x0000)
self.assertEqualHex(self.cpu.direct_page.value, 0x00)
self.assertMemory(
start=0x2220,
mem=[0xFF, 0x21, 0x22, 0x21, 0xFF, 0xFF]
)
def test_code02(self):
self.cpu_test_run(start=0x2000, end=None, mem=[
0x10, 0x8e, 0x30, 0x00, # 2000| LDY $3000
0xcc, 0x10, 0x00, # 2004| LDD $1000
0xed, 0xa4, # 2007| STD ,Y
0x86, 0x55, # 2009| LDA $55
0xA7, 0xb4, # 200B| STA ,[Y]
])
self.assertEqualHex(self.cpu.get_cc_value(), 0x00)
self.assertMemory(
start=0x1000,
mem=[0x55]
)
def test_code_LEAU_01(self):
self.cpu.user_stack_pointer.set(0xff)
self.cpu_test_run(start=0x0000, end=None, mem=[
0x33, 0x41, # 0000| LEAU 1,U
])
self.assertEqualHex(self.cpu.user_stack_pointer.value, 0x100)
def test_code_LEAU_02(self):
self.cpu.user_stack_pointer.set(0xff)
self.cpu_test_run(start=0x0000, end=None, mem=[
0xCE, 0x00, 0x00, # LDU #$0000
0x33, 0xC9, 0x1A, 0xBC, # LEAU $1abc,U
])
self.assertEqualHex(self.cpu.user_stack_pointer.value, 0x1abc)
def test_code_LDU_01(self):
self.cpu.user_stack_pointer.set(0xff)
self.cpu_test_run(start=0x0000, end=None, mem=[
0xCE, 0x12, 0x34, # LDU #$0000
])
self.assertEqualHex(self.cpu.user_stack_pointer.value, 0x1234)
def test_code_ORA_01(self):
self.cpu.set_cc(0xff)
self.cpu.accu_a.set(0x12)
self.cpu_test_run(start=0x0000, end=None, mem=[
0x8A, 0x21, # ORA $21
])
self.assertEqualHex(self.cpu.accu_a.value, 0x33)
self.assertEqual(self.cpu.N, 0)
self.assertEqual(self.cpu.Z, 0)
self.assertEqual(self.cpu.V, 0)
def test_code_ORCC_01(self):
self.cpu.set_cc(0x12)
self.cpu_test_run(start=0x0000, end=None, mem=[
0x1A, 0x21, # ORCC $21
])
self.assertEqualHex(self.cpu.get_cc_value(), 0x33)
|
class Test6809_Code(BaseCPUTestCase):
'''
Test with some small test codes
'''
def test_code01(self):
pass
def test_code02(self):
pass
def test_code_LEAU_01(self):
pass
def test_code_LEAU_02(self):
pass
def test_code_LDU_01(self):
pass
def test_code_ORA_01(self):
pass
def test_code_ORCC_01(self):
pass
| 8 | 1 | 10 | 0 | 10 | 3 | 1 | 0.29 | 1 | 0 | 0 | 0 | 7 | 0 | 7 | 90 | 84 | 9 | 72 | 8 | 64 | 21 | 39 | 8 | 31 | 1 | 4 | 0 | 7 |
1,406 |
6809/MC6809
|
6809_MC6809/MC6809/tests/test_cpu6809.py
|
MC6809.tests.test_cpu6809.Test6809_Ops
|
class Test6809_Ops(BaseCPUTestCase):
def test_TFR01(self):
self.cpu.index_x.set(512) # source
self.assertEqual(self.cpu.index_y.value, 0) # destination
self.cpu_test_run(start=0x1000, end=None, mem=[
0x1f, # TFR
0x12, # from index register X (0x01) to Y (0x02)
])
self.assertEqual(self.cpu.index_y.value, 512)
def test_TFR02(self):
self.cpu.accu_b.set(0x55) # source
self.assertEqual(self.cpu.get_cc_value(), 0) # destination
self.cpu_test_run(start=0x1000, end=0x1002, mem=[
0x1f, # TFR
0x9a, # from accumulator B (0x9) to condition code register CC (0xa)
])
self.assertEqual(self.cpu.get_cc_value(), 0x55) # destination
def test_TFR03(self):
self.cpu_test_run(start=0x4000, end=None, mem=[
0x10, 0x8e, 0x12, 0x34, # LDY Y=$1234
0x1f, 0x20, # TFR Y,D
])
self.assertEqualHex(self.cpu.accu_d.value, 0x1234) # destination
def test_CMPU_immediate(self):
u = 0x80
self.cpu.user_stack_pointer.set(u)
for m in range(0x7e, 0x83):
self.cpu_test_run(start=0x0000, end=None, mem=[
0x11, 0x83, # CMPU (immediate word)
0x00, m # the word that CMP reads
])
r = u - m
"""
80 - 7e = 02 -> ........
80 - 7f = 01 -> ........
80 - 80 = 00 -> .....Z..
80 - 81 = -1 -> ....N..C
80 - 82 = -2 -> ....N..C
"""
# print "%02x - %02x = %02x -> %s" % (
# u, m, r, self.cpu.get_info
# )
# test negative: 0x01 <= a <= 0x80
if r < 0:
self.assertEqual(self.cpu.N, 1)
else:
self.assertEqual(self.cpu.N, 0)
# test zero
if r == 0:
self.assertEqual(self.cpu.Z, 1)
else:
self.assertEqual(self.cpu.Z, 0)
# test overflow
self.assertEqual(self.cpu.V, 0)
# test carry is set if r=1-255 (hex: r=$01 - $ff)
if r < 0:
self.assertEqual(self.cpu.C, 1)
else:
self.assertEqual(self.cpu.C, 0)
def test_CMPA_immediate_byte(self):
a = 0x80
self.cpu.accu_a.set(a)
for m in range(0x7e, 0x83):
self.cpu_test_run(start=0x0000, end=None, mem=[
0x81, m # CMPA (immediate byte)
])
r = a - m
"""
80 - 7e = 02 -> ......V.
80 - 7f = 01 -> ......V.
80 - 80 = 00 -> .....Z..
80 - 81 = -1 -> ....N..C
80 - 82 = -2 -> ....N..C
"""
# print "%02x - %02x = %02x -> %s" % (
# a, m, r, self.cpu.get_info
# )
# test negative: 0x01 <= a <= 0x80
if r < 0:
self.assertEqual(self.cpu.N, 1)
else:
self.assertEqual(self.cpu.N, 0)
# test zero
if r == 0:
self.assertEqual(self.cpu.Z, 1)
else:
self.assertEqual(self.cpu.Z, 0)
# test overflow
if r > 0:
self.assertEqual(self.cpu.V, 1)
else:
self.assertEqual(self.cpu.V, 0)
# test carry is set if r=1-255 (hex: r=$01 - $ff)
if r < 0:
self.assertEqual(self.cpu.C, 1)
else:
self.assertEqual(self.cpu.C, 0)
def test_CMPX_immediate_word(self):
x = 0x80
self.cpu.index_x.set(x)
for m in range(0x7e, 0x83):
self.cpu_test_run(start=0x0000, end=None, mem=[
0x8c, 0x00, m # CMPX (immediate word)
])
r = x - m
"""
80 - 7e = 02 -> ........
80 - 7f = 01 -> ........
80 - 80 = 00 -> .....Z..
80 - 81 = -1 -> ....N..C
80 - 82 = -2 -> ....N..C
"""
# print "%02x - %02x = %02x -> %s" % (
# x, m, r, self.cpu.get_info
# )
# test negative: 0x01 <= a <= 0x80
if r < 0:
self.assertEqual(self.cpu.N, 1)
else:
self.assertEqual(self.cpu.N, 0)
# test zero
if r == 0:
self.assertEqual(self.cpu.Z, 1)
else:
self.assertEqual(self.cpu.Z, 0)
# test overflow
self.assertEqual(self.cpu.V, 0)
# test carry is set if r=1-255 (hex: r=$01 - $ff)
if r < 0:
self.assertEqual(self.cpu.C, 1)
else:
self.assertEqual(self.cpu.C, 0)
def test_ABX_01(self):
self.cpu.set_cc(0xff)
self.cpu.accu_b.set(0x0f)
self.cpu.index_x.set(0x00f0)
self.cpu_test_run(start=0x1000, end=None, mem=[
0x3A, # ABX
])
self.assertEqualHex(self.cpu.index_x.value, 0x00ff)
self.assertEqualHex(self.cpu.get_cc_value(), 0xff)
self.cpu.set_cc(0x00)
self.cpu_test_run(start=0x1000, end=None, mem=[
0x3A, # ABX
])
self.assertEqualHex(self.cpu.index_x.value, 0x010E)
self.assertEqualHex(self.cpu.get_cc_value(), 0x00)
|
class Test6809_Ops(BaseCPUTestCase):
def test_TFR01(self):
pass
def test_TFR02(self):
pass
def test_TFR03(self):
pass
def test_CMPU_immediate(self):
pass
def test_CMPA_immediate_byte(self):
pass
def test_CMPX_immediate_word(self):
pass
def test_ABX_01(self):
pass
| 8 | 0 | 23 | 2 | 15 | 9 | 3 | 0.57 | 1 | 1 | 0 | 0 | 7 | 0 | 7 | 90 | 168 | 21 | 105 | 17 | 97 | 60 | 75 | 17 | 67 | 6 | 4 | 2 | 20 |
1,407 |
6809/MC6809
|
6809_MC6809/MC6809/tests/test_cpu6809.py
|
MC6809.tests.test_cpu6809.Test6809_Register
|
class Test6809_Register(BaseCPUTestCase):
def test_registerA(self):
for i in range(255):
self.cpu.accu_a.set(i)
t = self.cpu.accu_a.value
self.assertEqual(i, t)
def test_register_8bit_overflow(self):
self.cpu.accu_a.set(0xff)
a = self.cpu.accu_a.value
self.assertEqualHex(a, 0xff)
self.cpu.accu_a.set(0x100)
a = self.cpu.accu_a.value
self.assertEqualHex(a, 0)
self.cpu.accu_a.set(0x101)
a = self.cpu.accu_a.value
self.assertEqualHex(a, 0x1)
def test_register_8bit_negative(self):
self.cpu.accu_a.set(0)
t = self.cpu.accu_a.value
self.assertEqualHex(t, 0)
self.cpu.accu_a.set(-1)
t = self.cpu.accu_a.value
self.assertEqualHex(t, 0xff)
self.cpu.accu_a.set(-2)
t = self.cpu.accu_a.value
self.assertEqualHex(t, 0xfe)
def test_register_16bit_overflow(self):
self.cpu.index_x.set(0xffff)
x = self.cpu.index_x.value
self.assertEqual(x, 0xffff)
self.cpu.index_x.set(0x10000)
x = self.cpu.index_x.value
self.assertEqual(x, 0)
self.cpu.index_x.set(0x10001)
x = self.cpu.index_x.value
self.assertEqual(x, 1)
def test_register_16bit_negative1(self):
self.cpu.index_x.set(-1)
x = self.cpu.index_x.value
self.assertEqualHex(x, 0xffff)
self.cpu.index_x.set(-2)
x = self.cpu.index_x.value
self.assertEqualHex(x, 0xfffe)
def test_register_16bit_negative2(self):
self.cpu.index_x.set(0)
self.cpu.index_x.decrement()
self.assertEqualHex(self.cpu.index_x.value, 0x10000 - 1)
self.cpu.index_x.set(0)
self.cpu.index_x.decrement(2)
self.assertEqualHex(self.cpu.index_x.value, 0x10000 - 2)
|
class Test6809_Register(BaseCPUTestCase):
def test_registerA(self):
pass
def test_register_8bit_overflow(self):
pass
def test_register_8bit_negative(self):
pass
def test_register_16bit_overflow(self):
pass
def test_register_16bit_negative1(self):
pass
def test_register_16bit_negative2(self):
pass
| 7 | 0 | 10 | 1 | 8 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 6 | 0 | 6 | 89 | 63 | 13 | 50 | 13 | 43 | 0 | 50 | 13 | 43 | 2 | 4 | 1 | 7 |
1,408 |
6809/MC6809
|
6809_MC6809/MC6809/tests/test_cpu6809.py
|
MC6809.tests.test_cpu6809.Test6809_Stack
|
class Test6809_Stack(BaseStackTestCase):
def test_PushPullSytemStack_01(self):
self.assertEqualHex(
self.cpu.system_stack_pointer.value,
self.INITIAL_SYSTEM_STACK_ADDR
)
self.cpu_test_run(start=0x4000, end=None, mem=[
0x86, 0x1a, # LDA A=$1a
0x34, 0x02, # PSHS A
])
self.assertEqualHex(
self.cpu.system_stack_pointer.value,
self.INITIAL_SYSTEM_STACK_ADDR - 1 # Byte added
)
self.assertEqualHex(self.cpu.accu_a.value, 0x1a)
self.cpu.accu_a.set(0xee)
self.assertEqualHex(self.cpu.accu_b.value, 0x00)
self.cpu_test_run(start=0x4000, end=None, mem=[
0x35, 0x04, # PULS B ; B gets the value from A = 1a
])
self.assertEqualHex(
self.cpu.system_stack_pointer.value,
self.INITIAL_SYSTEM_STACK_ADDR # Byte removed
)
self.assertEqualHex(self.cpu.accu_a.value, 0xee)
self.assertEqualHex(self.cpu.accu_b.value, 0x1a)
def test_PushPullSystemStack_02(self):
self.assertEqualHex(
self.cpu.system_stack_pointer.value,
self.INITIAL_SYSTEM_STACK_ADDR
)
self.cpu_test_run(start=0x4000, end=None, mem=[
0x86, 0xab, # LDA A=$ab
0x34, 0x02, # PSHS A
0x86, 0x02, # LDA A=$02
0x34, 0x02, # PSHS A
0x86, 0xef, # LDA A=$ef
])
self.assertEqualHex(self.cpu.accu_a.value, 0xef)
self.cpu_test_run(start=0x4000, end=None, mem=[
0x35, 0x04, # PULS B
])
self.assertEqualHex(self.cpu.accu_a.value, 0xef)
self.assertEqualHex(self.cpu.accu_b.value, 0x02)
self.cpu_test_run(start=0x4000, end=None, mem=[
0x35, 0x02, # PULS A
])
self.assertEqualHex(self.cpu.accu_a.value, 0xab)
self.assertEqualHex(self.cpu.accu_b.value, 0x02)
self.assertEqualHex(
self.cpu.system_stack_pointer.value,
self.INITIAL_SYSTEM_STACK_ADDR
)
def test_PushPullSystemStack_03(self):
self.assertEqualHex(
self.cpu.system_stack_pointer.value,
self.INITIAL_SYSTEM_STACK_ADDR
)
self.cpu_test_run(start=0x4000, end=None, mem=[
0xcc, 0x12, 0x34, # LDD D=$1234
0x34, 0x06, # PSHS B,A
0xcc, 0xab, 0xcd, # LDD D=$abcd
0x34, 0x06, # PSHS B,A
0xcc, 0x54, 0x32, # LDD D=$5432
])
self.assertEqualHex(self.cpu.accu_d.value, 0x5432)
self.cpu_test_run(start=0x4000, end=None, mem=[
0x35, 0x06, # PULS B,A
])
self.assertEqualHex(self.cpu.accu_d.value, 0xabcd)
self.assertEqualHex(self.cpu.accu_a.value, 0xab)
self.assertEqualHex(self.cpu.accu_b.value, 0xcd)
self.cpu_test_run(start=0x4000, end=None, mem=[
0x35, 0x06, # PULS B,A
])
self.assertEqualHex(self.cpu.accu_d.value, 0x1234)
def test_PushPullUserStack_01(self):
self.assertEqualHex(
self.cpu.user_stack_pointer.value,
self.INITIAL_USER_STACK_ADDR
)
self.cpu_test_run(start=0x4000, end=None, mem=[
0xcc, 0x12, 0x34, # LDD D=$1234
0x36, 0x06, # PSHU B,A
0xcc, 0xab, 0xcd, # LDD D=$abcd
0x36, 0x06, # PSHU B,A
0xcc, 0x54, 0x32, # LDD D=$5432
])
self.assertEqualHex(self.cpu.accu_d.value, 0x5432)
self.cpu_test_run(start=0x4000, end=None, mem=[
0x37, 0x06, # PULU B,A
])
self.assertEqualHex(self.cpu.accu_d.value, 0xabcd)
self.assertEqualHex(self.cpu.accu_a.value, 0xab)
self.assertEqualHex(self.cpu.accu_b.value, 0xcd)
self.cpu_test_run(start=0x4000, end=None, mem=[
0x37, 0x06, # PULU B,A
])
self.assertEqualHex(self.cpu.accu_d.value, 0x1234)
|
class Test6809_Stack(BaseStackTestCase):
def test_PushPullSytemStack_01(self):
pass
def test_PushPullSystemStack_02(self):
pass
def test_PushPullSystemStack_03(self):
pass
def test_PushPullUserStack_01(self):
pass
| 5 | 0 | 29 | 5 | 25 | 7 | 1 | 0.26 | 1 | 0 | 0 | 0 | 4 | 0 | 4 | 88 | 120 | 21 | 99 | 5 | 94 | 26 | 43 | 5 | 38 | 1 | 5 | 0 | 4 |
1,409 |
6809/MC6809
|
6809_MC6809/MC6809/tests/test_cpu6809.py
|
MC6809.tests.test_cpu6809.Test6809_TestInstructions
|
class Test6809_TestInstructions(BaseCPUTestCase):
def assertTST(self, i):
if 128 <= i <= 255: # test negative
self.assertEqual(self.cpu.N, 1)
else:
self.assertEqual(self.cpu.N, 0)
if i == 0: # test zero
self.assertEqual(self.cpu.Z, 1)
else:
self.assertEqual(self.cpu.Z, 0)
# test overflow
self.assertEqual(self.cpu.V, 0)
# test not affected flags:
self.assertEqual(self.cpu.E, 1)
self.assertEqual(self.cpu.F, 1)
self.assertEqual(self.cpu.H, 1)
self.assertEqual(self.cpu.I, 1)
self.assertEqual(self.cpu.C, 1)
def test_TST_direct(self):
for i in range(255):
self.cpu.accu_a.set(i)
self.cpu.set_cc(0xff) # Set all CC flags
self.cpu.memory.write_byte(address=0x00, value=i)
self.cpu_test_run(start=0x1000, end=None, mem=[
0x0D, 0x00 # TST $00
])
self.assertTST(i)
def test_TST_extended(self):
for i in range(255):
self.cpu.accu_a.set(i)
self.cpu.set_cc(0xff) # Set all CC flags
self.cpu.memory.write_byte(address=0x1234, value=i)
self.cpu_test_run(start=0x1000, end=None, mem=[
0x7D, 0x12, 0x34 # TST $1234
])
self.assertTST(i)
def test_TSTA(self):
for i in range(255):
self.cpu.accu_a.set(i)
self.cpu.set_cc(0xff) # Set all CC flags
self.cpu_test_run(start=0x1000, end=None, mem=[
0x4D # TSTA
])
self.assertTST(i)
def test_TSTB(self):
for i in range(255):
self.cpu.accu_b.set(i)
self.cpu.set_cc(0xff) # Set all CC flags
self.cpu_test_run(start=0x1000, end=None, mem=[
0x5D # TSTB
])
self.assertTST(i)
|
class Test6809_TestInstructions(BaseCPUTestCase):
def assertTST(self, i):
pass
def test_TST_direct(self):
pass
def test_TST_extended(self):
pass
def test_TSTA(self):
pass
def test_TSTB(self):
pass
| 6 | 0 | 12 | 1 | 10 | 2 | 2 | 0.24 | 1 | 1 | 0 | 0 | 5 | 0 | 5 | 88 | 63 | 11 | 50 | 10 | 44 | 12 | 40 | 10 | 34 | 3 | 4 | 1 | 11 |
1,410 |
6809/MC6809
|
6809_MC6809/MC6809/tests/test_cpu6809.py
|
MC6809.tests.test_cpu6809.Test6809_ZeroFlag
|
class Test6809_ZeroFlag(BaseCPUTestCase):
def test_DECA(self):
self.assertEqual(self.cpu.Z, 0)
self.cpu_test_run(start=0x4000, end=None, mem=[
0x86, 0x1, # LDA $01
0x4A, # DECA
])
self.assertEqual(self.cpu.Z, 1)
def test_DECB(self):
self.assertEqual(self.cpu.Z, 0)
self.cpu_test_run(start=0x4000, end=None, mem=[
0xC6, 0x1, # LDB $01
0x5A, # DECB
])
self.assertEqual(self.cpu.Z, 1)
def test_ADDA(self):
self.assertEqual(self.cpu.Z, 0)
self.cpu_test_run(start=0x4000, end=None, mem=[
0x86, 0xff, # LDA $FF
0x8B, 0x01, # ADDA #1
])
self.assertEqual(self.cpu.Z, 1)
def test_CMPA(self):
self.assertEqual(self.cpu.Z, 0)
self.cpu_test_run(start=0x4000, end=None, mem=[
0x86, 0x00, # LDA $00
0x81, 0x00, # CMPA %00
])
self.assertEqual(self.cpu.Z, 1)
def test_COMA(self):
self.assertEqual(self.cpu.Z, 0)
self.cpu_test_run(start=0x4000, end=None, mem=[
0x86, 0xFF, # LDA $FF
0x43, # COMA
])
self.assertEqual(self.cpu.Z, 1)
def test_NEGA(self):
self.assertEqual(self.cpu.Z, 0)
self.cpu_test_run(start=0x4000, end=None, mem=[
0x86, 0xFF, # LDA $FF
0x40, # NEGA
])
self.assertEqual(self.cpu.Z, 0)
def test_ANDA(self):
self.assertEqual(self.cpu.Z, 0)
self.cpu_test_run(start=0x4000, end=None, mem=[
0x86, 0xF0, # LDA $F0
0x84, 0x0F, # ANDA $0F
])
self.assertEqual(self.cpu.Z, 1)
def test_TFR(self):
self.assertEqual(self.cpu.Z, 0)
self.cpu_test_run(start=0x4000, end=None, mem=[
0x86, 0x04, # LDA $04
0x1F, 0x8a, # TFR A,CCR
])
self.assertEqual(self.cpu.Z, 1)
def test_CLRA(self):
self.assertEqual(self.cpu.Z, 0)
self.cpu_test_run(start=0x4000, end=None, mem=[
0x4F, # CLRA
])
self.assertEqual(self.cpu.Z, 1)
|
class Test6809_ZeroFlag(BaseCPUTestCase):
def test_DECA(self):
pass
def test_DECB(self):
pass
def test_ADDA(self):
pass
def test_CMPA(self):
pass
def test_COMA(self):
pass
def test_NEGA(self):
pass
def test_ANDA(self):
pass
def test_TFR(self):
pass
def test_CLRA(self):
pass
| 10 | 0 | 7 | 0 | 7 | 2 | 1 | 0.27 | 1 | 0 | 0 | 0 | 9 | 0 | 9 | 92 | 71 | 8 | 63 | 10 | 53 | 17 | 37 | 10 | 27 | 1 | 4 | 0 | 9 |
1,411 |
6809/MC6809
|
6809_MC6809/MC6809/tests/test_cpu6809.py
|
MC6809.tests.test_cpu6809.TestSimple6809ROM
|
class TestSimple6809ROM(BaseCPUTestCase):
"""
use routines from Simple 6809 ROM code
"""
def _is_carriage_return(self, a, pc):
self.cpu.accu_a.set(a)
self.cpu_test_run2(start=0x4000, count=3, mem=[
# origin start address in ROM: $db16
0x34, 0x02, # PSHS A
0x81, 0x0d, # CMPA #000d(CR) ; IS IT CARRIAGE RETURN?
0x27, 0x0b, # BEQ NEWLINE ; YES
])
self.assertEqualHex(self.cpu.program_counter.value, pc)
def test_is_not_carriage_return(self):
self._is_carriage_return(a=0x00, pc=0x4006)
def test_is_carriage_return(self):
self._is_carriage_return(a=0x0d, pc=0x4011)
|
class TestSimple6809ROM(BaseCPUTestCase):
'''
use routines from Simple 6809 ROM code
'''
def _is_carriage_return(self, a, pc):
pass
def test_is_not_carriage_return(self):
pass
def test_is_carriage_return(self):
pass
| 4 | 1 | 4 | 0 | 4 | 1 | 1 | 0.54 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 86 | 20 | 3 | 13 | 4 | 9 | 7 | 9 | 4 | 5 | 1 | 4 | 0 | 3 |
1,412 |
6809/MC6809
|
6809_MC6809/MC6809/tests/test_doctests.py
|
MC6809.tests.test_doctests.DocTests
|
class DocTests(BaseDocTests):
def test_doctests(self):
self.run_doctests(
modules=(MC6809,),
)
|
class DocTests(BaseDocTests):
def test_doctests(self):
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 5 | 0 | 5 | 2 | 3 | 0 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
1,413 |
6809/MC6809
|
6809_MC6809/MC6809/tests/test_example.py
|
MC6809.tests.test_example.ExampleTestCase
|
class ExampleTestCase(unittest.TestCase):
def test_example(self):
self.assertTrue(run_example())
|
class ExampleTestCase(unittest.TestCase):
def test_example(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 3 | 0 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
1,414 |
6809/MC6809
|
6809_MC6809/MC6809/tests/test_project_setup.py
|
MC6809.tests.test_project_setup.ProjectSetupTestCase
|
class ProjectSetupTestCase(TestCase):
def test_version(self):
self.assertIsNotNone(__version__)
version = Version(__version__) # Will raise InvalidVersion() if wrong formatted
self.assertEqual(str(version), __version__)
cli_bin = PACKAGE_ROOT / 'cli.py'
assert_is_file(cli_bin)
output = subprocess.check_output([cli_bin, 'version'], text=True)
self.assertIn(f'MC6809 v{__version__}', output)
dev_cli_bin = PACKAGE_ROOT / 'dev-cli.py'
assert_is_file(dev_cli_bin)
output = subprocess.check_output([dev_cli_bin, 'version'], text=True)
self.assertIn(f'MC6809 v{__version__}', output)
def test_code_style(self):
return_code = assert_code_style(package_root=PACKAGE_ROOT)
self.assertEqual(return_code, 0, 'Code style error, see output above!')
def test_check_editor_config(self):
check_editor_config(package_root=PACKAGE_ROOT)
max_line_length = get_py_max_line_length(package_root=PACKAGE_ROOT)
self.assertEqual(max_line_length, 119)
|
class ProjectSetupTestCase(TestCase):
def test_version(self):
pass
def test_code_style(self):
pass
def test_check_editor_config(self):
pass
| 4 | 0 | 8 | 2 | 6 | 0 | 1 | 0.05 | 1 | 2 | 0 | 0 | 3 | 0 | 3 | 75 | 28 | 8 | 20 | 10 | 16 | 1 | 20 | 10 | 16 | 1 | 2 | 0 | 3 |
1,415 |
6809/MC6809
|
6809_MC6809/MC6809/tests/test_readme_history.py
|
MC6809.tests.test_readme_history.ReadmeHistoryTestCase
|
class ReadmeHistoryTestCase(TestCase):
def test_readme_history(self):
git_history = get_git_history(
current_version=MC6809.__version__,
add_author=False,
)
history = '\n'.join(git_history)
assert_readme_block(
readme_path=PACKAGE_ROOT / 'README.md',
text_block=f'\n{history}\n',
start_marker_line='[comment]: <> (✂✂✂ auto generated history start ✂✂✂)',
end_marker_line='[comment]: <> (✂✂✂ auto generated history end ✂✂✂)',
)
|
class ReadmeHistoryTestCase(TestCase):
def test_readme_history(self):
pass
| 2 | 0 | 12 | 0 | 12 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 13 | 0 | 13 | 4 | 11 | 0 | 5 | 4 | 3 | 1 | 2 | 0 | 1 |
1,416 |
6809/MC6809
|
6809_MC6809/MC6809/components/cpu_utils/MC6809_registers.py
|
MC6809.components.cpu_utils.MC6809_registers.ValueStorage16Bit
|
class ValueStorage16Bit(ValueStorageBase):
WIDTH = 16 # 16 Bit
def set(self, v):
if v > 0xffff:
# log.info(" **** Value $%x is to big for %s (16-bit)", v, self.name)
v = v & 0xffff
# log.info(" ^^^^ Value %s (16-bit) wrap around to $%x", self.name, v)
elif v < 0:
# log.info(" **** %s value $%x is negative", self.name, v)
v = 0x10000 + v
# log.info(" **** Value %s (16-bit) wrap around to $%x", self.name, v)
self.value = v
def __str__(self):
return f"{self.name}={self.value:04x}"
|
class ValueStorage16Bit(ValueStorageBase):
def set(self, v):
pass
def __str__(self):
pass
| 3 | 0 | 6 | 0 | 4 | 2 | 2 | 0.5 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 7 | 16 | 2 | 10 | 5 | 7 | 5 | 9 | 5 | 6 | 3 | 1 | 1 | 4 |
1,417 |
6809/dragonlib
|
6809_dragonlib/dragonlib/core/basic_parser.py
|
dragonlib.core.basic_parser.BASIC_Data
|
class BASIC_Data(BaseCode):
PART_TYPE = CODE_TYPE_DATA
|
class BASIC_Data(BaseCode):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 1 | 0 | 0 |
1,418 |
6809/dragonlib
|
6809_dragonlib/dragonlib/tests/test_readme.py
|
dragonlib.tests.test_readme.ReadmeTestCase
|
class ReadmeTestCase(BaseTestCase):
def test_main_help(self):
stdout = invoke_click(cli, '--help')
self.assert_in_content(
got=stdout,
parts=(
'Usage: ./cli.py [OPTIONS] COMMAND [ARGS]...',
constants.CLI_EPILOG,
),
)
assert_cli_help_in_readme(text_block=stdout, marker='main help')
def test_dev_help(self):
stdout = invoke_click(dev_cli, '--help')
self.assert_in_content(
got=stdout,
parts=(
'Usage: ./dev-cli.py [OPTIONS] COMMAND [ARGS]...',
' check-code-style ',
' coverage ',
constants.CLI_EPILOG,
),
)
assert_cli_help_in_readme(text_block=stdout, marker='dev help')
|
class ReadmeTestCase(BaseTestCase):
def test_main_help(self):
pass
def test_dev_help(self):
pass
| 3 | 0 | 11 | 0 | 11 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 24 | 1 | 23 | 5 | 20 | 0 | 9 | 5 | 6 | 1 | 1 | 0 | 2 |
1,419 |
6809/dragonlib
|
6809_dragonlib/dragonlib/core/basic_parser.py
|
dragonlib.core.basic_parser.BASIC_Comment
|
class BASIC_Comment(BaseCode):
PART_TYPE = CODE_TYPE_COMMENT
|
class BASIC_Comment(BaseCode):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 1 | 0 | 0 |
1,420 |
6809/dragonlib
|
6809_dragonlib/dragonlib/core/basic_parser.py
|
dragonlib.core.basic_parser.BASIC_Code
|
class BASIC_Code(BaseCode):
PART_TYPE = CODE_TYPE_CODE
|
class BASIC_Code(BaseCode):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 1 | 0 | 0 |
1,421 |
6809/dragonlib
|
6809_dragonlib/dragonlib/core/basic_parser.py
|
dragonlib.core.basic_parser.BASICParser
|
class BASICParser:
"""
Split BASIC sourcecode into:
* line number
* Code parts
* DATA
* Strings
* Comments
"""
def __init__(self):
self.regex_line_no = re.compile(
# Split the line number from the code
r"^\s*(?P<no>\d+)\s?(?P<content>.+)\s*$",
re.MULTILINE,
)
self.regex_split_all = re.compile(
# To split a code line for parse CODE, DATA, STRING or COMMENT
r""" ( " | DATA | REM | ') """,
re.VERBOSE | re.MULTILINE,
)
self.regex_split_data = re.compile(
# To consume the complete DATA until " or :
r""" ( " | : ) """,
re.VERBOSE | re.MULTILINE,
)
self.regex_split_string = re.compile(
# To consume a string
r""" ( " ) """,
re.VERBOSE | re.MULTILINE,
)
def parse(self, ascii_listing):
"""
parse the given ASCII BASIC listing.
Return a ParsedBASIC() instance.
"""
self.parsed_lines = ParsedBASIC()
for match in self.regex_line_no.finditer(ascii_listing):
log.info("_" * 79)
log.info("parse line >>>%r<<<", match.group())
line_no = int(match.group("no"))
line_content = match.group("content")
self.line_data = []
self._parse_code(line_content)
log.info("*** line %s result: %r", line_no, self.line_data)
self.parsed_lines[line_no] = self.line_data
return self.parsed_lines
def _parse_data(self, line, old_data=""):
"""
Parse a DATA section until : or \n but exclude : in a string part.
e.g.:
10 DATA 1,"FOO:BAR",2:PRINT "NO DATA"
"""
log.debug("*** parse DATA: >>>%r<<< old data: >>>%r<<<", line, old_data)
parts = self.regex_split_data.split(line, maxsplit=1)
if len(parts) == 1: # end
return old_data + parts[0], None
pre, match, post = parts
log.debug("\tpre: >>>%r<<<", pre)
pre = old_data + pre
log.debug("\tmatch: >>>%r<<<", match)
log.debug("\tpost: >>>%r<<<", post)
if match == ":":
return old_data, match + post
elif match == '"':
string_part, rest = self._parse_string(post)
return self._parse_data(rest, old_data=pre + match + string_part)
raise RuntimeError("Wrong Reg.Exp.? match is: %r" % match)
def _parse_string(self, line):
"""
Consume the complete string until next " or \n
"""
log.debug("*** parse STRING: >>>%r<<<", line)
parts = self.regex_split_string.split(line, maxsplit=1)
if len(parts) == 1: # end
return parts[0], None
pre, match, post = parts
log.debug("\tpre: >>>%r<<<", pre)
log.debug("\tmatch: >>>%r<<<", match)
log.debug("\tpost: >>>%r<<<", post)
pre = pre + match
log.debug("Parse string result: %r,%r", pre, post)
return pre, post
def _parse_code(self, line):
"""
parse the given BASIC line and branch into DATA, String and
consume a complete Comment
"""
log.debug("*** parse CODE: >>>%r<<<", line)
parts = self.regex_split_all.split(line, maxsplit=1)
if len(parts) == 1: # end
self.line_data.append(BASIC_Code(parts[0]))
return
pre, match, post = parts
log.debug("\tpre: >>>%r<<<", pre)
log.debug("\tmatch: >>>%r<<<", match)
log.debug("\tpost: >>>%r<<<", post)
if match == '"':
log.debug("%r --> parse STRING", match)
self.line_data.append(BASIC_Code(pre))
string_part, rest = self._parse_string(post)
self.line_data.append(BASIC_String(match + string_part))
if rest:
self._parse_code(rest)
return
self.line_data.append(BASIC_Code(pre + match))
if match == "DATA":
log.debug("%r --> parse DATA", match)
data_part, rest = self._parse_data(post)
self.line_data.append(BASIC_Data(data_part))
if rest:
self._parse_code(rest)
return
elif match in ("'", "REM"):
log.debug("%r --> consume rest of the line as COMMENT", match)
if post:
self.line_data.append(BASIC_Comment(post))
return
raise RuntimeError("Wrong Reg.Exp.? match is: %r" % match)
|
class BASICParser:
'''
Split BASIC sourcecode into:
* line number
* Code parts
* DATA
* Strings
* Comments
'''
def __init__(self):
pass
def parse(self, ascii_listing):
'''
parse the given ASCII BASIC listing.
Return a ParsedBASIC() instance.
'''
pass
def _parse_data(self, line, old_data=""):
'''
Parse a DATA section until : or
but exclude : in a string part.
e.g.:
10 DATA 1,"FOO:BAR",2:PRINT "NO DATA"
'''
pass
def _parse_string(self, line):
'''
Consume the complete string until next " or
'''
pass
def _parse_code(self, line):
'''
parse the given BASIC line and branch into DATA, String and
consume a complete Comment
'''
pass
| 6 | 5 | 24 | 2 | 18 | 5 | 3 | 0.34 | 0 | 7 | 5 | 0 | 5 | 6 | 5 | 5 | 133 | 15 | 90 | 24 | 84 | 31 | 76 | 24 | 70 | 8 | 0 | 2 | 17 |
1,422 |
6809/dragonlib
|
6809_dragonlib/dragonlib/core/basic.py
|
dragonlib.core.basic.RenumTool
|
class RenumTool:
"""
Renumber a BASIC program
"""
def __init__(self, renum_regex):
self.line_no_regex = re.compile(r"(?P<no>\d+)(?P<code>.+)")
self.renum_regex = re.compile(renum_regex, re.VERBOSE)
def renum(self, ascii_listing):
self.renum_dict = self.create_renum_dict(ascii_listing)
log.info("renum: %s", ", ".join(["{}->{}".format(o, n) for o, n in sorted(self.renum_dict.items())]))
new_listing = []
for new_number, line in enumerate(self._iter_lines(ascii_listing), 1):
new_number *= 10
line = self.line_no_regex.sub(r"%s\g<code>" % new_number, line)
new_line = self.renum_regex.sub(self.renum_inline, line)
log.debug("%r -> %r", line, new_line)
new_listing.append(new_line)
return "\n".join(new_listing)
def get_destinations(self, ascii_listing):
"""
returns all line numbers that are used in a jump.
"""
self.destinations = set()
def collect_destinations(matchobj):
numbers = matchobj.group("no")
if numbers:
self.destinations.update({n.strip() for n in numbers.split(",")})
for line in self._iter_lines(ascii_listing):
self.renum_regex.sub(collect_destinations, line)
return sorted([int(no) for no in self.destinations if no])
def _iter_lines(self, ascii_listing):
lines = ascii_listing.splitlines()
lines = [line.strip() for line in lines if line.strip()]
yield from lines
def _get_new_line_number(self, line, old_number):
try:
new_number = "%s" % self.renum_dict[old_number]
except KeyError:
log.error("Error in line '%s': line no. '%s' doesn't exist.", line, old_number)
new_number = old_number
return new_number
def renum_inline(self, matchobj):
# log.critical(matchobj.groups())
old_numbers = matchobj.group("no")
if old_numbers[-1] == " ":
# e.g.: space before comment: ON X GOTO 1,2 ' Comment
space_after = " "
else:
space_after = ""
old_numbers = [n.strip() for n in old_numbers.split(",")]
new_numbers = [self._get_new_line_number(matchobj.group(0), old_number) for old_number in old_numbers]
return "".join([matchobj.group("statement"), matchobj.group("space"), ",".join(new_numbers), space_after])
def create_renum_dict(self, ascii_listing):
old_numbers = [match[0] for match in self.line_no_regex.findall(ascii_listing)]
renum_dict = {}
for new_number, old_number in enumerate(old_numbers, 1):
new_number *= 10
renum_dict[old_number] = new_number
return renum_dict
|
class RenumTool:
'''
Renumber a BASIC program
'''
def __init__(self, renum_regex):
pass
def renum(self, ascii_listing):
pass
def get_destinations(self, ascii_listing):
'''
returns all line numbers that are used in a jump.
'''
pass
def collect_destinations(matchobj):
pass
def _iter_lines(self, ascii_listing):
pass
def _get_new_line_number(self, line, old_number):
pass
def renum_inline(self, matchobj):
pass
def create_renum_dict(self, ascii_listing):
pass
| 9 | 2 | 8 | 0 | 7 | 1 | 2 | 0.16 | 0 | 4 | 0 | 0 | 7 | 4 | 7 | 7 | 69 | 10 | 51 | 26 | 42 | 8 | 50 | 26 | 41 | 2 | 0 | 1 | 14 |
1,423 |
6809/dragonlib
|
6809_dragonlib/dragonlib/core/basic.py
|
dragonlib.core.basic.BasicTokenUtil
|
class BasicTokenUtil:
def __init__(self, basic_token_dict):
self.basic_token_dict = basic_token_dict
self.ascii2token_dict = {code: token for token, code in list(basic_token_dict.items())}
regex = r"(%s)" % "|".join(
[re.escape(statement) for statement in sorted(list(self.basic_token_dict.values()), key=len, reverse=True)]
)
self.regex = re.compile(regex)
def token2ascii(self, value):
try:
result = self.basic_token_dict[value]
except KeyError:
if value > 0xFF:
log.info("ERROR: Token $%04x is not in BASIC_TOKENS!", value)
return ""
result = chr(value)
return result
def tokens2ascii(self, values):
line = ""
old_value = None
for value in values:
if value == 0xFF:
old_value = value
continue
if old_value is not None:
value = (old_value << 8) + value
old_value = None
code = self.token2ascii(value)
line += code
return line
def chars2tokens(self, chars):
return [ord(char) for char in chars]
def ascii2token(self, ascii_code, debug=False):
"""
TODO: replace no tokens in comments and strings
"""
log.info(repr(ascii_code))
parts = self.regex.split(ascii_code)
log.info(repr(parts))
tokens = []
for part in parts:
if not part:
continue
if part in self.ascii2token_dict:
new_token = self.ascii2token_dict[part]
log.info("\t%r -> %x", part, new_token)
if new_token > 0xFF:
tokens.append(new_token >> 8)
tokens.append(new_token & 0xFF)
else:
tokens.append(new_token)
else:
tokens += self.chars2tokens(part)
return tokens
def code_objects2token(self, code_objects):
tokens = []
for code_object in code_objects:
if code_object.PART_TYPE == basic_parser.CODE_TYPE_CODE:
# Code part
content = code_object.content
"""
NOTE: The BASIC interpreter changed REM shortcut and ELSE
internaly:
"'" <-> ":'"
"ELSE" <-> ":ELSE"
See also:
http://archive.worldofdragon.org/phpBB3/viewtopic.php?f=8&t=4310&p=11632#p11630
"""
log.info("replace ' and ELSE with :' and :ELSE")
content = content.replace("'", ":'")
content = content.replace("ELSE", ":ELSE")
tokens += self.ascii2token(content)
else:
# Strings, Comments or DATA
tokens += self.chars2tokens(code_object.content)
return tokens
def iter_token_values(self, tokens):
token_value = None
for token in tokens:
if token == 0xFF:
token_value = token
continue
if token_value is not None:
yield (token_value << 8) + token
token_value = None
else:
yield token
def pformat_tokens(self, tokens):
"""
format a tokenized BASIC program line. Useful for debugging.
returns a list of formated string lines.
"""
result = []
for token_value in self.iter_token_values(tokens):
char = self.token2ascii(token_value)
if token_value > 0xFF:
result.append("\t${:04x} -> {}".format(token_value, repr(char)))
else:
result.append("\t ${:02x} -> {}".format(token_value, repr(char)))
return result
|
class BasicTokenUtil:
def __init__(self, basic_token_dict):
pass
def token2ascii(self, value):
pass
def tokens2ascii(self, values):
pass
def chars2tokens(self, chars):
pass
def ascii2token(self, ascii_code, debug=False):
'''
TODO: replace no tokens in comments and strings
'''
pass
def code_objects2token(self, code_objects):
pass
def iter_token_values(self, tokens):
pass
def pformat_tokens(self, tokens):
'''
format a tokenized BASIC program line. Useful for debugging.
returns a list of formated string lines.
'''
pass
| 9 | 2 | 13 | 1 | 10 | 2 | 3 | 0.2 | 0 | 2 | 0 | 0 | 8 | 3 | 8 | 8 | 112 | 12 | 83 | 30 | 74 | 17 | 76 | 30 | 67 | 5 | 0 | 3 | 24 |
1,424 |
6809/dragonlib
|
6809_dragonlib/dragonlib/core/basic.py
|
dragonlib.core.basic.BasicListing
|
class BasicListing:
def __init__(self, basic_token_dict):
self.token_util = BasicTokenUtil(basic_token_dict)
def dump2basic_lines(self, dump, program_start, basic_lines=None):
if basic_lines is None:
basic_lines = []
log.debug("progam start $%04x", program_start)
try:
next_address = (dump[0] << 8) + dump[1]
except IndexError as err:
log.debug("Can't get address: %s", err)
return basic_lines
log.debug("next_address: $%04x", next_address)
if next_address == 0x0000:
# program end
log.debug("return: %s", repr(basic_lines))
return basic_lines
assert next_address > program_start, "Next address ${:04x} not bigger than program start ${:04x} ?!?".format(
next_address, program_start
)
line_number = (dump[2] << 8) + dump[3]
log.debug("line_number: %i", line_number)
length = next_address - program_start
log.debug("length: %i", length)
tokens = dump[4:length]
log.debug("tokens:\n\t%s", "\n\t".join(self.token_util.pformat_tokens(tokens)))
basic_line = BasicLine(self.token_util)
basic_line.token_load(line_number, tokens)
basic_lines.append(basic_line)
return self.dump2basic_lines(dump[length:], next_address, basic_lines)
def basic_lines2program_dump(self, basic_lines, program_start):
program_dump = bytearray()
current_address = program_start
count = len(basic_lines)
for no, line in enumerate(basic_lines, 1):
line.log_line()
line_tokens = line.get_tokens() + [0x00]
current_address += len(line_tokens) + 2
current_address_bytes = word2bytes(current_address) # e.g.: word2bytes(0xff09) -> (255, 9)
program_dump += bytearray(current_address_bytes)
if no == count: # It's the last line
line_tokens += [0x00, 0x00]
program_dump += bytearray(line_tokens)
return program_dump
def ascii_listing2basic_lines(self, txt):
basic_lines = []
for line in txt.splitlines():
line = line.strip()
if line:
basic_line = BasicLine(self.token_util)
basic_line.ascii_load(line)
basic_lines.append(basic_line)
return basic_lines
def pformat_program_dump(self, program_dump, program_start, formated_dump=None):
"""
format a BASIC program dump. Useful for debugging.
returns a list of formated string lines.
"""
if formated_dump is None:
formated_dump = []
formated_dump.append("program start address: $%04x" % program_start)
assert isinstance(program_dump, bytearray)
if not program_dump:
return program_dump
try:
next_address = (program_dump[0] << 8) + program_dump[1]
except IndexError as err:
raise IndexError(
"Can't get next address from: {} program start: ${:04x} (Origin error: {})".format(
repr(program_dump), program_start, err
)
)
if next_address == 0x0000:
formated_dump.append("$%04x -> end address" % next_address)
return formated_dump
assert next_address > program_start, "Next address ${:04x} not bigger than program start ${:04x} ?!?".format(
next_address, program_start
)
length = next_address - program_start
formated_dump.append("$%04x -> next address (length: %i)" % (next_address, length))
line_number = (program_dump[2] << 8) + program_dump[3]
formated_dump.append("$%04x -> %i (line number)" % (line_number, line_number))
tokens = program_dump[4:length]
formated_dump.append("tokens:")
formated_dump += self.token_util.pformat_tokens(tokens)
return self.pformat_program_dump(program_dump[length:], next_address, formated_dump)
def debug_listing(self, basic_lines):
for line in basic_lines:
line.log_line()
def log_ram_content(self, program_start, level=99):
ram_content = self.basic_lines2program_dump(program_start)
log_program_dump(ram_content, level)
def ascii_listing2program_dump(self, basic_program_ascii, program_start):
basic_lines = self.ascii_listing2basic_lines(basic_program_ascii)
self.debug_listing(basic_lines)
return self.basic_lines2program_dump(basic_lines, program_start)
# def parsed_lines2program_dump(self, parsed_lines, program_start):
# for line_no, code_objects in sorted(parsed_lines.items()):
# for code_object in code_objects:
def program_dump2ascii_lines(self, dump, program_start):
basic_lines = self.dump2basic_lines(dump, program_start)
log.info("basic_lines: %s", repr(basic_lines))
ascii_lines = []
for line in basic_lines:
ascii_lines.append(line.get_content())
return ascii_lines
|
class BasicListing:
def __init__(self, basic_token_dict):
pass
def dump2basic_lines(self, dump, program_start, basic_lines=None):
pass
def basic_lines2program_dump(self, basic_lines, program_start):
pass
def ascii_listing2basic_lines(self, txt):
pass
def pformat_program_dump(self, program_dump, program_start, formated_dump=None):
'''
format a BASIC program dump. Useful for debugging.
returns a list of formated string lines.
'''
pass
def debug_listing(self, basic_lines):
pass
def log_ram_content(self, program_start, level=99):
pass
def ascii_listing2program_dump(self, basic_program_ascii, program_start):
pass
def program_dump2ascii_lines(self, dump, program_start):
pass
| 10 | 1 | 13 | 2 | 11 | 1 | 2 | 0.1 | 0 | 5 | 2 | 0 | 9 | 1 | 9 | 9 | 133 | 27 | 98 | 37 | 88 | 10 | 90 | 35 | 80 | 5 | 0 | 2 | 22 |
1,425 |
6809/dragonlib
|
6809_dragonlib/dragonlib/core/basic.py
|
dragonlib.core.basic.BasicLine
|
class BasicLine:
def __init__(self, token_util):
self.token_util = token_util
self.line_number = None
self.line_code = None
try:
colon_token = self.token_util.ascii2token_dict[":"]
except KeyError: # XXX: Always not defined as token?
colon_token = ord(":")
rem_token = self.token_util.ascii2token_dict["'"]
else_token = self.token_util.ascii2token_dict["ELSE"]
self.tokens_replace_rules = (
((colon_token, rem_token), rem_token),
((colon_token, else_token), else_token),
)
def token_load(self, line_number, tokens):
self.line_number = line_number
assert tokens[-1] == 0x00, "line code {} doesn't ends with \\x00: {}".format(repr(tokens), repr(tokens[-1]))
"""
NOTE: The BASIC interpreter changed REM shortcut and ELSE
internaly:
"'" <-> ":'"
"ELSE" <-> ":ELSE"
See also:
http://archive.worldofdragon.org/phpBB3/viewtopic.php?f=8&t=4310&p=11632#p11630
"""
for src, dst in self.tokens_replace_rules:
log.info("Relace tokens %s with $%02x", pformat_byte_hex_list(src), dst)
log.debug("Before..: %s", pformat_byte_hex_list(tokens))
tokens = list_replace(tokens, src, dst)
log.debug("After...: %s", pformat_byte_hex_list(tokens))
self.line_code = tokens[:-1] # rstrip \x00
def ascii_load(self, line_ascii):
try:
line_number, ascii_code = line_ascii.split(" ", 1)
except ValueError as err:
msg = "Error split line number and code in line: {!r} (Origin error: {})".format(line_ascii, err)
raise ValueError(msg)
self.line_number = int(line_number)
self.line_code = self.token_util.ascii2token(ascii_code)
def code_objects_load(self, line_number, code_objects):
self.line_number = line_number
self.line_code = self.token_util.code_objects2token(code_objects)
def get_tokens(self):
"""
return two bytes line number + the code
"""
return list(word2bytes(self.line_number)) + self.line_code
def reformat(self):
# TODO: Use BASICParser to exclude string/comments etc.
space = self.token_util.ascii2token(" ")[0]
to_split = self.token_util.basic_token_dict.copy()
dont_split_tokens = self.token_util.ascii2token(":()+-*/^<=>")
for token_value in dont_split_tokens:
try:
del to_split[token_value]
except KeyError: # e.g.: () are not tokens
pass
tokens = tuple(self.token_util.iter_token_values(self.line_code))
temp = []
was_token = False
for no, token in enumerate(tokens):
try:
next_token = tokens[no + 1]
except IndexError:
next_token = None
if token in to_split:
log.debug("X%sX" % to_split[token])
try:
if temp[-1] != space:
temp.append(space)
except IndexError:
pass
temp.append(token)
if not (next_token and next_token in dont_split_tokens):
temp.append(space)
was_token = True
else:
if was_token and token == space:
was_token = False
continue
log.debug("Y%rY" % self.token_util.tokens2ascii([token]))
temp.append(token)
temp = list_replace(temp, self.token_util.ascii2token("GO TO"), self.token_util.ascii2token("GOTO"))
temp = list_replace(temp, self.token_util.ascii2token("GO SUB"), self.token_util.ascii2token("GOSUB"))
temp = list_replace(temp, self.token_util.ascii2token(": "), self.token_util.ascii2token(":"))
temp = list_replace(temp, self.token_util.ascii2token("( "), self.token_util.ascii2token("("))
temp = list_replace(temp, self.token_util.ascii2token(", "), self.token_util.ascii2token(","))
self.line_code = temp
def get_content(self, code=None):
if code is None: # start
code = self.line_code
line = "%i " % self.line_number
line += self.token_util.tokens2ascii(code)
return line
def __repr__(self):
return "{!r}: {}".format(self.get_content(), " ".join(["$%02x" % t for t in self.line_code]))
def log_line(self):
log.critical("%r:\n\t%s", self.get_content(), "\n\t".join(self.token_util.pformat_tokens(self.line_code)))
|
class BasicLine:
def __init__(self, token_util):
pass
def token_load(self, line_number, tokens):
pass
def ascii_load(self, line_ascii):
pass
def code_objects_load(self, line_number, code_objects):
pass
def get_tokens(self):
'''
return two bytes line number + the code
'''
pass
def reformat(self):
pass
def get_content(self, code=None):
pass
def __repr__(self):
pass
def log_line(self):
pass
| 10 | 1 | 13 | 2 | 10 | 2 | 2 | 0.18 | 0 | 7 | 0 | 0 | 9 | 4 | 9 | 9 | 122 | 23 | 87 | 31 | 77 | 16 | 83 | 30 | 73 | 10 | 0 | 4 | 22 |
1,426 |
6809/dragonlib
|
6809_dragonlib/dragonlib/api.py
|
dragonlib.api.Dragon32API
|
class Dragon32API(BaseAPI):
CONFIG_NAME = DRAGON32
MACHINE_NAME = "Dragon 32"
BASIC_TOKENS = DRAGON32_BASIC_TOKENS
PROGRAM_START_ADDR = 0x0019
VARIABLES_START_ADDR = 0x001B
ARRAY_START_ADDR = 0x001D
FREE_SPACE_START_ADDR = 0x001F
# Default memory location of BASIC listing start
DEFAULT_PROGRAM_START = 0x1E01
|
class Dragon32API(BaseAPI):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0.11 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 11 | 12 | 2 | 9 | 9 | 8 | 1 | 9 | 9 | 8 | 0 | 1 | 0 | 0 |
1,427 |
6809/dragonlib
|
6809_dragonlib/dragonlib/core/basic_parser.py
|
dragonlib.core.basic_parser.ParsedBASIC
|
class ParsedBASIC(dict):
"""
Normal dict with special __repr__
"""
def pformat(self):
'''
Manually pformat to force using """...""" and supress escaping apostrophe
'''
result = "{\n"
indent1 = " " * 4
indent2 = " " * 8
for line_no, code_objects in sorted(self.items()):
result += '%s%i: [\n' % (indent1, line_no)
for code_object in code_objects:
result += '{}"""<{}:{}>""",\n'.format(indent2, code_object.PART_TYPE, code_object.content)
result += '%s],\n' % indent1
result += "}"
return result
def __repr__(self):
return self.pformat()
|
class ParsedBASIC(dict):
'''
Normal dict with special __repr__
'''
def pformat(self):
'''
Manually pformat to force using """...""" and supress escaping apostrophe
'''
pass
def __repr__(self):
pass
| 3 | 2 | 9 | 1 | 7 | 2 | 2 | 0.43 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 29 | 23 | 3 | 14 | 8 | 11 | 6 | 14 | 8 | 11 | 3 | 2 | 2 | 4 |
1,428 |
6809/dragonlib
|
6809_dragonlib/dragonlib/core/basic_parser.py
|
dragonlib.core.basic_parser.BaseCode
|
class BaseCode:
def __init__(self, content):
self.content = content
def __repr__(self):
return "<{}:{}>".format(self.PART_TYPE, self.content)
|
class BaseCode:
def __init__(self, content):
pass
def __repr__(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 0 | 4 | 2 | 1 | 2 | 2 | 6 | 1 | 5 | 4 | 2 | 0 | 5 | 4 | 2 | 1 | 0 | 0 | 2 |
1,429 |
6809/dragonlib
|
6809_dragonlib/dragonlib/dragon32/pygments_lexer.py
|
dragonlib.dragon32.pygments_lexer.BasicLexer
|
class BasicLexer(RegexLexer):
"""
Pygments lexer for Dragon/CoCo BASIC
"""
name = 'Dragon/CoCo BASIC'
aliases = ['basic']
filenames = ['*.bas']
tokens = {
'root': [
(r"(REM|').*\n", Comment.Single),
(r'\s+', Text),
(r'^\d+', Name.Label),
(
r'RUN|RESTORE|STOP|RENUM|'
r'GOTO|'
r'OPEN|CLOSE|READ|CLOAD|CSAVE|DLOAD|LLIST|MOTOR|SKIPF|'
r'LIST|CLEAR|NEW|EXEC|DEL|EDIT|TRON|TROFF',
Keyword,
),
(
r'SOUND|AUDIOLINE|PLAY|' r'PCLS|PSET|SCREEN|PCLEAR|COLOR|CIRCLE|PAINT|GET|PUT|DRAW|PCOPY|PMODE',
Keyword.Reserved,
),
(r'DATA|DIM|LET|DEF', Keyword.Declaration),
(
r'PRINT|CLS|INPUT|INKEY$|'
r'HEX$|LEFT$|RIGHT$|MID$|STRING$|STR$|CHR$|'
r'SGN|INT|ABS|POS|RND|SQR|LOG|EXP|SIN|COS|TAN|ATN|LEN|VAL|ASC',
Name.Builtin,
),
(
r'FOR|TO|STEP|NEXT|IF|THEN|ELSE|RETURN|'
r'GOSUB|'
r'POKE|PEEK|'
r'ON|END|CONT|SET|RESET|PRESET|TAB|SUB|FN|OFF|'
r'USING|EOF|JOYSTK|FIX|POINT|MEM|VARPTR|INSTR|TIMER|PPOINT|USR',
Name.Function,
),
(r'([+\-*/^>=<])', Operator),
(r'AND|OR|NOT', Operator.Word),
(r'"[^"\n]*.', String),
(r'\d+|[-+]?\d*\.\d*(e[-+]?\d+)?', Number.Float),
(r'[(),:]', Punctuation),
(r'\w+[$%]?', Name),
]
}
def analyse_text(self, text):
# if it starts with a line number, it shouldn't be a "modern" Basic
# like VB.net
if re.match(r'\d+', text):
return 0.2
|
class BasicLexer(RegexLexer):
'''
Pygments lexer for Dragon/CoCo BASIC
'''
def analyse_text(self, text):
pass
| 2 | 1 | 5 | 0 | 3 | 2 | 2 | 0.11 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 30 | 54 | 3 | 46 | 6 | 44 | 5 | 8 | 6 | 6 | 2 | 5 | 1 | 2 |
1,430 |
6809/dragonlib
|
6809_dragonlib/dragonlib/tests/test_api.py
|
dragonlib.tests.test_api.Dragon32BASIC_HighLevel_ApiTest
|
class Dragon32BASIC_HighLevel_ApiTest(BaseDragon32ApiTestCase):
def test_program_dump2ascii(self):
listing = self.dragon32api.program_dump2ascii_lines(testdata.LISTING_02_BIN, program_start=0xABCD)
self.assertEqual("\n".join(listing), "\n".join(testdata.LISTING_02))
def test_ascii_listing2tokens(self):
basic_program_ascii = "\n".join(testdata.LISTING_02)
program_dump = self.dragon32api.ascii_listing2program_dump(basic_program_ascii, program_start=0xABCD)
# print("\n".join(
# self.dragon32api.pformat_program_dump(program_dump, program_start=0xabcd)
# ))
self.assertEqualProgramDump(program_dump, testdata.LISTING_02_BIN, program_start=0xABCD)
def test_ascii2RAM01(self):
tokens = self.dragon32api.ascii_listing2program_dump("10 CLS")
# log_hexlist(ram_content)
# log_hexlist(dump)
self.assertEqualProgramDump(
tokens,
(
0x1E,
0x07, # next_address
0x00,
0x0A, # 10
0xA0, # CLS
0x00, # end of line
0x00,
0x00, # program end
),
program_start=0x1E01,
)
def test_ascii2RAM02(self):
tokens = self.dragon32api.ascii_listing2program_dump("10 A=1\n" "20 B=2\n")
# log_hexlist(ram_content)
# log_hexlist(dump)
self.assertEqualProgramDump(
tokens,
(
0x1E,
0x09, # next_address
0x00,
0x0A, # 10
0x41,
0xCB,
0x31, # A=1
0x00, # end of line
0x1E,
0x11, # next_address
0x00,
0x14, # 20
0x42,
0xCB,
0x32, # B=2
0x00, # end of line
0x00,
0x00, # program end
),
program_start=0x1E01,
)
def test_listing2program_strings_dont_in_comment(self):
"""
Don't replace tokens in comments
"""
ascii_listing = self._prepare_text(
"""
10 'IF THEN ELSE"
"""
)
program_dump = (
0x1E,
0x15, # next address
0x00,
0x0A, # 10
0x3A, # :
0x83, # '
0x49,
0x46, # I, F
0x20, # " "
0x54,
0x48,
0x45,
0x4E, # T, H, E, N
0x20, # " "
0x45,
0x4C,
0x53,
0x45, # E, L, S, E
0x22, # "
0x00, # end of line
0x00,
0x00, # program end
)
self.assertListing2Dump(
ascii_listing,
program_dump,
program_start=0x1E01,
# debug=True
)
self.assertDump2Listing(ascii_listing, program_dump)
def test_listing2program_strings_dont_in_strings(self):
"""
Don't replace tokens in strings
"""
ascii_listing = self._prepare_text(
"""
10 PRINT"FOR NEXT
"""
)
program_dump = (
0x1E,
0x10, # next address
0x00,
0x0A, # 10
0x87, # PRINT
0x22, # "
0x46,
0x4F,
0x52, # F, O, R
0x20, # " "
0x4E,
0x45,
0x58,
0x54, # N, E, X, T
0x00, # end of line
0x00,
0x00, # program end
)
self.assertListing2Dump(
ascii_listing,
program_dump,
program_start=0x1E01,
# debug=True
)
self.assertDump2Listing(ascii_listing, program_dump)
def test_ascii_listing2program_dump_with_bigger_line_number(self):
"""
Don't replace tokens in strings
"""
ascii_listing = self._prepare_text(
"""
65000 CLS
"""
)
program_dump = (
0x1E,
0x07, # start address
0xFD,
0xE8, # 65000
0xA0, # CLS
0x00, # end of line
0x00,
0x00, # program end
)
self.assertListing2Dump(ascii_listing, program_dump, program_start=0x1E01, debug=True)
self.assertDump2Listing(ascii_listing, program_dump)
def test_auto_add_colon_before_comment(self):
"""
NOTE: The REM shortcut >'< would be replace by >:'< internally from
the BASIC Interpreter.
See also:
http://archive.worldofdragon.org/phpBB3/viewtopic.php?f=8&t=4310&p=11632#p11630
"""
ascii_listing = self._prepare_text(
"""
100 'FOO
"""
)
program_dump = (
0x1E,
0x0B, # next address (length: 10)
0x00,
0x64, # 100 (line number)
0x3A, # : ===> Insert/remove it automaticly
0x83, # '
0x46, # F
0x4F, # O
0x4F, # O
0x00, # EOL
0x00,
0x00, # end address
)
self.assertListing2Dump(
ascii_listing,
program_dump,
program_start=0x1E01,
# debug=True
)
self.assertDump2Listing(ascii_listing, program_dump)
def test_auto_add_colon_before_else(self):
"""
NOTE: The REM shortcut >'< would be replace by >:'< internally from
the BASIC Interpreter.
See also:
http://archive.worldofdragon.org/phpBB3/viewtopic.php?f=8&t=4310&p=11632#p11630
"""
ascii_listing = self._prepare_text(
"""
100 IF A=1 THEN 10 ELSE 20
"""
)
program_dump = (
0x1E,
0x16, # -> next address (length: 21)
0x00,
0x64, # -> 100 (line number)
0x85, # -> 'IF'
0x20, # -> ' '
0x41, # -> 'A'
0xCB, # -> '='
0x31, # -> '1'
0x20, # -> ' '
0xBF, # -> 'THEN'
0x20, # -> ' '
0x31, # -> '1'
0x30, # -> '0'
0x20, # -> ' '
0x3A, # : ===> Insert/remove it automaticly
0x84, # -> 'ELSE'
0x20, # -> ' '
0x32, # -> '2'
0x30, # -> '0'
0x00, # -> EOL
0x00,
0x00, # -> end address
)
self.assertListing2Dump(
ascii_listing,
program_dump,
program_start=0x1E01,
# debug=True
)
self.assertDump2Listing(ascii_listing, program_dump)
def test_two_byte_line_numbers(self):
"""
Every line number is saved as one word!
"""
ascii_listing = self._prepare_text(
"""
254 PRINT "A"
255 PRINT "B"
256 PRINT "C"
257 PRINT "D"
"""
)
program_dump = (
# program start address: $1e01
0x1E,
0x0B, # -> next address (length: 10)
0x00,
0xFE, # -> 254 (line number)
0x87, # -> 'PRINT'
0x20, # -> ' '
0x22, # -> '"'
0x41, # -> 'A'
0x22, # -> '"'
0x00, # -> '\x00'
0x1E,
0x15, # -> next address (length: 10)
0x00,
0xFF, # -> 255 (line number)
0x87, # -> 'PRINT'
0x20, # -> ' '
0x22, # -> '"'
0x42, # -> 'B'
0x22, # -> '"'
0x00, # -> '\x00'
0x1E,
0x1F, # -> next address (length: 10)
0x01,
0x00, # -> 256 (line number)
0x87, # -> 'PRINT'
0x20, # -> ' '
0x22, # -> '"'
0x43, # -> 'C'
0x22, # -> '"'
0x00, # -> '\x00'
0x1E,
0x29, # -> next address (length: 10)
0x01,
0x01, # -> 257 (line number)
0x87, # -> 'PRINT'
0x20, # -> ' '
0x22, # -> '"'
0x44, # -> 'D'
0x22, # -> '"'
0x00, # -> '\x00'
0x00,
0x00, # -> end address
)
self.assertListing2Dump(
ascii_listing,
program_dump,
program_start=0x1E01,
# debug=True
)
self.assertDump2Listing(ascii_listing, program_dump)
|
class Dragon32BASIC_HighLevel_ApiTest(BaseDragon32ApiTestCase):
def test_program_dump2ascii(self):
pass
def test_ascii_listing2tokens(self):
pass
def test_ascii2RAM01(self):
pass
def test_ascii2RAM02(self):
pass
def test_listing2program_strings_dont_in_comment(self):
'''
Don't replace tokens in comments
'''
pass
def test_listing2program_strings_dont_in_strings(self):
'''
Don't replace tokens in strings
'''
pass
def test_ascii_listing2program_dump_with_bigger_line_number(self):
'''
Don't replace tokens in strings
'''
pass
def test_auto_add_colon_before_comment(self):
'''
NOTE: The REM shortcut >'< would be replace by >:'< internally from
the BASIC Interpreter.
See also:
http://archive.worldofdragon.org/phpBB3/viewtopic.php?f=8&t=4310&p=11632#p11630
'''
pass
def test_auto_add_colon_before_else(self):
'''
NOTE: The REM shortcut >'< would be replace by >:'< internally from
the BASIC Interpreter.
See also:
http://archive.worldofdragon.org/phpBB3/viewtopic.php?f=8&t=4310&p=11632#p11630
'''
pass
def test_two_byte_line_numbers(self):
'''
Every line number is saved as one word!
'''
pass
| 11 | 6 | 30 | 0 | 26 | 14 | 1 | 0.54 | 1 | 0 | 0 | 0 | 10 | 0 | 10 | 96 | 305 | 11 | 257 | 28 | 246 | 139 | 44 | 28 | 33 | 1 | 4 | 0 | 10 |
1,431 |
6809/dragonlib
|
6809_dragonlib/dragonlib/tests/test_api.py
|
dragonlib.tests.test_api.Dragon32BASIC_LowLevel_ApiTest
|
class Dragon32BASIC_LowLevel_ApiTest(BaseDragon32ApiTestCase):
def setUp(self):
super().setUp()
self.token_util = self.dragon32api.listing.token_util
self.basic_line = BasicLine(self.token_util)
def test_load_from_dump(self):
dump = (
0x1E,
0x07, # next_address
0x00,
0x0A, # 10
0xA0, # CLS
0x00, # end of line
0x00,
0x00, # program end
)
basic_lines = self.dragon32api.listing.dump2basic_lines(dump, program_start=0x1E01)
ascii_listing = basic_lines[0].get_content()
self.assertEqual(ascii_listing, "10 CLS")
self.assertEqual(len(basic_lines), 1)
def test_tokens2ascii(self):
self.basic_line.token_load(
line_number=50,
tokens=(
0x49,
0x24,
0x20,
0xCB,
0x20,
0xFF,
0x9A,
0x3A,
0x85,
0x20,
0x49,
0x24,
0xCB,
0x22,
0x22,
0x20,
0xBF,
0x20,
0x35,
0x30,
0x00,
),
)
code = self.basic_line.get_content()
self.assertEqual(code, '50 I$ = INKEY$:IF I$="" THEN 50')
def test_ascii2tokens01(self):
basic_lines = self.dragon32api.listing.ascii_listing2basic_lines('10 CLS')
tokens = basic_lines[0].get_tokens()
self.assertHexList(
tokens,
[
0x00,
0x0A, # 10
0xA0, # CLS
],
)
self.assertEqual(len(basic_lines), 1)
def test_ascii2tokens02(self):
basic_lines = self.dragon32api.listing.ascii_listing2basic_lines('50 I$ = INKEY$:IF I$="" THEN 50')
tokens = basic_lines[0].get_tokens()
self.assertHexList(
tokens,
[
0x00,
0x32, # 50
# I$ = INKEY$:IF I$="" THEN 50
0x49,
0x24,
0x20,
0xCB,
0x20,
0xFF,
0x9A,
0x3A,
0x85,
0x20,
0x49,
0x24,
0xCB,
0x22,
0x22,
0x20,
0xBF,
0x20,
0x35,
0x30,
],
)
self.assertEqual(len(basic_lines), 1)
def test_format_tokens(self):
tokens = (0x49, 0x24, 0x20, 0xCB, 0x20, 0xFF, 0x9A) # I$ = INKEY$
formated_tokens = self.token_util.pformat_tokens(tokens)
self.assertEqual(
formated_tokens,
[
"\t $49 -> 'I'",
"\t $24 -> '$'",
"\t $20 -> ' '",
"\t $cb -> '='",
"\t $20 -> ' '",
"\t$ff9a -> 'INKEY$'",
],
)
|
class Dragon32BASIC_LowLevel_ApiTest(BaseDragon32ApiTestCase):
def setUp(self):
pass
def test_load_from_dump(self):
pass
def test_tokens2ascii(self):
pass
def test_ascii2tokens01(self):
pass
def test_ascii2tokens02(self):
pass
def test_format_tokens(self):
pass
| 7 | 0 | 18 | 0 | 18 | 2 | 1 | 0.09 | 1 | 2 | 1 | 0 | 6 | 2 | 6 | 92 | 112 | 5 | 106 | 19 | 99 | 10 | 29 | 19 | 22 | 1 | 4 | 0 | 6 |
1,432 |
6809/dragonlib
|
6809_dragonlib/dragonlib/tests/test_api.py
|
dragonlib.tests.test_api.Dragon32bin
|
class Dragon32bin(BaseDragon32ApiTestCase):
def test_bas2bin_bin2bas_api_1(self):
bas1 = "10 PRINT"
data = self.dragon32api.bas2bin(bas1, load_address=0x1234, exec_address=0x5678)
bas2 = self.dragon32api.bin2bas(data)
self.assertEqual(bas2, bas1)
def test_bas2bin_bin2bas_api_2(self):
bas1 = "\n".join(testdata.LISTING_01)
data = self.dragon32api.bas2bin(bas1, load_address=0xABCD, exec_address=0xEFEF)
bas2 = self.dragon32api.bin2bas(data)
self.assertEqual(bas2, bas1)
def test_bas2bin_api_1(self):
bin = self.dragon32api.bas2bin("\n".join(testdata.LISTING_01), load_address=0x1234, exec_address=0x5678)
self.assertBinEqual(bin, testdata.LISTING_01_DOS_DUMP)
def test_bas2bin_api_2(self):
bin = self.dragon32api.bas2bin("\n".join(testdata.LISTING_02), load_address=0xABCD, exec_address=0xDCBA)
self.assertBinEqual(bin, testdata.LISTING_02_DOS_DUMP)
def test_bin2bas(self):
example_listing = """\
10 CLS
20 PRINT" *** DYNAMIC MENU *** 14:11:18"
30 PRINT"/HOME/FOO/DWLOAD-FILES"
40 PRINT" 0 - HEXVIEW.BAS"
50 PRINT" 1 - TEST.BAS"
60 PRINT" 2 - SAVE"
70 PRINT"PLEASE SELECT (X FOR RELOAD) !"
80 A$=INKEY$:IF A$="" GOTO 80
90 IF A$="X" THEN DLOAD
100 IF A$="0" THEN DLOAD"HEXVIEW.BAS"
110 IF A$="1" THEN DLOAD"TEST.BAS"
120 IF A$="2" THEN DLOAD"SAVE"
130 GOTO 10"""
filepath = os.path.join(os.path.dirname(__file__), "AUTOLOAD.DWL")
self.assertTrue(os.path.isfile(filepath), "file %r not exists?!?" % filepath)
with open(filepath, "rb") as f:
data = f.read()
# print("\n".join(bin2hexline(data, width=16)))
bas1 = self.dragon32api.bin2bas(data)
self.assertEqual(bas1, example_listing)
bin = self.dragon32api.bas2bin(bas1, load_address=0x1E01, exec_address=0x1E01)
bin = padding(bin, size=256, b=b"\x00")
self.maxDiff = None
self.assertBinEqual(bin, data)
|
class Dragon32bin(BaseDragon32ApiTestCase):
def test_bas2bin_bin2bas_api_1(self):
pass
def test_bas2bin_bin2bas_api_2(self):
pass
def test_bas2bin_api_1(self):
pass
def test_bas2bin_api_2(self):
pass
def test_bin2bas(self):
pass
| 6 | 0 | 10 | 1 | 8 | 0 | 1 | 0.02 | 1 | 0 | 0 | 0 | 5 | 1 | 5 | 91 | 53 | 10 | 42 | 18 | 36 | 1 | 29 | 17 | 23 | 1 | 4 | 1 | 5 |
1,433 |
6809/dragonlib
|
6809_dragonlib/dragonlib/tests/test_api.py
|
dragonlib.tests.test_api.RenumTests
|
class RenumTests(BaseDragon32ApiTestCase):
def test_renum01(self):
old_listing = self._prepare_text(
"""
1 PRINT "ONE"
11 GOTO 12
12 PRINT "FOO":GOSUB 15
14 IF A=1 THEN 20 ELSE 1
15 PRINT "BAR"
16 RESUME
20 PRINT "END?"
"""
)
# print old_listing
# print "-"*79
new_listing = self.dragon32api.renum_ascii_listing(old_listing)
# print new_listing
self.assertEqual(
new_listing,
self._prepare_text(
"""
10 PRINT "ONE"
20 GOTO 30
30 PRINT "FOO":GOSUB 50
40 IF A=1 THEN 70 ELSE 10
50 PRINT "BAR"
60 RESUME
70 PRINT "END?"
"""
),
)
def test_missing_number01(self):
old_listing = self._prepare_text(
"""
1 GOTO 2
2 GOTO 123 ' 123 didn't exists
3 IF A=1 THEN 456 ELSE 2 ' 456 didn't exists
"""
)
new_listing = self.dragon32api.renum_ascii_listing(old_listing)
# print new_listing
self.assertEqual(
new_listing,
self._prepare_text(
"""
10 GOTO 20
20 GOTO 123 ' 123 didn't exists
30 IF A=1 THEN 456 ELSE 20 ' 456 didn't exists
"""
),
)
def test_on_goto(self):
old_listing = self._prepare_text(
"""
1 ON X GOTO 2,3
2 ?"A"
3 ?"B"
"""
)
new_listing = self.dragon32api.renum_ascii_listing(old_listing)
# print new_listing
self.assertEqual(
new_listing,
self._prepare_text(
"""
10 ON X GOTO 20,30
20 ?"A"
30 ?"B"
"""
),
)
def test_on_goto_spaces(self):
old_listing = self._prepare_text(
"""
1 ON X GOTO 2,30 , 4, 555
2 ?"A"
30 ?"B"
4 ?"C"
555 ?"D"
"""
)
new_listing = self.dragon32api.renum_ascii_listing(old_listing)
# print new_listing
self.assertEqual(
new_listing,
self._prepare_text(
"""
10 ON X GOTO 20,30,40,50
20 ?"A"
30 ?"B"
40 ?"C"
50 ?"D"
"""
),
)
def test_on_goto_space_after(self):
old_listing = self._prepare_text(
"""
1 ON X GOTO 1,2 ' space before comment?
2 ?"A"
"""
)
# print old_listing
# print "-"*79
new_listing = self.dragon32api.renum_ascii_listing(old_listing)
# print new_listing
self.assertEqual(
new_listing,
self._prepare_text(
"""
10 ON X GOTO 10,20 ' space before comment?
20 ?"A"
"""
),
)
def test_on_gosub_dont_exists(self):
old_listing = self._prepare_text(
"""
1 ON X GOSUB 1,2,3
2 ?"A"
"""
)
# print old_listing
# print "-"*79
new_listing = self.dragon32api.renum_ascii_listing(old_listing)
# print new_listing
self.assertEqual(
new_listing,
self._prepare_text(
"""
10 ON X GOSUB 10,20,3
20 ?"A"
"""
),
)
def test_get_destinations_1(self):
listing = self._prepare_text(
"""
10 PRINT "ONE"
20 GOTO 30
30 PRINT "FOO":GOSUB 50
40 IF A=1 THEN 20 ELSE 10
50 PRINT "BAR"
60 RESUME
70 PRINT "END?"
80 ON X GOTO 10, 20, 30 ,40 ,50
90 ON X GOSUB 10, 70, 999
"""
)
destinations = self.dragon32api.renum_tool.get_destinations(listing)
self.assertEqual(destinations, [10, 20, 30, 40, 50, 70, 999])
def test_on_gosub_and_goto(self):
old_listing = self._prepare_text(
"""
2 PRINT "2"
13 ON X GOSUB 18 :ONY GOSUB 2,2:NEXT:GOTO99
18 PRINT "18"
99 PRINT "99"
"""
)
# print(old_listing)
# print("-"*79)
new_listing = self.dragon32api.renum_ascii_listing(old_listing)
# print(new_listing)
self.assertEqual(
new_listing,
self._prepare_text(
"""
10 PRINT "2"
20 ON X GOSUB 30 :ONY GOSUB 10,10:NEXT:GOTO40
30 PRINT "18"
40 PRINT "99"
"""
),
)
|
class RenumTests(BaseDragon32ApiTestCase):
def test_renum01(self):
pass
def test_missing_number01(self):
pass
def test_on_goto(self):
pass
def test_on_goto_spaces(self):
pass
def test_on_goto_space_after(self):
pass
def test_on_gosub_dont_exists(self):
pass
def test_get_destinations_1(self):
pass
def test_on_gosub_and_goto(self):
pass
| 9 | 0 | 22 | 0 | 20 | 2 | 1 | 0.09 | 1 | 0 | 0 | 0 | 8 | 0 | 8 | 94 | 182 | 7 | 160 | 25 | 151 | 15 | 33 | 25 | 24 | 1 | 4 | 0 | 8 |
1,434 |
6809/dragonlib
|
6809_dragonlib/dragonlib/tests/test_base.py
|
dragonlib.tests.test_base.BaseTestCase
|
class BaseTestCase(unittest.TestCase):
"""
Only some special assertments.
"""
maxDiff = 3000
def assertHexList(self, first, second, msg=None):
first = ["$%x" % value for value in first]
second = ["$%x" % value for value in second]
self.assertEqual(first, second, msg)
def assertEqualHex(self, hex1, hex2, msg=None):
first = "$%x" % hex1
second = "$%x" % hex2
if msg is None:
msg = "{} != {}".format(first, second)
self.assertEqual(first, second, msg)
def assertIsByteRange(self, value):
self.assertTrue(0x0 <= value, "Value (dez: %i - hex: %x) is negative!" % (value, value))
self.assertTrue(0xFF >= value, "Value (dez: %i - hex: %x) is greater than 0xff!" % (value, value))
def assertIsWordRange(self, value):
self.assertTrue(0x0 <= value, "Value (dez: %i - hex: %x) is negative!" % (value, value))
self.assertTrue(0xFFFF >= value, "Value (dez: %i - hex: %x) is greater than 0xffff!" % (value, value))
def assertEqualHexByte(self, hex1, hex2, msg=None):
self.assertIsByteRange(hex1)
self.assertIsByteRange(hex2)
first = "$%02x" % hex1
second = "$%02x" % hex2
if msg is None:
msg = "{} != {}".format(first, second)
self.assertEqual(first, second, msg)
def assertEqualHexWord(self, hex1, hex2, msg=None):
self.assertIsWordRange(hex1)
self.assertIsWordRange(hex2)
first = "$%04x" % hex1
second = "$%04x" % hex2
if msg is None:
msg = "{} != {}".format(first, second)
self.assertEqual(first, second, msg)
def assertBinEqual(self, bin1, bin2, msg=None, width=16):
# first = bin2hexline(bin1, width=width)
# second = bin2hexline(bin2, width=width)
# self.assertSequenceEqual(first, second, msg)
first = "\n".join(bin2hexline(bin1, width=width))
second = "\n".join(bin2hexline(bin2, width=width))
self.assertMultiLineEqual(first, second, msg)
def _dedent(self, txt):
# Remove any common leading whitespace from every line
txt = textwrap.dedent(txt)
# strip whitespace at the end of every line
txt = "\n".join([line.rstrip() for line in txt.splitlines()])
txt = txt.strip()
return txt
def assertEqual_dedent(self, first, second, msg=None):
first = self._dedent(first)
second = self._dedent(second)
try:
self.assertEqual(first, second, msg)
except AssertionError as err:
# Py2 has a bad error message
msg = (
"%s\n"
" ------------- [first] -------------\n"
"%s\n"
" ------------- [second] ------------\n"
"%s\n"
" -----------------------------------\n"
) % (err, first, second)
raise AssertionError(msg)
|
class BaseTestCase(unittest.TestCase):
'''
Only some special assertments.
'''
def assertHexList(self, first, second, msg=None):
pass
def assertEqualHex(self, hex1, hex2, msg=None):
pass
def assertIsByteRange(self, value):
pass
def assertIsWordRange(self, value):
pass
def assertEqualHexByte(self, hex1, hex2, msg=None):
pass
def assertEqualHexWord(self, hex1, hex2, msg=None):
pass
def assertBinEqual(self, bin1, bin2, msg=None, width=16):
pass
def _dedent(self, txt):
pass
def assertEqual_dedent(self, first, second, msg=None):
pass
| 10 | 1 | 7 | 0 | 6 | 1 | 1 | 0.16 | 1 | 1 | 0 | 2 | 9 | 0 | 9 | 81 | 79 | 12 | 58 | 20 | 48 | 9 | 51 | 19 | 41 | 2 | 2 | 1 | 13 |
1,435 |
6809/dragonlib
|
6809_dragonlib/dragonlib/tests/test_basic_parser.py
|
dragonlib.tests.test_basic_parser.TestBASICParser
|
class TestBASICParser(unittest.TestCase):
def setUp(self):
self.parser = BASICParser()
def assertParser(self, ascii_listing, reference, print_parsed_lines=False):
'''
parse the given ASCII Listing and compare it with the reference.
Used a speacial representation of the parser result for a human
readable compare. Force using of """...""" to supress escaping apostrophe
'''
parsed_lines = self.parser.parse(ascii_listing)
string_dict = {}
for line_no, code_objects in list(parsed_lines.items()):
string_dict[line_no] = [repr(code_object) for code_object in code_objects]
if print_parsed_lines:
print("-" * 79)
print("parsed lines:", parsed_lines)
print("-" * 79)
print("reference:", reference)
print("-" * 79)
self.assertEqual(string_dict, reference)
def test_only_code(self):
ascii_listing = """
10 CLS
20 PRINT
"""
self.assertParser(
ascii_listing,
{
10: [
"""<CODE:CLS>""",
],
20: [
"""<CODE:PRINT>""",
],
},
# print_parsed_lines=True
)
def test_string(self):
ascii_listing = '10 A$="A STRING"'
self.assertParser(
ascii_listing,
{
10: [
"""<CODE:A$=>""",
"""<STRING:"A STRING">""",
],
},
# print_parsed_lines=True
)
def test_strings(self):
ascii_listing = """
10 A$="1":B=2:C$="4":CLS:PRINT "ONLY CODE"
"""
self.assertParser(
ascii_listing,
{
10: [
"""<CODE:A$=>""",
"""<STRING:"1">""",
"""<CODE::B=2:C$=>""",
"""<STRING:"4">""",
"""<CODE::CLS:PRINT >""",
"""<STRING:"ONLY CODE">""",
],
},
# print_parsed_lines=True
)
def test_string_and_comment(self):
ascii_listing = """
10 A$="NO :'REM" ' BUT HERE!
"""
self.assertParser(
ascii_listing,
{
10: [
"""<CODE:A$=>""",
"""<STRING:"NO :'REM">""",
"""<CODE: '>""",
"""<COMMENT: BUT HERE!>""",
],
},
# print_parsed_lines=True
)
def test_string_not_terminated(self):
ascii_listing = """
10 PRINT "NOT TERMINATED STRING
"""
self.assertParser(
ascii_listing,
{
10: [
"""<CODE:PRINT >""",
"""<STRING:"NOT TERMINATED STRING>""",
],
},
# print_parsed_lines=True
)
def test_data(self):
ascii_listing = """
10 DATA 1,2,A,FOO
"""
self.assertParser(
ascii_listing,
{
10: [
"""<CODE:DATA>""",
"""<DATA: 1,2,A,FOO>""",
],
},
# print_parsed_lines=True
)
def test_data_with_string1(self):
ascii_listing = """
10 DATA 1,2,"A","FOO BAR",4,5
"""
self.assertParser(
ascii_listing,
{
10: [
"""<CODE:DATA>""",
"""<DATA: 1,2,"A","FOO BAR",4,5>""",
],
},
# print_parsed_lines=True
)
def test_data_string_colon(self):
ascii_listing = """
10 DATA "FOO : BAR"
"""
self.assertParser(
ascii_listing,
{
10: [
"""<CODE:DATA>""",
"""<DATA: "FOO : BAR">""",
],
},
# print_parsed_lines=True
)
def test_code_after_data(self):
ascii_listing = """
10 DATA "FOO : BAR":PRINT 123
"""
self.assertParser(
ascii_listing,
{
10: [
"""<CODE:DATA>""",
"""<DATA: "FOO : BAR">""",
"""<CODE::PRINT 123>""",
],
},
# print_parsed_lines=True
)
def test_comment(self):
ascii_listing = """
10 REM A COMMENT
"""
self.assertParser(
ascii_listing,
{
10: [
"""<CODE:REM>""",
"""<COMMENT: A COMMENT>""",
],
},
# print_parsed_lines=True
)
def test_nothing_after_comment1(self):
ascii_listing = """
10 REM
"""
self.assertParser(
ascii_listing,
{
10: [
"""<CODE:REM>""",
],
},
# print_parsed_lines=True
)
def test_nothing_after_comment2(self):
ascii_listing = """
10 '
"""
self.assertParser(
ascii_listing,
{
10: [
"""<CODE:'>""",
],
},
# print_parsed_lines=True
)
def test_no_code_after_comment(self):
ascii_listing = """
10 REM FOR "FOO : BAR":PRINT 123
"""
self.assertParser(
ascii_listing,
{
10: [
"""<CODE:REM>""",
"""<COMMENT: FOR "FOO : BAR":PRINT 123>""",
],
},
# print_parsed_lines=True
)
def test_comment2(self):
ascii_listing = """
10 A=2 ' FOR "FOO : BAR":PRINT 123
"""
self.assertParser(
ascii_listing,
{
10: [
"""<CODE:A=2 '>""",
"""<COMMENT: FOR "FOO : BAR":PRINT 123>""",
],
},
# print_parsed_lines=True
)
def test_no_comment(self):
ascii_listing = """
10 B$="'"
"""
self.assertParser(
ascii_listing,
{
10: [
"""<CODE:B$=>""",
"""<STRING:"'">""",
],
},
# print_parsed_lines=True
)
def test_spaces_after_line_no(self):
ascii_listing = """
10 FOR I=1 TO 3:
20 PRINT I
30 NEXT
"""
self.assertParser(
ascii_listing,
{
10: [
"""<CODE:FOR I=1 TO 3:>""",
],
20: [
"""<CODE: PRINT I>""",
],
30: [
"""<CODE:NEXT>""",
],
},
# print_parsed_lines=True
)
|
class TestBASICParser(unittest.TestCase):
def setUp(self):
pass
def assertParser(self, ascii_listing, reference, print_parsed_lines=False):
'''
parse the given ASCII Listing and compare it with the reference.
Used a speacial representation of the parser result for a human
readable compare. Force using of """...""" to supress escaping apostrophe
'''
pass
def test_only_code(self):
pass
def test_string(self):
pass
def test_strings(self):
pass
def test_string_and_comment(self):
pass
def test_string_not_terminated(self):
pass
def test_data(self):
pass
def test_data_with_string1(self):
pass
def test_data_string_colon(self):
pass
def test_code_after_data(self):
pass
def test_comment(self):
pass
def test_nothing_after_comment1(self):
pass
def test_nothing_after_comment2(self):
pass
def test_no_code_after_comment(self):
pass
def test_comment2(self):
pass
def test_no_comment(self):
pass
def test_spaces_after_line_no(self):
pass
| 19 | 1 | 14 | 0 | 13 | 1 | 1 | 0.09 | 1 | 2 | 1 | 0 | 18 | 1 | 18 | 90 | 278 | 21 | 236 | 39 | 217 | 21 | 63 | 39 | 44 | 3 | 2 | 1 | 20 |
1,436 |
6809/dragonlib
|
6809_dragonlib/dragonlib/tests/test_binary_format.py
|
dragonlib.tests.test_binary_format.TestBinaryFile
|
class TestBinaryFile(BaseTestCase):
def setUp(self):
self.binary = BinaryFile()
def test_load_from_bin1(self):
"""test with one line listing: testdata.LISTING_01"""
# log_bytes(testdata.LISTING_01_BIN, msg="tokenised: %s")
self.binary.load_tokenised_dump(testdata.LISTING_01_BIN, load_address=0x1234, exec_address=0x5678)
# self.binary.debug2log(level=logging.CRITICAL)
self.assertBinEqual(self.binary.get_header(), testdata.LISTING_01_DOS_HEADER)
dragon_bin = self.binary.dump_DragonDosBinary()
# log_bytes(dragon_bin, msg="DragonDOS1: %s",level=logging.CRITICAL)
# log_bytes(testdata.LISTING_01_DOS_DUMP, msg="DragonDOS2: %s",level=logging.CRITICAL)
self.assertBinEqual(dragon_bin, testdata.LISTING_01_DOS_DUMP)
def test_load_from_bin2(self):
"""test with bigger testdata.LISTING_02"""
# log_bytes(testdata.LISTING_02_BIN, msg="tokenised: %s")
self.binary.load_tokenised_dump(testdata.LISTING_02_BIN, load_address=0xABCD, exec_address=0xDCBA)
# self.binary.debug2log(level=logging.CRITICAL)
self.assertBinEqual(self.binary.get_header(), testdata.LISTING_02_DOS_HEADER)
dragon_bin = self.binary.dump_DragonDosBinary()
# log_bytes(dragon_bin, msg="DragonDOS: %s")
self.assertBinEqual(dragon_bin, testdata.LISTING_02_DOS_DUMP)
|
class TestBinaryFile(BaseTestCase):
def setUp(self):
pass
def test_load_from_bin1(self):
'''test with one line listing: testdata.LISTING_01'''
pass
def test_load_from_bin2(self):
'''test with bigger testdata.LISTING_02'''
pass
| 4 | 2 | 9 | 2 | 4 | 3 | 1 | 0.69 | 1 | 1 | 1 | 0 | 3 | 1 | 3 | 84 | 30 | 8 | 13 | 7 | 9 | 9 | 13 | 7 | 9 | 1 | 3 | 0 | 3 |
1,437 |
6809/dragonlib
|
6809_dragonlib/dragonlib/tests/test_doctests.py
|
dragonlib.tests.test_doctests.DocTests
|
class DocTests(BaseDocTests):
def test_doctests(self):
self.run_doctests(
modules=(dragonlib,),
)
|
class DocTests(BaseDocTests):
def test_doctests(self):
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 5 | 0 | 5 | 2 | 3 | 0 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
1,438 |
6809/dragonlib
|
6809_dragonlib/dragonlib/tests/test_project_setup.py
|
dragonlib.tests.test_project_setup.ProjectSetupTestCase
|
class ProjectSetupTestCase(TestCase):
def test_version(self):
self.assertIsNotNone(__version__)
version = Version(__version__) # Will raise InvalidVersion() if wrong formatted
self.assertEqual(str(version), __version__)
cli_bin = PACKAGE_ROOT / 'cli.py'
assert_is_file(cli_bin)
output = subprocess.check_output([cli_bin, 'version'], text=True)
self.assertIn(f'dragonlib v{__version__}', output)
dev_cli_bin = PACKAGE_ROOT / 'dev-cli.py'
assert_is_file(dev_cli_bin)
output = subprocess.check_output([dev_cli_bin, 'version'], text=True)
self.assertIn(f'dragonlib v{__version__}', output)
def test_code_style(self):
return_code = assert_code_style(package_root=PACKAGE_ROOT)
self.assertEqual(return_code, 0, 'Code style error, see output above!')
def test_check_editor_config(self):
check_editor_config(package_root=PACKAGE_ROOT)
max_line_length = get_py_max_line_length(package_root=PACKAGE_ROOT)
self.assertEqual(max_line_length, 119)
|
class ProjectSetupTestCase(TestCase):
def test_version(self):
pass
def test_code_style(self):
pass
def test_check_editor_config(self):
pass
| 4 | 0 | 8 | 2 | 6 | 0 | 1 | 0.05 | 1 | 2 | 0 | 0 | 3 | 0 | 3 | 75 | 28 | 8 | 20 | 10 | 16 | 1 | 20 | 10 | 16 | 1 | 2 | 0 | 3 |
1,439 |
6809/dragonlib
|
6809_dragonlib/dragonlib/tests/test_api.py
|
dragonlib.tests.test_api.BaseDragon32ApiTestCase
|
class BaseDragon32ApiTestCase(BaseTestCase):
def setUp(self):
self.dragon32api = Dragon32API()
def assertEqualProgramDump(self, first, second, program_start, msg=None):
first = bytearray(first)
second = bytearray(second)
first = self.dragon32api.pformat_program_dump(first, program_start)
second = self.dragon32api.pformat_program_dump(second, program_start)
self.assertEqual(first, second, msg)
def assertListing2Dump(self, ascii_listing, program_dump, program_start, debug=False):
program_dump = bytearray(program_dump)
if debug:
print("\n" + "_" * 79)
print(" *** Debug Listing:\n%s" % ascii_listing)
print(" -" * 39)
print(" *** Debug Dump:\n%s\n" % ("\n".join(bin2hexline(program_dump))))
print(" -" * 39)
created_program_dump = self.dragon32api.ascii_listing2program_dump(ascii_listing, program_start)
self.assertTrue(isinstance(created_program_dump, bytearray))
if debug:
print(" *** Created dump from listing:\n%s\n" % (pformat_program_dump(created_program_dump)))
print(" -" * 39)
if not created_program_dump:
log.critical("Created dump empty? repr: %s", repr(created_program_dump))
if debug:
print(
" *** Full Dump:\n%s"
% "\n".join(self.dragon32api.pformat_program_dump(created_program_dump, program_start))
)
self.assertEqualProgramDump(created_program_dump, program_dump, program_start)
def assertDump2Listing(self, ascii_listing, program_dump):
program_dump = bytearray(program_dump)
# log_program_dump(created_program_dump)
# print "\n".join(
# self.dragon32api.pformat_program_dump(created_program_dump)
# )
created_listing = self.dragon32api.program_dump2ascii_lines(program_dump)
ascii_listing = ascii_listing.splitlines()
self.assertEqual(created_listing, ascii_listing)
def _prepare_text(self, txt):
"""
prepare the multiline, indentation text.
from python-creole
"""
return textwrap.dedent(txt).strip("\n")
'''
# txt = unicode(txt)
txt = txt.splitlines()
assert txt[0] == "", "First assertion line must be empty! Is: %s" % repr(txt[0])
txt = txt[1:] # Skip the first line
# get the indentation level from the first line
count = False
for count, char in enumerate(txt[0]):
if char != " ":
break
assert count != False, "second line is empty!"
# remove indentation from all lines
txt = [i[count:].rstrip(" ") for i in txt]
# ~ txt = re.sub("\n {2,}", "\n", txt)
txt = "\n".join(txt)
# strip *one* newline at the begining...
if txt.startswith("\n"):
txt = txt[1:]
# and strip *one* newline at the end of the text
if txt.endswith("\n"):
txt = txt[:-1]
# ~ print(repr(txt))
# ~ print("-"*79)
return str(txt) # turn to unicode, for better assertEqual error messages
'''
|
class BaseDragon32ApiTestCase(BaseTestCase):
def setUp(self):
pass
def assertEqualProgramDump(self, first, second, program_start, msg=None):
pass
def assertListing2Dump(self, ascii_listing, program_dump, program_start, debug=False):
pass
def assertDump2Listing(self, ascii_listing, program_dump):
pass
def _prepare_text(self, txt):
'''
prepare the multiline, indentation text.
from python-creole
'''
pass
| 6 | 1 | 16 | 2 | 7 | 7 | 2 | 0.89 | 1 | 2 | 1 | 4 | 5 | 1 | 5 | 86 | 86 | 16 | 37 | 9 | 31 | 33 | 34 | 9 | 28 | 5 | 3 | 1 | 9 |
1,440 |
6809/dragonlib
|
6809_dragonlib/dragonlib/core/basic_parser.py
|
dragonlib.core.basic_parser.BASIC_String
|
class BASIC_String(BaseCode):
PART_TYPE = CODE_TYPE_STRING
|
class BASIC_String(BaseCode):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 1 | 0 | 0 |
1,441 |
6809/dragonlib
|
6809_dragonlib/dragonlib/tests/test_highlighting.py
|
dragonlib.tests.test_highlighting.TestHighlighting
|
class TestHighlighting(unittest.TestCase):
def test(self):
lexer = BasicLexer()
listing = '10 PRINT"FOO"'
tokensource = lexer.get_tokens(listing)
self.assertEqual(
list(tokensource),
[
(Token.Name.Label, '10'),
(Token.Text, ' '),
(Token.Name.Builtin, 'PRINT'),
(Token.Literal.String, '"FOO"'),
(Token.Text, '\n'),
],
)
|
class TestHighlighting(unittest.TestCase):
def test(self):
pass
| 2 | 0 | 14 | 0 | 14 | 0 | 1 | 0 | 1 | 2 | 1 | 0 | 1 | 0 | 1 | 73 | 15 | 0 | 15 | 5 | 13 | 0 | 6 | 5 | 4 | 1 | 2 | 0 | 1 |
1,442 |
6809/dragonlib
|
6809_dragonlib/dragonlib/api.py
|
dragonlib.api.CoCoAPI
|
class CoCoAPI(Dragon32API):
"""
http://sourceforge.net/p/toolshed/code/ci/default/tree/cocoroms/dragon_equivs.asm
"""
CONFIG_NAME = COCO2B
MACHINE_NAME = "CoCo"
BASIC_TOKENS = COCO_BASIC_TOKENS
|
class CoCoAPI(Dragon32API):
'''
http://sourceforge.net/p/toolshed/code/ci/default/tree/cocoroms/dragon_equivs.asm
'''
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.75 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 8 | 1 | 4 | 4 | 3 | 3 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
1,443 |
6809/dragonlib
|
6809_dragonlib/dragonlib/api.py
|
dragonlib.api.BaseAPI
|
class BaseAPI:
RENUM_REGEX = r"""
(?P<statement> GOTO|GOSUB|THEN|ELSE ) (?P<space>\s*) (?P<no>[\d*,\s*]+)
"""
def __init__(self):
self.listing = BasicListing(self.BASIC_TOKENS)
self.renum_tool = RenumTool(self.RENUM_REGEX)
self.token_util = BasicTokenUtil(self.BASIC_TOKENS)
def program_dump2ascii_lines(self, dump, program_start=None):
"""
convert a memory dump of a tokensized BASIC listing into
ASCII listing list.
"""
dump = bytearray(dump)
# assert isinstance(dump, bytearray)
if program_start is None:
program_start = self.DEFAULT_PROGRAM_START
return self.listing.program_dump2ascii_lines(dump, program_start)
def parse_ascii_listing(self, basic_program_ascii):
parser = BASICParser()
parsed_lines = parser.parse(basic_program_ascii)
if not parsed_lines:
log.critical("No parsed lines {} from {} ?!?".format(repr(parsed_lines), repr(basic_program_ascii)))
log.debug("Parsed BASIC: %s", repr(parsed_lines))
return parsed_lines
def ascii_listing2basic_lines(self, basic_program_ascii, program_start):
parsed_lines = self.parse_ascii_listing(basic_program_ascii)
basic_lines = []
for line_no, code_objects in sorted(parsed_lines.items()):
basic_line = BasicLine(self.token_util)
basic_line.code_objects_load(line_no, code_objects)
basic_lines.append(basic_line)
return basic_lines
def ascii_listing2program_dump(self, basic_program_ascii, program_start=None):
"""
convert a ASCII BASIC program listing into tokens.
This tokens list can be used to insert it into the
Emulator RAM.
"""
if program_start is None:
program_start = self.DEFAULT_PROGRAM_START
basic_lines = self.ascii_listing2basic_lines(basic_program_ascii, program_start)
program_dump = self.listing.basic_lines2program_dump(basic_lines, program_start)
assert isinstance(program_dump, bytearray), "is type: {} and not bytearray: {}".format(
type(program_dump), repr(program_dump)
)
return program_dump
def pformat_tokens(self, tokens):
"""
format a tokenized BASIC program line. Useful for debugging.
returns a list of formated string lines.
"""
return self.listing.token_util.pformat_tokens(tokens)
def pformat_program_dump(self, program_dump, program_start=None):
"""
format a BASIC program dump. Useful for debugging.
returns a list of formated string lines.
"""
assert isinstance(program_dump, bytearray)
if program_start is None:
program_start = self.DEFAULT_PROGRAM_START
return self.listing.pformat_program_dump(program_dump, program_start)
def renum_ascii_listing(self, content):
return self.renum_tool.renum(content)
def reformat_ascii_listing(self, basic_program_ascii):
parsed_lines = self.parse_ascii_listing(basic_program_ascii)
ascii_lines = []
for line_no, code_objects in sorted(parsed_lines.items()):
print()
print(line_no, code_objects)
basic_line = BasicLine(self.token_util)
basic_line.code_objects_load(line_no, code_objects)
print(basic_line)
basic_line.reformat()
new_line = basic_line.get_content()
print(new_line)
ascii_lines.append(new_line)
return "\n".join(ascii_lines)
def bas2bin(self, basic_program_ascii, load_address=None, exec_address=None):
# FIXME: load_address/exec_address == program_start ?!?!
if load_address is None:
load_address = self.DEFAULT_PROGRAM_START
if exec_address is None:
exec_address = self.DEFAULT_PROGRAM_START
tokenised_dump = self.ascii_listing2program_dump(basic_program_ascii, load_address)
log.debug(type(tokenised_dump))
log.debug(repr(tokenised_dump))
log_bytes(tokenised_dump, msg="tokenised: %s")
binary_file = BinaryFile()
binary_file.load_tokenised_dump(
tokenised_dump,
load_address=load_address,
exec_address=exec_address,
)
binary_file.debug2log(level=logging.CRITICAL)
data = binary_file.dump_DragonDosBinary()
return data
def bin2bas(self, data):
"""
convert binary files to a ASCII basic string.
Supported are:
* Dragon DOS Binary Format
* TODO: CoCo DECB (Disk Extended Color BASIC) Format
see:
http://archive.worldofdragon.org/phpBB3/viewtopic.php?f=8&t=348&p=10139#p10139
"""
data = bytearray(data)
binary_file = BinaryFile()
binary_file.load_from_bin(data)
if binary_file.file_type != 0x01:
log.error("ERROR: file type $%02X is not $01 (tokenised BASIC)!", binary_file.file_type)
ascii_lines = self.program_dump2ascii_lines(
dump=binary_file.data,
# FIXME:
# program_start=bin.exec_address
program_start=binary_file.load_address,
)
return "\n".join(ascii_lines)
|
class BaseAPI:
def __init__(self):
pass
def program_dump2ascii_lines(self, dump, program_start=None):
'''
convert a memory dump of a tokensized BASIC listing into
ASCII listing list.
'''
pass
def parse_ascii_listing(self, basic_program_ascii):
pass
def ascii_listing2basic_lines(self, basic_program_ascii, program_start):
pass
def ascii_listing2program_dump(self, basic_program_ascii, program_start=None):
'''
convert a ASCII BASIC program listing into tokens.
This tokens list can be used to insert it into the
Emulator RAM.
'''
pass
def pformat_tokens(self, tokens):
'''
format a tokenized BASIC program line. Useful for debugging.
returns a list of formated string lines.
'''
pass
def pformat_program_dump(self, program_dump, program_start=None):
'''
format a BASIC program dump. Useful for debugging.
returns a list of formated string lines.
'''
pass
def renum_ascii_listing(self, content):
pass
def reformat_ascii_listing(self, basic_program_ascii):
pass
def bas2bin(self, basic_program_ascii, load_address=None, exec_address=None):
pass
def bin2bas(self, data):
'''
convert binary files to a ASCII basic string.
Supported are:
* Dragon DOS Binary Format
* TODO: CoCo DECB (Disk Extended Color BASIC) Format
see:
http://archive.worldofdragon.org/phpBB3/viewtopic.php?f=8&t=348&p=10139#p10139
'''
pass
| 12 | 5 | 12 | 2 | 8 | 3 | 2 | 0.33 | 0 | 8 | 6 | 1 | 11 | 3 | 11 | 11 | 147 | 29 | 89 | 34 | 77 | 29 | 78 | 34 | 66 | 3 | 0 | 1 | 20 |
1,444 |
6809/dragonlib
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/6809_dragonlib/dragonlib/tests/test_readme_history.py
|
dragonlib.tests.test_readme_history.ReadmeHistoryTestCase
|
class ReadmeHistoryTestCase(TestCase):
@skipIf(
# After a release the history may be "changed" because of version bump
# and we should not block merge requests because of this.
'GITHUB_ACTION' in os.environ,
reason='Skip on github actions',
)
def test_readme_history(self):
git_history = get_git_history(
current_version=dragonlib.__version__,
add_author=False,
)
history = '\n'.join(git_history)
assert_readme_block(
readme_path=PACKAGE_ROOT / 'README.md',
text_block=f'\n{history}\n',
start_marker_line='[comment]: <> (✂✂✂ auto generated history start ✂✂✂)',
end_marker_line='[comment]: <> (✂✂✂ auto generated history end ✂✂✂)',
)
|
class ReadmeHistoryTestCase(TestCase):
@skipIf(
# After a release the history may be "changed" because of version bump
# and we should not block merge requests because of this.
'GITHUB_ACTION' in os.environ,
reason='Skip on github actions',
)
def test_readme_history(self):
pass
| 3 | 0 | 12 | 0 | 12 | 0 | 1 | 0.12 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 19 | 0 | 17 | 8 | 11 | 2 | 5 | 4 | 3 | 1 | 2 | 0 | 1 |
1,445 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.HyperloglogTestCase
|
class HyperloglogTestCase(BaseTestCase):
class Data(redpipe.HyperLogLog):
keyspace = 'HYPERLOGLOG'
def test(self):
key1 = '1'
key2 = '2'
key3 = '3'
with redpipe.autoexec() as pipe:
c = self.Data(pipe=pipe)
pfadd = c.pfadd(key1, 'a', 'b', 'c')
pfcount = c.pfcount(key1)
c.pfadd(key2, 'b', 'c', 'd')
pfmerge = c.pfmerge(key3, key1, key2)
pfcount_aftermerge = c.pfcount(key3)
self.assertEqual(pfadd, 1)
self.assertEqual(pfcount, 3)
self.assertEqual(pfmerge, True)
self.assertEqual(pfcount_aftermerge, 4)
|
class HyperloglogTestCase(BaseTestCase):
class Data(redpipe.HyperLogLog):
def test(self):
pass
| 3 | 0 | 16 | 1 | 15 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 77 | 20 | 2 | 18 | 13 | 15 | 0 | 18 | 12 | 15 | 1 | 3 | 1 | 1 |
1,446 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.HashTestCase
|
class HashTestCase(StrictHashTestCase):
@classmethod
def setUpClass(cls):
cls.r = redislite.Redis()
redpipe.connect_redis(cls.r)
|
class HashTestCase(StrictHashTestCase):
@classmethod
def setUpClass(cls):
pass
| 3 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 79 | 5 | 0 | 5 | 3 | 2 | 0 | 4 | 2 | 2 | 1 | 4 | 0 | 1 |
1,447 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.HashFieldsTestCase
|
class HashFieldsTestCase(BaseTestCase):
class Data(redpipe.Hash):
keyspace = 'HASH'
fields = {
'b': redpipe.BooleanField(),
'i': redpipe.IntegerField(),
'f': redpipe.FloatField(),
't': redpipe.TextField(),
'l': redpipe.ListField(),
'd': redpipe.DictField(),
'sl': redpipe.StringListField(),
}
def test(self):
key = '1'
with redpipe.autoexec() as pipe:
c = self.Data(pipe=pipe)
hset = c.hset(key, 'i', 1)
hmset = c.hmset(key, {'b': True, 'f': 3.1, 't': utf8_sample})
hsetnx = c.hsetnx(key, 'b', False)
hget = c.hget(key, 'b')
hgetall = c.hgetall(key)
hincrby = c.hincrby(key, 'i', 2)
hincrbyfloat = c.hincrbyfloat(key, 'f', 2.1)
hmget = c.hmget(key, ['f', 'b'])
self.assertEqual(hset, True)
self.assertEqual(hmset, True)
self.assertEqual(hsetnx.result, 0)
self.assertEqual(hget, True)
self.assertEqual(
hgetall.result,
{'b': True, 'i': 1, 'f': 3.1, 't': utf8_sample})
self.assertEqual(hincrby.result, 3)
self.assertEqual(hincrbyfloat.result, 5.2)
self.assertEqual(hmget.result, [5.2, True])
def test_invalid_value(self):
key = '1'
with redpipe.pipeline() as pipe:
c = self.Data(pipe=pipe)
self.assertRaises(
redpipe.InvalidValue, lambda: c.hset(key, 'i', 'a'))
self.assertRaises(
redpipe.InvalidValue, lambda: c.hset(key, 't', 1))
c.hset(key, 'f', 1)
self.assertRaises(
redpipe.InvalidValue, lambda: c.hset(key, 'f', 'a'))
def test_dict(self):
key = 'd'
with redpipe.autoexec() as pipe:
data = {'a': 1, 'b': 'test'}
c = self.Data(pipe=pipe)
hset = c.hset(key, 'd', data)
hget = c.hget(key, 'd')
hmget = c.hmget(key, ['d'])
hgetall = c.hgetall(key, )
self.assertEqual(hset, 1)
self.assertEqual(hget, data)
self.assertEqual(hmget, [data])
self.assertEqual(hgetall, {'d': data})
def test_list(self):
key = '1'
with redpipe.autoexec() as pipe:
data = [1, 'a']
c = self.Data(pipe=pipe)
hset = c.hset(key, 'l', data)
hget = c.hget(key, 'l')
hmget = c.hmget(key, ['l'])
hgetall = c.hgetall(key, )
self.assertEqual(hset, 1)
self.assertEqual(hget, data)
self.assertEqual(hmget, [data])
self.assertEqual(hgetall, {'l': data})
def test_string_list(self):
key = '1'
with redpipe.autoexec() as pipe:
data = ['a', 'b']
c = self.Data(pipe=pipe)
hget_pre = c.hget(key, 'sl')
hset = c.hset(key, 'sl', data)
hget = c.hget(key, 'sl')
hmget = c.hmget(key, ['sl'])
hgetall = c.hgetall(key, )
self.assertEqual(hget_pre, None)
self.assertEqual(hset, 1)
self.assertEqual(hget, data)
self.assertEqual(hmget, [data])
self.assertEqual(hgetall, {'sl': data})
|
class HashFieldsTestCase(BaseTestCase):
class Data(redpipe.Hash):
def test(self):
pass
def test_invalid_value(self):
pass
def test_dict(self):
pass
def test_list(self):
pass
def test_string_list(self):
pass
| 7 | 0 | 16 | 1 | 15 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 5 | 0 | 5 | 81 | 97 | 11 | 86 | 48 | 79 | 0 | 73 | 43 | 66 | 1 | 3 | 1 | 5 |
1,448 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.FutureZeroTestCase
|
class FutureZeroTestCase(unittest.TestCase):
def setUp(self):
self.result = 0
self.future = redpipe.Future()
self.future.set(self.result)
def test(self):
self.assertEqual(repr(self.future), repr(self.result))
self.assertEqual(str(self.future), str(self.result))
self.assertEqual(self.future, self.result)
self.assertEqual(bool(self.future), bool(self.result))
self.assertTrue(self.future.IS(self.result))
self.assertEqual(hash(self.future), hash(self.result))
self.assertEqual(self.future + 1, self.result + 1)
self.assertEqual(1 + self.future, 1 + self.result)
self.assertEqual(self.future - 1, self.result - 1)
self.assertEqual(1 - self.future, 1 - self.result)
self.assertTrue(self.future < 2)
self.assertTrue(self.future <= 2)
self.assertTrue(self.future == 0)
self.assertTrue(self.future >= 0)
self.assertTrue(self.future != 2)
self.assertEqual(self.future * 1, self.result * 1)
self.assertEqual(pickle.loads(pickle.dumps(self.future)), self.result)
|
class FutureZeroTestCase(unittest.TestCase):
def setUp(self):
pass
def test(self):
pass
| 3 | 0 | 11 | 0 | 11 | 0 | 1 | 0 | 1 | 2 | 0 | 0 | 2 | 2 | 2 | 74 | 24 | 1 | 23 | 5 | 20 | 0 | 23 | 5 | 20 | 1 | 2 | 0 | 2 |
1,449 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.FutureTestCase
|
class FutureTestCase(unittest.TestCase):
def test(self):
f = redpipe.Future()
self.assertEqual(repr(f), repr(None))
self.assertRaises(redpipe.ResultNotReady, lambda: str(f))
self.assertRaises(redpipe.ResultNotReady, lambda: f[:])
|
class FutureTestCase(unittest.TestCase):
def test(self):
pass
| 2 | 0 | 5 | 0 | 5 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 73 | 6 | 0 | 6 | 3 | 4 | 0 | 6 | 3 | 4 | 1 | 2 | 0 | 1 |
1,450 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.FutureStringTestCase
|
class FutureStringTestCase(unittest.TestCase):
def setUp(self):
self.result = 'abc'
self.future = redpipe.Future()
self.future.set(self.result)
def test(self):
self.assertEqual(self.future[0:1], self.result[0:1])
self.assertEqual(len(self.future), len(self.result))
self.assertEqual(self.future + 'b', self.result + 'b')
self.assertEqual(self.future.split(), self.result.split())
self.assertEqual(repr(self.future), repr(self.result))
self.assertEqual(str(self.future), str(self.result))
self.assertEqual(self.future, self.result)
self.assertEqual(bool(self.future), bool(self.result))
|
class FutureStringTestCase(unittest.TestCase):
def setUp(self):
pass
def test(self):
pass
| 3 | 0 | 7 | 0 | 7 | 0 | 1 | 0 | 1 | 2 | 0 | 0 | 2 | 2 | 2 | 74 | 15 | 1 | 14 | 5 | 11 | 0 | 14 | 5 | 11 | 1 | 2 | 0 | 2 |
1,451 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.FutureNoneTestCase
|
class FutureNoneTestCase(unittest.TestCase):
def setUp(self):
self.result = None
self.future = redpipe.Future()
self.future.set(self.result)
def test(self):
self.assertEqual(repr(self.future), repr(self.result))
self.assertEqual(str(self.future), str(self.result))
self.assertEqual(self.future, self.result)
self.assertEqual(bool(self.future), bool(self.result))
self.assertTrue(self.future.IS(None))
self.assertTrue(redpipe.IS(self.future, None))
self.assertTrue(redpipe.IS(self.future, self.future))
self.assertTrue(self.future.isinstance(None.__class__))
self.assertTrue(redpipe.ISINSTANCE(self.future, None.__class__))
self.assertTrue(redpipe.ISINSTANCE(None, None.__class__))
self.assertEqual(pickle.loads(pickle.dumps(self.future)), self.result)
|
class FutureNoneTestCase(unittest.TestCase):
def setUp(self):
pass
def test(self):
pass
| 3 | 0 | 8 | 0 | 8 | 0 | 1 | 0 | 1 | 2 | 0 | 0 | 2 | 2 | 2 | 74 | 18 | 1 | 17 | 5 | 14 | 0 | 17 | 5 | 14 | 1 | 2 | 0 | 2 |
1,452 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.FutureListTestCase
|
class FutureListTestCase(unittest.TestCase):
def setUp(self):
self.result = ['a', 'b', 'c']
self.future = redpipe.Future()
self.future.set(self.result)
def test(self):
self.assertEqual(self.future, self.result)
self.assertEqual(list(self.future), list(self.result))
self.assertEqual([k for k in self.future], [k for k in self.result])
self.assertTrue('a' in self.future)
self.assertEqual(json.dumps(self.future), json.dumps(self.result))
self.assertEqual(self.future.id(), id(self.result))
self.assertEqual(self.future[1:-1], self.result[1:-1])
self.assertTrue(self.future.isinstance(self.result.__class__))
self.assertTrue(self.future.IS(self.result))
self.assertEqual([i for i in reversed(self.future)],
[i for i in reversed(self.result)])
|
class FutureListTestCase(unittest.TestCase):
def setUp(self):
pass
def test(self):
pass
| 3 | 0 | 8 | 0 | 8 | 0 | 1 | 0 | 1 | 2 | 0 | 0 | 2 | 2 | 2 | 74 | 18 | 1 | 17 | 5 | 14 | 0 | 16 | 5 | 13 | 1 | 2 | 0 | 2 |
1,453 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.FutureIntTestCase
|
class FutureIntTestCase(unittest.TestCase):
def setUp(self):
self.result = 1
self.future = redpipe.Future()
self.future.set(self.result)
def test(self):
self.assertEqual(repr(self.future), repr(self.result))
self.assertEqual(str(self.future), str(self.result))
self.assertEqual(self.future, self.result)
self.assertEqual(bool(self.future), bool(self.result))
self.assertTrue(self.future.IS(self.result))
self.assertEqual(hash(self.future), hash(self.result))
self.assertEqual(self.future + 1, self.result + 1)
self.assertEqual(1 + self.future, 1 + self.result)
self.assertEqual(self.future - 1, self.result - 1)
self.assertEqual(1 - self.future, 1 - self.result)
self.assertTrue(self.future < 2)
self.assertTrue(self.future <= 2)
self.assertTrue(self.future > 0)
self.assertTrue(self.future >= 1)
self.assertTrue(self.future != 2)
self.assertEqual(self.future * 1, self.result * 1)
self.assertEqual(1 * self.future, 1 * self.result)
self.assertEqual(self.future ** 1, self.result ** 1)
self.assertEqual(1 ** self.future, 1 ** self.result)
self.assertEqual(self.future / 1, self.result / 1)
self.assertEqual(1 / self.future, 1 / self.result)
self.assertEqual(self.future // 1, self.result // 1)
self.assertEqual(1 // self.future, 1 // self.result)
self.assertEqual(self.future % 1, self.result % 1)
self.assertEqual(1 % self.future, 1 % self.result)
self.assertEqual(self.future << 1, self.result << 1)
self.assertEqual(1 << self.future, 1 << self.result)
self.assertEqual(self.future >> 1, self.result >> 1)
self.assertEqual(1 >> self.future, 1 >> self.result)
self.assertEqual(self.future & 1, self.result & 1)
self.assertEqual(1 & self.future, 1 & self.result)
self.assertEqual(self.future | 1, self.result | 1)
self.assertEqual(1 | self.future, 1 | self.result)
self.assertEqual(self.future ^ 1, self.result ^ 1)
self.assertEqual(1 ^ self.future, 1 ^ self.result)
self.assertEqual(bytes(self.future), bytes(self.result))
self.assertEqual(int(self.future), int(self.result))
self.assertEqual(float(self.future), float(self.result))
self.assertEqual(round(self.future), round(self.result))
self.assertEqual(sum([self.future]), sum([self.result]))
|
class FutureIntTestCase(unittest.TestCase):
def setUp(self):
pass
def test(self):
pass
| 3 | 0 | 23 | 0 | 23 | 0 | 1 | 0 | 1 | 5 | 0 | 0 | 2 | 2 | 2 | 74 | 47 | 1 | 46 | 5 | 43 | 0 | 46 | 5 | 43 | 1 | 2 | 0 | 2 |
1,454 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.FutureDictTestCase
|
class FutureDictTestCase(unittest.TestCase):
def setUp(self):
self.result = {'a': 1, 'b': 2}
self.future = redpipe.Future()
self.future.set(self.result)
def test(self):
self.assertEqual(self.future.keys(), self.result.keys())
self.assertEqual(self.future.items(), self.result.items())
self.assertEqual(self.future, self.result)
self.assertEqual(dict(self.future), dict(self.result))
self.assertEqual([k for k in self.future], [k for k in self.result])
self.assertTrue('a' in self.future)
self.assertEqual(json.dumps(self.future), json.dumps(self.result))
self.assertRaises(TypeError, lambda: json.dumps(object()))
self.assertEqual(self.future.id(), id(self.result))
self.assertEqual(self.future['a'], self.result['a'])
self.assertRaises(KeyError, lambda: self.future['xyz'])
self.assertEqual(pickle.loads(pickle.dumps(self.future)), self.result)
|
class FutureDictTestCase(unittest.TestCase):
def setUp(self):
pass
def test(self):
pass
| 3 | 0 | 9 | 1 | 9 | 0 | 1 | 0 | 1 | 3 | 0 | 0 | 2 | 2 | 2 | 74 | 20 | 2 | 18 | 5 | 15 | 0 | 18 | 5 | 15 | 1 | 2 | 0 | 2 |
1,455 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.FutureCallableTestCase
|
class FutureCallableTestCase(unittest.TestCase):
def setUp(self):
def cb():
return True
self.result = cb
self.future = redpipe.Future()
self.future.set(self.result)
def test(self):
self.assertTrue(self.future)
self.assertEqual(bool(self.future), True)
|
class FutureCallableTestCase(unittest.TestCase):
def setUp(self):
pass
def cb():
pass
def test(self):
pass
| 4 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 2 | 2 | 2 | 74 | 12 | 2 | 10 | 6 | 6 | 0 | 10 | 6 | 6 | 1 | 2 | 0 | 3 |
1,456 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.FutureBooleanTestCase
|
class FutureBooleanTestCase(unittest.TestCase):
def setUp(self):
def cb():
return 1
self.result = cb
self.future = redpipe.Future()
self.future.set(self.result)
def test(self):
self.assertEqual(self.future, self.result)
self.assertEqual(self.future(), self.result())
self.assertEqual(self.future.id(), id(self.result))
self.assertTrue(self.future.isinstance(self.result.__class__))
self.assertTrue(self.future.IS(self.result))
|
class FutureBooleanTestCase(unittest.TestCase):
def setUp(self):
pass
def cb():
pass
def test(self):
pass
| 4 | 0 | 5 | 0 | 5 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 2 | 2 | 74 | 15 | 2 | 13 | 6 | 9 | 0 | 13 | 6 | 9 | 1 | 2 | 0 | 3 |
1,457 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.FieldsTestCase
|
class FieldsTestCase(unittest.TestCase):
def test_bool(self):
field = redpipe.BooleanField
self.assertEqual(field.encode(True), b'1')
self.assertEqual(field.encode('True'), b'1')
self.assertEqual(field.encode(False), b'')
self.assertEqual(field.encode('False'), b'')
self.assertEqual(field.encode('foo'), b'1')
def test_float(self):
field = redpipe.FloatField
self.assertRaises(redpipe.InvalidValue, lambda: field.encode(''))
self.assertRaises(redpipe.InvalidValue, lambda: field.encode('a'))
self.assertRaises(redpipe.InvalidValue, lambda: field.encode('1a'))
self.assertRaises(redpipe.InvalidValue, lambda: field.encode([]))
self.assertRaises(redpipe.InvalidValue, lambda: field.encode({}))
self.assertEqual(field.encode('1'), b'1')
self.assertEqual(field.encode(1), b'1')
self.assertEqual(field.encode(1.2), b'1.2')
self.assertEqual(field.encode(1.2345), b'1.2345')
self.assertEqual(field.decode('1'), 1)
self.assertEqual(field.decode('1.2'), 1.2)
self.assertEqual(field.decode('1.2345'), 1.2345)
self.assertRaises(ValueError, lambda: field.decode('x'))
def test_int(self):
field = redpipe.IntegerField
self.assertEqual(field.encode(0), b'0')
self.assertEqual(field.encode(2), b'2')
self.assertEqual(field.encode(123456), b'123456')
self.assertEqual(field.encode(1.2), b'1')
self.assertEqual(field.encode('1'), b'1')
self.assertEqual(field.encode(1), b'1')
self.assertRaises(redpipe.InvalidValue, lambda: field.encode(''))
self.assertRaises(redpipe.InvalidValue, lambda: field.encode('a'))
self.assertEqual(field.decode(b'1234'), 1234)
self.assertRaises(ValueError, lambda: field.decode('x'))
def test_text(self):
field = redpipe.TextField
self.assertRaises(redpipe.InvalidValue, lambda: field.encode(1))
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode(False))
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode(0.12345))
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode([]))
self.assertEqual(field.encode('d'), b'd')
self.assertEqual(field.encode(json.loads('"15\u00f8C"')),
b'15\xc3\xb8C')
self.assertEqual(field.encode(''), b'')
self.assertEqual(field.encode('a'), b'a')
self.assertEqual(field.encode('1'), b'1')
self.assertEqual(field.encode('1.2'), b'1.2')
self.assertEqual(field.encode('abc123$!'), b'abc123$!')
sample = json.loads('"15\u00f8C"')
self.assertEqual(
field.decode(field.encode(sample)),
sample
)
self.assertEqual(
field.decode(field.encode(utf8_sample)),
utf8_sample
)
def test_ascii(self):
field = redpipe.AsciiField
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode(1))
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode(False))
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode(0.1))
self.assertEqual(field.encode(''), b'')
self.assertEqual(field.encode('dddd'), b'dddd')
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode(json.loads('"15\u00f8C"')))
self.assertEqual(field.encode('1'), b'1')
self.assertEqual(field.encode('1.2'), b'1.2')
self.assertEqual(field.encode('abc123$!'), b'abc123$!')
sample = '#$%^&*()!@#aABc'
self.assertEqual(
field.decode(field.encode(sample)),
sample
)
def test_binary(self):
field = redpipe.BinaryField
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode(1))
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode(False))
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode(0.1))
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode(''))
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode('dddd'))
sample = json.loads('"15\u00f8C"')
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode(sample))
self.assertEqual(field.encode(b'1'), b'1')
self.assertEqual(field.encode(b'1.2'), b'1.2')
self.assertEqual(field.encode(b'abc123$!'), b'abc123$!')
sample = b'#$%^&*()!@#aABc'
self.assertEqual(
field.decode(field.encode(sample)),
sample
)
self.assertEqual(
field.decode(field.encode(sample)),
sample
)
sample = uuid.uuid4().bytes
self.assertEqual(
field.decode(field.encode(sample)),
sample
)
def test_list(self):
field = redpipe.ListField
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode(1))
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode(False))
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode(0.1))
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode('ddd'))
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode({}))
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode({'a': 1}))
self.assertEqual(field.encode([1]), b'[1]')
data = ['a', 1]
self.assertEqual(
field.decode(field.encode(data)),
data)
self.assertEqual(field.decode(data), data)
def test_dict(self):
field = redpipe.DictField
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode(1))
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode(False))
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode(0.1))
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode('ddd'))
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode([]))
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode([1]))
self.assertEqual(field.encode({'a': 1}), b'{"a": 1}')
data = {'a': 1}
self.assertEqual(
field.decode(field.encode(data)),
data)
self.assertEqual(field.decode(data), data)
def test_string_list(self):
field = redpipe.StringListField
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode(1))
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode(False))
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode(0.1))
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode('ddd'))
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode([1]))
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode({}))
self.assertRaises(redpipe.InvalidValue,
lambda: field.encode({'a': 1}))
self.assertEqual(field.encode(['1']), b'1')
data = ['a', 'b', 'c']
self.assertEqual(
field.decode(field.encode(data)),
data)
self.assertEqual(field.decode(data), data)
self.assertIsNone(field.decode(b''))
self.assertIsNone(field.decode(None))
self.assertIsNone(field.decode({}))
|
class FieldsTestCase(unittest.TestCase):
def test_bool(self):
pass
def test_float(self):
pass
def test_int(self):
pass
def test_text(self):
pass
def test_ascii(self):
pass
def test_binary(self):
pass
def test_list(self):
pass
def test_dict(self):
pass
def test_string_list(self):
pass
| 10 | 0 | 22 | 2 | 20 | 0 | 1 | 0.01 | 1 | 4 | 3 | 0 | 9 | 0 | 9 | 81 | 208 | 30 | 178 | 25 | 168 | 2 | 121 | 25 | 111 | 1 | 2 | 0 | 9 |
1,458 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.DictKeysTestCase
|
class DictKeysTestCase(BaseTestCase):
# "Tests a bug with dict-keys not being properly treated as a list"
class Data(redpipe.Hash):
keyspace = 'HASH'
def test(self):
with redpipe.autoexec() as pipe:
key = '1'
c = self.Data(pipe=pipe)
hset = c.hset(key, 'a', '1')
hmset = c.hmset(key, {'b': '2', 'c': '3', 'd': '4'})
hlen = c.hlen(key, )
hdel = c.hdel(key, 'a', 'b')
hkeys = c.hkeys(key)
hexists = c.hexists(key, 'c')
hincrby = c.hincrby(key, 'd', 2)
hmget = c.hmget(key, {'c': 'TEST', 'd': 'TET123'}.keys())
hvals = c.hvals(key)
self.assertEqual(hset.result, True)
self.assertEqual(hmset.result, True)
self.assertEqual(hlen.result, 4)
self.assertEqual(hdel.result, 2)
self.assertEqual(set(hkeys.result), {'c', 'd'})
self.assertTrue(hexists.result)
self.assertEqual(hincrby.result, 6)
self.assertEqual(set(hmget.result), {'3', '6'})
self.assertEqual(set(hvals.result), {'3', '6'})
self.assertEqual(c._parse_values(True), [True])
self.assertEqual(c._parse_values(1), [1])
|
class DictKeysTestCase(BaseTestCase):
class Data(redpipe.Hash):
def test(self):
pass
| 3 | 0 | 26 | 2 | 24 | 0 | 1 | 0.04 | 1 | 2 | 1 | 0 | 1 | 0 | 1 | 77 | 31 | 3 | 27 | 16 | 24 | 1 | 27 | 15 | 24 | 1 | 3 | 1 | 1 |
1,459 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.ConnectTestCase
|
class ConnectTestCase(unittest.TestCase):
def tearDown(self):
redpipe.reset()
def incr_a(self, key, pipe=None):
with redpipe.autoexec(pipe, name='a') as pipe:
return pipe.incr(key)
def incr_b(self, key, pipe=None):
with redpipe.autoexec(pipe, name='b') as pipe:
return pipe.incr(key)
def test(self):
r = redislite.Redis()
redpipe.connect_redis(r)
redpipe.connect_redis(r)
self.assertRaises(
redpipe.AlreadyConnected,
lambda: redpipe.connect_redis(redislite.Redis()))
redpipe.disconnect()
redpipe.connect_redis(redislite.Redis())
# tear down the connection
redpipe.disconnect()
# calling it multiple times doesn't hurt anything
redpipe.disconnect()
redpipe.connect_redis(r)
redpipe.connect_redis(
redis.Redis(connection_pool=r.connection_pool))
redpipe.connect_redis(r)
self.assertRaises(
redpipe.AlreadyConnected,
lambda: redpipe.connect_redis(
redislite.Redis()))
def test_with_decode_responses(self):
def connect():
redpipe.connect_redis(
redislite.Redis(decode_responses=True))
self.assertRaises(redpipe.InvalidPipeline, connect)
def test_single_nested(self):
redpipe.connect_redis(redislite.Redis(), 'a')
def mid_level(pipe=None):
with redpipe.autoexec(pipe, name='a') as pipe:
return self.incr_a('foo', pipe=pipe)
def top_level(pipe=None):
with redpipe.autoexec(pipe, name='a') as pipe:
return mid_level(pipe)
with redpipe.autoexec(name='a') as pipe:
ref = top_level(pipe)
self.assertRaises(redpipe.ResultNotReady, lambda: ref.result)
self.assertEqual(ref.result, 1)
def test_sync(self):
try:
redpipe.disable_threads()
self.assertEqual(redpipe.tasks.TaskManager.task,
redpipe.tasks.SynchronousTask)
self.test_single_nested()
self.tearDown()
self.test_pipeline_nested_mismatched_name()
self.tearDown()
self.test_multi_invalid_connection()
self.tearDown()
self.test_sleeping_cb()
finally:
redpipe.enable_threads()
self.assertEqual(redpipe.tasks.TaskManager.task,
redpipe.tasks.AsynchronousTask)
def test_sleeping_cb(self):
redpipe.connect_redis(redislite.Redis(), 'a')
redpipe.connect_redis(redislite.Redis(), 'b')
with redpipe.autoexec(name='a') as pipe:
pipe.set('foo', '1')
with redpipe.autoexec(pipe=pipe, name='b') as p:
ref = p.blpop('1', timeout=1)
self.assertEqual(ref.result, None)
def test_multi(self):
a_conn = redislite.Redis()
b_conn = redislite.Redis()
redpipe.connect_redis(a_conn, name='a')
redpipe.connect_redis(b_conn, name='b')
key = 'foo'
verify_callback = []
with redpipe.pipeline() as pipe:
a = self.incr_a(key, pipe)
b = self.incr_b(key, pipe)
def cb():
verify_callback.append(1)
pipe.on_execute(cb)
pipe.execute()
self.assertEqual(a.result, 1)
self.assertEqual(b.result, 1)
self.assertEqual(verify_callback, [1])
# test failure
try:
with redpipe.autoexec() as pipe:
a = self.incr_a(key, pipe)
raise Exception('boo')
except Exception:
pass
self.assertRaises(redpipe.ResultNotReady, lambda: a.result)
def test_multi_auto(self):
a_conn = redislite.Redis()
b_conn = redislite.Redis()
redpipe.connect_redis(a_conn)
redpipe.connect_redis(a_conn, name='a')
redpipe.connect_redis(b_conn, name='b')
key = 'foo'
verify_callback = []
with redpipe.autoexec() as pipe:
a = self.incr_a(key, pipe)
b = self.incr_b(key, pipe)
def cb():
verify_callback.append(1)
pipe.on_execute(cb)
self.assertEqual(a.result, 1)
self.assertEqual(b.result, 1)
self.assertEqual(verify_callback, [1])
def test_multi_invalid_connection(self):
a_conn = redislite.Redis()
b_conn = redislite.Redis(port=987654321)
redpipe.connect_redis(a_conn, name='a')
redpipe.connect_redis(b_conn, name='b')
key = 'foo'
verify_callback = []
with redpipe.pipeline(name='a') as pipe:
a = self.incr_a(key, pipe)
b = self.incr_b(key, pipe)
def cb():
verify_callback.append(1)
pipe.on_execute(cb)
self.assertRaises(redis.ConnectionError, pipe.execute)
# you can see here that it's not a 2-phase commit.
# the goal is not tranactional integrity.
# it is parallel execution of network tasks.
self.assertRaises(redpipe.ResultNotReady, lambda: a.result)
self.assertRaises(redpipe.ResultNotReady, lambda: b.result)
self.assertEqual(verify_callback, [])
def test_pipeline_mismatched_name(self):
a_conn = redislite.Redis()
b_conn = redislite.Redis()
redpipe.connect_redis(a_conn, name='a')
redpipe.connect_redis(b_conn, name='b')
with redpipe.pipeline(name='b') as pipe:
ref = self.incr_a(key='foo', pipe=pipe)
self.assertRaises(redpipe.ResultNotReady, lambda: ref.result)
pipe.execute()
def test_pipeline_nested_mismatched_name(self):
a_conn = redislite.Redis()
b_conn = redislite.Redis()
redpipe.connect_redis(a_conn, name='a')
redpipe.connect_redis(b_conn, name='b')
def my_function(pipe=None):
with redpipe.pipeline(pipe=pipe, name='b') as pipe:
ref = self.incr_a(key='foo', pipe=pipe)
self.assertRaises(redpipe.ResultNotReady, lambda: ref.result)
pipe.execute()
return ref
with redpipe.pipeline(name='a') as pipe:
ref1 = my_function(pipe=pipe)
ref2 = my_function(pipe=pipe)
self.assertRaises(redpipe.ResultNotReady, lambda: ref1.result)
self.assertRaises(redpipe.ResultNotReady, lambda: ref2.result)
pipe.execute()
self.assertEqual(ref1.result, 1)
self.assertEqual(ref2.result, 2)
def test_pipeline_invalid_object(self):
a_conn = redislite.Redis()
b_conn = redislite.Redis()
redpipe.connect_redis(a_conn)
redpipe.connect_redis(a_conn, name='a')
redpipe.connect_redis(b_conn, name='b')
def do_invalid():
self.incr_a(key='foo', pipe='invalid')
self.assertRaises(redpipe.InvalidPipeline, do_invalid)
def test_unconfigured_pipeline(self):
def invalid():
self.incr_a(key='foo')
def nested_invalid():
with redpipe.autoexec() as pipe:
self.incr_a(key='foo', pipe=pipe)
self.assertRaises(redpipe.InvalidPipeline, invalid)
self.assertRaises(redpipe.InvalidPipeline, nested_invalid)
|
class ConnectTestCase(unittest.TestCase):
def tearDown(self):
pass
def incr_a(self, key, pipe=None):
pass
def incr_b(self, key, pipe=None):
pass
def test(self):
pass
def test_with_decode_responses(self):
pass
def connect():
pass
def test_single_nested(self):
pass
def mid_level(pipe=None):
pass
def top_level(pipe=None):
pass
def test_sync(self):
pass
def test_sleeping_cb(self):
pass
def test_multi(self):
pass
def cb():
pass
def test_multi_auto(self):
pass
def cb():
pass
def test_multi_invalid_connection(self):
pass
def cb():
pass
def test_pipeline_mismatched_name(self):
pass
def test_pipeline_nested_mismatched_name(self):
pass
def my_function(pipe=None):
pass
def test_pipeline_invalid_object(self):
pass
def do_invalid():
pass
def test_unconfigured_pipeline(self):
pass
def invalid():
pass
def nested_invalid():
pass
| 26 | 0 | 10 | 1 | 8 | 0 | 1 | 0.03 | 1 | 5 | 3 | 0 | 15 | 0 | 15 | 87 | 227 | 49 | 172 | 66 | 146 | 6 | 162 | 57 | 136 | 2 | 2 | 2 | 26 |
1,460 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.Issue2NamedConnectionsTestCase
|
class Issue2NamedConnectionsTestCase(unittest.TestCase):
conn = redislite.Redis()
class T(redpipe.Struct):
connection = 't'
keyspace = 't'
fields = {
'foo': redpipe.IntegerField()
}
class H(redpipe.Hash):
connection = 't'
keyspace = 'h'
def setUp(self):
redpipe.connect_redis(self.conn, 't')
def tearDown(self):
redpipe.reset()
def test_struct(self):
with redpipe.pipeline(name='t', autoexec=True) as pipe:
self.T('1', pipe=pipe, no_op=True).incr('foo', 10)
with redpipe.pipeline(name=None, autoexec=True) as pipe:
c = self.T('1', pipe=pipe)
self.assertEqual(c['foo'], 10)
self.assertEqual(c['_key'], '1')
def test_hash(self):
with redpipe.pipeline(name='t', autoexec=True) as pipe:
h = self.H(pipe=pipe)
h.hincrby('foo', 'val', 3)
res = h.hget('foo', 'val')
self.assertEqual(res, '3')
|
class Issue2NamedConnectionsTestCase(unittest.TestCase):
class T(redpipe.Struct):
class H(redpipe.Hash):
def setUp(self):
pass
def tearDown(self):
pass
def test_struct(self):
pass
def test_hash(self):
pass
| 7 | 0 | 5 | 0 | 4 | 0 | 1 | 0 | 1 | 2 | 2 | 0 | 4 | 0 | 4 | 76 | 36 | 8 | 28 | 18 | 21 | 0 | 26 | 16 | 19 | 1 | 2 | 1 | 4 |
1,461 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.ListTestCase
|
class ListTestCase(StrictListTestCase):
@classmethod
def setUpClass(cls):
cls.r = redislite.Redis()
redpipe.connect_redis(cls.r)
|
class ListTestCase(StrictListTestCase):
@classmethod
def setUpClass(cls):
pass
| 3 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 81 | 5 | 0 | 5 | 3 | 2 | 0 | 4 | 2 | 2 | 1 | 4 | 0 | 1 |
1,462 |
72squared/redpipe
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
|
test.StructTestCase.UserWithAttributes
|
class UserWithAttributes(StructUser):
field_attr_on = True
keyspace = 'U'
fields = {
'first_name': redpipe.TextField(),
'last_name': redpipe.TextField(),
}
|
class UserWithAttributes(StructUser):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 7 | 0 | 7 | 4 | 6 | 0 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
1,463 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.RedisClusterTestCase
|
class RedisClusterTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.c = SingleNodeRedisCluster()
cls.r = cls.c.client
redpipe.connect_redis(cls.r)
@classmethod
def tearDownClass(cls):
cls.r = None
cls.c.shutdown()
cls.c = None
redpipe.reset()
def tearDown(self):
self.r.flushall()
def test_basic(self):
with redpipe.autoexec() as pipe:
pipe.set('foo', 'bar')
res = pipe.get('foo')
self.assertEqual(res, b'bar')
def test_list(self):
class Test(redpipe.List):
keyspace = 'T'
with redpipe.autoexec() as pipe:
t = Test(pipe)
append = t.rpush('1', 'a', 'b', 'c')
lrange = t.lrange('1', 0, -1)
lpop = t.lpop('1')
self.assertEqual(append, 3)
self.assertEqual(lrange, ['a', 'b', 'c'])
self.assertEqual(lpop, 'a')
def test_set(self):
class Test(redpipe.Set):
keyspace = 'T'
with redpipe.autoexec() as pipe:
t = Test(pipe)
sadd = t.sadd('1', 'a', 'b', 'c')
smembers = t.smembers('1')
spop = t.spop('1')
scard = t.scard('1')
expected = {'a', 'b', 'c'}
self.assertEqual(sadd, 3)
self.assertEqual(smembers, expected)
self.assertIn(spop, expected)
self.assertEqual(scard, 2)
def test_string(self):
class Test(redpipe.String):
keyspace = 'T'
with redpipe.autoexec() as pipe:
t = Test(pipe)
set_result = t.set('1', 'a')
get_result = t.get('1')
delete_result = t.delete('1')
self.assertEqual(set_result, 1)
self.assertEqual(get_result, 'a')
self.assertEqual(delete_result, 1)
def test_sorted_sets(self):
class Test(redpipe.SortedSet):
keyspace = 'T'
with redpipe.autoexec() as pipe:
t = Test(pipe)
t.zadd('1', 'a', 1)
t.zadd('1', 'b', 2)
zadd = t.zadd('1', 'c', 3)
zrange = t.zrange('1', 0, -1)
zincrby = t.zincrby('1', 'a', 1)
self.assertEqual(zadd, 1)
self.assertEqual(zrange, ['a', 'b', 'c'])
self.assertEqual(zincrby, 2)
def test_hll_commands(self):
class Test(redpipe.HyperLogLog):
keyspace = 'T'
with redpipe.autoexec() as pipe:
t = Test(pipe)
pfadd = t.pfadd('1', 'a', 'b', 'c')
t.pfadd('1', 'a', 'b', 'c')
t.pfadd('1', 'd')
pfcount = t.pfcount('1')
self.assertEqual(pfadd, 1)
self.assertEqual(pfcount, 4)
|
class RedisClusterTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
pass
@classmethod
def tearDownClass(cls):
pass
def tearDownClass(cls):
pass
def test_basic(self):
pass
def test_list(self):
pass
class Test(redpipe.List):
def test_set(self):
pass
class Test(redpipe.List):
def test_string(self):
pass
class Test(redpipe.List):
def test_sorted_sets(self):
pass
class Test(redpipe.List):
def test_hll_commands(self):
pass
class Test(redpipe.List):
| 17 | 0 | 10 | 1 | 8 | 0 | 1 | 0 | 1 | 6 | 6 | 0 | 7 | 0 | 9 | 81 | 97 | 18 | 79 | 50 | 62 | 0 | 77 | 42 | 62 | 1 | 2 | 1 | 9 |
1,464 |
72squared/redpipe
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
|
test.HashFieldsTestCase.Data
|
class Data(redpipe.Hash):
keyspace = 'HASH'
fields = {
'b': redpipe.BooleanField(),
'i': redpipe.IntegerField(),
'f': redpipe.FloatField(),
't': redpipe.TextField(),
'l': redpipe.ListField(),
'd': redpipe.DictField(),
'sl': redpipe.StringListField(),
}
|
class Data(redpipe.Hash):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 42 | 11 | 0 | 11 | 3 | 10 | 0 | 3 | 3 | 2 | 0 | 3 | 0 | 0 |
1,465 |
72squared/redpipe
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/redpipe/structs.py
|
redpipe.structs.StructMeta.__new__.StructHash
|
class StructHash(Hash):
keyspace = d.get('keyspace', name)
connection = d.get('connection', None)
fields = d.get('fields', {})
keyparse = d.get('keyparse', TextField)
valueparse = d.get('valueparse', TextField)
memberparse = d.get('memberparse', TextField)
keyspace_template = d.get('keyspace_template', '%s{%s}')
|
class StructHash(Hash):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 42 | 8 | 0 | 8 | 8 | 7 | 0 | 8 | 8 | 7 | 0 | 3 | 0 | 0 |
1,466 |
72squared/redpipe
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/redpipe/keyspaces.py
|
redpipe.keyspaces.HashedStringMeta.__new__.Core
|
class Core(Hash):
keyspace = d.get('keyspace', name)
connection = d.get('connection', None)
fields = d.get('fields', {})
keyparse = d.get('keyparse', TextField)
valueparse = d.get('valueparse', TextField)
memberparse = d.get('memberparse', TextField)
keyspace_template = d.get('keyspace_template', '%s{%s}')
|
class Core(Hash):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 | 0 | 8 | 8 | 7 | 0 | 8 | 8 | 7 | 0 | 1 | 0 | 0 |
1,467 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.SyncTestCase
|
class SyncTestCase(unittest.TestCase):
def test(self):
def sleeper():
time.sleep(0.3)
return 1
t = redpipe.tasks.SynchronousTask(target=sleeper)
t.start()
self.assertEqual(t.result, 1)
def test_exceptions(self):
def blow_up():
raise Exception('boom')
t = redpipe.tasks.SynchronousTask(target=blow_up)
t.start()
self.assertRaises(Exception, lambda: t.result)
|
class SyncTestCase(unittest.TestCase):
def test(self):
pass
def sleeper():
pass
def test_exceptions(self):
pass
def blow_up():
pass
| 5 | 0 | 5 | 1 | 5 | 0 | 1 | 0 | 1 | 2 | 1 | 0 | 2 | 0 | 2 | 74 | 17 | 3 | 14 | 7 | 9 | 0 | 14 | 7 | 9 | 1 | 2 | 0 | 4 |
1,468 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.StructUser
|
class StructUser(redpipe.Struct):
keyspace = 'U'
fields = {
'first_name': redpipe.TextField(),
'last_name': redpipe.TextField(),
}
@property
def name(self):
names = [self.get('first_name', None), self.get('last_name', None)]
return ' '.join([v for v in names if v is not None])
|
class StructUser(redpipe.Struct):
@property
def name(self):
pass
| 3 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 3 | 1 | 0 | 1 | 1 | 11 | 1 | 10 | 6 | 7 | 0 | 6 | 5 | 4 | 1 | 1 | 0 | 1 |
1,469 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.StructTestCase
|
class StructTestCase(BaseTestCase):
User = StructUser
class UserWithPk(StructUser):
key_name = 'user_id'
class UserWithAttributes(StructUser):
field_attr_on = True
keyspace = 'U'
fields = {
'first_name': redpipe.TextField(),
'last_name': redpipe.TextField(),
}
def test(self):
u = self.User('1')
self.assertFalse(u.persisted)
self.assertEqual(dict(u), {'_key': '1'})
u = self.UserWithAttributes({'_key': '1'})
self.assertEqual(u.first_name, None)
self.assertEqual(u.last_name, None)
u.update({'first_name': 'Fred', 'last_name': 'Flintstone'})
self.assertTrue(u.persisted)
u = self.UserWithAttributes('1')
self.assertTrue(u.persisted)
self.assertEqual(u['first_name'], 'Fred')
self.assertEqual(u.first_name, 'Fred')
self.assertEqual(u.last_name, 'Flintstone')
self.assertRaises(AttributeError, lambda: u.non_existent_field)
self.assertIn('U', str(u))
self.assertIn('1', str(u))
self.assertEqual(u['last_name'], 'Flintstone')
self.assertEqual('Fred Flintstone', u.name)
u.remove(['last_name', 'test_field'])
self.assertRaises(KeyError, lambda: u['last_name'])
self.assertRaises(AttributeError, lambda: u.non_existent_field)
u.update({'first_name': 'Wilma', 'arbitrary_field': 'a'})
self.assertEqual(u['first_name'], 'Wilma')
self.assertEqual(u.arbitrary_field, 'a')
u = self.UserWithAttributes('1')
core = self.User.core()
self.assertTrue(core.exists('1'))
self.assertEqual(u['first_name'], 'Wilma')
self.assertEqual('Wilma', u['first_name'])
with self.assertRaises(redpipe.InvalidOperation):
u.first_name = 'test'
with self.assertRaises(AttributeError):
u.non_existent_field = 1
with self.assertRaises(redpipe.InvalidOperation):
u['first_name'] = 'a'
with self.assertRaises(redpipe.InvalidOperation):
del u['first_name']
u_copy = dict(u)
u_clone = self.User(u, no_op=True)
u.clear()
self.assertFalse(core.exists('1'))
self.assertRaises(KeyError, lambda: u['first_name'])
self.assertEqual(u_clone['first_name'], 'Wilma')
self.assertFalse(u.persisted)
u = self.User(u_copy)
self.assertTrue(core.exists('1'))
self.assertEqual(u['first_name'], 'Wilma')
self.assertEqual(u['arbitrary_field'], 'a')
self.assertIn('_key', u)
self.assertEqual(u.key, '1')
self.assertEqual(u['_key'], '1')
self.assertEqual(repr(u), repr(dict(u)))
self.assertEqual(json.dumps(u), json.dumps(dict(u)))
u_pickled = pickle.loads(pickle.dumps(u))
self.assertEqual(u_pickled, u)
self.assertEqual(len(u), 3)
self.assertIn('first_name', u)
u.update({'first_name': 'Pebbles'})
self.assertEqual(core.hget(u.key, 'first_name'), 'Pebbles')
self.assertEqual(u['first_name'], 'Pebbles')
self.assertEqual(dict(u.copy()), dict(u))
self.assertEqual(u, dict(u))
self.assertEqual(u, u)
self.assertNotEqual(u, 1)
self.assertNotEqual(u, u.keys())
self.assertEqual({k for k in u}, set(u.keys()))
u.remove(['arbitrary_field'])
self.assertEqual(u.get('arbitrary_field'), None)
self.assertEqual(core.hget(u.key, 'arbitrary_field'), None)
u_pickled.update({'first_name': 'Dummy'})
self.assertEqual(u_pickled['first_name'], 'Dummy')
self.assertEqual(core.hget(u.key, 'first_name'), 'Dummy')
u = self.User('1')
with self.assertRaises(AttributeError):
assert (u.first_name is None)
with self.assertRaises(AttributeError):
u.first_name = 'test'
def fake_user_data(self, **kwargs):
data = {
'first_name': 'Bubba',
'last_name': 'Jones',
'email': '[email protected]',
}
data.update(kwargs)
return data
def test_empty_fields_init(self):
class Test(redpipe.Struct):
key_name = 't'
default_fields = 'all'
t = Test({'t': '1', 'orig': '1'})
self.assertEqual(t, {'t': '1', 'orig': '1'})
t = Test('1', fields=[])
self.assertEqual(t, {'t': '1'})
t = Test('1')
self.assertEqual(t, {'t': '1', 'orig': '1'})
t = Test({'t': '1', 'new': '1'}, fields=[])
self.assertEqual(t, {'t': '1', 'new': '1'})
def test_core(self):
data = self.fake_user_data(_key='1')
self.User(data)
ref = self.User.core().hgetall('1')
self.assertEqual(ref.result['first_name'], data['first_name'])
def test_pipeline(self):
user_ids = ["%s" % i for i in range(1, 3)]
with redpipe.autoexec() as pipe:
users = [self.User(self.fake_user_data(_key=i, b='123'), pipe=pipe)
for i in user_ids]
self.assertEqual([u.persisted for u in users],
[False for _ in user_ids])
retrieved_users = [self.User(i, pipe=pipe) for i in user_ids]
# before executing the pipe (exiting the with block),
# the data will not show as persisted.
# once pipe execute happens, it is persisted.
self.assertEqual(
[u.persisted for u in users],
[True for _ in user_ids])
self.assertEqual(
[u['b'] for u in retrieved_users],
['123' for _ in retrieved_users])
def test_fields(self):
class Multi(redpipe.Struct):
keyspace = 'M'
fields = {
'boolean': redpipe.BooleanField,
'integer': redpipe.IntegerField,
'float': redpipe.FloatField,
'text': redpipe.TextField,
}
data = {
'_key': 'm1',
'text': 'xyz',
'integer': 5,
'boolean': False,
'float': 2.123}
m = Multi(data)
expected = {'_key': 'm1'}
expected.update(data)
self.assertEqual(dict(m), expected)
self.assertEqual(m['boolean'], data['boolean'])
self.assertEqual(m.get('boolean'), data['boolean'])
self.assertEqual(m.get('non_existent', 'foo'), 'foo')
self.assertEqual(m.get('non_existent'), None)
data.update({'_key': 'm2'})
m = Multi(data)
self.assertEqual(dict(m), data)
m = Multi('m2')
self.assertEqual(dict(m), data)
self.assertRaises(
redpipe.InvalidValue,
lambda: Multi({'_key': 'm3', 'text': 123}))
def test_extra_fields(self):
data = self.fake_user_data(_key='1', first_name='Bob',
last_name='smith', nickname='BUBBA')
u = self.User(data)
u = self.User('1')
self.assertEqual(u['_key'], '1')
self.assertEqual(u['nickname'], 'BUBBA')
self.assertEqual(u.get('nickname'), 'BUBBA')
self.assertEqual(u.get('nonexistent', 'test'), 'test')
self.assertRaises(KeyError, lambda: u['nonexistent'])
def test_missing_fields(self):
data = self.fake_user_data(_key='1', first_name='Bob')
del data['last_name']
u = self.User(data)
u = self.User('1')
self.assertRaises(KeyError, lambda: u['last_name'])
def test_load_fields(self):
data = self.fake_user_data(_key='1', first_name='Bob')
u = self.User(data)
u = self.User('1', fields=['first_name', 'non_existent_field'])
self.assertEqual(u['first_name'], data['first_name'])
self.assertRaises(KeyError, lambda: u['last_name'])
self.assertRaises(KeyError, lambda: u['non_existent_field'])
def test_set(self):
data = self.fake_user_data(_key='1', first_name='Bob')
del data['last_name']
u = self.User(data)
with redpipe.autoexec() as pipe:
u.update({'first_name': 'Cool', 'last_name': 'Dude'}, pipe=pipe)
self.assertEqual(u['first_name'], 'Bob')
self.assertRaises(KeyError, lambda: u['last_name'])
self.assertEqual(u['first_name'], 'Cool')
self.assertEqual(u['last_name'], 'Dude')
def test_remove_pk(self):
data = self.fake_user_data(_key='1')
u = self.User(data)
self.assertRaises(redpipe.InvalidOperation,
lambda: u.remove(['_key']))
self.assertRaises(redpipe.InvalidOperation,
lambda: u.update({'_key': '2'}))
def test_custom_pk(self):
data = self.fake_user_data(user_id='1')
u = self.UserWithPk(data)
self.assertEqual(u['user_id'], '1')
self.assertIn('user_id', u)
u_copy = self.UserWithPk(u, no_op=True)
self.assertEqual(u_copy, u)
u = self.UserWithPk('1')
self.assertEqual(u_copy, u)
with self.assertRaises(AttributeError):
self.assertEqual(u.user_id, '1')
def test_custom_pk_attr(self):
class UserWithPkAttr(StructUser):
key_name = 'user_id'
field_attr_on = True
data = self.fake_user_data(user_id='1')
u = UserWithPkAttr(data)
self.assertEqual(u.user_id, '1')
def test_copy_with_no_pk(self):
data = {'first_name': 'Bill'}
self.assertRaises(redpipe.InvalidOperation,
lambda: self.User(data))
self.assertRaises(redpipe.InvalidOperation,
lambda: self.UserWithPk(data))
def test_incr(self):
key = '1'
class T(redpipe.Struct):
keyspace = 'T'
fields = {
}
field = 'arbitrary_field'
t = T(key)
t.incr(field)
self.assertEqual(t[field], '1')
with redpipe.autoexec() as pipe:
t.incr(field, pipe=pipe)
self.assertEqual(t[field], '1')
self.assertEqual(t[field], '2')
t.incr(field, 3)
self.assertEqual(t[field], '5')
t.decr(field)
self.assertEqual(t[field], '4')
t.decr(field, 2)
self.assertEqual(t[field], '2')
def test_typed_incr(self):
key = '1'
class T(redpipe.Struct):
keyspace = 'T'
fields = {
'counter': redpipe.IntegerField
}
field = 'counter'
t = T(key)
t.incr(field)
self.assertEqual(t[field], 1)
with redpipe.autoexec() as pipe:
t.incr(field, pipe=pipe)
self.assertEqual(t[field], 1)
self.assertEqual(t[field], 2)
t.incr(field, 3)
self.assertEqual(t[field], 5)
t.decr(field)
self.assertEqual(t[field], 4)
t.decr(field, 2)
self.assertEqual(t[field], 2)
arbitrary_field = t.pop(field)
self.assertEqual(arbitrary_field, 2)
self.assertEqual(t.get(field), None)
def test_delete(self):
keys = ['1', '2', '3']
for k in keys:
data = self.fake_user_data(_key=k)
self.User(data)
for k in keys:
u = self.User(k)
self.assertTrue(u.persisted)
self.User.delete(keys)
for k in keys:
u = self.User(k)
self.assertFalse(u.persisted)
def test_indirect_overlap_of_pk(self):
key = '1'
other_key = '2'
data = self.fake_user_data(user_id=key)
u = self.UserWithPk(data)
u.core().hset(key, 'user_id', other_key)
u = self.UserWithPk(key)
self.assertEqual(dict(u)['user_id'], key)
self.assertNotIn('user_id', u._data) # noqa
self.assertEqual(u.key, key)
def test_update_with_none_future(self):
f = redpipe.Future()
f.set(None)
data = self.fake_user_data(user_id='1')
u = self.UserWithPk(data)
u.update({'first_name': f})
u = self.UserWithPk('1')
self.assertRaises(KeyError, lambda: u['first_name'])
def test_with_empty_update(self):
class Test(redpipe.Struct):
keyspace = 'U'
fields = {
'a': redpipe.TextField,
}
key_name = 'k'
data = {'k': '1', 'a': 'foo', 'b': 'bar'}
t = Test(data)
t.update({})
self.assertEqual(t, data)
def test_fields_custom_default(self):
class Test(redpipe.Struct):
keyspace = 'U'
fields = {
'a': redpipe.TextField,
'b': redpipe.TextField,
}
default_fields = ['a']
key_name = 'k'
data = {'k': '1', 'a': 'foo', 'b': 'bar'}
t = Test(data)
self.assertEqual(t, data)
t = Test(data['k'])
self.assertEqual(t, {'k': '1', 'a': 'foo'})
t.load(['b'])
self.assertEqual(t, data)
t = Test(data['k'], fields='all')
self.assertEqual(t, data)
def test_fields_custom_default_defined_only(self):
class Test(redpipe.Struct):
keyspace = 'U'
fields = {
'a': redpipe.TextField,
'b': redpipe.TextField,
}
default_fields = 'defined'
key_name = 'k'
data = {'k': '1', 'a': 'foo', 'b': 'bar', 'c': 'bazz'}
t = Test(data)
self.assertEqual(t, data)
t = Test(data['k'])
self.assertEqual(t, {'k': '1', 'a': 'foo', 'b': 'bar'})
t.load(['c'])
self.assertEqual(t, data)
t = Test(data['k'], fields='all')
self.assertEqual(t, data)
def test_nx(self):
class Test(redpipe.Struct):
keyspace = 'U'
fields = {
'f1': redpipe.TextField,
'f2': redpipe.TextField,
}
key_name = 'k'
t = Test({'k': '1', 'f1': 'a'})
self.assertEqual(t['f1'], 'a')
t = Test({'k': '1', 'f1': 'b', 'f2': 'c'}, nx=True)
self.assertEqual(t['f1'], 'a')
self.assertEqual(t['f2'], 'c')
def test_required_fields(self):
class Test(redpipe.Struct):
keyspace = 'U'
fields = {
'a': redpipe.IntegerField,
'b': redpipe.IntegerField
}
required = set('b')
t = Test({'_key': 'abc', 'b': 123})
self.assertEqual(t['b'], 123)
with self.assertRaises(redpipe.InvalidOperation):
Test({'_key': 'abc', 'a': 123}) # Create obj w/o required field
with self.assertRaises(redpipe.InvalidOperation):
# Update obj removing a required field
t.update({'a': 456, 'b': None})
# Make sure the other fields did NOT update on the failed update
self.assertIsNone(t.get('a', None))
t.update({'a': 456, 'b': 789}) # Update required field of obj
self.assertEqual(t['a'], 456)
self.assertEqual(t['b'], 789)
t.update({'a': None}) # Update non-required field of obj
self.assertIsNone(t.get('a', None))
def test_required_adding_later(self):
class Test(redpipe.Struct):
keyspace = 'U'
fields = {
'a': redpipe.IntegerField,
'b': redpipe.IntegerField
}
class Test2(redpipe.Struct):
required = {'new_required_field'}
keyspace = 'U'
fields = {
'a': redpipe.IntegerField,
'b': redpipe.IntegerField
}
Test({'_key': 'abc', 'b': 123})
t = Test2('abc')
t.update({'b': 456, 'random_field': 'hello_world'})
self.assertEqual(t['b'], 456)
self.assertEqual(t['random_field'], 'hello_world')
self.assertIsNone(t.get('new_required_field', None))
with self.assertRaises(redpipe.InvalidOperation):
# Update obj removing a required field that didn't yet exist
t.update({'a': 456, 'new_required_field': None})
|
class StructTestCase(BaseTestCase):
class UserWithPk(StructUser):
class UserWithAttributes(StructUser):
def test(self):
pass
def fake_user_data(self, **kwargs):
pass
def test_empty_fields_init(self):
pass
class Test(redpipe.Struct):
def test_core(self):
pass
def test_pipeline(self):
pass
def test_fields(self):
pass
class Multi(redpipe.Struct):
def test_extra_fields(self):
pass
def test_missing_fields(self):
pass
def test_load_fields(self):
pass
def test_set(self):
pass
def test_remove_pk(self):
pass
def test_custom_pk(self):
pass
def test_custom_pk_attr(self):
pass
class UserWithPkAttr(StructUser):
def test_copy_with_no_pk(self):
pass
def test_incr(self):
pass
class Test(redpipe.Struct):
def test_typed_incr(self):
pass
class Test(redpipe.Struct):
def test_delete(self):
pass
def test_indirect_overlap_of_pk(self):
pass
def test_update_with_none_future(self):
pass
def test_with_empty_update(self):
pass
class Test(redpipe.Struct):
def test_fields_custom_default(self):
pass
class Test(redpipe.Struct):
def test_fields_custom_default_defined_only(self):
pass
class Test(redpipe.Struct):
def test_nx(self):
pass
class Test(redpipe.Struct):
def test_required_fields(self):
pass
class Test(redpipe.Struct):
def test_required_adding_later(self):
pass
class Test(redpipe.Struct):
class Test2(redpipe.Struct):
| 40 | 0 | 18 | 2 | 16 | 0 | 1 | 0.03 | 1 | 20 | 14 | 0 | 25 | 0 | 25 | 101 | 478 | 73 | 399 | 140 | 359 | 10 | 346 | 135 | 306 | 4 | 3 | 1 | 28 |
1,470 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.StructExpiresTestCase
|
class StructExpiresTestCase(unittest.TestCase):
conn = redislite.Redis()
class T(redpipe.Struct):
connection = 't'
keyspace = 't'
ttl = 30
fields = {
'foo': redpipe.IntegerField()
}
def setUp(self):
redpipe.connect_redis(self.conn, 't')
def tearDown(self):
redpipe.reset()
def test_set(self):
with redpipe.pipeline(name='t', autoexec=True) as pipe:
t = self.T('1', pipe=pipe, no_op=True)
t.update({'foo': 1})
pttl = self.T.core(pipe=pipe).pttl('1')
self.assertAlmostEqual(pttl, 30000, delta=50)
with redpipe.pipeline(name=None, autoexec=True) as pipe:
c = self.T('1', pipe=pipe)
pttl = self.T.core(pipe=pipe).pttl('1')
self.assertAlmostEqual(pttl, 30000, delta=100)
self.assertEqual(c['foo'], 1)
self.assertEqual(c['_key'], '1')
with redpipe.pipeline(name=None, autoexec=True) as pipe:
c = self.T('1', pipe=pipe, no_op=True)
c.remove(['foo'])
pttl = self.T.core(pipe=pipe).pttl('1')
self.assertEqual(pttl, -2)
with redpipe.pipeline(name=None, autoexec=True) as pipe:
c = self.T('1', pipe=pipe)
c.update({'foo': 1, 'bar': 'b'})
c.remove(['foo'])
pttl = self.T.core(pipe=pipe).pttl('1')
self.assertEqual(dict(c), {'_key': '1', 'bar': 'b'})
self.assertAlmostEqual(pttl, 30000, delta=50)
def test_incr(self):
with redpipe.pipeline(name='t', autoexec=True) as pipe:
self.T('1', pipe=pipe, no_op=True).incr('foo', 10)
pttl = self.T.core(pipe=pipe).pttl('1')
self.assertAlmostEqual(pttl, 30000, delta=50)
with redpipe.pipeline(name=None, autoexec=True) as pipe:
c = self.T('1', pipe=pipe)
pttl = self.T.core(pipe=pipe).pttl('1')
self.assertAlmostEqual(pttl, 30000, delta=100)
self.assertEqual(c['foo'], 10)
self.assertEqual(c['_key'], '1')
|
class StructExpiresTestCase(unittest.TestCase):
class T(redpipe.Struct):
def setUp(self):
pass
def tearDown(self):
pass
def test_set(self):
pass
def test_incr(self):
pass
| 6 | 0 | 13 | 3 | 10 | 0 | 1 | 0 | 1 | 2 | 1 | 0 | 4 | 0 | 4 | 76 | 65 | 17 | 48 | 18 | 42 | 0 | 46 | 16 | 40 | 1 | 2 | 1 | 4 |
1,471 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.BaseTestCase
|
class BaseTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.r = redislite.Redis()
redpipe.connect_redis(cls.r)
@classmethod
def tearDownClass(cls):
cls.r = None
redpipe.reset()
def setUp(self):
self.r.flushall()
def tearDown(self):
self.r.flushall()
|
class BaseTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
pass
@classmethod
def tearDownClass(cls):
pass
def setUpClass(cls):
pass
def tearDownClass(cls):
pass
| 7 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 11 | 2 | 0 | 4 | 76 | 16 | 3 | 13 | 7 | 6 | 0 | 11 | 5 | 6 | 1 | 2 | 0 | 4 |
1,472 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.StringTestCase
|
class StringTestCase(StrictStringTestCase):
@classmethod
def setUpClass(cls):
cls.r = redislite.Redis()
redpipe.connect_redis(cls.r)
|
class StringTestCase(StrictStringTestCase):
@classmethod
def setUpClass(cls):
pass
| 3 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 84 | 5 | 0 | 5 | 3 | 2 | 0 | 4 | 2 | 2 | 1 | 4 | 0 | 1 |
1,473 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.StrictSortedSetTestCase
|
class StrictSortedSetTestCase(BaseTestCase):
class Data(redpipe.SortedSet):
keyspace = 'SORTEDSET'
def test(self):
with redpipe.autoexec() as pipe:
key = '1'
s = self.Data(pipe=pipe)
s.zadd(key, '2', 2)
s.zadd(key, '3', 3)
add = s.zadd(key, '4', 4)
zaddincr = s.zadd(key, '4', 1, incr=True)
zscore_after_incr = s.zscore(key, '4')
zaddnx = s.zadd(key, '4', 4.1, nx=True)
zaddxx = s.zadd(key, '4', 4.2, xx=True)
zaddch = s.zadd(key, '4', 4.3, ch=True)
zscore = s.zscore(key, '4')
remove = s.zrem(key, '4')
members = s.zrange(key, 0, -1)
zaddmulti = s.zadd(key, {'4': 4, '5': 5})
zincrby = s.zincrby(key, '5', 2)
zrevrank = s.zrevrank(key, '5')
zrevrange = s.zrevrange(key, 0, 1)
zrange_withscores = s.zrange(key, 0, 1, withscores=True)
zrevrange_withscores = s.zrevrange(key, 0, 1, withscores=True)
self.assertRaises(
redpipe.InvalidOperation,
lambda: s.zadd(key, '4', 4, xx=True, nx=True))
s.delete(key)
zrange = s.zrange(key, 0, -1)
self.assertRaises(redpipe.ResultNotReady, lambda: members.result)
self.assertEqual(add.result, 1)
self.assertEqual(zaddincr.result, 5)
self.assertEqual(zscore_after_incr.result, 5)
self.assertEqual(zaddnx, 0)
self.assertEqual(zaddxx, 0)
self.assertEqual(zaddch, 1)
self.assertEqual(zscore, 4.3)
self.assertEqual(remove, 1)
self.assertEqual(members, ['2', '3'])
self.assertEqual(zaddmulti, 2)
self.assertEqual(zrange, [])
self.assertEqual(zincrby, 7.0)
self.assertEqual(zrevrank, 0)
self.assertEqual(zrevrange, ['5', '4'])
self.assertEqual(zrange_withscores, [('2', 2.0), ('3', 3.0)])
self.assertEqual(zrevrange_withscores, [('5', 7.0), ('4', 4.0)])
with redpipe.autoexec() as pipe:
key = '1'
s = self.Data(pipe=pipe)
s.zadd(key, 'a', 1)
s.zadd(key, 'b', 2)
zrangebyscore = s.zrangebyscore(key, 0, 10, start=0, num=1)
zrangebyscore_withscores = s.zrangebyscore(key,
0, 10, start=0, num=1,
withscores=True)
zrevrangebyscore = s.zrevrangebyscore(key, 10, 0, start=0, num=1)
zrevrangebyscore_withscores = s.zrevrangebyscore(key,
10, 0, start=0,
num=1,
withscores=True)
zcard = s.zcard(key)
zcount = s.zcount(key, '-inf', '+inf')
zrank = s.zrank(key, 'b')
zlexcount = s.zlexcount(key, '-', '+')
zrangebylex = s.zrangebylex(key, '-', '+')
zrevrangebylex = s.zrevrangebylex(key, '+', '-')
zremrangebyrank = s.zremrangebyrank(key, 0, 0)
zremrangebyscore = s.zremrangebyscore(key, 2, 2)
zremrangebylex = s.zremrangebylex(key, '-', '+')
self.assertEqual(zrangebyscore, ['a'])
self.assertEqual(zrangebyscore_withscores, [('a', 1.0)])
self.assertEqual(zrevrangebyscore, ['b'])
self.assertEqual(zrevrangebyscore_withscores, [('b', 2.0)])
self.assertEqual(zcard, 2)
self.assertEqual(zcount, 2)
self.assertEqual(zrank, 1)
self.assertEqual(zremrangebyrank, 1)
self.assertEqual(zremrangebyscore, 1)
self.assertEqual(zlexcount, 2)
self.assertEqual(zrangebylex, ['a', 'b'])
self.assertEqual(zrevrangebylex, ['b', 'a'])
self.assertEqual(zremrangebylex, 0)
def test_scan(self):
with redpipe.autoexec() as pipe:
key = '1'
s = self.Data(pipe=pipe)
s.zadd(key, 'a1', 1.0)
s.zadd(key, 'a2', 2)
s.zadd(key, 'b1', 1)
s.zadd(key, 'b2', 2)
sscan = s.zscan(key, 0, match='a*')
sort = s.sort(key, alpha=True)
sort_store = s.sort(key, alpha=True, store='store_result_key')
self.assertEqual(sscan[0], 0)
self.assertEqual(set(sscan[1]), {('a1', 1.0), ('a2', 2.0)})
self.assertEqual(sort, ['a1', 'a2', 'b1', 'b2'])
self.assertEqual(sort_store, 4)
with redpipe.autoexec() as pipe:
self.assertRaises(
redpipe.InvalidOperation,
lambda: {k for k in self.Data(pipe=pipe).zscan_iter(key)})
data = {k for k in self.Data().zscan_iter(key)}
expected = {('a1', 1.0), ('a2', 2.0), ('b1', 1.0), ('b2', 2.0)}
self.assertEqual(data, expected)
def test_union(self):
key1 = '1'
key2 = '2'
key3 = '3'
with redpipe.autoexec() as pipe:
s = self.Data(pipe=pipe)
s.zadd(key1, 'a', 1)
s.zadd(key1, 'b', 2)
s.zadd(key2, 'c', 3)
s.zadd(key2, 'd', 4)
zunionstore = s.zunionstore(key3, [key1, key2])
zrange = s.zrange(key3, 0, -1)
self.assertEqual(zunionstore, 4)
self.assertEqual(zrange, ['a', 'b', 'c', 'd'])
|
class StrictSortedSetTestCase(BaseTestCase):
class Data(redpipe.SortedSet):
def test(self):
pass
def test_scan(self):
pass
def test_union(self):
pass
| 5 | 0 | 41 | 2 | 38 | 0 | 1 | 0 | 1 | 2 | 1 | 1 | 3 | 0 | 3 | 79 | 128 | 10 | 118 | 53 | 113 | 0 | 109 | 50 | 104 | 1 | 3 | 1 | 3 |
1,474 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.StrictSetTestCase
|
class StrictSetTestCase(BaseTestCase):
class Data(redpipe.Set):
keyspace = 'SET'
def test(self):
with redpipe.autoexec() as pipe:
key = '1'
c = self.Data(pipe=pipe)
sadd = c.sadd(key, ['a', 'b', 'c'])
saddnx = c.sadd(key, 'a')
srem = c.srem(key, 'c')
smembers = c.smembers(key)
card = c.scard(key)
ismember_a = c.sismember(key, 'a')
c.srem(key, 'b')
ismember_b = c.sismember(key, 'b')
srandmember = c.srandmember(key)
srandmembers = c.srandmember(key, number=2)
spop = c.spop(key)
self.assertEqual(sadd.result, 3)
self.assertEqual(saddnx.result, 0)
self.assertEqual(srem.result, 1)
self.assertEqual(smembers.result, {'a', 'b'})
self.assertIn(spop.result, {'a', 'b'})
self.assertEqual(card.result, 2)
self.assertTrue(ismember_a.result)
self.assertFalse(ismember_b.result)
self.assertTrue(srandmember.result, b'a')
self.assertTrue(srandmembers.result, [b'a'])
def test_scan(self):
with redpipe.autoexec() as pipe:
key = '1'
s = self.Data(pipe=pipe)
s.sadd(key, 'a1', 'a2', 'b1', 'b2')
sscan = s.sscan(key, 0, match='a*')
self.assertEqual(sscan[0], 0)
self.assertEqual(set(sscan[1]), {'a1', 'a2'})
with redpipe.autoexec() as pipe:
self.assertRaises(
redpipe.InvalidOperation,
lambda: {k for k in self.Data(pipe=pipe).sscan_iter('1')})
data = {k for k in self.Data().sscan_iter('1')}
self.assertEqual(data, {'a1', 'a2', 'b1', 'b2'})
def test_sdiff(self):
key1 = '1'
key2 = '2'
key3 = '3'
with redpipe.autoexec() as pipe:
s = self.Data(pipe=pipe)
s.sadd(key1, 'a', 'b', 'c')
s.sadd(key2, 'a', 'b', 'd', 'e')
sdiff = s.sdiff(key2, key1)
sinter = s.sinter(key1, key2)
sinter_missing = s.sinter(key3, key2)
sdiffstore = s.sdiffstore(key3, key2, key1)
sdiffstore_get = s.smembers(key3)
sinterstore = s.sinterstore(key3, key2, key1)
sinterstore_get = s.smembers(key3)
sunion = s.sunion(key1, key2)
sunionstore = s.sunionstore(key3, key1, key2)
sunionstore_get = s.smembers(key3)
self.assertEqual(sdiff, {'e', 'd'})
self.assertEqual(sinter, {'a', 'b'})
self.assertEqual(sinter_missing, set())
self.assertEqual(sdiffstore, 2)
self.assertEqual(sdiffstore_get, {'e', 'd'})
self.assertEqual(sinterstore, 2)
self.assertEqual(sinterstore_get, {'a', 'b'})
self.assertEqual(sunion, {'a', 'b', 'c', 'd', 'e'})
self.assertEqual(sunionstore, 5)
self.assertEqual(sunionstore_get, {'a', 'b', 'c', 'd', 'e'})
|
class StrictSetTestCase(BaseTestCase):
class Data(redpipe.Set):
def test(self):
pass
def test_scan(self):
pass
def test_sdiff(self):
pass
| 5 | 0 | 24 | 2 | 22 | 0 | 1 | 0 | 1 | 2 | 1 | 1 | 3 | 0 | 3 | 79 | 78 | 8 | 70 | 39 | 65 | 0 | 68 | 36 | 63 | 1 | 3 | 1 | 3 |
1,475 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.StrictListTestCase
|
class StrictListTestCase(BaseTestCase):
class Data(redpipe.List):
keyspace = 'LIST'
def test(self):
with redpipe.autoexec() as pipe:
key = '1'
c = self.Data(pipe=pipe)
lpush = c.lpush(key, 'a', 'b', 'c', 'd')
members = c.lrange(key, 0, -1)
rpush = c.rpush(key, 'e')
llen = c.llen(key, )
lrange = c.lrange(key, 0, -1)
rpop = c.rpop(key)
lrem = c.lrem(key, 'a', 1)
ltrim = c.ltrim(key, 0, 1)
members_after_ltrim = c.lrange(key, 0, -1)
lindex = c.lindex(key, 1)
lset = c.lset(key, 1, 'a')
lindex_after = c.lindex(key, 1)
lpop = c.lpop(key)
self.assertEqual(lpush.result, 4)
self.assertEqual(members.result, ['d', 'c', 'b', 'a'])
self.assertEqual(rpush.result, 5)
self.assertEqual(llen.result, 5)
self.assertEqual(lrange.result, ['d', 'c', 'b', 'a', 'e'])
self.assertEqual(rpop.result, 'e')
self.assertEqual(lrem.result, 1)
self.assertEqual(ltrim.result, 1)
self.assertEqual(members_after_ltrim.result, ['d', 'c'])
self.assertEqual(lindex.result, 'c')
self.assertEqual(lset.result, 1)
self.assertEqual(lindex_after.result, 'a')
self.assertEqual(lpop.result, 'd')
def test_scan(self):
with redpipe.autoexec() as pipe:
d = self.Data(pipe=pipe)
d.lpush('1a', '1')
d.lpush('1b', '1')
d.lpush('2a', '1')
d.lpush('2b', '1')
sscan = d.scan(0, match='1*')
sscan_all = d.scan()
self.assertEqual(sscan[0], 0)
self.assertEqual(set(sscan[1]), {'1a', '1b'})
self.assertEqual(set(sscan_all[1]), {'1a', '1b', '2a', '2b'})
self.assertEqual({k for k in self.Data().scan_iter()},
{'1a', '1b', '2a', '2b'})
with redpipe.autoexec() as pipe:
s = self.Data(pipe=pipe)
self.assertRaises(redpipe.InvalidOperation,
lambda: [v for v in s.scan_iter()])
def test_scan_with_no_keyspace(self):
with redpipe.autoexec() as pipe:
t = redpipe.List(pipe=pipe)
t.lpush('1a', '1')
t.lpush('1b', '1')
t.lpush('2a', '1')
t.lpush('2b', '1')
sscan = t.scan(0, match='1*')
self.assertEqual(sscan[0], 0)
self.assertEqual(set(sscan[1]), {'1a', '1b'})
def test_pop(self):
key1 = '1'
key2 = '2'
key3 = '3'
with redpipe.autoexec() as pipe:
t = self.Data(pipe=pipe)
t.rpush(key1, 'a', 'b')
t.rpush(key2, 'c', 'd')
blpop = t.blpop([key1])
brpop = t.brpop([key1])
blpop_missing = t.blpop(['4', '5'], timeout=1)
brpop_missing = t.brpop(['4', '5'], timeout=1)
brpoplpush = t.brpoplpush(key2, key3, timeout=1)
rpoplpush = t.rpoplpush(key2, key3)
members = t.lrange(key3, 0, -1)
self.assertEqual(blpop, ('1', 'a'))
self.assertEqual(brpop, ('1', 'b'))
self.assertEqual(blpop_missing, None)
self.assertEqual(brpop_missing, None)
self.assertEqual(brpoplpush, 'd')
self.assertEqual(rpoplpush, 'c')
self.assertEqual(members, ['c', 'd'])
|
class StrictListTestCase(BaseTestCase):
class Data(redpipe.List):
def test(self):
pass
def test_scan(self):
pass
def test_scan_with_no_keyspace(self):
pass
def test_pop(self):
pass
| 6 | 0 | 21 | 1 | 20 | 0 | 1 | 0 | 1 | 3 | 2 | 1 | 4 | 0 | 4 | 80 | 92 | 9 | 83 | 43 | 77 | 0 | 81 | 39 | 75 | 1 | 3 | 1 | 4 |
1,476 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.StrictHashTestCase
|
class StrictHashTestCase(BaseTestCase):
class Data(redpipe.Hash):
keyspace = 'HASH'
def test(self):
with redpipe.autoexec() as pipe:
key = '1'
c = self.Data(pipe=pipe)
hset = c.hset(key, 'a', '1')
hmset = c.hmset(key, {'b': '2', 'c': '3', 'd': '4'})
hsetnx = c.hsetnx(key, 'b', '9999')
hget = c.hget(key, 'a')
hgetall = c.hgetall(key, )
hlen = c.hlen(key, )
hdel = c.hdel(key, 'a', 'b')
hkeys = c.hkeys(key)
hexists = c.hexists(key, 'c')
hincrby = c.hincrby(key, 'd', 2)
hmget = c.hmget(key, ['c', 'd'])
hvals = c.hvals(key)
self.assertEqual(hset.result, True)
self.assertEqual(hmset.result, True)
self.assertEqual(hsetnx.result, 0)
self.assertEqual(hget.result, '1')
self.assertEqual(
hgetall.result,
{'a': '1', 'd': '4', 'b': '2', 'c': '3'})
self.assertEqual(hlen.result, 4)
self.assertEqual(hdel.result, 2)
self.assertEqual(set(hkeys.result), {'c', 'd'})
self.assertTrue(hexists.result)
self.assertEqual(hincrby.result, 6)
self.assertEqual(hmget.result, ['3', '6'])
self.assertEqual(set(hvals.result), {'3', '6'})
def test_scan(self):
key = '1'
with redpipe.autoexec() as pipe:
s = self.Data(pipe=pipe)
s.hmset(key, {'a1': '1', 'a2': '2', 'b1': '1', 'b2': '2'})
hscan = s.hscan(key, 0, match='a*')
self.assertEqual(hscan[0], 0)
self.assertEqual(hscan[1], {'a1': '1', 'a2': '2'})
with redpipe.autoexec() as pipe:
s = self.Data(pipe=pipe)
self.assertRaises(redpipe.InvalidOperation,
lambda: [v for v in s.hscan_iter(key)])
data = {k: v for k, v in self.Data().hscan_iter(key)}
self.assertEqual(data, {'b2': '2', 'b1': '1', 'a1': '1', 'a2': '2'})
|
class StrictHashTestCase(BaseTestCase):
class Data(redpipe.Hash):
def test(self):
pass
def test_scan(self):
pass
| 4 | 0 | 24 | 2 | 22 | 0 | 1 | 0 | 1 | 2 | 1 | 1 | 2 | 0 | 2 | 78 | 53 | 6 | 47 | 25 | 43 | 0 | 44 | 23 | 40 | 1 | 3 | 1 | 2 |
1,477 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.SortedSetTestCase
|
class SortedSetTestCase(StrictSortedSetTestCase):
@classmethod
def setUpClass(cls):
cls.r = redislite.Redis()
redpipe.connect_redis(cls.r)
|
class SortedSetTestCase(StrictSortedSetTestCase):
@classmethod
def setUpClass(cls):
pass
| 3 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 80 | 5 | 0 | 5 | 3 | 2 | 0 | 4 | 2 | 2 | 1 | 4 | 0 | 1 |
1,478 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.SingleNodeRedisCluster
|
class SingleNodeRedisCluster(object):
__slots__ = ['node', 'port', 'client']
def __init__(self, starting_port=7000):
port = starting_port
while port < 55535:
try:
self._check_port(port)
self._check_port(port + 10000)
break
except IOError:
pass
port += 1
self.port = port
self.node = redislite.Redis(
serverconfig={
'cluster-enabled': 'yes',
'port': port
}
)
self.node.execute_command('CLUSTER ADDSLOTS', *range(0, 16384))
for i in range(0, 100):
try:
self.node.set('__test__', '1')
self.node.delete('__test__')
break
except redis.exceptions.ResponseError:
pass
time.sleep(0.1)
self.client = redis.RedisCluster.from_url(
'redis://127.0.0.1:%d' % port)
@staticmethod
def _check_port(port):
s = socket.socket()
try:
s.bind(('', port))
finally:
s.close()
def shutdown(self):
if self.client:
self.client.close()
self.client = None
if self.node:
self.node.execute_command('CLIENT KILL SKIPME yes')
self.node._cleanup() # noqa
self.node = None
def __del__(self):
self.shutdown()
|
class SingleNodeRedisCluster(object):
def __init__(self, starting_port=7000):
pass
@staticmethod
def _check_port(port):
pass
def shutdown(self):
pass
def __del__(self):
pass
| 6 | 0 | 13 | 2 | 11 | 0 | 3 | 0.02 | 1 | 2 | 0 | 0 | 3 | 3 | 4 | 4 | 57 | 10 | 47 | 13 | 41 | 1 | 39 | 12 | 34 | 5 | 1 | 2 | 10 |
1,479 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.SetTestCase
|
class SetTestCase(StrictSetTestCase):
@classmethod
def setUpClass(cls):
cls.r = redislite.Redis()
redpipe.connect_redis(cls.r)
|
class SetTestCase(StrictSetTestCase):
@classmethod
def setUpClass(cls):
pass
| 3 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 80 | 5 | 0 | 5 | 3 | 2 | 0 | 4 | 2 | 2 | 1 | 4 | 0 | 1 |
1,480 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.StrictStringTestCase
|
class StrictStringTestCase(BaseTestCase):
class Data(redpipe.String):
keyspace = 'STRING'
def super_get(self, key):
f = redpipe.Future()
with self.super_pipe as pipe:
res = self.get(key)
def cb():
f.set(res.result)
pipe.on_execute(cb)
return f
def test_super_pipe(self):
foo = []
def cb():
foo.append(1)
with redpipe.autoexec(exit_handler=cb) as pipe:
key = '1'
s = self.Data(pipe=pipe)
s.set(key, '2')
res = s.super_get(key)
self.assertEqual(res, '2')
self.assertEqual(foo, [1])
def test(self):
with redpipe.autoexec() as pipe:
key = '1'
s = self.Data(pipe=pipe)
self.assertEqual(s.redis_key(key), b'STRING{1}')
s.set(key, '2')
before = s.get(key)
mget_res = s.mget([key])
serialize = s.dump(key)
s.expire(key, 3)
ttl = s.ttl(key)
s.delete(key)
exists = s.exists(key)
after = s.get(key)
self.assertRaises(redpipe.ResultNotReady, lambda: before.result)
self.assertEqual(before, '2')
self.assertEqual(['2'], mget_res)
self.assertEqual(after, None)
self.assertAlmostEqual(ttl, 3, delta=1)
self.assertIsNotNone(serialize.result)
self.assertFalse(exists.result)
with redpipe.autoexec() as pipe:
key = '2'
s = self.Data(pipe=pipe)
restore = s.restore(key, serialize.result)
restorenx = s.restorenx(key, serialize.result)
ref = s.get(key)
idle = s.object('IDLETIME', key)
persist = s.persist(key)
incr = s.incr(key)
incrby = s.incrby(key, 2)
incrbyfloat = s.incrbyfloat(key, 2.1)
setnx = s.setnx(key, 'foo')
getaftersetnx = s.get(key)
setex = s.setex(key, 'bar', 60)
getaftersetex = s.get(key)
ttl = s.ttl(key)
psetex = s.psetex(key, 'bar', 6000)
self.assertEqual(restore.result, 'OK')
self.assertEqual(restorenx.result, 0)
self.assertEqual(ref, '2')
self.assertEqual(str(s), '<Data>')
self.assertEqual(idle, 0)
self.assertEqual(persist, 0)
self.assertEqual(incr, 3)
self.assertEqual(incrby.result, 5)
self.assertEqual(incrbyfloat.result, 7.1)
self.assertEqual(setnx.result, 0)
self.assertEqual(float(getaftersetnx.result), 7.1)
self.assertEqual(setex, 1)
self.assertEqual(getaftersetex, 'bar')
self.assertAlmostEqual(ttl, 60, delta=1)
self.assertEqual(psetex, 1)
with redpipe.autoexec() as pipe:
key = '3'
s = self.Data(pipe=pipe)
s.set(key, 'bar')
append = s.append(key, 'r')
substr = s.substr(key, 1, 3)
strlen = s.strlen(key)
setrange = s.setrange(key, 1, 'azz')
get = s.get(key)
self.assertEqual(append, 4)
self.assertEqual(strlen, 4)
self.assertEqual(substr, 'arr')
self.assertEqual(setrange, 4)
self.assertEqual(get, 'bazz')
def test_bitwise(self):
with redpipe.autoexec() as pipe:
key = '1'
s = self.Data(pipe=pipe)
setbit = s.setbit(key, 2, 1)
getbit = s.getbit(key, 2)
bitcount = s.bitcount(key)
self.assertEqual(setbit, 0)
self.assertEqual(getbit, 1)
self.assertEqual(bitcount, 1)
def test_rename(self):
with redpipe.autoexec() as pipe:
key1 = '1'
key2 = '2'
key3 = '3'
s = self.Data(pipe=pipe)
s.set(key1, '1')
rename = s.rename(key1, key2)
s.set(key3, '3')
renamenx = s.renamenx(key3, key2)
get = s.get(key2)
self.assertEqual(rename, 1)
self.assertEqual(renamenx, 0)
self.assertEqual(get, '1')
def test_dict(self):
key1 = '1'
with redpipe.autoexec() as pipe:
s = self.Data(pipe=pipe)
s[key1] = 'a'
get = s[key1]
self.assertEqual(get, 'a')
def test_bare(self):
with redpipe.autoexec() as pipe:
key = 'foo'
f = redpipe.String(pipe=pipe)
self.assertEqual(f.redis_key(key), b'foo')
f.set(key, '2')
before = f.get(key)
serialize = f.dump(key)
f.expire(key, 3)
ttl = f.ttl(key)
pttl = f.pttl(key)
pexpire = f.pexpire(key, 3000)
pexpireat = f.pexpireat(key, int(time.time() * 1000) + 1000)
f.delete(key)
exists = f.exists(key)
after = f.get(key)
self.assertRaises(redpipe.ResultNotReady, lambda: before.result)
self.assertEqual(before.result, '2')
self.assertEqual(after.result, None)
self.assertAlmostEqual(ttl.result, 3, delta=1)
self.assertAlmostEqual(pttl, 3000, delta=100)
self.assertEqual(pexpire, 1)
self.assertEqual(pexpireat, 1)
self.assertIsNotNone(serialize.result)
self.assertFalse(exists.result)
def test_eval(self):
key1 = '1'
script = """return redis.call("SET", KEYS[1], ARGV[1])"""
with redpipe.autoexec() as pipe:
s = self.Data(pipe=pipe)
s.eval(script, 1, key1, 'a')
get = s.get(key1)
self.assertEqual(get, 'a')
|
class StrictStringTestCase(BaseTestCase):
class Data(redpipe.String):
def super_get(self, key):
pass
def cb():
pass
def test_super_pipe(self):
pass
def cb():
pass
def test_super_pipe(self):
pass
def test_bitwise(self):
pass
def test_rename(self):
pass
def test_dict(self):
pass
def test_bare(self):
pass
def test_eval(self):
pass
| 12 | 0 | 17 | 1 | 15 | 0 | 1 | 0 | 1 | 5 | 2 | 1 | 7 | 0 | 7 | 83 | 175 | 22 | 153 | 82 | 141 | 0 | 153 | 74 | 141 | 1 | 3 | 1 | 10 |
1,481 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.PipelineTestCase
|
class PipelineTestCase(BaseTestCase):
def test_string(self):
p = redpipe.pipeline()
p.set('foo', b'bar')
g = p.get('foo')
# can't access it until it's ready
self.assertRaises(redpipe.ResultNotReady, lambda: g.result)
p.execute()
self.assertEqual(g, b'bar')
def test_zset(self):
p = redpipe.pipeline()
p.zadd('foo', {'a': 1})
p.zadd('foo', {'b': 2})
p.zadd('foo', {'c': 3})
z = p.zrange('foo', 0, -1)
# can't access it until it's ready
self.assertRaises(redpipe.ResultNotReady, lambda: z.result)
p.execute()
self.assertEqual(z, [b'a', b'b', b'c'])
def test_callback(self):
p = redpipe.pipeline()
results = {}
def incr(k, v):
ref = p.incrby(k, v)
def cb():
results[k] = ref.result
p.on_execute(cb)
incr('foo', 1)
incr('bar', 2)
incr('bazz', 3)
self.assertEqual(results, {})
p.execute()
self.assertEqual(results, {
'foo': 1,
'bar': 2,
'bazz': 3
})
def test_reset(self):
with redpipe.pipeline() as p:
ref = p.zadd('foo', 1, 'a')
self.assertEqual(p._callbacks, [])
self.assertEqual(p._stack, [])
self.assertRaises(redpipe.ResultNotReady, lambda: ref.result)
self.assertEqual(self.r.zrange('foo', 0, -1), [])
with redpipe.pipeline() as p:
ref = p.zadd('foo', {'a': 1})
p.execute()
self.assertEqual(p._callbacks, [])
self.assertEqual(p._stack, [])
self.assertEqual(ref, 1)
self.assertEqual(self.r.zrange('foo', 0, -1), [b'a'])
p = redpipe.pipeline()
ref = p.zadd('foo', {'a': 1})
p.reset()
p.execute()
self.assertRaises(redpipe.ResultNotReady, lambda: ref.result)
|
class PipelineTestCase(BaseTestCase):
def test_string(self):
pass
def test_zset(self):
pass
def test_callback(self):
pass
def incr(k, v):
pass
def cb():
pass
def test_reset(self):
pass
| 7 | 0 | 13 | 2 | 10 | 0 | 1 | 0.04 | 1 | 0 | 0 | 0 | 4 | 0 | 4 | 80 | 71 | 15 | 54 | 16 | 47 | 2 | 50 | 15 | 43 | 1 | 3 | 1 | 6 |
1,482 |
72squared/redpipe
|
72squared_redpipe/test.py
|
test.AsyncTestCase
|
class AsyncTestCase(unittest.TestCase):
def test(self):
def sleeper():
time.sleep(0.3)
return 1
t = redpipe.tasks.AsynchronousTask(target=sleeper)
t.start()
self.assertEqual(t.result, 1)
def test_exceptions(self):
def blow_up():
raise Exception('boom')
t = redpipe.tasks.AsynchronousTask(target=blow_up)
t.start()
self.assertRaises(Exception, lambda: t.result)
|
class AsyncTestCase(unittest.TestCase):
def test(self):
pass
def sleeper():
pass
def test_exceptions(self):
pass
def blow_up():
pass
| 5 | 0 | 5 | 1 | 5 | 0 | 1 | 0 | 1 | 2 | 1 | 0 | 2 | 0 | 2 | 74 | 17 | 3 | 14 | 7 | 9 | 0 | 14 | 7 | 9 | 1 | 2 | 0 | 4 |
1,483 |
72squared/redpipe
|
72squared_redpipe/setup.py
|
setup.TestCommand
|
class TestCommand(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys
import subprocess
raise SystemExit(
subprocess.call([sys.executable, '-m', 'test']))
|
class TestCommand(Command):
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
pass
| 4 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 3 | 0 | 3 | 33 | 15 | 4 | 11 | 7 | 5 | 0 | 10 | 7 | 4 | 1 | 1 | 0 | 3 |
1,484 |
72squared/redpipe
|
72squared_redpipe/redpipe/fields.py
|
redpipe.fields.StringListField
|
class StringListField(object):
"""
Used for storing a list of strings, serialized as a comma-separated list.
"""
_encoding = 'utf-8'
@classmethod
def decode(cls,
value: Union[bytes, None, typing.List[str]]
) -> Optional[typing.List[str]]:
"""
decode the data from redis.
:param value: bytes
:return: list
"""
if value is None or isinstance(value, list):
return value
try:
data = [v for v in value.decode(cls._encoding).split(',') if
v != '']
return data if data else None
except AttributeError:
return None
@classmethod
def encode(cls, value: typing.List[str]) -> bytes:
"""
encode the list it so it can be stored in redis.
:param value: list
:return: bytes
"""
try:
coerced = [str(v) for v in value]
if coerced == value:
return ",".join(coerced).encode(cls._encoding) if len(
value) > 0 else b''
except TypeError:
pass
raise InvalidValue('not a list of strings')
|
class StringListField(object):
'''
Used for storing a list of strings, serialized as a comma-separated list.
'''
@classmethod
def decode(cls,
value: Union[bytes, None, typing.List[str]]
) -> Optional[typing.List[str]]:
'''
decode the data from redis.
:param value: bytes
:return: list
'''
pass
@classmethod
def encode(cls, value: typing.List[str]) -> bytes:
'''
encode the list it so it can be stored in redis.
:param value: list
:return: bytes
'''
pass
| 5 | 3 | 17 | 2 | 10 | 5 | 4 | 0.54 | 1 | 6 | 1 | 0 | 0 | 0 | 2 | 2 | 42 | 5 | 24 | 10 | 17 | 13 | 18 | 6 | 15 | 4 | 1 | 2 | 8 |
1,485 |
72squared/redpipe
|
72squared_redpipe/redpipe/fields.py
|
redpipe.fields.ListField
|
class ListField(object):
"""
A list field. Marshalled in and out of redis via json.
Values of the list can be any arbitrary data.
"""
_encoding = 'utf-8'
@classmethod
def encode(cls, value: list) -> bytes:
"""
take a list and turn it into a utf-8 encoded byte-string for redis.
:param value: list
:return: bytes
"""
try:
coerced = list(value)
if coerced == value:
return json.dumps(coerced).encode(cls._encoding)
except TypeError:
pass
raise InvalidValue('not a list')
@classmethod
def decode(cls, value: Union[bytes, None, list]) -> Optional[list]:
"""
take a utf-8 encoded byte-string from redis and
turn it back into a list
:param value: bytes
:return: list
"""
try:
return None if value is None else \
list(json.loads(value.decode(cls._encoding))) # type: ignore
except (TypeError, AttributeError):
return list(value)
|
class ListField(object):
'''
A list field. Marshalled in and out of redis via json.
Values of the list can be any arbitrary data.
'''
@classmethod
def encode(cls, value: list) -> bytes:
'''
take a list and turn it into a utf-8 encoded byte-string for redis.
:param value: list
:return: bytes
'''
pass
@classmethod
def decode(cls, value: Union[bytes, None, list]) -> Optional[list]:
'''
take a utf-8 encoded byte-string from redis and
turn it back into a list
:param value: bytes
:return: list
'''
pass
| 5 | 3 | 14 | 2 | 7 | 7 | 3 | 0.94 | 1 | 5 | 1 | 0 | 0 | 0 | 2 | 2 | 38 | 5 | 18 | 7 | 13 | 17 | 15 | 5 | 12 | 3 | 1 | 2 | 6 |
1,486 |
72squared/redpipe
|
72squared_redpipe/redpipe/fields.py
|
redpipe.fields.IntegerField
|
class IntegerField(object):
"""
Used for integer numeric fields.
"""
@classmethod
def decode(cls, value: Optional[bytes]) -> Optional[int]:
"""
read bytes from redis and turn it back into an integer.
:param value: bytes
:return: int
"""
return None if value is None else int(float(value))
@classmethod
def encode(cls, value: int) -> bytes:
"""
take an integer and turn it into a string representation
to write into redis.
:param value: int
:return: str
"""
try:
return repr(int(float(value))).encode()
except (TypeError, ValueError):
raise InvalidValue('not an int')
|
class IntegerField(object):
'''
Used for integer numeric fields.
'''
@classmethod
def decode(cls, value: Optional[bytes]) -> Optional[int]:
'''
read bytes from redis and turn it back into an integer.
:param value: bytes
:return: int
'''
pass
@classmethod
def encode(cls, value: int) -> bytes:
'''
take an integer and turn it into a string representation
to write into redis.
:param value: int
:return: str
'''
pass
| 5 | 3 | 10 | 1 | 4 | 6 | 2 | 1.4 | 1 | 6 | 1 | 0 | 0 | 0 | 2 | 2 | 28 | 4 | 10 | 5 | 5 | 14 | 8 | 3 | 5 | 2 | 1 | 1 | 4 |
1,487 |
72squared/redpipe
|
72squared_redpipe/redpipe/fields.py
|
redpipe.fields.FloatField
|
class FloatField(object):
"""
Numeric field that supports integers and floats (values are turned into
floats on load from persistence).
"""
@classmethod
def decode(cls, value: Optional[bytes]) -> Optional[float]:
"""
decode the bytes from redis back into a float
:param value: bytes
:return: float
"""
return None if value is None else float(value)
@classmethod
def encode(cls, value: float) -> bytes:
"""
encode a floating point number to bytes in redis
:param value: float
:return: bytes
"""
try:
coerced = float(value)
except (TypeError, ValueError):
raise InvalidValue('not a float')
response = repr(coerced)
if response.endswith('.0'):
response = response[:-2]
return response.encode()
|
class FloatField(object):
'''
Numeric field that supports integers and floats (values are turned into
floats on load from persistence).
'''
@classmethod
def decode(cls, value: Optional[bytes]) -> Optional[float]:
'''
decode the bytes from redis back into a float
:param value: bytes
:return: float
'''
pass
@classmethod
def encode(cls, value: float) -> bytes:
'''
encode a floating point number to bytes in redis
:param value: float
:return: bytes
'''
pass
| 5 | 3 | 12 | 1 | 6 | 5 | 3 | 1 | 1 | 5 | 1 | 0 | 0 | 0 | 2 | 2 | 32 | 4 | 14 | 7 | 9 | 14 | 12 | 5 | 9 | 3 | 1 | 1 | 5 |
1,488 |
72squared/redpipe
|
72squared_redpipe/redpipe/fields.py
|
redpipe.fields.Field
|
class Field(Protocol, Generic[T]):
@classmethod
def encode(cls, value: T) -> bytes: ...
@classmethod
def decode(cls, value: Optional[bytes]) -> Optional[T]: ...
|
class Field(Protocol, Generic[T]):
@classmethod
def encode(cls, value: T) -> bytes:
pass
@classmethod
def decode(cls, value: Optional[bytes]) -> Optional[T]:
pass
| 5 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 2 | 1 | 0 | 0 | 0 | 0 | 2 | 26 | 6 | 1 | 5 | 5 | 2 | 0 | 5 | 3 | 2 | 1 | 5 | 0 | 2 |
1,489 |
72squared/redpipe
|
72squared_redpipe/redpipe/fields.py
|
redpipe.fields.DictField
|
class DictField(object):
_encoding = 'utf-8'
@classmethod
def encode(cls, value: dict) -> bytes:
"""
encode the dict as a json string to be written into redis.
:param value: dict
:return: bytes
"""
try:
coerced = dict(value)
if coerced == value:
return json.dumps(coerced).encode(cls._encoding)
except (TypeError, ValueError):
pass
raise InvalidValue('not a dict')
@classmethod
def decode(cls, value: Union[bytes, None, dict]) -> Optional[dict]:
"""
decode the data from a json string in redis back into a dict object.
:param value: bytes
:return: dict
"""
try:
return None if value is None else \
dict(json.loads(value.decode(cls._encoding))) # type: ignore
except (TypeError, AttributeError):
return dict(value)
|
class DictField(object):
@classmethod
def encode(cls, value: dict) -> bytes:
'''
encode the dict as a json string to be written into redis.
:param value: dict
:return: bytes
'''
pass
@classmethod
def decode(cls, value: Union[bytes, None, dict]) -> Optional[dict]:
'''
decode the data from a json string in redis back into a dict object.
:param value: bytes
:return: dict
'''
pass
| 5 | 2 | 13 | 1 | 7 | 6 | 3 | 0.67 | 1 | 6 | 1 | 0 | 0 | 0 | 2 | 2 | 32 | 4 | 18 | 7 | 13 | 12 | 15 | 5 | 12 | 3 | 1 | 2 | 6 |
1,490 |
72squared/redpipe
|
72squared_redpipe/redpipe/fields.py
|
redpipe.fields.BooleanField
|
class BooleanField(object):
"""
Used for boolean fields.
"""
@classmethod
def is_true(cls, val):
if val is True:
return True
if val is False:
return False
strval = str(val).lower()
if strval in ['true', '1']:
return True
if strval in ['false', '0', 'none', '']:
return False
return True if val else False
@classmethod
def encode(cls, value: bool) -> bytes:
"""
convert a boolean value into something we can persist to redis.
An empty string is the representation for False.
:param value: bool
:return: bytes
"""
return b'1' if cls.is_true(value) else b''
@classmethod
def decode(cls, value: Optional[bytes]) -> Optional[bool]:
"""
convert from redis bytes into a boolean value
:param value: bytes
:return: bool
"""
return None if value is None else bool(value)
|
class BooleanField(object):
'''
Used for boolean fields.
'''
@classmethod
def is_true(cls, val):
pass
@classmethod
def encode(cls, value: bool) -> bytes:
'''
convert a boolean value into something we can persist to redis.
An empty string is the representation for False.
:param value: bool
:return: bytes
'''
pass
@classmethod
def decode(cls, value: Optional[bytes]) -> Optional[bool]:
'''
convert from redis bytes into a boolean value
:param value: bytes
:return: bool
'''
pass
| 7 | 3 | 10 | 2 | 5 | 4 | 3 | 0.74 | 1 | 3 | 0 | 0 | 0 | 0 | 3 | 3 | 40 | 7 | 19 | 8 | 12 | 14 | 16 | 5 | 12 | 6 | 1 | 1 | 10 |
1,491 |
72squared/redpipe
|
72squared_redpipe/redpipe/fields.py
|
redpipe.fields.BinaryField
|
class BinaryField(object):
"""
A bytes field. Not encoded.
"""
@classmethod
def encode(cls, value: bytes) -> bytes:
"""
write binary data into redis without encoding it.
:param value: bytes
:return: bytes
"""
try:
coerced = bytes(value)
if coerced == value:
return coerced
except (TypeError, UnicodeError):
pass
raise InvalidValue('not binary')
@classmethod
def decode(cls, value: Optional[bytes]) -> Optional[bytes]:
"""
read binary data from redis and pass it on through.
:param value: bytes
:return: bytes
"""
return None if value is None else bytes(value)
|
class BinaryField(object):
'''
A bytes field. Not encoded.
'''
@classmethod
def encode(cls, value: bytes) -> bytes:
'''
write binary data into redis without encoding it.
:param value: bytes
:return: bytes
'''
pass
@classmethod
def decode(cls, value: Optional[bytes]) -> Optional[bytes]:
'''
read binary data from redis and pass it on through.
:param value: bytes
:return: bytes
'''
pass
| 5 | 3 | 12 | 2 | 5 | 5 | 3 | 1 | 1 | 4 | 1 | 0 | 0 | 0 | 2 | 2 | 31 | 5 | 13 | 6 | 8 | 13 | 11 | 4 | 8 | 3 | 1 | 2 | 5 |
1,492 |
72squared/redpipe
|
72squared_redpipe/redpipe/fields.py
|
redpipe.fields.AsciiField
|
class AsciiField(TextField):
"""
Used for ascii-only text
"""
PATTERN = re.compile('^([ -~]+)?$')
@classmethod
def encode(cls, value: str) -> bytes:
"""
take a list of strings and turn it into utf-8 byte-string
:param value:
:return:
"""
coerced = str(value)
if coerced == value and cls.PATTERN.match(coerced):
return coerced.encode(cls._encoding)
raise InvalidValue('not ascii')
|
class AsciiField(TextField):
'''
Used for ascii-only text
'''
@classmethod
def encode(cls, value: str) -> bytes:
'''
take a list of strings and turn it into utf-8 byte-string
:param value:
:return:
'''
pass
| 3 | 2 | 12 | 2 | 5 | 5 | 2 | 1 | 1 | 3 | 1 | 0 | 0 | 0 | 1 | 3 | 19 | 3 | 8 | 5 | 5 | 8 | 7 | 4 | 5 | 2 | 2 | 1 | 2 |
1,493 |
72squared/redpipe
|
72squared_redpipe/redpipe/exceptions.py
|
redpipe.exceptions.ResultNotReady
|
class ResultNotReady(Error):
"""
Raised when you access a data from a Future before it is assigned.
"""
|
class ResultNotReady(Error):
'''
Raised when you access a data from a Future before it is assigned.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 3 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 4 | 0 | 1 | 1 | 0 | 3 | 1 | 1 | 0 | 0 | 4 | 0 | 0 |
1,494 |
72squared/redpipe
|
72squared_redpipe/redpipe/exceptions.py
|
redpipe.exceptions.InvalidValue
|
class InvalidValue(Error):
"""
Raised when data assigned to a field is the wrong type
"""
|
class InvalidValue(Error):
'''
Raised when data assigned to a field is the wrong type
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 3 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 4 | 0 | 1 | 1 | 0 | 3 | 1 | 1 | 0 | 0 | 4 | 0 | 0 |
1,495 |
72squared/redpipe
|
72squared_redpipe/redpipe/exceptions.py
|
redpipe.exceptions.InvalidPipeline
|
class InvalidPipeline(Error):
"""
raised when you try to use a pipeline that isn't configured correctly.
"""
|
class InvalidPipeline(Error):
'''
raised when you try to use a pipeline that isn't configured correctly.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 3 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 4 | 0 | 1 | 1 | 0 | 3 | 1 | 1 | 0 | 0 | 4 | 0 | 0 |
1,496 |
72squared/redpipe
|
72squared_redpipe/redpipe/exceptions.py
|
redpipe.exceptions.InvalidOperation
|
class InvalidOperation(Error):
"""
Raised when trying to perform an operation disallowed by the redpipe api.
"""
|
class InvalidOperation(Error):
'''
Raised when trying to perform an operation disallowed by the redpipe api.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 3 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 4 | 0 | 1 | 1 | 0 | 3 | 1 | 1 | 0 | 0 | 4 | 0 | 0 |
1,497 |
72squared/redpipe
|
72squared_redpipe/redpipe/exceptions.py
|
redpipe.exceptions.AlreadyConnected
|
class AlreadyConnected(Error):
"""
raised when you try to connect and change the ORM connection
without explicitly disconnecting first.
"""
|
class AlreadyConnected(Error):
'''
raised when you try to connect and change the ORM connection
without explicitly disconnecting first.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 4 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 5 | 0 | 1 | 1 | 0 | 4 | 1 | 1 | 0 | 0 | 4 | 0 | 0 |
1,498 |
72squared/redpipe
|
72squared_redpipe/redpipe/connections.py
|
redpipe.connections.ConnectionManager
|
class ConnectionManager(object):
"""
A Connection manager. Used as a singleton.
Don't invoke methods on this class directly.
Instead use the convenience methods defined in this module:
* connect_redis
* disconnect
* reset
"""
connections: Dict[Optional[str], Callable] = {}
@classmethod
def get(cls, name: Optional[str] = None) -> redis.client.Pipeline:
"""
Get a new redis-py pipeline object or similar object.
Called by the redpipe.pipelines module.
Don't call this directly.
:param name: str
:return: callable implementing the redis-py pipeline interface.
"""
try:
return cls.connections[name]()
except KeyError:
raise InvalidPipeline('%s is not configured' % name)
@classmethod
def connect(cls, pipeline_method: Callable,
name: Optional[str] = None) -> None:
"""
Low level logic to bind a callable method to a name.
Don't call this directly unless you know what you are doing.
:param pipeline_method: callable
:param name: str optional
:return: None
"""
try:
if cls.get(name).get_connection_kwargs() \
!= pipeline_method().get_connection_kwargs():
raise AlreadyConnected("can't change connection for %s" % name)
except InvalidPipeline:
pass
cls.connections[name] = pipeline_method
@classmethod
def connect_redis(cls, redis_client, name=None, transaction=False) -> None:
"""
Store the redis connection in our connector instance.
Do this during your application bootstrapping.
We call the pipeline method of the redis client.
The ``redis_client`` can be either a redis or redis cluster client.
We use the interface, not the actual class.
That means we can handle either one identically.
The transaction flag is a boolean value we hold on to and
pass to the invocation of something equivalent to:
.. code-block:: python
redis_client.pipeline(transaction=transation)
Unlike redis-py, this flag defaults to False.
You can configure it to always use the MULTI/EXEC flags,
but I don't see much point.
If you need transactional support I recommend using a LUA script.
**RedPipe** is about improving network round-trip efficiency.
:param redis_client: redis.Redis()
:param name: identifier for the connection, optional
:param transaction: bool, defaults to False
:return: None
"""
if redis_client.get_connection_kwargs().get('decode_responses', False):
raise InvalidPipeline('decode_responses set to True')
def pipeline_method():
"""
A closure wrapping the pipeline.
:return: pipeline object
"""
return redis_client.pipeline(transaction=transaction)
# set up the connection.
cls.connect(pipeline_method=pipeline_method, name=name)
@classmethod
def disconnect(cls, name: Optional[str] = None) -> None:
"""
remove a connection by name.
If no name is passed in, it assumes default.
Useful for testing.
:param name:
:return:
"""
try:
del cls.connections[name]
except KeyError:
pass
@classmethod
def reset(cls) -> None:
"""
remove all connections.
Useful for testing scenarios.
:return: None
"""
cls.connections = {}
|
class ConnectionManager(object):
'''
A Connection manager. Used as a singleton.
Don't invoke methods on this class directly.
Instead use the convenience methods defined in this module:
* connect_redis
* disconnect
* reset
'''
@classmethod
def get(cls, name: Optional[str] = None) -> redis.client.Pipeline:
'''
Get a new redis-py pipeline object or similar object.
Called by the redpipe.pipelines module.
Don't call this directly.
:param name: str
:return: callable implementing the redis-py pipeline interface.
'''
pass
@classmethod
def connect(cls, pipeline_method: Callable,
name: Optional[str] = None) -> None:
'''
Low level logic to bind a callable method to a name.
Don't call this directly unless you know what you are doing.
:param pipeline_method: callable
:param name: str optional
:return: None
'''
pass
@classmethod
def connect_redis(cls, redis_client, name=None, transaction=False) -> None:
'''
Store the redis connection in our connector instance.
Do this during your application bootstrapping.
We call the pipeline method of the redis client.
The ``redis_client`` can be either a redis or redis cluster client.
We use the interface, not the actual class.
That means we can handle either one identically.
The transaction flag is a boolean value we hold on to and
pass to the invocation of something equivalent to:
.. code-block:: python
redis_client.pipeline(transaction=transation)
Unlike redis-py, this flag defaults to False.
You can configure it to always use the MULTI/EXEC flags,
but I don't see much point.
If you need transactional support I recommend using a LUA script.
**RedPipe** is about improving network round-trip efficiency.
:param redis_client: redis.Redis()
:param name: identifier for the connection, optional
:param transaction: bool, defaults to False
:return: None
'''
pass
def pipeline_method():
'''
A closure wrapping the pipeline.
:return: pipeline object
'''
pass
@classmethod
def disconnect(cls, name: Optional[str] = None) -> None:
'''
remove a connection by name.
If no name is passed in, it assumes default.
Useful for testing.
:param name:
:return:
'''
pass
@classmethod
def reset(cls) -> None:
'''
remove all connections.
Useful for testing scenarios.
:return: None
'''
pass
| 12 | 7 | 18 | 4 | 5 | 9 | 2 | 1.76 | 1 | 4 | 2 | 0 | 0 | 0 | 5 | 5 | 122 | 28 | 34 | 14 | 21 | 60 | 27 | 8 | 20 | 3 | 1 | 2 | 11 |
1,499 |
72squared/redpipe
|
72squared_redpipe/redpipe/fields.py
|
redpipe.fields.TextField
|
class TextField(object):
"""
A unicode string field.
Encoded via utf-8 before writing to persistence.
"""
_encoding = 'utf-8'
@classmethod
def encode(cls, value: str) -> bytes:
"""
take a valid unicode string and turn it into utf-8 bytes
:param value: unicode, str
:return: bytes
"""
coerced = str(value)
if coerced == value:
return coerced.encode(cls._encoding)
raise InvalidValue('not text')
@classmethod
def decode(cls, value: Optional[bytes]) -> Optional[str]:
"""
take bytes from redis and turn them into unicode string
:param value:
:return:
"""
return None if value is None else str(value.decode(cls._encoding))
|
class TextField(object):
'''
A unicode string field.
Encoded via utf-8 before writing to persistence.
'''
@classmethod
def encode(cls, value: str) -> bytes:
'''
take a valid unicode string and turn it into utf-8 bytes
:param value: unicode, str
:return: bytes
'''
pass
@classmethod
def decode(cls, value: Optional[bytes]) -> Optional[str]:
'''
take bytes from redis and turn them into unicode string
:param value:
:return:
'''
pass
| 5 | 3 | 10 | 2 | 4 | 5 | 2 | 1.27 | 1 | 3 | 1 | 1 | 0 | 0 | 2 | 2 | 31 | 6 | 11 | 7 | 6 | 14 | 9 | 5 | 6 | 2 | 1 | 1 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.