Пример #1
0
def main():
    keeper = Keeper(CONFIG)
    options = sys.argv[1:]
    comm = keeper.comm(options) if len(options) <= 2 else False

    if comm and callable(comm):
        print(comm())
    else:
        print(comm)
Пример #2
0
 def _show_info(self):
     """
     显示swall信息
     """
     keeper = Keeper(self.config)
     valid_nodes = keeper.get_valid_nodes()
     info = {
         "config": self.config,
         "node_list": valid_nodes
     }
     print format_obj(info)
Пример #3
0
    def setUp(self):
        self.original_stream = console.stream
        console.stream = sys.stdout
        self.keeper_root = 'testkeeper'
        shutil.rmtree(self.keeper_root, ignore_errors=True)

        try:
            os.mkdir(self.keeper_root)
        except FileExistsError:
            pass
        self.keeper = Keeper(self.keeper_root)
Пример #4
0
 def main(self):
     """
     init zookeeper
     """
     self.parse_args()
     keeper = Keeper(self.config)
     if keeper.init_db(self.options.force):
         sys.stdout.write(c("init zookeeper db ok\n", 'g'))
     else:
         sys.stdout.write(c("init zookeeper db fail\n", 'r'))
     sys.stdout.flush()
Пример #5
0
    def test_cleanup_pending_add_buffered_stream(self):
        # Temporarily ignore warnings
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")

            stream = self.keeper.add_buffered_stream()
            stream.write(b"The very hungry caterpillar")
            self.assertIs(stream.key, None)
            # deliberately omitted close causes an intentional ResourceWarning
            self.assertEqual(len(self.keeper), 0)

            self.keeper = Keeper(self.keeper_root)
            stream = self.keeper.add_buffered_stream()
            stream.write(b"The very hungry caterpillar")
            stream.close()
            self.assertEqual(len(self.keeper), 1)
Пример #6
0
async def start_keeper(params, _loop=None):
    backend = None

    try:
        backend = Backend(params, _loop)
        await backend.connect()

        geodetector = get_geodetector(params, backend)

        frame_engine = Frame(geodetector)
        vehicles_engine = Vehicles(backend)

        keeper = Keeper(frame_engine, vehicles_engine)

        uri = f"ws://{params.wsaddr}{params.wspath}:{params.wsport}"
        async with websockets.connect(uri) as websocket:
            while True:
                message = await websocket.recv()
                try:
                    await keeper.serve(json.loads(message))
                except JSONDecodeError:
                    # todo logging
                    pass
                except error.KeeperError as e:
                    print(e)
                    break

    except error.KeeperBackendConnectionError as e:
        # todo организовать обработку прочик исключений
        pass
    except error.KeeperError:
        pass
    finally:
        await backend.destroy()
Пример #7
0
 def test_zoo_pay_worker_no_budget(self):
     z = Zoo("Zoo", 200, 2, 2)
     z.hire_worker(Vet("John", 23, 100))
     z.hire_worker(Keeper("Bill", 28, 150))
     res = z.pay_workers()
     self.assertEqual(
         res, "You have no budget to pay your workers. They are unhappy")
Пример #8
0
 def test_zoo_pay_worker_success(self):
     z = Zoo("Zoo", 1500, 2, 2)
     z.hire_worker(Vet("John", 23, 100))
     z.hire_worker(Keeper("Bill", 28, 150))
     res = z.pay_workers()
     self.assertEqual(z._Zoo__budget, 1250)
     self.assertEqual(
         res, "You payed your workers. They are happy. Budget left: 1250")
Пример #9
0
 def createDatabase(self):
     if self.file and self.savePageBeforeClose() == -1:
         return 0
     try:
         self.file = str(self.showFileSaveDialog()[0])
         if file:
             self.keeper = Keeper()
     except: self.showCritical("Error","Can't create %s" % file)
Пример #10
0
    def test_restore_check_content(self):
        """Test restoring a file and check contents"""
        # Set paths
        cwd = os.getcwd()
        file_paths = [
            cwd + "/tmp/keeper_test_r_check/a/b/file1.txt",
            cwd + "/tmp/keeper_test_r_check/a/b/c/file2.txt",
            cwd + "/tmp/keeper_test_r_check/a/b/c/file3.txt",
            cwd + "/tmp/keeper_test_r_check/a/b/c/e/f4",
            cwd + "/tmp/keeper_test_r_check/a/b/d/file5.txt"
        ]
        folder_paths_to_create = [
            cwd + "/tmp/keeper_test_r_check/a/b/c/e/",
            cwd + "/tmp/keeper_test_r_check/a/b/d"
        ]
        directories_to_backup = [
            cwd + "/tmp/keeper_test_r_check/a/b/d/"
        ]
        file_expected_in_restore = os.path.join(
            cwd + "/tmp/keeper_test_r_check/a/b/d/file5.txt"
        )

        # Set sails
        keeper = Keeper(system_directories=directories_to_backup,
                        show_progress=False)

        # Create all directories
        for path in folder_paths_to_create:
            self._create_dir(path)

        # Create all files for backup
        for path in file_paths:
            # Create file
            with open(path, "w") as file_handle:
                file_handle.write("For Gondor!\n")

        # Create backup
        keeper.backup(
            destination_path=cwd + "/tmp/keeper_test_r_check",
            filename="restore_test.tar.gz"
        )

        # Purge the source directory
        self._purge_directory(cwd + "/tmp/keeper_test_r_check/a")

        # Restore
        keeper.restore(
            cwd + "/tmp/keeper_test_r_check/restore_test.tar.gz")

        # Get file contents
        with open(file_expected_in_restore, 'r') as restored_file:
            content = restored_file.read()
            logging.debug("content " + content)

        self.assertEqual(content, "For Gondor!\n")

        # Clean up test files and directories
        self._purge_directory(cwd + "/tmp/keeper_test_r_check")
Пример #11
0
 def test_instantiating(self):
     """Test that Keeper class can be instantiated"""
     directories = [
         "/var/lib/rundeck/data",          # database
         "/var/lib/rundeck/logs",          # execution logs (by far biggest)
         "/var/lib/rundeck/.ssh",          # ssh keys
         "/var/lib/rundeck/var/storage",   # key storage files and metadata
         "/var/rundeck/projects"           # project definitions
     ]
     Keeper(system_directories=directories, show_progress=False)
Пример #12
0
 def test_worker_status(self):
     z = Zoo("My Zoo", 500, 3, 3)
     z.hire_worker(Vet("Leo", 35, 100))
     z.hire_worker(Keeper("Tigy", 40, 100))
     z.hire_worker(Caretaker("Chi", 24, 100))
     res = z.workers_status()
     self.assertEqual(
         res,
         "You have 3 workers\n----- 1 Keepers:\nName: Tigy, Age: 40, Salary: 100\n----- 1 Caretakers:\nName: Chi, Age: 24, Salary: 100\n----- 1 Vets:\nName: Leo, Age: 35, Salary: 100"
     )
Пример #13
0
 def test_raises_exception_on_relative_paths(self):
     """Test that relative paths raise an exception"""
     contains_relative_paths = [
         "some/path/here",
         "some/other/path",
         "/this/is/valid/though"
     ]
     with self.assertRaises(Exception):
         Keeper(
             system_directories=contains_relative_paths,
             show_progress=False
         )
Пример #14
0
def main():
    try:
        if args.conf:
            log.info("Reading conf from {}".format(args.conf))
            with open(args.conf, 'r') as pipes_file:
                conf = json.load(pipes_file,
                                 object_pairs_hook=collections.OrderedDict)

        simulators = []
        cache = Cache(args.db)

        admin_user = cache["users"]["admin"]
        admin_user["auth_url"] = cache["api"]["auth_url"]

        admin_factory = ClientFactory(admin_user)
        admin_keeper = Keeper(cache, admin_factory)

        if args.clean:
            log.info("Starting cleanup")
            admin_keeper.clean(args.clean)
            sys.exit()

        # This section for default initialization of cirros image
        log.debug("Caching default cirros image")
        (cache["glance"]["images"][admin_keeper.get(
            "glance", "images", "name",
            lambda x: x == "cirros-0.3.4-x86_64-uec")[0].id]) = False
        for flavor in admin_factory.nova().flavors.list():
            log.debug(
                "Caching flavor with name {name}".format(name=flavor.name))
            (cache["nova"]["flavors"][flavor.id]) = False

        for pipe_name, pipe in conf.iteritems():
            simulators.append(Simulator(pipe_name, pipe, cache, admin_keeper))

        for simulator in simulators:
            simulator.simulate()
    except KeyboardInterrupt:
        print('\nThe process was interrupted by the user')
        raise SystemExit
Пример #15
0
    def test_raises_exception_on_overlapping_dirs_reversed(self):
        """Test that exception is raised for overlapping dirs.

        For example /tmp/a/b,/tmp/a/b/c should fail
        """
        # Set bad directories
        bad_directories = [
            "/tmp/keeper_python_unittest_raises/a/b",
            "/tmp/keeper_python_unittest_raises/a/b/c"
        ]
        # Set sails
        with self.assertRaises(Exception):
            Keeper(system_directories=bad_directories, show_progress=False)
Пример #16
0
def main(args):
    keeper = Keeper()

    if args['download']:
        keeper.download()

    if args['upload']:
        keeper.upload()
Пример #17
0
    def __init__(self, config_file, nbr_total_item):
        """Constructeur.

        Argument(2):
        config_file : structure du labyrinthe
        nbr_total_item : nombre total d'objet présent dans la structure"""

        pygame.init()
        self.window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_WIDTH))
        pygame.display.set_caption("P3 : labyrinthe")
        font = pygame.font.Font(None, 64)
        self.text_victoire = font.render("Victoire !", 1, (0, 255, 0))
        self.text_defeat = font.render("Défaite !", 1, (255, 0, 0))
        self.level = Gameboard(config_file, nbr_total_item)
        self.character = Character(self.level)
        self.keeper = Keeper()
        i = 0
        while i < nbr_total_item:
            self.item = Item(self.level.gameboard)
            self.level.gameboard[self.item.pos_y][self.item.pos_x] = "I"
            i += 1
Пример #18
0
    def loadConfig(self):
    # initialization of variables
        self.keeper = Keeper()
        if not self.keeper.isKdb:
            self.showMessage("Warning!", "".join(("Can't load keepass module.",
                      " Nickname will be saved in plain text,",
                             " passwords will be not saved.")))

        self.password = ""
        self.file = ""
        self.salt = ""
        self.icons = ""
        self.images = ""
        self.config = Config(self, "pass") # self.homeDir
        self.config.createUserConfig(["icons", "images", "pass.py"])
        self.config.loadConfig() # self.file, self.salt, self.icons, self.images

        if self.file and type(self.file) != 'bool':
            self.setDatabase(self.file)
        else:
            self.setPassword()

        if not self.salt:
            self.salt = os.path.join(self.homeDir, "pass.py")
            if not os.path.exists(self.salt):
                with open(os.path.join(self.homeDir, "salt")) as f:
                    f.write("##")

        if not self.icons:
            self.icons = os.path.join(self.homeDir, "icons")
            if not os.path.isdir(self.icons):
                self.icons = "./icons"

        if not self.images:
            self.images = os.path.join(self.homeDir, "images")
            if not os.path.isdir(self.images):
                self.images = "./images"

        self.generator = Generator(self)
        self.generator.set_salt(self.salt)
Пример #19
0
import sys
from keeper import Keeper

if __name__ == '__main__':
    Keeper(sys.argv[1:]).main()
Пример #20
0
 def test_keeper_repr(self):
     k = Keeper("ally", 36, 190)
     res = str(k)
     self.assertEqual(res, "Name: ally, Age: 36, Salary: 190")
Пример #21
0
 def test_keeper_init(self):
     k = Keeper("john", 21, 200)
     self.assertEqual(k.name, "john")
     self.assertEqual(k.age, 21)
     self.assertEqual(k.salary, 200)
Пример #22
0
# Copyright:   (c) CNYS 2015
# Licence:     <your licence>
#-------------------------------------------------------------------------------
#class imports
from maze import Maze
from keeper import Keeper
from crate import Crate

#add in the pygame imports
import random, sys, copy, os, pygame
from pygame.locals import *

score = 0
moves = 0
maze = Maze()
keeper = Keeper("^", 4, 1)
crate1 = Crate("/", 4, 2)
maze.placeCrate("/", 4, 2)



FPS = 30                    # frames per second to update the screen
WINWIDTH = 800              # width of the program's window, in pixels
WINHEIGHT = 600             # height in pixels
HALF_WINWIDTH = int(WINWIDTH / 2) #you need to know 1/2 sizes so you can
HALF_WINHEIGHT = int(WINHEIGHT / 2) #place things centrally

# The total width and height of each tile in pixels.
TILEWIDTH = 32
TILEHEIGHT = 32
TILEFLOORHEIGHT = 32
Пример #23
0
    def test_restore(self):
        """Test restoring a set of directories and files from a backup file"""
        # Set paths
        cwd = os.getcwd()
        file_paths = [
            cwd + "/tmp/keeper_test_restore/hotel/lobby/file1.txt",
            cwd + "/tmp/keeper_test_restore/hotel/lobby/desk/file2.txt",
            cwd + "/tmp/keeper_test_restore/hotel/lobby/desk/file3.txt",
            cwd + "/tmp/keeper_test_restore/hotel/lobby/desk/drawer/f4",
            cwd + "/tmp/keeper_test_restore/hotel/lobby/locker/file5.txt"
        ]
        folder_paths_to_create = [
            cwd + "/tmp/keeper_test_restore/hotel/lobby/desk/drawer/",
            cwd + "/tmp/keeper_test_restore/hotel/lobby/locker"
        ]
        directories_to_backup = [
            cwd + "/tmp/keeper_test_restore/hotel/lobby/desk/drawer/",
            cwd + "/tmp/keeper_test_restore/hotel/lobby/locker/"
        ]
        files_expected_in_restore = [
            cwd + "/tmp/keeper_test_restore/hotel/lobby/desk/drawer/f4",
            cwd + "/tmp/keeper_test_restore/hotel/lobby/locker/file5.txt"
        ]

        # Set sails
        keeper = Keeper(system_directories=directories_to_backup,
                        show_progress=False)

        # Create all directories
        for path in folder_paths_to_create:
            self._create_dir(path)

        # Create all files for backup
        for path in file_paths:
            # Create file
            with open(path, "w") as file_handle:
                file_handle.write("For Gondor!\n")

        # Create backup
        keeper.backup(
            destination_path=cwd + "/tmp/keeper_test_restore",
            filename="restore_test.tar.gz"
        )

        # Purge the source directory
        self._purge_directory(cwd + "/tmp/keeper_test_restore/hotel")

        # Restore
        keeper.restore(
            cwd + "/tmp/keeper_test_restore/restore_test.tar.gz")

        # List all directories
        restored = cwd + "/tmp/keeper_test_restore/hotel"
        files_found = []
        for root, dirs, files in os.walk(restored):
            for f in files:
                files_found.append(os.path.join(root, f))

        self.assertEqual(files_found, files_expected_in_restore)

        # Clean up test files and directories
        self._purge_directory(cwd + "/tmp/keeper_test_restore")
Пример #24
0
 def test_zoo_fire_worker_success(self):
     z = Zoo("Zoo", 1500, 1, 1)
     z.hire_worker(Keeper("K", 45, 100))
     res = z.fire_worker("K")
     self.assertEqual(res, "K fired successfully")
     self.assertEqual(z.workers, [])
Пример #25
0
class BufferedStreamTests(unittest.TestCase):

    def setUp(self):
        self.original_stream = console.stream
        console.stream = sys.stdout
        self.keeper_root = 'testkeeper'
        shutil.rmtree(self.keeper_root, ignore_errors=True)

        try:
            os.mkdir(self.keeper_root)
        except FileExistsError:
            pass
        self.keeper = Keeper(self.keeper_root)

    def tearDown(self):
        try:
            shutil.rmtree(self.keeper_root)
        except FileNotFoundError:
            pass
        console.stream = self.original_stream


    def test_add_buffered_stream_in_context(self):
        with self.keeper.add_buffered_stream() as stream:
            stream.write(b"The quick brown fox jumped over the lazy dog")
        self.assertIn(stream.key, self.keeper)

    def test_add_buffered_stream_with_close(self):
        stream = self.keeper.add_buffered_stream()
        stream.write(b"The very hungry caterpillar")
        stream.close()
        self.assertIn(stream.key, self.keeper)

    def test_key_in_none_before_close(self):
        stream = self.keeper.add_buffered_stream()
        stream.write(b"The very hungry caterpillar")
        self.assertIs(stream.key, None)
        stream.close()

    def test_key_identical_bytes_add_before_stream(self):
        key1 = self.keeper.add(b'gdgdgdggd')
        with self.keeper.add_buffered_stream() as stream:
            stream.write(b'gdgdgdggd')
        key2 = stream.key
        self.assertEqual(key1, key2)
        self.assertEqual(len(self.keeper), 1)

    def test_key_identical_bytes_stream_before_add(self):
        with self.keeper.add_buffered_stream() as stream:
            stream.write(b'gdgdgdggd')
        key1 = stream.key
        key2 = self.keeper.add(b'gdgdgdggd')
        self.assertEqual(key1, key2)
        self.assertEqual(len(self.keeper), 1)

    def test_key_identical_strings_add_before_stream(self):
        key1 = self.keeper.add('gdgdgdggd')
        with self.keeper.add_buffered_stream(encoding=sys.getdefaultencoding()) as stream:
            stream.write('gdgdgdggd')
        key2 = stream.key
        self.assertEqual(key1, key2)
        self.assertEqual(len(self.keeper), 1)

    def test_key_identical_strings_stream_before_add(self):
        with self.keeper.add_buffered_stream(encoding=sys.getdefaultencoding()) as stream:
            stream.write('gdgdgdggd')
        key1 = stream.key
        key2 = self.keeper.add('gdgdgdggd')
        self.assertEqual(key1, key2)
        self.assertEqual(len(self.keeper), 1)

    def test_cleanup_pending_add_buffered_stream(self):
        # Temporarily ignore warnings
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")

            stream = self.keeper.add_buffered_stream()
            stream.write(b"The very hungry caterpillar")
            self.assertIs(stream.key, None)
            # deliberately omitted close causes an intentional ResourceWarning
            self.assertEqual(len(self.keeper), 0)

            self.keeper = Keeper(self.keeper_root)
            stream = self.keeper.add_buffered_stream()
            stream.write(b"The very hungry caterpillar")
            stream.close()
            self.assertEqual(len(self.keeper), 1)
Пример #26
0
#!/usr/bin/env python2

import os,sys
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(__file__)),'maxi'))
from keepass import kpdb
from keeper import Keeper

test = kpdb.Database()

k = Keeper()
#print str(k.db)
k.load("./tests/test.kdb", "123")
#print str(k.db)
#print k.urls

k.db.add_entry("Internet","test","test","test","test","test",imageid=0,append=True)

k.db.add_entry("Internet","test1","test1","test1","test1","test1",imageid=0,append=True)

k.db.remove_entry("test1","test1")

#print str(k.db)
#print k.urls

k.save("./tests/test.kdb", "123")
print str(k.db)
k.load("./tests/test.kdb", "123")
print str(k.db)
#print k.urls

k.db.remove_entry("test","test")
# Animals creation
animals = [
    Cheetah("Cheeto", "Male", 2),
    Cheetah("Cheetia", "Female", 1),
    Lion("Simba", "Male", 4),
    Tiger("Zuba", "Male", 3),
    Tiger("Tigeria", "Female", 1),
    Lion("Nala", "Female", 4)
]

# Animal prices
prices = [200, 190, 204, 156, 211, 140]

# Workers creation
workers = [
    Keeper("John", 26, 100),
    Keeper("Adam", 29, 80),
    Keeper("Anna", 31, 95),
    Caretaker("Bill", 21, 68),
    Caretaker("Marie", 32, 105),
    Caretaker("Stacy", 35, 140),
    Vet("Peter", 40, 300),
    Vet("Kasey", 37, 280),
    Vet("Sam", 29, 220)
]

# Adding all animals
for i in range(len(animals)):
    animal = animals[i]
    price = prices[i]
    print(zoo.add_animal(animal, price))
Пример #28
0
 def push(self, event, now=None):
     entries=[]
     for resolution, timestamp in self.get_timestamps_for_push(now):
         entries.append(self.get_event_entry(event, resolution, timestamp))
     Keeper.write(entries)
Пример #29
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--conf', dest='conf',
                        default='/etc/spamostack/conf.json',
                        help='Path to the config file with pipes')
    parser.add_argument('--db', dest='db', default='./db',
                        help='Path to the database directory')
    parser.add_argument('--verbose', action='store_true',
                        help='Increase verbose output')
    parser.add_argument('--clean', dest='clean', nargs='+',
                        help='Path to the database directory')
    args = parser.parse_args()

    log = logging.getLogger(__name__)
    if args.verbose:
        log.setLevel(logging.DEBUG)
        level = 'DEBUG'
    else:
        log.setLevel(logging.INFO)
        level = 'INFO'
    log.addHandler(logger.SpamStreamHandler())
    coloredlogs.install(level=level)

    try:
        log.info("Reading conf from {}".format(args.conf))
        with open(args.conf, 'r') as pipes_file:
            conf = json.load(pipes_file,
                             object_pairs_hook=collections.OrderedDict)

        simulators = []
        cache = Cache(args.db)

        users = cache["users"]
        admin_user = users["admin"]
        api = cache["api"]
        admin_user["auth_url"] = api["auth_url"]

        admin_factory = ClientFactory(admin_user)
        admin_keeper = Keeper(cache, admin_factory)

        if args.clean:
            log.info("Starting cleanup")
            admin_keeper.clean(args.clean)
            sys.exit()

        # This section for default initialization of cirros image
        log.debug("Caching default cirros image")
        (cache["glance"]["images"]
         [admin_keeper.get(
             "glance", "images", "name",
             lambda x: x == "cirros-0.3.4-x86_64-uec")[0].id]) = False
        for flavor in admin_factory.nova().flavors.list():
            log.debug("Caching flavor with name {name}".
                      format(name=flavor.name))
            (cache["nova"]["flavors"][flavor.id]) = False

        for pipe_name, pipe in conf.iteritems():
            simulators.append(Simulator(pipe_name, pipe, cache, admin_keeper))

        for simulator in simulators:
            simulator.simulate()
    except KeyboardInterrupt:
        print('\nThe process was interrupted by the user')
        raise SystemExit
Пример #30
0
class KeeperTests(unittest.TestCase):

    def setUp(self):
        self.original_stream = console.stream
        console.stream = sys.stdout
        self.keeper_root = 'testkeeper'
        shutil.rmtree(self.keeper_root, ignore_errors=True)

        try:
            os.mkdir(self.keeper_root)
        except FileExistsError:
            pass
        self.keeper = Keeper(self.keeper_root)

    def tearDown(self):
        try:
            shutil.rmtree(self.keeper_root)
        except FileNotFoundError:
            pass
        console.stream = self.original_stream

    def test_create(self):
        pass

    def test_len_empty(self):
        self.assertEqual(len(self.keeper), 0)

    def test_len_one(self):
        self.keeper.add(b'hsgshsgsha')
        self.assertEqual(len(self.keeper), 1)

    def test_len_two(self):
        self.keeper.add(b'hsgshsgsha')
        self.keeper.add(b'fdfdsffsdf')
        self.assertEqual(len(self.keeper), 2)

    def test_len_identical(self):
        key1 = self.keeper.add(b'gdgdgdggd')
        key2 = self.keeper.add(b'gdgdgdggd')
        self.assertEqual(len(self.keeper), 1)

    def test_distinct_keys(self):
        key1 = self.keeper.add(b'hsgshsgsha')
        key2 = self.keeper.add(b'xsgshsgsha')
        self.assertNotEqual(key1, key2)

    def test_key_identical(self):
        key1 = self.keeper.add(b'gdgdgdggd')
        key2 = self.keeper.add(b'gdgdgdggd')
        self.assertEqual(key1, key2)

    def test_store_strings(self):
        key1 = self.keeper.add("The quick brown fox jumped over the lazy dog")
        pass

    def test_store_unicode_strings(self):
        key1 = self.keeper.add("Søker for kanaler")
        pass

    def test_retrieve_bytes(self):
        string = "The hunting of the snark"
        key1 = self.keeper.add(string)
        value = self.keeper[key1]
        self.assertEqual(value.as_string(), string)

    def test_string_encoding(self):
        string = "It was the best of times. It was the worst of times."
        key1 = self.keeper.add(string)
        value = self.keeper[key1]
        self.assertEqual(value.meta.encoding, sys.getdefaultencoding())

    def test_unknown_key(self):
        with self.assertRaises(KeyError):
            _ = self.keeper['hello']

    def test_encoding(self):
        data = "søker sjåfør".encode('utf-16')
        key = self.keeper.add(data, encoding='utf-16')
        self.assertEqual(self.keeper[key].meta.encoding, 'utf-16')

    def test_add_bytes_retrieve_string(self):
        string = "søker sjåfør"
        data = string.encode('utf-16')
        key = self.keeper.add(data, encoding='utf-16')
        self.assertEqual(self.keeper[key].as_string(), string)

    def test_add_string_retrieve_bytes(self):
        string = "søker sjåfør"
        key = self.keeper.add(string)
        self.assertEqual(self.keeper[key].as_bytes(), string.encode())

    def test_length(self):
        data = b'The quick brown fox jumped over the lazy dog.'
        key = self.keeper.add(data)
        self.assertEqual(len(self.keeper[key].as_bytes()), self.keeper[key].meta.length)

    def test_mime_type(self):
        string = "<!DOCTYPE html><html><body><b>Thunderbirds are go</b></body></html>"
        key = self.keeper.add(string, mime="text/html")
        self.assertEqual(self.keeper[key].meta.mime, "text/html")

    def test_bytes_encoding(self):
        string = "<!DOCTYPE html><html><body><b>Thunderbirds are go</b></body></html>"
        data = string.encode('utf-32')
        key = self.keeper.add(data, encoding='utf-32')
        self.assertEqual(self.keeper[key].meta.encoding, 'utf-32')

    def test_meta_attributes_default(self):
        key = self.keeper.add(b'')
        meta = self.keeper[key].meta
        self.assertIn('length', meta)
        self.assertIn('mime', meta)
        self.assertIn('encoding', meta)

    def test_iterate_default_meta_attributes(self):
        key = self.keeper.add(b'')
        meta = self.keeper[key].meta
        attributes = list(self.keeper[key].meta)
        self.assertEqual(len(attributes), 3)
        self.assertIn('length', attributes)
        self.assertIn('mime', attributes)
        self.assertIn('encoding', attributes)

    def test_arbitrary_metadata(self):
        text = "We'll attach some arbitrary meta data to this"
        key = self.keeper.add(text, mime="text/plain", filename="foo.txt", author="Joe Bloggs")
        self.assertEqual(self.keeper[key].meta.filename, "foo.txt")
        self.assertEqual(self.keeper[key].meta.author, "Joe Bloggs")

    def test_iterate_arbitrary_metadata(self):
        text = "We'll attach some arbitrary meta data to this"
        key = self.keeper.add(text, mime="text/plain", filename="foo.txt", author="Joe Bloggs")
        attributes = list(self.keeper[key].meta)
        self.assertEqual(len(attributes), 5)
        self.assertIn('length', attributes)
        self.assertIn('mime', attributes)
        self.assertIn('encoding', attributes)
        self.assertIn('filename', attributes)
        self.assertIn('author', attributes)

    def test_meta_keys_distinct(self):
        string = "<!DOCTYPE html><html><body><b>Thunderbirds are go</b></body></html>"
        key1 = self.keeper.add(string, mime="text/html")
        key2 = self.keeper.add(string, mime="text/plain")
        self.assertNotEqual(key1, key2)

    def test_encodings_distinct(self):
        key1 = self.keeper.add(b'', encoding='utf-8')
        key2 = self.keeper.add(b'', encoding='utf-16')
        self.assertNotEqual(key1, key2)

    def test_large_data(self):
        data = os.urandom(10 * 1024 * 1024)
        key = self.keeper.add(data)
        data2 = self.keeper[key].as_bytes()
        self.assertEqual(data, data2)

    def test_contains_negative(self):
        self.assertNotIn('2a206783b16f327a53555861331980835a0e059e', self.keeper)

    def test_contains_positive(self):
        key = self.keeper.add("Some data")
        self.assertIn(key, self.keeper)

    def test_remove_item_positive(self):
        text = "We'll attach some arbitrary meta data to this"
        key = self.keeper.add(text, mime="text/plain", filename="foo.txt", author="Joe Bloggs")
        self.assertIn(key, self.keeper)
        del self.keeper[key]
        self.assertNotIn(key, self.keeper)

    def test_remove_item_negative(self):
        with self.assertRaises(KeyError):
            _ = self.keeper['2a206783b16f327a53555861331980835a0e059e']
Пример #31
0
class Pass(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.ui = Ui_Pass()
        self.ui.setupUi(self)
        self.loadConfig()
        
        # set size and background
        self.setFixedSize(600, 400)
        randImage = random.choice(getFiles(self.images))
        if randImage:
            br = QtGui.QBrush()
            Image = QtGui.QImage(randImage)
            br.setTextureImage(Image.scaled(600, 400))
            plt = self.palette()
            plt.setBrush(plt.Background, br)
            self.setPalette(plt)
        self.setWindowIcon(QtGui.QIcon(os.path.join(self.icons, 'ps.png')))

        self.ui.lineEditPass.setEchoMode(self.ui.lineEditPass.Password)
        self.ui.deliteButton.setEnabled(False)
        self.ui.saveButton.setEnabled(False)
        self.ui.lineEditGive.setEchoMode(self.ui.lineEditGive.Password)
        self.ui.listWidget.setSortingEnabled(True)

        self.ui.pushButton.clicked.connect(self.add)
        self.ui.deliteButton.clicked.connect(self.delete)
        self.ui.saveButton.clicked.connect(self.saveDatabase)
        QtCore.QObject.connect(self.ui.listWidget, 
              QtCore.SIGNAL("itemDoubleClicked(QListWidgetItem*)"),
                              self.getLoginFromList)
        self.ui.checkBox.stateChanged.connect(self.setPasswordVisible)
        
        # clipboard
        self.globalClipboard = QtGui.QApplication.clipboard()
        self.clipboard = QtGui.QClipboard

        # tray & menu
        self.createNewAction = QtGui.QAction(QtGui.QIcon.fromTheme("document-new"),
                                  '&Create new database', self)
        self.createNewAction.triggered.connect(self.createDatabase)

        self.loadAction = QtGui.QAction(QtGui.QIcon.fromTheme("document-open"),
                                '&Load database', self)
        self.loadAction.setShortcut('Ctrl+O')
        self.loadAction.setStatusTip('Opening Database')
        self.loadAction.triggered.connect(self.setDatabase)

        self.saveAction = QtGui.QAction(QtGui.QIcon.fromTheme("document-save"),
                                 '&Save database', self)
        self.saveAction.setShortcut('Ctrl+S')
        self.saveAction.setStatusTip('Saving Database')
        self.saveAction.triggered.connect(self.saveDatabase)

        self.saveAsAction = QtGui.QAction(QtGui.QIcon.fromTheme("document-save-as"),
                                  '&Save database as', self)
        self.saveAsAction.triggered.connect(self.saveAsDatabase)
        
        self.changePasswordAction = QtGui.QAction('&Change Password', self)
        self.changePasswordAction.triggered.connect(self.setPassword)

        self.aboutAction = QtGui.QAction(QtGui.QIcon.fromTheme("help-about"),
                                    '&About', self)
        self.aboutAction.triggered.connect(self.about)

        self.quitAction = QtGui.QAction(QtGui.QIcon.fromTheme("application-exit"),
                                        '&Quit', self)
        self.quitAction.setShortcut('Ctrl+Q')
        self.quitAction.setStatusTip('Exit application')
        self.quitAction.triggered.connect(self.close)

        self.fileMenu = self.ui.menubar.addMenu('&File')
        self.fileMenu.addAction(self.createNewAction)
        self.fileMenu.addAction(self.loadAction)
        self.fileMenu.addAction(self.saveAction)
        self.fileMenu.addAction(self.saveAsAction)
        self.fileMenu.addAction(self.changePasswordAction)
        self.fileMenu.addAction(self.aboutAction)
        self.fileMenu.addAction(self.quitAction)

        self.trayIconMenu = QtGui.QMenu(self)
        self.trayIconMenu.addAction(self.saveAction)
        self.trayIconMenu.addAction(self.saveAsAction)
        self.trayIconMenu.addAction(self.quitAction)
        self.trayIconPixmap = QtGui.QPixmap(os.path.join(self.icons, "ps.png"))
        self.trayIcon = QtGui.QSystemTrayIcon(self)
        self.trayIcon.setContextMenu(self.trayIconMenu)
        self.trayIcon.setIcon(QtGui.QIcon(self.trayIconPixmap))
        self.trayIcon.show()
        self.trayIcon.activated.connect(self.changeVisible)

    def loadConfig(self):
    # initialization of variables
        self.keeper = Keeper()
        if not self.keeper.isKdb:
            self.showMessage("Warning!", "".join(("Can't load keepass module.",
                      " Nickname will be saved in plain text,",
                             " passwords will be not saved.")))

        self.password = ""
        self.file = ""
        self.salt = ""
        self.icons = ""
        self.images = ""
        self.config = Config(self, "pass") # self.homeDir
        self.config.createUserConfig(["icons", "images", "pass.py"])
        self.config.loadConfig() # self.file, self.salt, self.icons, self.images

        if self.file and type(self.file) != 'bool':
            self.setDatabase(self.file)
        else:
            self.setPassword()

        if not self.salt:
            self.salt = os.path.join(self.homeDir, "pass.py")
            if not os.path.exists(self.salt):
                with open(os.path.join(self.homeDir, "salt")) as f:
                    f.write("##")

        if not self.icons:
            self.icons = os.path.join(self.homeDir, "icons")
            if not os.path.isdir(self.icons):
                self.icons = "./icons"

        if not self.images:
            self.images = os.path.join(self.homeDir, "images")
            if not os.path.isdir(self.images):
                self.images = "./images"

        self.generator = Generator(self)
        self.generator.set_salt(self.salt)

    def saveConfig(self):
        if not self.file:
            self.file = ""
        self.config.saveConfig(["file", "salt", "icons", "images"])

    def createDatabase(self):
        if self.file and self.savePageBeforeClose() == -1:
            return 0
        try:
            self.file = str(self.showFileSaveDialog()[0])
            if file:
                self.keeper = Keeper()
        except: self.showCritical("Error","Can't create %s" % file)

    def setDatabase(self, file=""):
        if self.file and self.savePageBeforeClose() == -1:
            return 0
        back_file = self.file
        back_password = self.password
        if not file:
            self.file = self.showFileOpenDialog()[0]
        else:
            self.file = file
        self.setPassword(self.file)
        if self.file and self.password: 
            try:
                self.keeper.load(self.file, self.password)
                self.setUsersUrls()
            except:
                self.showCritical("Some error with set db", "Some error occurred when opening %s as database" 
                        %(self.file))
                self.file = back_file
                self.password = back_password
        else:
            self.file = back_file
            self.password = back_password

    def setUsersUrls(self):
        self.ui.listWidget.clear()
        for url in self.keeper.urls.keys():
            for name in self.keeper.urls[url].keys():
                if name != "SUSTEM" and url != "$":
                    self.ui.listWidget.insertItem(0, 
                          str(url) + " : " + str(name))
        if self.ui.listWidget.count():
            self.ui.deliteButton.setEnabled(True)
            self.ui.saveButton.setEnabled(True)

    def saveDatabase(self):
        if  self.file:
            self.file = self.keeper.save(self.file, self.password)
        else:
            self.saveAsDatabase()

    def saveAsDatabase(self):
        if self.ui.listWidget.count():
            try:
                file = self.showFileSaveDialog()[0]
                if file:
                    self.file = self.keeper.save(file, self.password)
            except: self.showCritical("Error","Can't save %s" % file)

    def setPassword(self, databaseName = None):
        if not databaseName:
            dlg = Password('Input Password',
                           'Input your password here:', self)
            dlg.exec_()
            text, ok = dlg.getPassword()
        else:
            text = 'Input your password for %s here:' % (str(databaseName))
            dlg = Password('Input Password', text, self)
            dlg.exec_()
            text, ok = dlg.getPassword()
        if ok:
            self.password = str(text)
            self.ui.lineEditPass.setText(self.password)

    def about(self):
        about = ""
        self.showMessage("About paSs", about)

    def getLoginFromList(self):
        item = self.ui.listWidget.item(self.ui.listWidget.currentRow())
        text = str(item.text())
        b = text.find(" : ")
        self.ui.lineEditURL.setText(text[:b])
        self.ui.lineEditUser.setText(text[b+3:])
        self.ui.lineEditPass.setFocus()

    def delete(self):
        item = self.ui.listWidget.takeItem(self.ui.listWidget.currentRow())
        text = str(item.text())
        begin = text.find(" : ")
        url = text[:begin]
        name = text[begin + 3:]
        for u in self.keeper.urls.keys():
            if u in url and name in self.keeper.urls[u].keys():
                del self.keeper.urls[u][name]
        self.ui.listWidget.removeItemWidget(item)
        if not self.ui.listWidget.count():
            self.ui.deliteButton.setEnabled(False)

    def add(self):
        name = str(self.ui.lineEditUser.text())
        url = str(self.ui.lineEditURL.text())
        nick =  " : ".join((url, name)) 
        password = self.generator.generate_simple(str(self.ui.lineEditUser.text()),
                      str(self.ui.lineEditURL.text()), self.password, 32)
        self.ui.lineEditURL.clear()
        self.ui.lineEditUser.clear()
        self.ui.lineEditGive.setText(password)
        self.clipboard.setText(self.globalClipboard, password)
        if name and url and (url not in self.keeper.urls.keys() \
          or name not in self.keeper.urls[url].keys() \
            or password != self.keeper.urls[url][name][0]):
            self.keeper.urls[url] = {name : [password, "simple 32"]}
            self.ui.listWidget.insertItem(0, nick)
            # enable buttons
            self.ui.deliteButton.setEnabled(True)
            self.ui.saveButton.setEnabled(True)

    def savePageBeforeClose(self):
        if self.ui.listWidget.count():
            q = "Do you want to save your changes?"
            if self.file:
                q = "Do you want to save your changes as %s?" % self.file
            choice = self.showChoice("?!", q)
            if choice == -1:
                return -1
            elif choice:
                self.saveDatabase()
            return 1

    def showChoice(self, title, text):
        q = QtGui.QMessageBox.question(self, 
                  title,
                  text,
                  QtGui.QMessageBox.No |
                  QtGui.QMessageBox.Cancel |
                  QtGui.QMessageBox.Yes,)
        if q == QtGui.QMessageBox.Yes:
            return True
        elif q == QtGui.QMessageBox.No:
            return False
        return -1

    def setPasswordVisible(self, e):
        if e:
            self.ui.lineEditGive.setEchoMode(self.ui.lineEditGive.Password)
        else:
            self.ui.lineEditGive.setEchoMode(self.ui.lineEditGive.Normal)

    def showFileOpenDialog(self, path="", filer=""):
        if not path:
            path = self.homeDir
        return QtGui.QFileDialog.getOpenFileName(self,
                      'Open file', path, filer)

    def showFileSaveDialog(self, path="", filer=""):
        if not path:
            path = self.homeDir
        return QtGui.QFileDialog.getSaveFileName(self,
                    'Save file as:', path, filer)

    def showMessage(self, title, text):
        QtGui.QMessageBox.information(self, str(title), str(text))

    def showCritical(self, title, text):
        QtGui.QMessageBox.critical(self, str(title), str(text))

    def changeVisible(self,r):
        if r == QtGui.QSystemTrayIcon.Trigger:
            if self.isHidden():
                self.showNormal()
            else:
                self.hide()
    
    def changeEvent(self, e):
        # to tray
        if self.isMinimized():
            self.hide()
            e.ignore()

    def closeEvent(self, e):
        if self.savePageBeforeClose() != -1:
            self.saveConfig()
            six.print_(("bye!"), file=sys.stdout, end="\n", sep=" ")
            self.close()
        else:
            e.ignore()
Пример #32
0
    def test_backup(self):
        """Test creating a backup file from a set of directories"""
        cwd = os.getcwd()
        # Set paths
        file_paths = [
            cwd + "/tmp/keeper_test_backup/house/room/file1.txt",
            cwd + "/tmp/keeper_test_backup/house/room/desk/file2.txt",
            cwd + "/tmp/keeper_test_backup/house/room/desk/file3.txt",
            cwd + "/tmp/keeper_test_backup/house/room/desk/drawer/file4",
            cwd + "/tmp/keeper_test_backup/house/room/locker/file5.txt"
        ]
        folder_paths_to_create = [
            cwd + "/tmp/keeper_test_backup/house/room/desk/drawer",
            cwd + "/tmp/keeper_test_backup/house/room/locker"
        ]
        directories_to_backup = [
            cwd + "/tmp/keeper_test_backup/house/room/desk/drawer",
            cwd + "/tmp/keeper_test_backup/house/room/locker"
        ]
        files_expected_in_tar = [
            os.path.join(
                cwd.strip("/"),
                "tmp/keeper_test_backup/house/room/desk/drawer"
            ),
            os.path.join(
                cwd.strip("/"),
                "tmp/keeper_test_backup/house/room/desk/drawer/file4"
            ),
            os.path.join(
                cwd.strip("/"),
                "tmp/keeper_test_backup/house/room/locker"
            ),
            os.path.join(
                cwd.strip("/"),
                "tmp/keeper_test_backup/house/room/locker/file5.txt"
            )
        ]

        # Set sails
        keeper = Keeper(system_directories=directories_to_backup,
                        show_progress=False)

        # Create all directories
        for path in folder_paths_to_create:
            self._create_dir(path)

        # Create all files for backup test
        for path in file_paths:
            # Create file
            with open(path, "w") as file_handle:
                file_handle.write("For Gondor!\n")

        # Create backup
        keeper.backup(
            destination_path=cwd + "/tmp/keeper_test_backup",
            filename="backup_test.tar.gz"
        )

        # Get list of all file paths inside tar file
        files_in_tar = self._list_files_in_tar(
            cwd + "/tmp/keeper_test_backup/backup_test.tar.gz")

        # tar file can't be empty
        self.assertNotEqual(len(files_in_tar), 0)

        # Normpath the paths
        # NOTE: I don't know why this is necessary
        files_expected_in_tar = [
            os.path.normpath(p) for p in files_expected_in_tar
        ]
        files_in_tar = [
            os.path.normpath(p) for p in files_in_tar
        ]

        # Compare tar file and list of files
        self.assertEqual(files_expected_in_tar,
                         files_in_tar)

        # Recursively remove all directories and files used in test
        self._purge_directory(cwd + "/tmp/keeper_test_backup")
Пример #33
0
    def test_restore_does_not_overwrite(self):
        """Test that existing files are not overwritten by restore"""
        cwd = os.getcwd()
        base = cwd + "/tmp/keeper_python_unittest_restore_no_overwrite"
        # Set paths
        file_paths = [
            base + "/hotel/lobby/file1.txt",
            base + "/hotel/lobby/desk/file2.txt",
            base + "/hotel/lobby/desk/file3.txt",
            base + "/hotel/lobby/desk/drawer/f4",
            base + "/hotel/lobby/locker/file5.txt"
        ]
        folder_paths_to_create = [
            base + "/hotel/lobby/desk/drawer/",
            base + "/hotel/lobby/locker"
        ]
        directories_to_backup = [
            base + "/hotel/lobby/desk/drawer/",
            base + "/hotel/lobby/locker/"
        ]
        files_expected_in_restore = [
            base + "/hotel/lobby/desk/drawer/f4",
            base + "/hotel/lobby/locker/file5.txt"
        ]

        # Set sails
        keeper = Keeper(system_directories=directories_to_backup,
                        show_progress=False)

        # Create all directories
        for path in folder_paths_to_create:
            self._create_dir(path)

        # Create all files for backup
        for path in file_paths:
            # Create file
            with open(path, "w") as file_handle:
                file_handle.write("For Gondor!\n")

        # Create backup
        keeper.backup(
            destination_path=base,
            filename="restore_test.tar.gz"
        )

        # Write to files again
        for name in files_expected_in_restore:
            with open(name, "w") as file_handle:
                file_handle.write("new version\n")

        # Restore should raise exception on existing file
        with self.assertRaises(Exception):
            keeper.restore(base + "/restore_test.tar.gz")

        # Get file contents
        files_content = []
        for name in files_expected_in_restore:
            with open(name, "r") as file_handle:
                content = file_handle.read()
                files_content.append(content)

        self.assertEqual(
            files_content,
            [
                "new version\n",
                "new version\n"
            ]
        )

        # Purge the test directory
        self._purge_directory(base)
Пример #34
0
from flask import Flask, Blueprint, request, Response, jsonify
from flask_api import status
from keeper import Keeper

app = Flask(__name__)
keep = Keeper()

@app.route('/<list_id>', methods=['GET'])
def listItems(list_id):
    return jsonify(
        uncheckedItems = keep.getUncheckedItems(list_id),
        checkedItems = keep.getCheckedItems(list_id)
    ), status.HTTP_200_OK

@app.route('/<list_id>', methods=['POST'])
def addListItem(list_id):
    content = request.json
    item = content['item']
    keep.addItem(list_id, item)

    return jsonify(
        addedItem = item,
    ), status.HTTP_200_OK

@app.route('/<list_id>', methods=['PUT'])
def checkUncheck(list_id):
    content = request.json
    item = content['item']

    keep.modifyCheckState(list_id, item)