Commits

Laurent Bachelier committed 84b08eb

Require file handle

Comments (0)

Files changed (3)

         print "Usage: %s TYPE NAME" % sys.argv[0]
         exit(1)
 
-    os.chdir(os.path.dirname(__file__))
-
     eventname = unicode(sys.argv[1], locale.getpreferredencoding())
     name = unicode(" ".join(sys.argv[2:]), locale.getpreferredencoding())
 
     event = rtn.Event(eventname, name)
 
-    events = rtn.Events()
-    events.load()
-    events.append(event)
-    events.save()
+    with open(os.path.join(os.path.dirname(__file__), 'events.db'), 'a+b') as db:
+        events = rtn.Events(db)
+        events.load()
+        events.append(event)
+        events.save()
 
     feed = events.build_rss()
-    feed.write_xml(open("rt2rss.xml", "w"), "utf-8")
+    with open(os.path.join(os.path.dirname(__file__), 'rt2rss.xml'), 'w') as f:
+        feed.write_xml(f, "utf-8")

rtorrentnotify.py

 
 
 class Events(object):
-    def __init__(self, filename="events.db", max=20):
+    def __init__(self, db, max=20):
         self._events = []
-        self.filename = filename
+        self.db = db
         self.max = max
 
     def save(self):
         events = self._events[:self.max - 1]
-        pickle.dump(events, open(self.filename, "w+b"), pickle.HIGHEST_PROTOCOL)
+        self.db.truncate(0)
+        pickle.dump(events, self.db, pickle.HIGHEST_PROTOCOL)
 
     def load(self):
         try:
-            self._events = pickle.load(open(self.filename, "a+b"))
+            self.db.seek(0)
+            self._events = pickle.load(self.db)
         except EOFError:
             # first run
             self._events = []
 
 def test_load():
     # TODO create the actual DB
-    os.chdir(os.path.dirname(__file__))
+    with open(os.path.join(os.path.dirname(__file__), 'events.db')) as db:
+        events = rtn.Events(db)
+        events.load()
 
-    events = rtn.Events()
-    events.load()
-
-    print unicode(events)
+    assert len(unicode(events).splitlines()) > 1
 
 
 def test_add():
-    events = rtn.Events()
+    events = rtn.Events(StringIO())
     events.append(rtn.Event('LOL', 'cat'))
     events.append(rtn.Event('LOL', 'cat'))
     out = unicode(events)
 
 
 def test_rss():
-    events = rtn.Events()
+    events = rtn.Events(StringIO())
     events.append(rtn.Event('a', 'b'))
     events.append(rtn.Event('c', u'héhéhé'))