Best Python code snippet using avocado_python
do_delete_audio_file_from_db_test.py
Source:do_delete_audio_file_from_db_test.py
1import os2import time3import unittest4from mock import patch5from chirp.library import audio_file_test6from chirp.library import do_delete_audio_file_from_db7from chirp.library import database8TEST_DB_NAME_PATTERN = "/tmp/chirp-library-db_test.%d.sqlite"9class DeleteFingerprintTest(unittest.TestCase):10 def setUp(self):11 self.name = TEST_DB_NAME_PATTERN % int(time.time() * 1000000)12 self.db = database.Database(self.name)13 def tearDown(self):14 os.unlink(self.name)15 def _add_test_audiofiles(self):16 test_volume = 1717 test_import_timestamp = 123095952018 # populate some dummy audiofiles into the database19 all_au_files = [audio_file_test.get_test_audio_file(i)20 for i in xrange(10)]21 add_txn = self.db.begin_add(test_volume, test_import_timestamp)22 for au_file in all_au_files:23 au_file.volume = test_volume24 au_file.import_timestamp = test_import_timestamp25 for au_file in all_au_files:26 add_txn.add(au_file)27 add_txn.commit()28 def test_del_audiofilese__full_delete_single(self):29 # SETUP30 test_fingerprint = "0000000000000007"31 # Create db tables32 self.assertTrue(self.db.create_tables())33 self._add_test_audiofiles()34 # make sure 10 records exist35 self.assertEqual(len(list(self.db.get_all())), 10)36 # quick confirmation that the audiofile that we want to test exists.37 af = self.db.get_by_fingerprint(test_fingerprint)38 self.assertEquals(af.fingerprint, test_fingerprint)39 afm = do_delete_audio_file_from_db.AudioFileManager(40 library_db_file=self.name)41 # TEST42 afm.del_audiofiles([test_fingerprint])43 # RESULTS44 # verify audiofile doesn't exist45 af = self.db.get_by_fingerprint(test_fingerprint)46 self.assertEquals(af, None)47 # make sure only 9 records exist now48 self.assertEqual(len(list(self.db.get_all())), 9)49 def test_del_audiofiles__full_delete_multiple(self):50 # SETUP51 test_fingerprint_1 = "0000000000000005"52 test_fingerprint_2 = "0000000000000007"53 # Create db tables54 self.assertTrue(self.db.create_tables())55 self._add_test_audiofiles()56 # make sure 10 records exist57 self.assertEqual(len(list(self.db.get_all())), 10)58 # quick confirmation that the audiofiles that we want to test exists.59 af = self.db.get_by_fingerprint(test_fingerprint_1)60 self.assertEquals(af.fingerprint, test_fingerprint_1)61 af = self.db.get_by_fingerprint(test_fingerprint_2)62 self.assertEquals(af.fingerprint, test_fingerprint_2)63 afm = do_delete_audio_file_from_db.AudioFileManager(64 library_db_file=self.name)65 # TEST66 afm.del_audiofiles([test_fingerprint_1, test_fingerprint_2])67 # RESULTS68 # verify audiofiles don't exist69 af = self.db.get_by_fingerprint(test_fingerprint_1)70 self.assertEquals(af, None)71 af = self.db.get_by_fingerprint(test_fingerprint_2)72 self.assertEquals(af, None)73 # make sure only 8 records exist now74 self.assertEqual(len(list(self.db.get_all())), 8)75 def test_del_audiofiles__full_delete_non_existing_fingerprint(self):76 # SETUP77 test_fingerprint_1 = "0000000000000020"78 # Create db tables79 self.assertTrue(self.db.create_tables())80 self._add_test_audiofiles()81 # make sure 10 records exist82 self.assertEqual(len(list(self.db.get_all())), 10)83 afm = do_delete_audio_file_from_db.AudioFileManager(84 library_db_file=self.name)85 # TEST86 afm.del_audiofiles([test_fingerprint_1])87 # RESULTS88 # make sure nothing was deleted89 self.assertEqual(len(list(self.db.get_all())), 10)90 def test_del_audiofiles__raises_exception(self):91 # SETUP92 test_fingerprint_1 = "0000000000000007"93 # Create db tables94 self.assertTrue(self.db.create_tables())95 self._add_test_audiofiles()96 # make sure 10 records exist97 self.assertEqual(len(list(self.db.get_all())), 10)98 afm = do_delete_audio_file_from_db.AudioFileManager(99 library_db_file=self.name)100 # TEST101 def _raise_exception(*args, **kwargs):102 raise Exception('Test')103 with patch.object(afm, 'conn', autospec=True) as mock_conn:104 mock_conn.execute.side_effect = _raise_exception105 with self.assertRaises(Exception):106 afm.del_audiofiles([test_fingerprint_1])107 mock_conn.rollback.assert_called_with()108 def test_get_audio_files__existing_record(self):109 # SETUP110 test_fingerprint = "0000000000000007"111 # Create db tables112 self.assertTrue(self.db.create_tables())113 self._add_test_audiofiles()114 afm = do_delete_audio_file_from_db.AudioFileManager(115 library_db_file=self.name)116 # TEST117 af = afm.get_audio_files(fingerprints=[test_fingerprint])118 # RESULTS119 self.assertSetEqual(120 set(a['fingerprint'] for a in af),121 set([test_fingerprint]))122 def test_get_audio_files__non_existing_records(self):123 # SETUP124 test_fingerprint_1 = "0000000000000020"125 # Create db tables126 self.assertTrue(self.db.create_tables())127 self._add_test_audiofiles()128 afm = do_delete_audio_file_from_db.AudioFileManager(129 library_db_file=self.name)130 # TEST131 af = afm.get_audio_files(132 fingerprints=[test_fingerprint_1])133 # RESULTS134 self.assertEqual(len(list(af)), 0)135 def test_get_tags__existing_record(self):136 # SETUP137 test_fingerprint_1 = "0000000000000005"138 # Create db tables139 self.assertTrue(self.db.create_tables())140 self._add_test_audiofiles()141 afm = do_delete_audio_file_from_db.AudioFileManager(142 library_db_file=self.name)143 # TEST144 af = afm.get_tags(145 fingerprints=[test_fingerprint_1])146 # RESULTS147 self.assertListEqual(148 list(a['fingerprint'] for a in af),149 5 * [test_fingerprint_1])150 def test_get_tags__non_existing_records(self):151 # SETUP152 test_fingerprint_1 = "0000000000000020"153 # Create db tables154 self.assertTrue(self.db.create_tables())155 self._add_test_audiofiles()156 afm = do_delete_audio_file_from_db.AudioFileManager(157 library_db_file=self.name)158 # TEST159 af = afm.get_tags(160 fingerprints=[test_fingerprint_1])161 # RESULTS162 self.assertEqual(len(list(af)), 0)163 def test_print_rows_can_handle_non_ascii(self):164 afm = do_delete_audio_file_from_db.AudioFileManager(165 library_db_file=self.name166 )167 afm.print_rows([168 [u'non-ascii string with a \xf8 character'],...
fingerprint_recognizer.py
Source:fingerprint_recognizer.py
1import numpy as np2import pandas as pd3import imageio4import glob5from sklearn.multiclass import OneVsRestClassifier6from sklearn.svm import SVC7from natsort import natsorted8def RGBConversion(image):9 R = image[:,:,0].flatten()10 G = image[:,:,1].flatten()11 B = image[:,:,2].flatten()12 bitMap = np.ceil((R+G+B) / 3)13 return bitMap14def loadImages(train_fingerprint, test_fingerprint):15 trainImages = []16 testImages = []17 count = 018 fingerPrintListTrain=[]19 sortedListTrain= natsorted(glob.glob(train_fingerprint +'/*.bmp'))20 maxCount = len(sortedListTrain)21 for fingerprintTrain in sortedListTrain:22 im = imageio.imread(fingerprintTrain)23 if im is not None:24 row = RGBConversion(im)25 if count < maxCount:26 n = len(fingerprintTrain.split('/'))27 arr = np.asarray(row)28 arr = np.append([arr],[int(fingerprintTrain.split('/')[n-1].split('_')[0])])29 fingerPrintListTrain.append(arr.tolist())30 count += 131 elif im is None:32 print ("Error loading: " + fingerprintTrain)33 continue34 trainImages = pd.DataFrame(fingerPrintListTrain)35 36 fingerPrintListTest=[]37 sortedListTest = natsorted(glob.glob(test_fingerprint +'/*.bmp'))38 for fingerprintTest in sortedListTest:39 im = imageio.imread(fingerprintTest)40 if im is not None:41 row = RGBConversion(im)42 arr = np.asarray(row)43 arr = np.append([arr],[int(fingerprintTest.split('/')[n-1].split('_')[0])])44 fingerPrintListTest.append(arr.tolist())45 elif im is None:46 print ("Error loading: " + fingerprintTest)47 continue48 testImages = pd.DataFrame(fingerPrintListTest)49 return trainImages, testImages50train_fingerprint, test_fingerprint = loadImages( r'/Volumes/Shared/MAC/UCDenver_CSE/MachineLearning/Assignment4/training',51 r'/Volumes/Shared/MAC/UCDenver_CSE/MachineLearning/Assignment4/testB')52print('Data Loaded!!!')53xTrain = train_fingerprint.iloc[:,:-1]54xTrain = np.c_[np.ones((xTrain.shape[0])),xTrain]55yTrain = train_fingerprint.iloc[:,-1]56yTrain = yTrain.as_matrix(columns=None)57xTest = test_fingerprint.iloc[:,:-1]58xTest = np.c_[np.ones((xTest.shape[0])),xTest]59yTest = test_fingerprint.iloc[:,-1]60yTest = yTest.as_matrix(columns=None)61#Normalize the data set62xTrain = xTrain / 25563row, column = xTrain.shape[0], xTrain.shape[1]64div = sum(xTrain.sum(axis=1)) / (row * column)65xTrain = xTrain - div66xTest = xTest / 25567row, column = xTest.shape[0], xTest.shape[1]68div = sum(xTest.sum(axis=1)) / (row * column)69xTest = xTest - div70clf = OneVsRestClassifier(SVC(kernel='rbf', tol=0.03 ,C=1/0.2, gamma=0.03 ,probability=True))71clf = clf.fit(xTrain, yTrain)72accuracy = clf.score(xTest,yTest)73print('Accuracy of data: ',accuracy*100)74clf.decision_function(xTrain)75predLabel = clf.predict(xTest)76correct = np.sum(predLabel == yTest)77print("%d out of %d predictions correct" % (correct, len(predLabel)))...
test_parser.py
Source:test_parser.py
1"""2Unit tests for gpg_keymanager.keys.directory module3"""4import pytest5from gpg_keymanager.exceptions import PGPKeyError6from gpg_keymanager.keys.parser import PublicKeyDataParser, UserPublicKeys7from ..base import mock_called_process_error, mock_pgp_key_error8TOTAL_KEY_COUNT = 59EXPIRED_KEY_COUNT = 210REVOKED_KEYS_COUNT = 111TEST_EMAIL = 'hile@iki.fi'12TEST_KEY_ID = '0x3119E470AD3CCDEC'13TEST_FINGERPRINT = '87DF5EA2B85E025D159888ACC660ACF1DA570475'14# pylint: disable=too-few-public-methods15class MockCalledMethod:16 """17 Test class to check a method was called18 """19 def __init__(self):20 self.call_count = 021 self.args = None22 self.kwargs = None23 def __call__(self, *args, **kwargs):24 self.call_count += 125 self.args = args26 self.kwargs = kwargs27def test_parser_init():28 """29 Test initializing a PublicKeyDataParser object30 """31 parser = PublicKeyDataParser()32 assert len(parser.__items__) == 033 assert parser.is_loaded is False34# pylint: disable=unused-argument35def test_user_keys_load(mock_gpg_key_list):36 """37 Test loading user gpg key list with mocked test data38 """39 keys = UserPublicKeys()40 keys.load()41 assert len(keys) == TOTAL_KEY_COUNT42 assert len(keys.expired_keys) == EXPIRED_KEY_COUNT43 assert len(keys.revoked_keys) == REVOKED_KEYS_COUNT44 assert len(keys.filter_keys(email=TEST_EMAIL)) == 445 assert len(keys.filter_keys(key_id=TEST_KEY_ID)) == 146 assert len(keys.filter_keys(fingerprint=TEST_FINGERPRINT)) == 147 keys.clear()48 assert keys.get(TEST_KEY_ID) is not None49 assert keys.get(TEST_FINGERPRINT) is not None50 with pytest.raises(PGPKeyError):51 keys.get(TEST_EMAIL)52# pylint: disable=unused-argument53def test_user_keys_load_error(monkeypatch, mock_gpg_key_list):54 """55 Test error parsing keys when loading user keys56 """57 monkeypatch.setattr(58 'gpg_keymanager.keys.public_key.PublicKey.__load_child_record__',59 mock_pgp_key_error60 )61 keys = UserPublicKeys()62 with pytest.raises(PGPKeyError):63 keys.load()64# pylint: disable=unused-argument65def test_user_keys_load_fail(monkeypatch, mock_gpg_key_list):66 """67 Test failure loading user keys68 """69 monkeypatch.setattr(70 'gpg_keymanager.keys.parser.run_command_lineoutput',71 mock_called_process_error72 )73 keys = UserPublicKeys()74 with pytest.raises(PGPKeyError):75 keys.load()76# pylint: disable=unused-argument77def test_user_keys_trustdb_cleanup(monkeypatch, mock_gpg_key_list):78 """79 Test calling cleanup of user trus database from user keys80 """81 keys = UserPublicKeys()82 mock_method = MockCalledMethod()83 monkeypatch.setattr(84 'gpg_keymanager.keys.trustdb.OwnerTrustDB.remove_stale_entries',85 mock_method86 )87 keys.cleanup_owner_trust_database()88 assert mock_method.call_count == 189 with pytest.raises(PGPKeyError):90 keys.__gpg_args__ = [TEST_KEY_ID]...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!