Many tests done, still more to come.
[szyfrow.git] / tests / test_bifid.py
1 import pytest
2 import string
3
4 from szyfrow.bifid import *
5 from szyfrow.support.utilities import *
6
7 def test_grid():
8 trans, f_grid, r_grid = bifid_grid('bayes', KeywordWrapAlphabet.from_a, None)
9 assert len(f_grid) == 25
10 assert len(r_grid) == 25
11 for l in f_grid:
12 assert l == r_grid[f_grid[l]]
13 assert r_grid[1, 1] == 'b'
14 assert r_grid[2, 1] == 'c'
15
16
17 def test_encipher_message():
18 assert bifid_encipher("indiajelly", 'iguana') == 'ibidonhprm'
19 assert bifid_encipher("indiacurry", 'iguana', period=4, fillvalue='x') == 'ibnhgaqltzml'
20 with pytest.raises(ValueError):
21 bifid_encipher("indiacurry", 'iguana', period=4)
22
23
24 def test_decipher_message():
25 plaintext = 'hereissometexttoencipher'
26 for key in ['bayes', 'samplekey']:
27 enciphered = bifid_encipher(plaintext, key)
28 deciphered = bifid_decipher(enciphered, key)
29 assert deciphered == plaintext
30
31 for key in ['bayes', 'samplekey']:
32 enciphered = bifid_encipher(plaintext, key, period=5, fillvalue='a')
33 deciphered = bifid_decipher(enciphered, key, period=5, fillvalue='a')
34 assert deciphered == plaintext + pad(len(plaintext), 5, 'a')
35
36
37 def test_bifid_break():
38 plaintext = sanitise('''It is a truth universally acknowledged, that a single man in
39 possession of a good fortune, must be in want of a wife. However
40 little known the feelings or views of such a man may be on his
41 first entering a neighbourhood, this truth is so well fixed in
42 the minds of the surrounding families, that he is considered the
43 rightful property of some one or other of their daughters.''')
44 expected_key = 'encipher'
45 expected_wrap = KeywordWrapAlphabet.from_a
46 expected_period = 0
47 expected_score = Pletters(plaintext)
48 ciphertext = bifid_encipher(plaintext, expected_key,
49 wrap_alphabet=expected_wrap)
50
51 (key, wrap, period), score = bifid_break(ciphertext,
52 wordlist='encipher fourteen keyword'.split())
53
54 assert key == expected_key
55 assert wrap == expected_wrap
56 assert period == expected_period
57 assert score == pytest.approx(expected_score)