From: Mariana Mărășoiu Date: Fri, 2 Sep 2011 16:43:36 +0000 (+0300) Subject: ppf/new: Update code according to PEP 8. X-Git-Url: http://p2p-next.cs.pub.ro/gitweb/?a=commitdiff_plain;h=94648dcad7c4fc3d0b73c0b585099ac474a0e95d;p=cs-p2p-next.git ppf/new: Update code according to PEP 8. Add docstrings for classes and most functions. Limit maximum line length to 79 characters. Update alignment. --- diff --git a/ppf/new/config.py b/ppf/new/config.py index 5e08598..84f3a14 100644 --- a/ppf/new/config.py +++ b/ppf/new/config.py @@ -26,7 +26,8 @@ ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # Create formatter. -formatter = logging.Formatter('%(filename)s:%(lineno)s - %(levelname)s: %(message)s') +formatter = logging.Formatter('%(filename)s:%(lineno)s - ' + '%(levelname)s: %(message)s') # Add formatter to console handler. ch.setFormatter(formatter) @@ -34,15 +35,22 @@ ch.setFormatter(formatter) # Add console handler to logger. logger.addHandler(ch) + class SwarmDescription(object): + + """Swarm Description class based on ConfigParser.""" + def __init__(self): + """Initialize the data field as an instance of ConfigParser().""" self.data = ConfigParser.ConfigParser() def load(self, swarm_config_file): - """ Load configuration file and use ConfigParser. - Expect configuration file without first section for swarm information. + """Load configuration file. + Expect configuration file without first section for swarm information. + Ignore tabs in configuration file. """ + NOSECTION = 'swarm' try: text = open(swarm_config_file).read() @@ -53,13 +61,13 @@ class SwarmDescription(object): self.data.readfp(f) def store(self, ini_file): - """ Write configuration information to file. """ + """Write configuration information to file.""" f = open(ini_file, 'w') self.data.write(f) f.close() def get_swarm(self): - """ Return Swarm object containing information from config file. """ + """Return Swarm object containing information from config file.""" swarm_data = dict(self.data.items('swarm')) swarm = storage.Swarm(swarm_data['torrent_filename'], swarm_data['data_size'], @@ -67,7 +75,7 @@ class SwarmDescription(object): return swarm def get_session_entries(self): - """ Return list of SessionEntry instances. """ + """Return list of SessionEntry instances.""" session_names = self.data.sections() session_names.remove('swarm') session_list = [] @@ -80,13 +88,13 @@ class SwarmDescription(object): return session_list def update_session_entry_id(self, session_entry, cs_id): - """ Add or modify client session id. """ + """Add or modify client session id in self and session_entry.""" session_name = session_entry.data.sections()[0] self.data.set(session_name, 'client_session_id', str(cs_id)) session_entry.data.set(session_name, 'client_session_id', str(cs_id)) def get_file_archives(self): - """ Return a list containing all archives from swarm. """ + """Return a list containing all archives from swarm.""" archives = [] for section in self.data.sections(): try: @@ -95,13 +103,18 @@ class SwarmDescription(object): pass return archives + class SessionEntry(object): + + """Session Description class based on ConfigParser.""" + def __init__(self, session): + """Initialize the data field as an instance of ConfigParser().""" self.data = ConfigParser.ConfigParser() self.data.add_section(session) def get_session(self): - """ Return name of the session. """ + """Return name of the session.""" session = self.data.sections()[0] cs_data = dict(self.data.items(session)) cs = storage.ClientSession( @@ -122,10 +135,11 @@ class SessionEntry(object): return cs def get_session_id(self): - """ Return client session id corresponding to the entry. - If the session entry hasn't been asigned a session id raise error. + """Return client session id corresponding to the entry. + If the session entry hasn't been asigned a session id raise error. """ + section = self.data.sections()[0] try: cs_id = self.data.get(section, 'client_session_id') @@ -134,12 +148,17 @@ class SessionEntry(object): logger.debug("No client session id for entry: %s" %section) return None + class AccessConfig(object): + + """Access Configuration class based on ConfigParser.""" + def __init__(self): + """Initialize the data field as an instance of ConfigParser().""" self.data = ConfigParser.ConfigParser() def load(self, access_config_file): - """ Load configuration file and use ConfigParser. """ + """Load configuration file.""" try: text = open(access_config_file).read() except IOError: @@ -149,17 +168,18 @@ class AccessConfig(object): self.data.readfp(f) def store(self, ini_file): - """ Write configuration information to file. """ + """Write configuration information to file.""" f = open(ini_file, 'w') self.data.write(f) f.close() def get_swarm_writer(self): - """ Return storage.SwarmWriter instance. - For each section create coresponding storage.*Access instance - and add to SwarmWriter.handlers list. + """Return storage.SwarmWriter instance. + For each section create coresponding storage.*Access instance + and add it to SwarmWriter.handlers list. """ + sw = storage.SwarmWriter() for section in self.data.sections(): if section == 'mysql': diff --git a/ppf/new/storage.py b/ppf/new/storage.py index 8cb9535..a469595 100644 --- a/ppf/new/storage.py +++ b/ppf/new/storage.py @@ -29,7 +29,8 @@ ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # Create formatter. -formatter = logging.Formatter('%(filename)s:%(lineno)s - %(levelname)s: %(message)s') +formatter = logging.Formatter('%(filename)s:%(lineno)s - ' + '%(levelname)s: %(message)s') # Add formatter to console handler. ch.setFormatter(formatter) @@ -203,7 +204,16 @@ class VerboseMessage(object): self.length = length self.listen_port = listen_port + class SwarmDataAccess(object): + + """Base class for swarm information storage. + + Define main operations on storage objects: Swarm, ClientSession, + StatusMessage, PeerStatusMessage, VerboseMessage. + Each object has four corresponding operations: add, remove, get, update. + """ + def __init__(self): pass @@ -267,15 +277,22 @@ class SwarmDataAccess(object): def update_verbose_message(self): pass + class FileAccess(SwarmDataAccess): + + """Subclass of SwarmDataAccess providing access for file storage.""" + def __init__(self, path): + """Add base_path attribute received as argument.""" self.base_path = path + def find_last_numeric_subfolder(path): - """ - Find last numeric folder in base_path folder. + """Find last numeric folder in base_path folder. + The last numeric folder is the last swarm_id. """ + dir_list = [] pattern = re.compile("[0-9]+") @@ -293,8 +310,13 @@ def find_last_numeric_subfolder(path): dir_list.sort() return dir_list[len(dir_list)-1] + class TreeTextFileAccess(FileAccess): + + """Child class of FileAccess for directory tree structure access.""" + def __init__(self, path): + """Use superclass method for initialisation of constructor.""" super(TreeTextFileAccess, self).__init__(path) def add_swarm(self, swarm): @@ -367,6 +389,7 @@ class TreeTextFileAccess(FileAccess): f.close() def add_peer_status_message(self, msg): + """Add peer status msg line to file. msg type is PeerStatusMessage.""" # TODO: id is number of lines in file. swarm_path = os.path.join(self.base_path, str(msg.swarm_id)) session_path = os.path.join(swarm_path, str(msg.client_session_id)) @@ -380,6 +403,7 @@ class TreeTextFileAccess(FileAccess): f.close() def add_status_message(self, msg): + """Add status msg line to file. msg type is StatusMessage.""" # TODO: id is number of lines in file. swarm_path = os.path.join(self.base_path, str(msg.swarm_id)) session_path = os.path.join(swarm_path, str(msg.client_session_id)) @@ -394,6 +418,7 @@ class TreeTextFileAccess(FileAccess): f.close() def add_verbose_message(self, msg): + """Add verbose msg line to file. msg type is VerboseMessage.""" # TODO: id is number of lines in file. swarm_path = os.path.join(self.base_path, str(msg.swarm_id)) session_path = os.path.join(swarm_path, str(msg.client_session_id)) @@ -408,22 +433,37 @@ class TreeTextFileAccess(FileAccess): f.close() class DatabaseAccess(SwarmDataAccess): + + """Subclass of SwarmDataAccess providing functions for database usage.""" + def __init__(self, database): + """Add database attribute received as argument. + + The argument may be a name or a list with options for connection. + """ + self.database = database def connect(self): + """Initialize access attributes.""" self.conn = None self.cursor = None def disconnect(self): + """Close connection with database.""" self.cursor.close() self.conn.close() class SQLiteDatabaseAccess(DatabaseAccess): - def __init___(self, database): + + """Child class of DatabaseAccess for SQLite access.""" + + def __init__(self, database): + """Use superclass method for initialisation of constructor.""" super(SQLiteDatabaseAccess, self).__init__(database) def connect(self): + """Connect to sqlite3 database.""" self.conn = sqlite3.connect(self.database) self.cursor = self.conn.cursor() # Use foreign key support if available. @@ -440,6 +480,7 @@ class SQLiteDatabaseAccess(DatabaseAccess): self.values = self.values + "'" + str(data_value) + "'" + ", " def add_swarm(self, swarm): + """Insert swarm in database. swarm type is Swarm.""" self.reset_query() self.append_to_insert_query("torrent_filename", swarm.torrent_filename) self.append_to_insert_query("data_size", swarm.data_size) @@ -453,13 +494,15 @@ class SQLiteDatabaseAccess(DatabaseAccess): self.conn.commit() def add_client_session(self, session): + """Insert session in database. session type is Session.""" self.reset_query() self.append_to_insert_query("swarm_id", session.swarm_id) # TODO: search database for client ID self.append_to_insert_query("btclient_id", bittorrent_clients[session.btclient]['id']) self.append_to_insert_query("system_os", session.system_os) - self.append_to_insert_query("system_os_version", session.system_os_version) + self.append_to_insert_query("system_os_version", + session.system_os_version) self.append_to_insert_query("system_ram", session.system_ram) self.append_to_insert_query("system_cpu", session.system_cpu) self.append_to_insert_query("public_ip", session.public_ip) @@ -469,7 +512,8 @@ class SQLiteDatabaseAccess(DatabaseAccess): self.append_to_insert_query("start_time", session.start_time) self.append_to_insert_query("dht_enabled", session.dht_enabled) self.append_to_insert_query("pxe_enabled", session.pxe_enabled) - self.append_to_insert_query("streaming_enabled", session.streaming_enabled) + self.append_to_insert_query("streaming_enabled", + session.streaming_enabled) self.append_to_insert_query("features", session.features) self.append_to_insert_query("description", session.description) @@ -488,6 +532,9 @@ class SQLiteDatabaseAccess(DatabaseAccess): 1000 * ts.microsecond) def add_peer_status_message(self, msg): + """Insert peer status message in database. + msg type is PeerStatusMessage. + """ self.reset_query() self.append_to_insert_query("client_session_id", msg.client_session_id) @@ -510,6 +557,7 @@ class SQLiteDatabaseAccess(DatabaseAccess): self.conn.commit() def add_status_message(self, msg): + """Insert status msg in database. msg type is StatusMessage.""" self.reset_query() self.append_to_insert_query("client_session_id", msg.client_session_id) @@ -534,6 +582,7 @@ class SQLiteDatabaseAccess(DatabaseAccess): self.conn.commit() def add_verbose_message(self, msg): + """Insert verbose msg in database. msg type is VerboseMessage.""" self.reset_query() self.append_to_insert_query("client_session_id", msg.client_session_id) @@ -561,16 +610,24 @@ class SQLiteDatabaseAccess(DatabaseAccess): self.conn.commit() class MySQLDatabaseAccess(DatabaseAccess): - def __init___(self, database): + + """Child class of DatabaseAccess for MySQL access.""" + + def __init__(self, database): + """Initialize the database attribute of the class. + + Use superclass method for initialisation of constructor. + """ + super(MySQLDatabaseAccess, self).__init__(database) def connect(self): - # TODO Add support for reading connection information from config_file + """Connect to MySQL database.""" self.conn = MySQLdb.Connection(db=self.database['database'], user=self.database['user'], passwd=self.database['password'], host=self.database['host'], - port=self.database['port']) + port=int(self.database['port'])) self.cursor = self.conn.cursor() self.conn.commit() @@ -584,6 +641,7 @@ class MySQLDatabaseAccess(DatabaseAccess): self.values = self.values + "'" + str(data_value) + "'" + ", " def add_swarm(self, swarm): + """Insert swarm in database. swarm type is Swarm.""" self.reset_query() self.append_to_insert_query("torrent_filename", swarm.torrent_filename) self.append_to_insert_query("data_size", swarm.data_size) @@ -597,13 +655,15 @@ class MySQLDatabaseAccess(DatabaseAccess): self.conn.commit() def add_client_session(self, session): + """Insert session in database. session type is Session.""" self.reset_query() self.append_to_insert_query("swarm_id", session.swarm_id) # TODO: search database for client ID self.append_to_insert_query("btclient_id", bittorrent_clients[session.btclient]['id']) self.append_to_insert_query("system_os", session.system_os) - self.append_to_insert_query("system_os_version", session.system_os_version) + self.append_to_insert_query("system_os_version", + session.system_os_version) self.append_to_insert_query("system_ram", session.system_ram) self.append_to_insert_query("system_cpu", session.system_cpu) self.append_to_insert_query("public_ip", session.public_ip) @@ -613,7 +673,8 @@ class MySQLDatabaseAccess(DatabaseAccess): self.append_to_insert_query("start_time", session.start_time) self.append_to_insert_query("dht_enabled", session.dht_enabled) self.append_to_insert_query("pxe_enabled", session.pxe_enabled) - self.append_to_insert_query("streaming_enabled", session.streaming_enabled) + self.append_to_insert_query("streaming_enabled", + session.streaming_enabled) self.append_to_insert_query("features", session.features) self.append_to_insert_query("description", session.description) @@ -630,6 +691,9 @@ class MySQLDatabaseAccess(DatabaseAccess): %(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second) def add_peer_status_message(self, msg): + """Insert peer status message in database. + msg type is PeerStatusMessage. + """ self.reset_query() self.append_to_insert_query("client_session_id", msg.client_session_id) @@ -650,6 +714,7 @@ class MySQLDatabaseAccess(DatabaseAccess): self.conn.commit() def add_status_message(self, msg): + """Insert status msg in database. msg type is StatusMessage.""" self.reset_query() self.append_to_insert_query("client_session_id", msg.client_session_id) @@ -673,6 +738,7 @@ class MySQLDatabaseAccess(DatabaseAccess): self.conn.commit() def add_verbose_message(self, msg): + """Insert verbose msg in database. msg type is VerboseMessage.""" self.reset_query() self.append_to_insert_query("client_session_id", msg.client_session_id) @@ -699,9 +765,10 @@ class MySQLDatabaseAccess(DatabaseAccess): self.conn.commit() class SwarmWriter(object): - """ - Wrapper class for swarm storage write actions. Multiple *Access - objects may be added to the clas resulting in multiple storage types. + """Wrapper class for swarm storage write actions. + + Multiple *Access objects may be added to the clas resulting in multiple + storage types. For example, adding a swarm could result in * adding a table entry in a MySQL database (MySQLDatabaseAccess) * adding a table entry in an SQLite database (SQLiteDatabaseAccess) diff --git a/ppf/new/tests/test_config.py b/ppf/new/tests/test_config.py index 073e44b..40e49e5 100644 --- a/ppf/new/tests/test_config.py +++ b/ppf/new/tests/test_config.py @@ -14,9 +14,8 @@ import config import storage class SwarmDescriptionTest(unittest.TestCase): - """ - Test suite for SwarmDescription class in config.py. - """ + + """Test suite for SwarmDescription class in config.py.""" # Class specific variables. Initialized in setUp, used throughout tests. config_file = "config.sample.ini" @@ -24,10 +23,13 @@ class SwarmDescriptionTest(unittest.TestCase): sd = None def setUp(self): - self.test_data = {'swarm': {'torrent_filename': 'fedora-11-cds.torrent', + self.test_data = {'swarm': {'torrent_filename': + 'fedora-11-cds.torrent', 'data_size': '12345678', - 'description': 'BitTorrent Distribution Experiment, Fedora 11, i386 netinst'}, - 'p2p-next-01': {'bittorrent_client': 'libtorrent-rasterbar', + 'description': ('BitTorrent Distribution ' + 'Experiment, Fedora 11, i386 netinst')}, + 'p2p-next-01': {'bittorrent_client': + 'libtorrent-rasterbar', 'system_os': 'Linux', 'system_os_version': '2.6.26', 'system_ram': '1999', @@ -36,13 +38,17 @@ class SwarmDescriptionTest(unittest.TestCase): 'public_port': '6881', 'ds_limit': '0', 'us_limit': '0', - 'start_time': 'Thu Aug 11 15:36:35 EEST 2010', + 'start_time': + 'Thu Aug 11 15:36:35 EEST 2010', 'dht_enabled': 'true', 'pxe_enabled': 'false', 'streaming_enabled': 'false', 'description': 'NCIT Cluster System', - 'log_file': 'p2p-next-01.grid.pub.ro/btex-fedora-11/dbex-fedora-cds.tar.gz'}, - 'p2p-next-03': {'bittorrent_client': 'libtorrent-rasterbar', + 'log_file': + 'p2p-next-01.grid.pub.ro/btex-fe' + 'dora-11/dbex-fedora-cds.tar.gz'}, + 'p2p-next-03': {'bittorrent_client': + 'libtorrent-rasterbar', 'system_os': 'Linux', 'system_os_version': '2.6.26', 'system_ram': '2007', @@ -51,13 +57,17 @@ class SwarmDescriptionTest(unittest.TestCase): 'public_port': '6881', 'ds_limit': '0', 'us_limit': '0', - 'start_time': 'Thu Aug 11 15:36:35 EEST 2010', + 'start_time': + 'Thu Aug 11 15:36:35 EEST 2010', 'dht_enabled': 'true', 'pxe_enabled': 'false', 'streaming_enabled': 'false', 'description': 'NCIT Cluster System', - 'log_file': 'p2p-next-03.grid.pub.ro/btex-fedora-11/dbex-fedora-cds.tar.gz'}, - 'p2p-next-04': {'bittorrent_client': 'libtorrent-rasterbar', + 'log_file': + 'p2p-next-03.grid.pub.ro/btex-fe' + 'dora-11/dbex-fedora-cds.tar.gz'}, + 'p2p-next-04': {'bittorrent_client': + 'libtorrent-rasterbar', 'system_os': 'Linux', 'system_os_version': '2.6.26', 'system_ram': '2007', @@ -66,13 +76,17 @@ class SwarmDescriptionTest(unittest.TestCase): 'public_port': '6881', 'ds_limit': '0', 'us_limit': '0', - 'start_time': 'Thu Aug 11 15:36:35 EEST 2010', + 'start_time': + 'Thu Aug 11 15:36:35 EEST 2010', 'dht_enabled': 'true', 'pxe_enabled': 'false', 'streaming_enabled': 'false', 'description': 'NCIT Cluster System', - 'log_file': 'p2p-next-04.grid.pub.ro/btex-fedora-11/dbex-fedora-cds.tar.gz'}, - 'p2p-next-09': {'bittorrent_client': 'libtorrent-rasterbar', + 'log_file': + 'p2p-next-04.grid.pub.ro/btex-fe' + 'dora-11/dbex-fedora-cds.tar.gz'}, + 'p2p-next-09': {'bittorrent_client': + 'libtorrent-rasterbar', 'system_os': 'Linux', 'system_os_version': '2.6.26', 'system_ram': '1999', @@ -81,12 +95,15 @@ class SwarmDescriptionTest(unittest.TestCase): 'public_port': '6881', 'ds_limit': '0', 'us_limit': '0', - 'start_time': 'Thu Aug 11 15:36:35 EEST 2010', + 'start_time': + 'Thu Aug 11 15:36:35 EEST 2010', 'dht_enabled': 'true', 'pxe_enabled': 'false', 'streaming_enabled': 'false', 'description': 'NCIT Cluster System', - 'log_file': 'p2p-next-09.grid.pub.ro/btex-fedora-11/dbex-fedora-cds.tar.gz'}} + 'log_file': + 'p2p-next-09.grid.pub.ro/btex-fe' + 'dora-11/dbex-fedora-cds.tar.gz'}} config_file_path = os.path.join(os.path.dirname(__file__), self.config_file) @@ -119,9 +136,9 @@ class SwarmDescriptionTest(unittest.TestCase): def test_get_swarm(self): swarm = self.sd.get_swarm() expected_swarm = storage.Swarm( - self.test_data['swarm']['torrent_filename'], - self.test_data['swarm']['data_size'], - self.test_data['swarm']['description']) + self.test_data['swarm']['torrent_filename'], + self.test_data['swarm']['data_size'], + self.test_data['swarm']['description']) self.assertEqual(swarm.torrent_filename, expected_swarm.torrent_filename) @@ -149,17 +166,17 @@ class SwarmDescriptionTest(unittest.TestCase): def test_get_file_archives(self): archives = self.sd.get_file_archives() expected_archives = [ - 'p2p-next-01.grid.pub.ro/btex-fedora-11/dbex-fedora-cds.tar.gz', - 'p2p-next-03.grid.pub.ro/btex-fedora-11/dbex-fedora-cds.tar.gz', - 'p2p-next-04.grid.pub.ro/btex-fedora-11/dbex-fedora-cds.tar.gz', - 'p2p-next-09.grid.pub.ro/btex-fedora-11/dbex-fedora-cds.tar.gz'] + 'p2p-next-01.grid.pub.ro/btex-fedora-11/dbex-fedora-cds.tar.gz', + 'p2p-next-03.grid.pub.ro/btex-fedora-11/dbex-fedora-cds.tar.gz', + 'p2p-next-04.grid.pub.ro/btex-fedora-11/dbex-fedora-cds.tar.gz', + 'p2p-next-09.grid.pub.ro/btex-fedora-11/dbex-fedora-cds.tar.gz'] self.assertEqual(archives.sort(),expected_archives.sort()) + class SessionEntryTest(unittest.TestCase): - """ - Test suite for SessionEntry class in config.py. - """ + + """Test suite for SessionEntry class in config.py.""" # Class specific variables. Initialized in setUp, used throughout tests. se = None @@ -190,10 +207,10 @@ class SessionEntryTest(unittest.TestCase): cs_id = self.se.get_session_id() self.assertEqual(str(cs_id), str(test_cs_id)) + class AccessConfigTest(unittest.TestCase): - """ - Test suite for AccessConfig class in config.py. - """ + + """Test suite for AccessConfig class in config.py.""" # Class specific variables. Initialized in setUp, used throughout tests. access_file = "access.sample.ini" @@ -242,5 +259,6 @@ class AccessConfigTest(unittest.TestCase): self.assertEqual(expected_handlers, handlers) + if __name__ == "__main__": unittest.main() diff --git a/ppf/new/tests/test_storage.py b/ppf/new/tests/test_storage.py index 33fe26b..66c15de 100644 --- a/ppf/new/tests/test_storage.py +++ b/ppf/new/tests/test_storage.py @@ -51,9 +51,8 @@ def create_numeric_files(path): f.close() class StorageTest(unittest.TestCase): - """ - Test suite for stand alone functions in storage.py. - """ + + """Test suite for stand alone functions in storage.py.""" # Class specific variables. Initialized in setUp, used throughout tests. path = "/tmp/ttfa-test" @@ -78,7 +77,8 @@ class StorageTest(unittest.TestCase): id = storage.find_last_numeric_subfolder(self.path) self.assertEqual(id, None) - def test_find_last_numeric_subfolder_only_numeric_subfolders_sequential(self): + def test_find_last_numeric_subfolder_only_numeric_subfolders_sequential( + self): """ Test return of correct id when sequential numeric named subfolders only are present (1, 2, 3, ...). @@ -88,7 +88,8 @@ class StorageTest(unittest.TestCase): id = storage.find_last_numeric_subfolder(self.path) self.assertEqual(id, 5) - def test_find_last_numeric_subfolder_only_numeric_subfolders_nonsequential(self): + def test_find_last_numeric_subfolder_only_numeric_subfolders_nonsequential( + self): """ Test return of correct id when nonsequential numeric named subfolders only are present (32, 5, 423, ...). @@ -135,9 +136,8 @@ class StorageTest(unittest.TestCase): class TreeTextFileAccessTest(unittest.TestCase): - """ - Test suite for TreeTextFileAccess class in storage.py. - """ + + """Test suite for TreeTextFileAccess class in storage.py.""" # Class specific variables. Initialized in setUp, used throughout tests. path = "/tmp/ttfa-test" @@ -154,12 +154,12 @@ class TreeTextFileAccessTest(unittest.TestCase): # Create instance of class and add swarm. a = storage.TreeTextFileAccess(self.path) s = storage.Swarm(torrent_filename="fedora.torrent", - data_size=102400) + data_size=102400) a.add_swarm(s) expected_swarm_subfolder = 1 expected_swarm_path = os.path.join(self.path, - str(expected_swarm_subfolder)) + str(expected_swarm_subfolder)) expected_swarm_config = os.path.join(expected_swarm_path, "swarm.conf") self.assertEqual(os.path.isdir(expected_swarm_path), True) @@ -170,24 +170,27 @@ class TreeTextFileAccessTest(unittest.TestCase): # Add swarm. s = storage.Swarm(torrent_filename="fedora.torrent", - data_size=102400) + data_size=102400) a.add_swarm(s) # Add client session. cs = storage.ClientSession(swarm_id=1, btclient="Tribler", - system_os="Linux", system_os_version="2.6.26", - system_ram=2048, system_cpu=3000, public_ip="141.85.224.201", - public_port="50500", ds_limit=300, us_limit=200) + system_os="Linux", + system_os_version="2.6.26", + system_ram=2048, system_cpu=3000, + public_ip="141.85.224.201", + public_port="50500", ds_limit=300, + us_limit=200) a.add_client_session(cs) expected_swarm_subfolder = 1 expected_session_subfolder = 1 expected_swarm_path = os.path.join(self.path, - str(expected_swarm_subfolder)) + str(expected_swarm_subfolder)) expected_session_path = os.path.join(expected_swarm_path, - str(expected_session_subfolder)) + str(expected_session_subfolder)) expected_session_config = os.path.join(expected_session_path, - "client_session.conf") + "client_session.conf") self.assertEqual(os.path.isdir(expected_session_path), True) self.assertEqual(os.path.isfile(expected_session_config), True) @@ -197,30 +200,34 @@ class TreeTextFileAccessTest(unittest.TestCase): # Add swarm. s = storage.Swarm(torrent_filename="fedora.torrent", - data_size=102400) + data_size=102400) a.add_swarm(s) # Add client session. cs = storage.ClientSession(swarm_id=1, btclient="Tribler", - system_os="Linux", system_os_version="2.6.26", - system_ram=2048, system_cpu=3000, public_ip="141.85.224.201", - public_port="50500", ds_limit=300, us_limit=200) + system_os="Linux", + system_os_version="2.6.26", + system_ram=2048, system_cpu=3000, + public_ip="141.85.224.201", + public_port="50500", ds_limit=300, + us_limit=200) a.add_client_session(cs) # Add peer status message. msg = storage.PeerStatusMessage(swarm_id=1, client_session_id=1, - peer_ip="141.85.224.202", peer_port="12345", - download_speed=13, upload_speed=98) + peer_ip="141.85.224.202", + peer_port="12345", download_speed=13, + upload_speed=98) a.add_peer_status_message(msg) expected_swarm_subfolder = 1 expected_session_subfolder = 1 expected_swarm_path = os.path.join(self.path, - str(expected_swarm_subfolder)) + str(expected_swarm_subfolder)) expected_session_path = os.path.join(expected_swarm_path, - str(expected_session_subfolder)) + str(expected_session_subfolder)) expected_message_file = os.path.join(expected_session_path, - "peer_status.txt") + "peer_status.txt") self.assertEqual(os.path.isfile(expected_message_file), True) @@ -232,30 +239,34 @@ class TreeTextFileAccessTest(unittest.TestCase): # Add swarm. s = storage.Swarm(torrent_filename="fedora.torrent", - data_size=102400) + data_size=102400) a.add_swarm(s) # Add client session. cs = storage.ClientSession(swarm_id=1, btclient="Tribler", - system_os="Linux", system_os_version="2.6.26", - system_ram=2048, system_cpu=3000, public_ip="141.85.224.201", - public_port="50500", ds_limit=300, us_limit=200) + system_os="Linux", + system_os_version="2.6.26", + system_ram=2048, system_cpu=3000, + public_ip="141.85.224.201", + public_port="50500", ds_limit=300, + us_limit=200) a.add_client_session(cs) # Add status message. msg = storage.StatusMessage(swarm_id=1, client_session_id=1, - num_peers=10, num_dht_peers=3, download_speed=102, - upload_speed=99, download_size=10213, upload_size=3301) + num_peers=10, num_dht_peers=3, + download_speed=102, upload_speed=99, + download_size=10213, upload_size=3301) a.add_status_message(msg) expected_swarm_subfolder = 1 expected_session_subfolder = 1 expected_swarm_path = os.path.join(self.path, - str(expected_swarm_subfolder)) + str(expected_swarm_subfolder)) expected_session_path = os.path.join(expected_swarm_path, - str(expected_session_subfolder)) + str(expected_session_subfolder)) expected_message_file = os.path.join(expected_session_path, - "status.txt") + "status.txt") self.assertEqual(os.path.isfile(expected_message_file), True) @@ -267,40 +278,44 @@ class TreeTextFileAccessTest(unittest.TestCase): # Add swarm. s = storage.Swarm(torrent_filename="fedora.torrent", - data_size=102400) + data_size=102400) a.add_swarm(s) # Add client session. cs = storage.ClientSession(swarm_id=1, btclient="Tribler", - system_os="Linux", system_os_version="2.6.26", - system_ram=2048, system_cpu=3000, public_ip="141.85.224.201", - public_port="50500", ds_limit=300, us_limit=200) + system_os="Linux", + system_os_version="2.6.26", + system_ram=2048, system_cpu=3000, + public_ip="141.85.224.201", + public_port="50500", ds_limit=300, + us_limit=200) a.add_client_session(cs) # Add verbose message. msg = storage.VerboseMessage(swarm_id=1, client_session_id=1, - transfer_direction="send", peer_ip="141.85.224.202", - peer_port="12345", message_type="CHOKE") + transfer_direction="send", + peer_ip="141.85.224.202", + peer_port="12345", message_type="CHOKE") a.add_verbose_message(msg) expected_swarm_subfolder = 1 expected_session_subfolder = 1 expected_swarm_path = os.path.join(self.path, - str(expected_swarm_subfolder)) + str(expected_swarm_subfolder)) expected_session_path = os.path.join(expected_swarm_path, - str(expected_session_subfolder)) + str(expected_session_subfolder)) expected_message_file = os.path.join(expected_session_path, - "verbose.txt") + "verbose.txt") self.assertEqual(os.path.isfile(expected_message_file), True) def test_add_verbose_message_number_of_lines(self): self.assertEqual(True, True) + class SQLiteDatabaseAccessTest(unittest.TestCase): - """ - Test suite for SQLiteDatabaseAccess class in storage.py. - """ + + """Test suite for SQLiteDatabaseAccess class in storage.py.""" # Class specific variables. Initialized in setUp, used throughout tests. database = "test.db" @@ -313,7 +328,7 @@ class SQLiteDatabaseAccessTest(unittest.TestCase): expected_verbmsg_count = 0 def get_swarm_count(self): - """ Retrieve number of entries in `swarms` table. """ + """Retrieve number of entries in `swarms` table.""" conn = sqlite3.connect(self.database) cursor = conn.cursor() @@ -326,7 +341,7 @@ class SQLiteDatabaseAccessTest(unittest.TestCase): return count def get_session_count(self): - """ Retrieve number of entries in `client_sessions` table. """ + """Retrieve number of entries in `client_sessions` table.""" conn = sqlite3.connect(self.database) cursor = conn.cursor() @@ -339,7 +354,7 @@ class SQLiteDatabaseAccessTest(unittest.TestCase): return count def get_statmsg_count(self): - """ Retrieve number of entries in `status_messages` table. """ + """Retrieve number of entries in `status_messages` table.""" conn = sqlite3.connect(self.database) cursor = conn.cursor() @@ -352,7 +367,7 @@ class SQLiteDatabaseAccessTest(unittest.TestCase): return count def get_pstatmsg_count(self): - """ Retrieve number of entries in `peer_status_messages` table. """ + """Retrieve number of entries in `peer_status_messages` table.""" conn = sqlite3.connect(self.database) cursor = conn.cursor() @@ -365,7 +380,7 @@ class SQLiteDatabaseAccessTest(unittest.TestCase): return count def get_verbmsg_count(self): - """ Retrieve number of entries in `verbose_messages` table. """ + """Retrieve number of entries in `verbose_messages` table.""" conn = sqlite3.connect(self.database) cursor = conn.cursor() @@ -378,11 +393,11 @@ class SQLiteDatabaseAccessTest(unittest.TestCase): return count def setUp(self): - """ Create database file and instantiate objects. """ + """Create database file and instantiate objects.""" # Create database file. Create tables and indices. # TODO: Check exceptions. sql_create_script_path = os.path.join(os.path.dirname(__file__), - self.sql_create_script) + self.sql_create_script) f = open(sql_create_script_path, 'r') p = subprocess.Popen(["sqlite3", self.database], stdin=f) ret = os.waitpid(p.pid, 0)[1] @@ -391,7 +406,7 @@ class SQLiteDatabaseAccessTest(unittest.TestCase): # Populate database. # TODO: Check exceptions. sql_init_script_path = os.path.join(os.path.dirname(__file__), - self.sql_init_script) + self.sql_init_script) f = open(sql_init_script_path, 'r') p = subprocess.Popen(["sqlite3", self.database], stdin=f) ret = os.waitpid(p.pid, 0)[1] @@ -405,13 +420,13 @@ class SQLiteDatabaseAccessTest(unittest.TestCase): self.expected_verbmsg_count = 2 def tearDown(self): - """ Close connection and remove database file. """ + """Close connection and remove database file.""" os.remove(self.database) def test_add_swarm_new_entry_in_table(self): # Add new swarm. s = storage.Swarm(torrent_filename="fedora.torrent", - data_size=102400) + data_size=102400) a = storage.SQLiteDatabaseAccess(self.database) a.connect() a.add_swarm(s) @@ -426,9 +441,12 @@ class SQLiteDatabaseAccessTest(unittest.TestCase): def test_add_client_session_new_entry_in_table(self): # Add new client session. cs = storage.ClientSession(swarm_id=1, btclient="Tribler", - system_os="Linux", system_os_version="2.6.26", - system_ram=2048, system_cpu=3000, public_ip="141.85.224.201", - public_port="50500", ds_limit=300, us_limit=200) + system_os="Linux", + system_os_version="2.6.26", + system_ram=2048, system_cpu=3000, + public_ip="141.85.224.201", + public_port="50500", ds_limit=300, + us_limit=200) a = storage.SQLiteDatabaseAccess(self.database) a.connect() a.add_client_session(cs) @@ -443,10 +461,11 @@ class SQLiteDatabaseAccessTest(unittest.TestCase): def test_add_status_message_new_entry_in_table(self): # Add new status message. ts = datetime.datetime.strptime("2010-09-12 08:43:15", - "%Y-%m-%d %H:%M:%S") + "%Y-%m-%d %H:%M:%S") msg = storage.StatusMessage(client_session_id=1, timestamp=ts, - num_peers=10, num_dht_peers=3, download_speed=102, - upload_speed=99, download_size=10213, upload_size=3301) + num_peers=10, num_dht_peers=3, + download_speed=102, upload_speed=99, + download_size=10213, upload_size=3301) a = storage.SQLiteDatabaseAccess(self.database) a.connect() a.add_status_message(msg) @@ -461,10 +480,11 @@ class SQLiteDatabaseAccessTest(unittest.TestCase): def test_add_peer_status_message_new_entry_in_table(self): # Add new peer status message. ts = datetime.datetime.strptime("2010-09-12 13:43:25", - "%Y-%m-%d %H:%M:%S") + "%Y-%m-%d %H:%M:%S") msg = storage.PeerStatusMessage(client_session_id=1, timestamp=ts, - peer_ip="141.85.224.202", peer_port="12345", - download_speed=13, upload_speed=98) + peer_ip="141.85.224.202", + peer_port="12345", download_speed=13, + upload_speed=98) a = storage.SQLiteDatabaseAccess(self.database) a.connect() a.add_peer_status_message(msg) @@ -476,13 +496,15 @@ class SQLiteDatabaseAccessTest(unittest.TestCase): self.assertEqual(pstatmsg_count, self.expected_pstatmsg_count) - def test_add_verbose_message_new_entry_in_databas(self): + def test_add_verbose_message_new_entry_in_database(self): # Add new verbose message. ts = datetime.datetime.strptime("2010-09-12 13:43:24", - "%Y-%m-%d %H:%M:%S") + "%Y-%m-%d %H:%M:%S") msg = storage.VerboseMessage(client_session_id=1, timestamp=ts, - transfer_direction="send", peer_ip="141.85.224.202", - peer_port="12345", message_type="CHOKE") + transfer_direction="send", + peer_ip="141.85.224.202", + peer_port="12345", + message_type="CHOKE") a = storage.SQLiteDatabaseAccess(self.database) a.connect() a.add_verbose_message(msg) @@ -496,9 +518,8 @@ class SQLiteDatabaseAccessTest(unittest.TestCase): class MySQLDatabaseAccessTest(unittest.TestCase): - """ - Test suite for MySQLDatabaseAccess class in storage.py. - """ + + """Test suite for MySQLDatabaseAccess class in storage.py.""" # Class specific variables. Initialized in setUp, used throughout tests. database = "p2p_test" @@ -515,43 +536,42 @@ class MySQLDatabaseAccessTest(unittest.TestCase): expected_verbmsg_count = 0 def get_swarm_count(self): - """ Retrieve number of entries in `swarms` table. """ - + """Retrieve number of entries in `swarms` table.""" self.cursor.execute('SELECT COUNT(id) FROM swarms') count = self.cursor.fetchone()[0] return count def get_session_count(self): - """ Retrieve number of entries in `client_sessions` table. """ + """Retrieve number of entries in `client_sessions` table.""" self.cursor.execute('SELECT COUNT(id) FROM client_sessions') count = self.cursor.fetchone()[0] return count def get_statmsg_count(self): - """ Retrieve number of entries in `status_messages` table. """ + """Retrieve number of entries in `status_messages` table.""" self.cursor.execute('SELECT COUNT(id) FROM status_messages') count = self.cursor.fetchone()[0] return count def get_pstatmsg_count(self): - """ Retrieve number of entries in `peer_status_messages` table. """ + """Retrieve number of entries in `peer_status_messages` table.""" self.cursor.execute('SELECT COUNT(id) FROM peer_status_messages') count = self.cursor.fetchone()[0] return count def get_verbmsg_count(self): - """ Retrieve number of entries in `verbose_messages` table. """ + """Retrieve number of entries in `verbose_messages` table.""" self.cursor.execute('SELECT COUNT(id) FROM verbose_messages') count = self.cursor.fetchone()[0] return count def setUp(self): - """ Create database and instantiate objects. """ + """Create database and instantiate objects.""" # Create database. Create tables and indices. # TODO: Check exceptions. @@ -569,11 +589,11 @@ class MySQLDatabaseAccessTest(unittest.TestCase): "--password=%s" %self.password], stdin=f) ret = os.waitpid(p.pid, 0)[1] f.close() - + # Populate database. # TODO: Check exceptions. sql_init_script_path = os.path.join(os.path.dirname(__file__), - self.sql_init_script) + self.sql_init_script) f = open(sql_init_script_path, 'r') p = subprocess.Popen(["mysql", self.database, "--user=%s" %self.user, @@ -597,7 +617,7 @@ class MySQLDatabaseAccessTest(unittest.TestCase): def test_add_swarm_new_entry_in_table(self): # Add new swarm. s = storage.Swarm(torrent_filename="fedora.torrent", - data_size=102400) + data_size=102400) a = storage.MySQLDatabaseAccess(self.database) a.connect() a.add_swarm(s) @@ -612,9 +632,12 @@ class MySQLDatabaseAccessTest(unittest.TestCase): def test_add_client_session_new_entry_in_table(self): # Add new client session. cs = storage.ClientSession(swarm_id=1, btclient="Tribler", - system_os="Linux", system_os_version="2.6.26", - system_ram=2048, system_cpu=3000, public_ip="141.85.224.201", - public_port="50500", ds_limit=300, us_limit=200) + system_os="Linux", + system_os_version="2.6.26", + system_ram=2048, system_cpu=3000, + public_ip="141.85.224.201", + public_port="50500", ds_limit=300, + us_limit=200) a = storage.MySQLDatabaseAccess(self.database) a.connect() a.add_client_session(cs) @@ -629,10 +652,11 @@ class MySQLDatabaseAccessTest(unittest.TestCase): def test_add_status_message_new_entry_in_table(self): # Add new status message. ts = datetime.datetime.strptime("2010-09-12 08:43:15", - "%Y-%m-%d %H:%M:%S") + "%Y-%m-%d %H:%M:%S") msg = storage.StatusMessage(client_session_id=1, timestamp=ts, - num_peers=10, num_dht_peers=3, download_speed=102, - upload_speed=99, download_size=10213, upload_size=3301) + num_peers=10, num_dht_peers=3, + download_speed=102, upload_speed=99, + download_size=10213, upload_size=3301) a = storage.MySQLDatabaseAccess(self.database) a.connect() a.add_status_message(msg) @@ -647,10 +671,11 @@ class MySQLDatabaseAccessTest(unittest.TestCase): def test_add_peer_status_message_new_entry_in_table(self): # Add new peer status message. ts = datetime.datetime.strptime("2010-09-12 13:43:25", - "%Y-%m-%d %H:%M:%S") + "%Y-%m-%d %H:%M:%S") msg = storage.PeerStatusMessage(client_session_id=1, timestamp=ts, - peer_ip="141.85.224.202", peer_port="12345", - download_speed=13, upload_speed=98) + peer_ip="141.85.224.202", + peer_port="12345", download_speed=13, + upload_speed=98) a = storage.MySQLDatabaseAccess(self.database) a.connect() a.add_peer_status_message(msg) @@ -662,13 +687,15 @@ class MySQLDatabaseAccessTest(unittest.TestCase): self.assertEqual(pstatmsg_count, self.expected_pstatmsg_count) - def test_add_verbose_message_new_entry_in_databas(self): + def test_add_verbose_message_new_entry_in_database(self): # Add new verbose message. ts = datetime.datetime.strptime("2010-09-12 13:43:24", - "%Y-%m-%d %H:%M:%S") + "%Y-%m-%d %H:%M:%S") msg = storage.VerboseMessage(client_session_id=1, timestamp=ts, - transfer_direction="send", peer_ip="141.85.224.202", - peer_port="12345", message_type="CHOKE") + transfer_direction="send", + peer_ip="141.85.224.202", + peer_port="12345", + message_type="CHOKE") a = storage.MySQLDatabaseAccess(self.database) a.connect() a.add_verbose_message(msg) @@ -680,5 +707,6 @@ class MySQLDatabaseAccessTest(unittest.TestCase): self.assertEqual(verbmsg_count, self.expected_verbmsg_count) + if __name__ == "__main__": unittest.main()