import sqlite3

from gdbackup.google.finished_folders import FinishedFolders


class TestBackupTest:
    def setUp(self):
        self._remove_db_file()

    def tearDown(self):
        self._remove_db_file()

    def test_conn(self):
        folders = FinishedFolders('xxxxxx')
        conn = folders.conn
        assert isinstance(conn, sqlite3.Connection)

        cur = conn.execute('''
            select name from sqlite_master where type = ? AND name = ?
        ''', ('table', 'finished_folders'))
        assert 'finished_folders' == cur.fetchone()[0]

    def test_load(self):
        folders = FinishedFolders('xxxxxx')

        # add dummy data
        sql = 'insert into finished_folders (id, root_id) values (?, ?)'
        folders.conn.execute(sql, ('foo', 1))
        folders.conn.commit()

        # load no data, ignore dummy data
        folders = FinishedFolders('xxxxxx')
        folders.load()
        assert len(folders) == 0

        # add 'foo'
        folders.add('foo')
        assert 'foo' in folders
        folders.save()

        # load
        folders = FinishedFolders('xxxxxx')
        folders.load()
        assert 'foo' in folders
        assert len(folders) == 1

    def test_save(self):
        folders = FinishedFolders('xxxxxx')

        # add 'foo'
        folders.add('foo')
        assert 'foo' in folders
        folders.save()

        # check if only 'foo' exists
        ids = set()
        sql = 'select id from finished_folders where root_id = ?'
        for row in folders.conn.execute(sql, ('xxxxxx',)):
            ids.add(row[0])
        assert 'foo' in ids
        assert len(ids) == 1

        # add 'bar'
        folders.add('bar')
        assert 'bar' in folders
        folders.save()

        # check if both 'foo' and 'bar' exist
        ids = set()
        sql = 'select id from finished_folders where root_id = ?'
        for row in folders.conn.execute(sql, ('xxxxxx',)):
            ids.add(row[0])
        assert 'foo' in ids
        assert 'bar' in ids
        assert len(ids) == 2

@@ -1,12 +1,22 @@
+import os%0A
 import sqlit
@@ -19,16 +19,31 @@
 qlite3%0A%0A
+import pytest%0A%0A
 from gdb
@@ -127,109 +127,263 @@
     
-def setUp(self):%0A        self._remove_
+@pytest.fixture(autouse=True)%0A    def delete_db_file(self, request):%0A        def fin():%0A            file = FinishedFolders('xxxxxx').
 db_file
-()%0A
 %0A    
-def tearDown(self):%0A        self._remove_db_file
+        if os.path.isfile(file):%0A                os.unlink(file)%0A        request.addfinalizer(fin)%0A        fin
 ()%0A%0A

remove db file