moved tests to parent directory

This commit is contained in:
Kevin Froman 2019-09-12 21:22:25 -05:00
parent ab49e3eaf6
commit 4f6f83f383
No known key found for this signature in database
GPG key ID: 0D414D0FE405B63B
17 changed files with 31 additions and 18 deletions

View file

@ -1,33 +0,0 @@
#!/usr/bin/env python3
import sys, os
sys.path.append(".")
import unittest, uuid, hashlib
import onionrblocks
import onionrstorage
from utils import createdirs
from onionrutils import bytesconverter
import onionrcrypto
import onionrblockapi
def setup_test():
TEST_DIR = 'testdata/%s-%s' % (uuid.uuid4(), os.path.basename(__file__)) + '/'
print("Test directory:", TEST_DIR)
os.environ["ONIONR_HOME"] = TEST_DIR
createdirs.create_dirs()
class OnionrBlockTests(unittest.TestCase):
def test_plaintext_insert(self):
setup_test()
message = 'hello world'
bl = onionrblocks.insert(message)
self.assertTrue(bl.startswith('0'))
self.assertIn(bytesconverter.str_to_bytes(message), onionrstorage.getData(bl))
def test_encrypted_insert(self):
setup_test()
message = 'hello world2'
bl = onionrblocks.insert(message, asymPeer=onionrcrypto.pub_key)
self.assertIn(bytesconverter.str_to_bytes(message), onionrblockapi.Block(bl, decrypt=True).bcontent)
unittest.main()

View file

@ -1,19 +0,0 @@
from unittest.mock import patch
import sys, os
sys.path.append(".")
import unittest, uuid
TEST_DIR = 'testdata/%s-%s' % (uuid.uuid4(), os.path.basename(__file__)) + '/'
print("Test directory:", TEST_DIR)
os.environ["ONIONR_HOME"] = TEST_DIR
from onionrcommands import parser
class OnionrTests(unittest.TestCase):
def test_no_command(self):
testargs = ["onionr.py"]
with patch.object(sys, 'argv', testargs):
parser.register()
def test_version_command(self):
testargs = ["onionr.py", "version"]
with patch.object(sys, 'argv', testargs):
parser.register()
unittest.main()

View file

@ -1,39 +0,0 @@
#!/usr/bin/env python3
import sys, os
sys.path.append(".")
import unittest, uuid, sqlite3
TEST_DIR = 'testdata/%s-%s' % (uuid.uuid4(), os.path.basename(__file__)) + '/'
print("Test directory:", TEST_DIR)
os.environ["ONIONR_HOME"] = TEST_DIR
from urllib.request import pathname2url
from coredb import keydb
from utils import createdirs
createdirs.create_dirs()
class OnionrTests(unittest.TestCase):
def test_address_add(self):
testAddresses = ['facebookcorewwwi.onion', '56kmnycrvepfarolhnx6t2dvmldfeyg7jdymwgjb7jjzg47u2lqw2sad.onion', '5bvb5ncnfr4dlsfriwczpzcvo65kn7fnnlnt2ln7qvhzna2xaldq.b32.i2p']
for address in testAddresses:
keydb.addkeys.add_address(address)
dbAddresses = keydb.listkeys.list_adders()
for address in testAddresses:
self.assertIn(address, dbAddresses)
invalidAddresses = [None, '', ' ', '\t', '\n', ' test ', 24, 'fake.onion', 'fake.b32.i2p']
for address in invalidAddresses:
try:
keydb.addkeys.add_address(address)
except TypeError:
pass
dbAddresses = keydb.listkeys.list_adders()
for address in invalidAddresses:
self.assertNotIn(address, dbAddresses)
def test_address_info(self):
adder = 'nytimes3xbfgragh.onion'
keydb.addkeys.add_address(adder)
self.assertNotEqual(keydb.transportinfo.get_address_info(adder, 'success'), 1000)
keydb.transportinfo.set_address_info(adder, 'success', 1000)
self.assertEqual(keydb.transportinfo.get_address_info(adder, 'success'), 1000)
unittest.main()

View file

@ -1,21 +0,0 @@
import sys, os
sys.path.append(".")
import unittest, uuid, json
TEST_DIR = 'testdata/%s-%s' % (uuid.uuid4(), os.path.basename(__file__)) + '/'
print("Test directory:", TEST_DIR)
os.environ["ONIONR_HOME"] = TEST_DIR
import onionrblocks
from utils import createdirs
from utils import readstatic
createdirs.create_dirs()
class OnionrConfig(unittest.TestCase):
def test_default_file(self):
json.loads(readstatic.read_static('default_config.json'))
def test_installed_config(self):
import onionrsetup
onionrsetup.setup_config()
with open(TEST_DIR + 'config.json') as conf:
json.loads(conf.read())
unittest.main()

View file

@ -1,43 +0,0 @@
#!/usr/bin/env python3
import sys, os, random
sys.path.append(".")
import unittest, uuid
TEST_DIR_1 = 'testdata/%s-%s' % (uuid.uuid4(), os.path.basename(__file__)) + '/'
TEST_DIR_2 = 'testdata/%s-%s' % (uuid.uuid4(), os.path.basename(__file__)) + '/'
import time
os.environ["ONIONR_HOME"] = TEST_DIR_1
from utils import createdirs
createdirs.create_dirs()
import onionrexceptions, onionrcrypto as crypto
from onionrusers import onionrusers
from onionrusers import contactmanager
class OnionrForwardSecrecyTests(unittest.TestCase):
'''
Tests both the onionrusers class and the contactmanager (which inherits it)
'''
def test_forward_encrypt(self):
friend = crypto.generate()
friendUser = onionrusers.OnionrUser(friend[0], saveUser=True)
for x in range(5):
message = 'hello world %s' % (random.randint(1, 1000))
forwardKey = friendUser.generateForwardKey()
fakeForwardPair = crypto.generate()
self.assertTrue(friendUser.addForwardKey(fakeForwardPair[0]))
encrypted = friendUser.forwardEncrypt(message)
decrypted = crypto.encryption.pub_key_decrypt(encrypted[0], privkey=fakeForwardPair[1], encodedData=True)
self.assertEqual(decrypted, message.encode())
return
unittest.main()

View file

@ -1,16 +0,0 @@
#!/usr/bin/env python3
import sys, os
sys.path.append(".")
import unittest, uuid
TEST_DIR = 'testdata/%s-%s' % (uuid.uuid4(), os.path.basename(__file__)) + '/'
print("Test directory:", TEST_DIR)
os.environ["ONIONR_HOME"] = TEST_DIR
import netcontroller
class GetOpenPortTest(unittest.TestCase):
def test_open_port(self):
open_port = int(netcontroller.get_open_port())
self.assertGreaterEqual(open_port, 1024)
unittest.main()

View file

@ -1,121 +0,0 @@
#!/usr/bin/env python3
import sys, os
sys.path.append(".")
import unittest, uuid, hashlib, base64
import nacl.exceptions
import nacl.signing, nacl.hash, nacl.encoding
TEST_DIR = 'testdata/%s-%s' % (uuid.uuid4(), os.path.basename(__file__)) + '/'
print("Test directory:", TEST_DIR)
os.environ["ONIONR_HOME"] = TEST_DIR
from utils import createdirs
createdirs.create_dirs()
from onionrutils import stringvalidators, mnemonickeys
import onionrcrypto as crypto, onionrexceptions
class OnionrCryptoTests(unittest.TestCase):
def test_blake2b(self):
self.assertEqual(crypto.hashers.blake2b_hash('test'), crypto.hashers.blake2b_hash(b'test'))
self.assertEqual(crypto.hashers.blake2b_hash(b'test'), crypto.hashers.blake2b_hash(b'test'))
self.assertNotEqual(crypto.hashers.blake2b_hash(''), crypto.hashers.blake2b_hash(b'test'))
try:
crypto.hashers.blake2b_hash(None)
except nacl.exceptions.TypeError:
pass
else:
self.assertTrue(False)
self.assertEqual(nacl.hash.blake2b(b'test'), crypto.hashers.blake2b_hash(b'test'))
def test_sha3256(self):
hasher = hashlib.sha3_256()
self.assertEqual(crypto.hashers.sha3_hash('test'), crypto.hashers.sha3_hash(b'test'))
self.assertEqual(crypto.hashers.sha3_hash(b'test'), crypto.hashers.sha3_hash(b'test'))
self.assertNotEqual(crypto.hashers.sha3_hash(''), crypto.hashers.sha3_hash(b'test'))
try:
crypto.hashers.sha3_hash(None)
except TypeError:
pass
else:
self.assertTrue(False)
hasher.update(b'test')
normal = hasher.hexdigest()
self.assertEqual(crypto.hashers.sha3_hash(b'test'), normal)
def valid_default_id(self):
self.assertTrue(stringvalidators.validate_pub_key(crypto.pub_key))
def test_human_readable_length(self):
human = mnemonickeys.get_human_readable_ID()
self.assertTrue(len(human.split(' ')) == 24)
def test_safe_compare(self):
self.assertTrue(crypto.cryptoutils.safe_compare('test', 'test'))
self.assertTrue(crypto.cryptoutils.safe_compare('test', b'test'))
self.assertFalse(crypto.cryptoutils.safe_compare('test', 'test2'))
try:
crypto.cryptoutils.safe_compare('test', None)
except TypeError:
pass
else:
self.assertTrue(False)
def test_random_shuffle(self):
# Small chance that the randomized list will be same. Rerun test a couple times if it fails
startList = ['cat', 'dog', 'moose', 'rabbit', 'monkey', 'crab', 'human', 'dolphin', 'whale', 'etc'] * 10
self.assertNotEqual(startList, list(crypto.cryptoutils.random_shuffle(startList)))
self.assertTrue(len(list(crypto.cryptoutils.random_shuffle(startList))) == len(startList))
def test_asymmetric(self):
keyPair = crypto.generate()
keyPair2 = crypto.generate()
message = "hello world"
self.assertTrue(len(crypto.encryption.pub_key_encrypt(message, keyPair2[0], encodedData=True)) > 0)
encrypted = crypto.encryption.pub_key_encrypt(message, keyPair2[0], encodedData=False)
decrypted = crypto.encryption.pub_key_decrypt(encrypted, privkey=keyPair2[1], encodedData=False)
self.assertTrue(decrypted.decode() == message)
try:
crypto.encryption.pub_key_encrypt(None, keyPair2[0])
except TypeError:
pass
else:
self.assertTrue(False)
blankMessage = crypto.encryption.pub_key_encrypt('', keyPair2[0])
self.assertTrue('' == crypto.encryption.pub_key_decrypt(blankMessage, privkey=keyPair2[1], encodedData=False).decode())
# Try to encrypt arbitrary bytes
crypto.encryption.pub_key_encrypt(os.urandom(32), keyPair2[0])
def test_deterministic(self):
password = os.urandom(32)
gen = crypto.generate_deterministic(password)
self.assertTrue(stringvalidators.validate_pub_key(gen[0]))
try:
crypto.generate_deterministic('weakpassword')
except onionrexceptions.PasswordStrengthError:
pass
else:
self.assertFalse(True)
try:
crypto.generate_deterministic(None)
except TypeError:
pass
else:
self.assertFalse(True)
gen = crypto.generate_deterministic('weakpassword', bypassCheck=True)
password = base64.b64encode(os.urandom(32))
gen1 = crypto.generate_deterministic(password)
gen2 = crypto.generate_deterministic(password)
self.assertFalse(gen == gen1)
self.assertTrue(gen1 == gen2)
self.assertTrue(stringvalidators.validate_pub_key(gen1[0]))
unittest.main()

View file

@ -1,15 +0,0 @@
#!/usr/bin/env python3
import sys, os
sys.path.append(".")
import unittest, uuid
from utils import identifyhome
class IdentifyHomeTest(unittest.TestCase):
def test_standard_linux(self):
del os.environ["ONIONR_HOME"]
self.assertEqual(identifyhome.identify_home(), os.path.expanduser('~') + '/.local/share/onionr/')
def test_environ(self):
os.environ["ONIONR_HOME"] = "testhome"
self.assertEqual(os.getcwd() + "/testhome/", identifyhome.identify_home())
unittest.main()

View file

@ -1,38 +0,0 @@
#!/usr/bin/env python3
import sys, os
sys.path.append(".")
import unittest, uuid
TEST_DIR = 'testdata/%s-%s' % (uuid.uuid4(), os.path.basename(__file__)) + '/'
print("Test directory:", TEST_DIR)
os.environ["ONIONR_HOME"] = TEST_DIR
from utils import createdirs
from coredb import keydb
import onionrsetup as setup, keymanager, filepaths
from onionrutils import stringvalidators
createdirs.create_dirs()
setup.setup_config()
pub_key = keymanager.KeyManager().getPubkeyList()[0]
class KeyManagerTest(unittest.TestCase):
def test_sane_default(self):
self.assertGreaterEqual(len(pub_key), 52)
self.assertLessEqual(len(pub_key), 56)
self.assertEqual(pub_key, keymanager.KeyManager().getPubkeyList()[0])
stringvalidators.validate_pub_key(pub_key)
def test_change(self):
new_key = keymanager.KeyManager().addKey()[0]
self.assertNotEqual(new_key, pub_key)
self.assertEqual(new_key, keymanager.KeyManager().getPubkeyList()[1])
stringvalidators.validate_pub_key(new_key)
def test_remove(self):
manager = keymanager.KeyManager()
new_key = manager.addKey()[0]
priv_key = manager.getPrivkey(new_key)
self.assertIn(new_key, manager.getPubkeyList())
with open(filepaths.keys_file, 'r') as keyfile:
self.assertIn(new_key, keyfile.read())
manager.removeKey(new_key)
with open(filepaths.keys_file, 'r') as keyfile:
self.assertNotIn(new_key, keyfile.read())
unittest.main()

View file

@ -1,31 +0,0 @@
#!/usr/bin/env python3
import sys, os
sys.path.append(".")
import unittest, uuid
TEST_DIR = 'testdata/%s-%s' % (uuid.uuid4(), os.path.basename(__file__)) + '/'
print("Test directory:", TEST_DIR)
os.environ["ONIONR_HOME"] = TEST_DIR
from utils import networkmerger, createdirs
from coredb import keydb
import onionrsetup as setup
from utils import createdirs
createdirs.create_dirs()
setup.setup_config()
class NetworkMergerTest(unittest.TestCase):
def test_valid_merge(self):
adders = 'facebookcorewwwi.onion,mporbyyjhmz2c62shctbi3ngrslne5lpcyav6uzhxok45iblodhgjoad.onion'
networkmerger.mergeAdders(adders)
added = keydb.listkeys.list_adders()
self.assertIn('mporbyyjhmz2c62shctbi3ngrslne5lpcyav6uzhxok45iblodhgjoad.onion', added)
self.assertNotIn('inwalidkcorewwi.onion', added)
self.assertIn('facebookcorewwwi.onion', added)
def test_invalid_mergeself(self):
adders = 'facebookc0rewwi.onion,sdfsdfsdf.onion, ssdf324, null, \n'
networkmerger.mergeAdders(adders)
added = keydb.listkeys.list_adders()
for adder in adders:
self.assertNotIn(adder, added)
unittest.main()

View file

@ -1,92 +0,0 @@
#!/usr/bin/env python3
import sys, os
sys.path.append(".")
import unittest, uuid
import json
TEST_DIR = 'testdata/%s-%s' % (uuid.uuid4(), os.path.basename(__file__)) + '/'
print("Test directory:", TEST_DIR)
os.environ["ONIONR_HOME"] = TEST_DIR
import onionrexceptions
from onionrusers import onionrusers
from onionrusers import contactmanager
import onionrcrypto as crypto
from coredb import keydb
from utils import identifyhome, createdirs
createdirs.create_dirs()
class OnionrUserTests(unittest.TestCase):
'''
Tests both the onionrusers class and the contactmanager (which inherits it)
'''
def test_users(self):
keypair = crypto.generate()
onionrusers.OnionrUser(keypair[0])
return
def test_contact_init_no_save(self):
contact = crypto.generate()[0]
contact = contactmanager.ContactManager(contact)
self.assertFalse(contact.publicKey in keydb.listkeys.list_peers())
def test_contact_create(self):
contact = crypto.generate()[0]
contact = contactmanager.ContactManager(contact, saveUser=True)
self.assertTrue(contact.publicKey in keydb.listkeys.list_peers())
def test_contact_set_info(self):
contact = crypto.generate()[0]
contact = contactmanager.ContactManager(contact, saveUser=True)
fileLocation = '%s/contacts/%s.json' % (identifyhome.identify_home(), contact.publicKey)
contact.set_info('alias', 'bob')
self.assertTrue(os.path.exists(fileLocation))
with open(fileLocation, 'r') as data:
data = data.read()
data = json.loads(data)
self.assertEqual(data['alias'], 'bob')
def test_contact_get_info(self):
contact = crypto.generate()[0]
contact = contactmanager.ContactManager(contact, saveUser=True)
fileLocation = '%s/contacts/%s.json' % (identifyhome.identify_home(), contact.publicKey)
with open(fileLocation, 'w') as contactFile:
contactFile.write('{"alias": "bob"}')
self.assertEqual(contact.get_info('alias', forceReload=True), 'bob')
self.assertEqual(contact.get_info('fail', forceReload=True), None)
self.assertEqual(contact.get_info('fail'), None)
def test_encrypt(self):
contactPair = crypto.generate()
contact = contactmanager.ContactManager(contactPair[0], saveUser=True)
encrypted = contact.encrypt('test')
decrypted = crypto.encryption.pub_key_decrypt(encrypted, privkey=contactPair[1], encodedData=True).decode()
self.assertEqual('test', decrypted)
def test_delete_contact(self):
contact = crypto.generate()[0]
contact = contactmanager.ContactManager(contact, saveUser=True)
fileLocation = '%s/contacts/%s.json' % (identifyhome.identify_home(), contact.publicKey)
self.assertFalse(os.path.exists(fileLocation))
with open(fileLocation, 'w') as contactFile:
contactFile.write('{"alias": "test"}')
self.assertTrue(os.path.exists(fileLocation))
contact.delete_contact()
self.assertFalse(os.path.exists(fileLocation))
try:
contact.get_info('alias')
except onionrexceptions.ContactDeleted:
pass
else:
self.assertTrue(False)
try:
contact.set_info('alias', 'test2')
except onionrexceptions.ContactDeleted:
pass
else:
self.assertTrue(False)
unittest.main()

View file

@ -1,47 +0,0 @@
import sys, os
sys.path.append(".")
import unittest, uuid
TEST_DIR = 'testdata/%s-%s' % (uuid.uuid4(), os.path.basename(__file__)) + '/'
os.environ["ONIONR_HOME"] = TEST_DIR
import config
import logger
from utils import createdirs
import onionrsetup as setup
from utils import createdirs
import onionrblocks
import filepaths
import onionrexceptions
import storagecounter
import onionrstorage
def _test_setup():
TEST_DIR = 'testdata/%s-%s' % (uuid.uuid4(), os.path.basename(__file__)) + '/'
print("Test directory:", TEST_DIR)
os.environ["ONIONR_HOME"] = TEST_DIR
createdirs.create_dirs()
setup.setup_config()
class TestStorageCounter(unittest.TestCase):
def test_basic_amount(self):
_test_setup()
self.assertIsNotNone(config.get('allocations.disk'))
self.assertGreaterEqual(config.get('allocations.disk'), 1000000)
def test_insert_too_much(self):
_test_setup()
config.set('allocations.disk', 1000)
self.assertRaises(onionrexceptions.DiskAllocationReached, onionrblocks.insert, "test")
def test_count(self):
_test_setup()
counter = storagecounter.StorageCounter()
start_value = counter.get_amount()
b_hash = onionrblocks.insert("test")
self.assertGreater(counter.get_amount(), start_value)
onionrstorage.removeblock.remove_block(b_hash)
self.assertEqual(counter.get_amount(), start_value)
unittest.main()

View file

@ -1,71 +0,0 @@
#!/usr/bin/env python3
import sys, os
sys.path.append(".")
import unittest, uuid
TEST_DIR = 'testdata/%s-%s' % (uuid.uuid4(), os.path.basename(__file__)) + '/'
print("Test directory:", TEST_DIR)
os.environ["ONIONR_HOME"] = TEST_DIR
from onionrutils import stringvalidators
class OnionrValidations(unittest.TestCase):
def test_peer_validator(self):
# Test hidden service domain validities
valid = ['facebookcorewwwi.onion', 'vww6ybal4bd7szmgncyruucpgfkqahzddi37ktceo3ah7ngmcopnpyyd.onion',
'5bvb5ncnfr4dlsfriwczpzcvo65kn7fnnlnt2ln7qvhzna2xaldq.b32.i2p']
invalid = [None, 'dsfewjirji0ejipdfs', '', ' ', '\n', '\r\n', 'f$ce%^okc+rewwwi.onion', 'facebookc0rewwi.onion']
for x in valid:
print('testing', x)
self.assertTrue(stringvalidators.validate_transport(x))
for x in invalid:
print('testing', x)
self.assertFalse(stringvalidators.validate_transport(x))
def test_hash_validator(self):
valid = ['00003b3813a166e706e490238e9515633cc3d083efe982a67753d50d87a00c96\n', '00003b3813a166e706e490238e9515633cc3d083efe982a67753d50d87a00c96', b'00003b3813a166e706e490238e9515633cc3d083efe982a67753d50d87a00c96',
'00003b3813a166e706e490238e9515633cc36', b'00003b3813a166e706e490238e9515633cc3d083']
invalid = [None, 0, 1, True, False, '%#W483242#', '00003b3813a166e706e490238e9515633cc3d083efe982a67753d50d87a00c9666', '', b'',
b'00003b3813a166e706e490238e9515633cc3d083efe982a67753d50d87a00c9666666', b' ', '\n', '00003b3813a166e706e490238e9515633cc3d083efe982a67753d50d87a00ccccc\n']
for x in valid:
self.assertTrue(stringvalidators.validate_hash(x))
for x in invalid:
try:
result = stringvalidators.validate_hash(x)
print('testing', x, result)
except AttributeError:
result = False
try:
self.assertFalse(result)
except AssertionError:
raise AssertionError("%s returned true" % (x,))
def test_pubkey_validator(self):
# Test ed25519 public key validity
valids = ['JZ5VE72GUS3C7BOHDRIYZX4B5U5EJMCMLKHLYCVBQQF3UKHYIRRQ====', 'JZ5VE72GUS3C7BOHDRIYZX4B5U5EJMCMLKHLYCVBQQF3UKHYIRRQ']
invalid = [None, '', ' ', 'dfsg', '\n', 'JZ5VE72GUS3C7BOHDRIYZX4B5U5EJMCMLKHLYCVBQQF3UKHYIR$Q====']
for valid in valids:
print('testing', valid)
self.assertTrue(stringvalidators.validate_pub_key(valid))
for x in invalid:
#print('testing', x)
self.assertFalse(stringvalidators.validate_pub_key(x))
def test_integer_string(self):
valid = ["1", "100", 100, "-5", -5]
invalid = ['test', "1d3434", "1e100", None]
for x in valid:
#print('testing', x)
self.assertTrue(stringvalidators.is_integer_string(x))
for x in invalid:
#print('testing', x)
self.assertFalse(stringvalidators.is_integer_string(x))
unittest.main()

View file

@ -1,21 +0,0 @@
#!/usr/bin/env python3
import unittest, sys
sys.path.append(".")
from utils import reconstructhash
class ZFill_Hash(unittest.TestCase):
def test_reconstruct(self):
h = b"4d20d791cbc293999b97cc627aa011692d317dede3d0fbd390c763210b0d"
self.assertEqual(reconstructhash.reconstruct_hash(h), b"0000" + h)
h = b"4d20d791cbc293999b97cc627aa011692d317dede3d0fbd390c763210b0d"
self.assertEqual(reconstructhash.reconstruct_hash(h, 62), b"00" + h)
def test_deconstruct(self):
h = b"0000e918d24999ad9b0ff00c1d414f36b74afc93871a0ece4bd452f82b56af87"
h_no = b"e918d24999ad9b0ff00c1d414f36b74afc93871a0ece4bd452f82b56af87"
self.assertEqual(reconstructhash.deconstruct_hash(h), h_no)
h = "0000e918d24999ad9b0ff00c1d414f36b74afc93871a0ece4bd452f82b56af87"
h_no = "e918d24999ad9b0ff00c1d414f36b74afc93871a0ece4bd452f82b56af87"
self.assertEqual(reconstructhash.deconstruct_hash(h), h_no)
unittest.main()