[gevice] src/test.py: add script to test gevicedatabase.py



commit 5c236da1362ba3155ab63766e91edd106be3f87d
Author: Alejandro ValdÃs Jimenez <avaldes gnome org>
Date:   Tue Dec 18 00:08:10 2012 -0300

    src/test.py: add script to test gevicedatabase.py

 ChangeLog             |    4 +
 data/other/testing.db |  Bin 0 -> 5120 bytes
 src/gevice.py         |   99 ++++++++++++++-----
 src/gevicedatabase.py |  262 +++++++++++++++++++++++++------------------------
 src/gevicemodel.py    |    6 +-
 src/test.py           |   22 ++++
 6 files changed, 233 insertions(+), 160 deletions(-)
---
diff --git a/ChangeLog b/ChangeLog
index 4987334..3b7d3f2 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,7 @@
+2012-12-18  Alejandro ValdéJimenez  <avaldes gnome org>
+	* data/other/testing.db: testing
+	* src/test.py: add script to test gevicedatabase.py
+
 2012-12-14  Alejandro ValdéJimenez  <avaldes gnome org>
 	* data/ui/find.xml: change to modal window.
 	* src/gevice.py: enable find option.
diff --git a/data/other/testing.db b/data/other/testing.db
new file mode 100644
index 0000000..37a654f
Binary files /dev/null and b/data/other/testing.db differ
diff --git a/src/gevice.py b/src/gevice.py
index a9a52a6..dcfb24c 100755
--- a/src/gevice.py
+++ b/src/gevice.py
@@ -20,7 +20,6 @@ from gi.repository import Gtk, GdkPixbuf, Vte, GLib
 
 import os
 import os.path
-from struct import unpack
 
 import config
 import gevicefind
@@ -40,8 +39,6 @@ from gettext import gettext as _
 
 class Gevice:
   def __init__ (self):
-    # SQLite format 3 (header string)
-    self.magic = ('\x53', '\x51', '\x4c', '\x69', '\x74', '\x65', '\x20', '\x66', '\x6f', '\x72', '\x6d', '\x61', '\x74', '\x20', '\x33', '\x00')
     self.connected_to_database = False
     self.context_id = None
     self.session = "ssh"
@@ -250,35 +247,59 @@ class Gevice:
   def on_action_quit (self,action):
     self.on_delete_event ()
 
-  def on_action_open (self,action):
-    if (not self.connected_to_database):    
-      filechooser = Gtk.FileChooserDialog(title=_("Open Database"), 
-        parent=self.window_main, 
-        action=Gtk.FileChooserAction.OPEN, 
-        buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.ACCEPT))	
+  def get_filename (self):
+    filechooser = Gtk.FileChooserDialog(title=_("Open Database"),
+      parent=self.window_main, 
+      action=Gtk.FileChooserAction.OPEN, 
+      buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.ACCEPT))
 
-      filechooser.set_select_multiple(False)
+    filechooser.set_select_multiple(False)
+    response = filechooser.run()
 
-      response = filechooser.run()
+    if response == Gtk.ResponseType.ACCEPT:
+      dbsqlite = filechooser.get_filename()
+      filechooser.destroy()
+      return dbsqlite
+    else:
+      filechooser.destroy()
+      return None
 
-      if response == Gtk.ResponseType.ACCEPT:
-        dbsqlite = filechooser.get_filename()
+  def insert_data_into_model(self,node,iterp):
+    for n in node.children:
+      itern = self.gmodel.treestore.append(iterp)
+      self.gmodel.insert_new_item (itern,n.name,n.ip)
+      self.insert_data_into_model(n,itern)
 
-      filechooser.destroy()    
+  def on_action_open (self,action):
+    self.gmodel.treestore.clear()
+    self.gmodel.treeview.set_model(None)
+    
+    if (not self.connected_to_database):
+      dbsqlite = self.get_filename()
+      if (dbsqlite):
+        self.gdbase = gevicedatabase.GeviceDatabase (dbsqlite)
+        tree = self.gdbase.get_data()
+        
+        self.gmodel.treeview.set_model(self.gmodel.treestore)
+        
+        for n in tree.children:
+          itern = self.gmodel.treestore.append(None)
+          self.gmodel.insert_new_item (itern,n.name,n.ip)
+          self.insert_data_into_model(n, itern)
         
-      with open(dbsqlite, 'rb') as handle:
-        s = unpack('cccccccccccccccc', handle.read(16))
-        if s == self.magic:
-          self.gdbase = gevicedatabase.GeviceDatabase (dbsqlite,self)
-          self.update_statusbar (dbsqlite)
-          self.actiongroup_device.set_sensitive (False)
-        else:
-          result = self.show_infobar_message (_("Seems not sqlite3: " + dbsqlite), 
-            Gtk.MessageType.ERROR)
+        self.gmodel.treeview.expand_all()
+        self.actiongroup_model.set_sensitive(True)
+        self.actiongroup_device.set_sensitive (True)
+        
+        self.update_statusbar (dbsqlite)
+        self.actiongroup_device.set_sensitive (False)
+        
+        action_open = self.actiongroup_window.get_action("Open")
+        action_open.set_property ("stock-id",Gtk.STOCK_CONNECT)
+        action_open.set_property ("tooltip",_("Disconnect from database"))
+        action_open.set_property ("label",_("Disconnect"))
+        self.connected_to_database = True
     else:
-      self.gmodel.treestore.clear()
-      self.gmodel.treeview.set_model(None)
-      
       action_open = self.actiongroup_window.get_action("Open")
       action_open.set_property ("stock-id",Gtk.STOCK_DISCONNECT)
       action_open.set_property ("tooltip",_("Connect to database"))
@@ -350,12 +371,36 @@ class Gevice:
       self.gmodel.treeview.collapse_row(path)
 
   def on_action_save (self,action):
-    self.gdbase.save_data_to_database(self)
+    self.devices_to_connect = []
+    self.gdbase.clear_database()
+
+    # save devices into database
+    self.gmodel.treestore.foreach(self.copy_device_to_dbase,None)
+
+    for connected in self.devices_to_connect:
+      self.gdbase.insert_connections(connected)
+
+    ###self.gdbase.conn.commit()
     
     ### FIXME: Validate to error
     result = self.show_infobar_message (_("Model saved"), Gtk.MessageType.INFO)
     ###result = self.show_infobar_message (_("Model Not saved"), Gtk.MessageType.ERROR)
 
+  def copy_device_to_dbase (self,model,path,iter,data):
+    data = self.gmodel.treestore.get(iter,0,1)
+
+    self.gdbase.insert_device (data)
+
+    if (self.gmodel.treestore.iter_has_child(iter)):
+      iterc = self.gmodel.treestore.iter_children(iter)
+      next = iterc
+      
+      while next:
+        child = self.gmodel.treestore.get(next,0)
+        self.devices_to_connect.append ("'" + data[0] + "','" + child[0] + "'")
+        next2 = self.gmodel.treestore.iter_next(next)
+        next = next2
+
   def on_toggle_tree (self,action):
     if (action.get_active() == True):
       self.vboxtreeview.show()
diff --git a/src/gevicedatabase.py b/src/gevicedatabase.py
index c439522..0d66e6e 100644
--- a/src/gevicedatabase.py
+++ b/src/gevicedatabase.py
@@ -16,9 +16,9 @@
 # You should have received a copy of the GNU General Public License along
 # with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-from gi.repository import Gtk
 import os
 import sqlite3
+from struct import unpack
 
 import config
 
@@ -28,43 +28,76 @@ gettext.textdomain(config.PACKAGE)
 gettext.bind_textdomain_codeset (config.PACKAGE, "UTF-8");
 from gettext import gettext as _
 
+class Node(object):
+  """
+  Used to store the devices and create the tree of devices. the attributes are:
+  name = name
+  ip = ip
+  children = []
+  """
+  def __init__(self, name, ip):
+    """
+    @param name The name of device.
+    @param ip The IP address of device.
+    """
+    self.name = name
+    self.ip = ip
+    self.children = []
+
+  def add_child(self, obj):
+    """
+    Add a node child.
+    @param obj The node to add.
+    """
+    self.children.append(obj)
+
 class GeviceDatabase:
-  def __init__ (self,dbsqlite,gevice):
+  def __init__ (self,dbsqlite):
+    """
+    @parama dbsqlite The filename of sqlite database.
+    """
+    # SQLite format 3 (header string)
+    self.magic = ('\x53', '\x51', '\x4c', '\x69', '\x74', '\x65', '\x20', '\x66', '\x6f', '\x72', '\x6d', '\x61', '\x74', '\x20', '\x33', '\x00')
     self.dbsqlite = dbsqlite
     self.cur = None
     self.devices_to_connect = []
-    
-    self.conn = self.connect (gevice)    
-
-    if (self.conn):
-      gevice.connected_to_database = True
-      self.cur = self.conn.cursor()
-
-      if (self.if_enable_foreign_key(gevice) == False):
-        self.enable_foreign_key(gevice)
-
-      self.load_data_from_database(gevice)
-
-      action_open = gevice.actiongroup_window.get_action("Open")
-      action_open.set_property ("stock-id",Gtk.STOCK_CONNECT)
-      action_open.set_property ("tooltip",_("Disconnect from database"))
-      action_open.set_property ("label",_("Disconnect"))
-
-    else:
-      gevice.connected_to_database = False
-
-  def connect (self, gevice):
-    try:
-      conn = sqlite3.connect(self.dbsqlite)
-      return conn
-    except:
-      result = gevice.show_message (_("Unable to connect to the database"), Gtk.MessageType.ERROR, (Gtk.STOCK_OK, Gtk.ResponseType.OK), None)
-      return False
-
-  def enable_foreign_key (self,gevice):
+    self.treedevice = Node("root", None)
+
+    # verify valid format of file
+    with open(dbsqlite, 'rb') as handle:
+      s = unpack('cccccccccccccccc', handle.read(16))
+      if s == self.magic:
+        self.__connect()
+        
+        if (self.conn):
+          self.cur = self.conn.cursor()
+          
+          if (self.__if_enable_foreign_key() == False):
+            self.__enable_foreign_key()
+            self.load_data()
+
+  def get_data(self):
+    """
+    Return a tree of devices.
+    """
+    return self.treedevice
+
+  def __connect (self):
+    """
+    Connect to database.
+    """
+    self.conn = sqlite3.connect(self.dbsqlite)
+
+  def __enable_foreign_key (self):
+    """
+    Enable foreign key.
+    """
     self.cur.execute ("PRAGMA foreign_keys = ON ")
 
-  def if_enable_foreign_key(self,gevice):
+  def __if_enable_foreign_key(self):
+    """
+    Verify if foreign key is enabled.
+    """
     self.cur.execute ("PRAGMA foreign_keys")
     rows = self.cur.fetchall()
 
@@ -73,116 +106,85 @@ class GeviceDatabase:
     else:
       return True
 
-  def execute_sql_select (self,gevice,sql):  
-    try:
-      self.cur.execute(sql)
-      rows = self.cur.fetchall()
-      return rows
-    except:
-      result = gevice.show_message (_("Unable to execute SQL: " + sql), Gtk.MessageType.ERROR, (Gtk.STOCK_OK, Gtk.ResponseType.OK), None)
-      return False
-
-  def load_data_from_database (self,gevice):
-    gevice.gmodel.treestore.clear()
-    gevice.gmodel.treeview.set_model(None)
-    gevice.gmodel.treeview.set_model(gevice.gmodel.treestore)
+  def execute_sql_select (self,sql):
+    """
+    Execute a select SQL.
+    @param sql to execute.
+    """
+    self.cur.execute(sql)
+    rows = self.cur.fetchall()
+    self.conn.commit()
+    return rows
 
-    self.lserial = []
+  def load_data (self):
+    """
+    Read and load the data into tree of devices.
+    """
+    # get root device (or roots)
     sql = "select device.id_dev from device where device.id_dev "
     sql = sql + "not in (select id_devc from connect order by id_devc)"
 
-    rows = self.execute_sql_select(gevice,sql)
+    rows = self.execute_sql_select(sql)
 
     if rows:
-      # copy to list
-      for row in rows:
-        self.lserial.append(row[0])
-
-      # for every serial, get your children
+      # for each root device, get your children
       token = None
-      for serial in self.lserial:
-        if (not serial == token):
-          self.process_row (serial,None,gevice)
-          token = serial
-
-      gevice.gmodel.treeview.expand_all()        
-
-    gevice.actiongroup_model.set_sensitive(True)
-    gevice.actiongroup_device.set_sensitive (True)
-
-  def process_row (self,serial,iterp,gevice):
-    sql = "select id_dev, ip_dev from device where id_dev='" + str(serial) + "'"
-
-    row = self.execute_sql_select(gevice,sql)
-
+      for row in rows:
+        if (not row[0] == token):
+          self.__process_row (row[0], self.treedevice)
+          token = row[0]
+    
+  def __process_row (self,device,rootnode):
+    """
+    Process each device and your children.
+    @param device The name of device to process.
+    @param rootnode The root node to which to add the child nodes.
+    """
+    # get data of device
+    sql = "select id_dev, ip_dev from device where id_dev='" + str(device) + "'"
+
+    row = self.execute_sql_select(sql)
     if row:
-      itern = gevice.gmodel.treestore.append(iterp)
-      gevice.gmodel.insert_new_item (itern,row,None,None)
+      node = Node(row[0][0], row[0][1])
+      rootnode.add_child(node)
 
-      sql2 = "select id_devc from connect where id_devp='" + str(serial) + "'"
-      rows = self.execute_sql_select(gevice,sql2)
+      # get children of device
+      sql2 = "select id_devc from connect where id_devp='" + str(device) + "'"
+      rows = self.execute_sql_select(sql2)
 
-      if rows:        
+      if rows:
         for children in rows:
-          self.process_row (children[0],itern,gevice)
-
-  def save_data_to_database (self,gevice):
-    self.execute_sql(gevice,"delete from connect")
-    self.execute_sql(gevice,"delete from device")
-    self.devices_to_connect = []
-
-    # save devices into database
-    gevice.gmodel.treestore.foreach(self.copy_device_to_dbase,gevice)
-
-    for connected in self.devices_to_connect:
-      self.insert_connections(connected,gevice)
-
-    self.conn.commit()
-
-  def copy_device_to_dbase (self,model,path,iter,gevice):
-    data = gevice.gmodel.treestore.get(iter,0,1)
-
-    self.insert_device (data,gevice)
-
-    if (gevice.gmodel.treestore.iter_has_child(iter)):
-      iterc = gevice.gmodel.treestore.iter_children(iter)
-      next = iterc
-      
-      while next:
-        child = gevice.gmodel.treestore.get(next,0)
-        self.devices_to_connect.append ("'" + data[0] + "','" + child[0] + "'")
-        next2 = gevice.gmodel.treestore.iter_next(next)
-        next = next2
-
-  def insert_device (self,data,gevice):
+          self.__process_row (children[0],node)
+
+  def clear_database(self):
+    """
+    Clear all data of database.
+    """
+    self.__execute_sql("delete from connect")
+    self.__execute_sql("delete from device")
+
+  def insert_device (self,data):
+    """
+    Insert data into database.
+    @param data The [name,ip] as list.
+    """
     sql = "insert into device (id_dev,ip_dev) "
     sql = sql + "values ('" + data[0] + "','" + data[1] + "');"
-    st = self.execute_sql(gevice,sql)
-    print st
-
-  def insert_connections (self,serials,gevice):
-    sql = "insert into connect (id_devp,id_devc) values (" + serials + ");"
-    self.execute_sql (gevice,sql)
-
-  def get_list_of_data (self,gevice,sql):
-    liststore = Gtk.ListStore(str,int)
-
-    rows = self.execute_sql_select(gevice,sql)
-
-    if rows:
-      for row in rows:
-        iter = liststore.append ()
-        liststore.set_value (iter,0,str(row[0]))
-        liststore.set_value (iter,1,int(row[1]))
+    st = self.__execute_sql(sql)
+    self.conn.commit()
 
-      return liststore
-    else:
-      return False
+  def insert_connections (self,links):
+    """
+    Insert links between devices.
+    @param links The 'name1','name2' as string
+    """
+    sql = "insert into connect (id_devp,id_devc) values (" + links + ");"
+    self.__execute_sql (sql)
+    self.conn.commit()
 
-  def execute_sql (self,gevice,sql):
-    try:
-      self.cur.execute(sql)
-      return True
-    except:
-      result = gevice.show_message (_("Unable to execute SQL: " + sql), Gtk.MessageType.ERROR, (Gtk.STOCK_OK, Gtk.ResponseType.OK), None)      
-      return False
+  def __execute_sql (self,sql):
+    """
+    Execute a SQL.
+    """
+    self.cur.execute(sql)
+    self.conn.commit()
diff --git a/src/gevicemodel.py b/src/gevicemodel.py
index 63afaca..b3eb9eb 100644
--- a/src/gevicemodel.py
+++ b/src/gevicemodel.py
@@ -56,9 +56,9 @@ class GeviceModel:
 
     return
 
-  def insert_new_item (self,newiter,row,id_type_link,iconpixbuf):
-    self.treestore.set_value (newiter,0,str(row[0][0]))
-    self.treestore.set_value (newiter,1,str(row[0][1]))
+  def insert_new_item (self,newiter,name, ip):
+    self.treestore.set_value (newiter,0,str(name))
+    self.treestore.set_value (newiter,1,str(ip))
 
 
   def on_device_selection_changed (self,selection,gevice):
diff --git a/src/test.py b/src/test.py
new file mode 100644
index 0000000..bf8d7ed
--- /dev/null
+++ b/src/test.py
@@ -0,0 +1,22 @@
+import gevicedatabase
+
+def process_node(node,line):  
+  for ch in node.children:
+    print line + ch.name
+    process_node(ch,line*2)
+
+def show_data(tree):
+  for n in tree.children:
+    print n.name
+    process_node(n,"--")
+
+dbase = gevicedatabase.GeviceDatabase("../data/other/testing.db")
+tree = dbase.get_data()
+
+#data = ("appn6","127.0.0.1")
+#dbase.insert_device(data)
+#link = "'distn2','appn6'"
+#dbase.insert_connections(link)
+
+tree = dbase.get_data()
+show_data(tree)



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]