Skip to content

Commit

Permalink
Merge 55814d2 into 5def5fa
Browse files Browse the repository at this point in the history
  • Loading branch information
garciparedes committed May 11, 2019
2 parents 5def5fa + 55814d2 commit 9979fa8
Show file tree
Hide file tree
Showing 12 changed files with 197 additions and 51 deletions.
4 changes: 2 additions & 2 deletions examples/example.py → examples/example_deque.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import logging

from ringer import RingMemory
import ringer as rg


def main():
logging.basicConfig(level='DEBUG')

ring = RingMemory(3)
ring = rg.RingerDeque(capacity=3, storage=rg.Storage.MEMORY)

ring.append("A")
ring.append("B")
Expand Down
29 changes: 29 additions & 0 deletions examples/example_list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import logging
from pathlib import Path

import ringer as rg


def main():
logging.basicConfig(level='DEBUG')

file_path = Path('test.rgr')
ring = rg.RingerList(file_path=file_path, storage=rg.Storage.FILE)

ring.append("A")
ring.append("A")
ring.append("A")
ring.append("A")

ring[1] = "B"
ring[2] = "C"
ring[3] = "D"

print(ring[0])
print(ring[1])
print(ring[2])
print(ring[3])


if __name__ == '__main__':
main()
16 changes: 4 additions & 12 deletions ringer/__init__.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,8 @@
from .version import \
VERSION, \
__version__

from .exceptions import \
RingException, \
EmptyRingException

from .rings import \
Ring, \
RingDirectory, \
RingFile, \
RingMemory

from .manager import \
Manager
RingerException, \
EmptyRingerException
from .collections import *
from .storages import *
3 changes: 3 additions & 0 deletions ringer/collections/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .base import Ringer
from .deques import RingerDeque
from .lists import RingerList
14 changes: 14 additions & 0 deletions ringer/collections/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from abc import ABC
from typing import Any
from uuid import uuid4

from ..storages import Storage


class Ringer(ABC):

def __init__(self, storage: Storage, uuid: Any = None, *args, **kwargs):
if uuid is None:
uuid = uuid4()
self.uuid = uuid
self.storage = storage
35 changes: 9 additions & 26 deletions ringer/rings.py → ringer/collections/deques.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,21 @@
import logging
from abc import ABC, abstractmethod

from typing import Any
from uuid import uuid4

from .exceptions import EmptyRingException
from ..storages import Storage
from ..exceptions import EmptyRingerException
from .base import Ringer

logger = logging.getLogger(__name__)


class Ring(ABC):

def __init__(self, **kwargs):
self.uuid = uuid4()

@abstractmethod
def append(self, value: Any):
pass

@abstractmethod
def pop(self, index=None) -> Any:
pass


class RingFile(Ring):
pass


class RingDirectory(Ring):
pass
class RingerDeque(Ringer):

def __init__(self, capacity: int, **kwargs):

class RingMemory(Ring):
if kwargs.get('storage') != Storage.MEMORY:
raise NotImplementedError

def __init__(self, capacity: int, **kwargs):
super().__init__(**kwargs)
self._container = dict()
self._capacity = capacity
Expand Down Expand Up @@ -73,7 +56,7 @@ def pop(self, index=None) -> Any:
try:
value = self._container.pop(index)
except KeyError as e:
raise EmptyRingException
raise EmptyRingerException
self._pop_index = (self._pop_index + 1) % self.capacity

logger.debug('Performed pop(). Container: "{}", Extracted value: "{}".'.format(self._container, value))
Expand Down
71 changes: 71 additions & 0 deletions ringer/collections/lists.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import logging
from collections import MutableSequence
from pathlib import Path
from typing import Any

from ..storages import Storage
from .base import Ringer

logger = logging.getLogger(__name__)


class RingerList(Ringer, MutableSequence):

def __init__(self, file_path: Path, *args, **kwargs):
if kwargs.get('storage') != Storage.FILE:
raise NotImplementedError

super().__init__(*args, **kwargs)

self._file_path = file_path
open(str(self._file_path), 'w').close()

def insert(self, index: int, value: Any) -> None:
logger.debug('Inserting "{}" on "{}" index.'.format(str(value)[:30], index))

if self._file_path.exists():
with open(str(self._file_path)) as file_reader:
file_data = file_reader.readlines()
else:
file_data = list()
raw_value = '{}\n'.format(value)
file_data.insert(index, raw_value)

with open(str(self._file_path), 'w') as file_writer:
file_writer.writelines(file_data)

def __setitem__(self, index, value):
logger.debug('Setting "{}" on "{}" index.'.format(str(value)[:30], index))

if self._file_path.exists():
with open(str(self._file_path)) as file_reader:
file_data = file_reader.readlines()
else:
file_data = list()
raw_value = '{}\n'.format(value)
file_data[index] = raw_value

with open(str(self._file_path), 'w') as file_writer:
file_writer.writelines(file_data)

def __delitem__(self, index):
logger.debug('Deleting on "{}" index.'.format(index))

if self._file_path.exists():
with open(str(self._file_path)) as file_reader:
file_data = file_reader.readlines()
else:
file_data = list()
del file_data[index]

with open(str(self._file_path), 'w') as file_writer:
file_writer.writelines(file_data)

def __getitem__(self, index):
logger.debug('Getting on "{}" index.'.format(index))
with open(str(self._file_path)) as file_reader:
return file_reader.readlines()[index].strip()

def __len__(self):
with open(str(self._file_path)) as f:
return sum(1 for _ in f)
4 changes: 2 additions & 2 deletions ringer/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
class RingException(Exception):
class RingerException(Exception):
pass


class EmptyRingException(RingException):
class EmptyRingerException(RingerException):
pass
2 changes: 0 additions & 2 deletions ringer/manager.py

This file was deleted.

7 changes: 7 additions & 0 deletions ringer/storages.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from enum import Enum


class Storage(Enum):
MEMORY = 'memory'
FILE = 'file'
DIRECTORY = 'directory'
51 changes: 51 additions & 0 deletions tests/test_list_file.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import unittest
from pathlib import Path

import ringer as rg


class TestRingMemory(unittest.TestCase):

def setUp(self) -> None:
self.file_path = Path('test.rgr')
self.ring = rg.RingerList(file_path=self.file_path, storage=rg.Storage.FILE)

def tearDown(self) -> None:
self.file_path.unlink()

def test_append(self):
self.ring.append('A')
self.assertEqual(len(self.ring), 1)

self.ring.append('B')
self.assertEqual(len(self.ring), 2)

self.ring.append('C')
self.assertEqual(len(self.ring), 3)

self.ring.append('D')
self.assertEqual(len(self.ring), 4)

def test_pop(self):
self.ring.append('A')
self.ring.append('B')
self.ring.append('C')
self.ring.append('D')

result = self.ring.pop()
self.assertEqual(result, 'D')

result = self.ring.pop()
self.assertEqual(result, 'C')

result = self.ring.pop()
self.assertEqual(result, 'B')

result = self.ring.pop()
self.assertEqual(result, 'A')

self.assertEqual(len(self.ring), 0)


if __name__ == '__main__':
unittest.main()
12 changes: 5 additions & 7 deletions tests/test_memory.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
import unittest

from ringer import \
RingMemory, \
EmptyRingException
import ringer as rg


class TestRingMemory(unittest.TestCase):

def test_constructor(self):
capacity = 5
ring = RingMemory(capacity=capacity)
ring = rg.RingerDeque(capacity=capacity, storage=rg.Storage.MEMORY)
self.assertEqual(ring.capacity, capacity)

def test_append(self):
ring = RingMemory(3)
ring = rg.RingerDeque(capacity=3, storage=rg.Storage.MEMORY)

ring.append('A')
self.assertEqual(len(ring), 1)
Expand All @@ -28,7 +26,7 @@ def test_append(self):
self.assertEqual(len(ring), 3)

def test_pop(self):
ring = RingMemory(3)
ring = rg.RingerDeque(capacity=3, storage=rg.Storage.MEMORY)

ring.append('A')
ring.append('B')
Expand All @@ -44,7 +42,7 @@ def test_pop(self):
result = ring.pop()
self.assertEqual(result, 'D')

self.assertRaises(EmptyRingException, ring.pop)
self.assertRaises(rg.EmptyRingerException, ring.pop)


if __name__ == '__main__':
Expand Down

0 comments on commit 9979fa8

Please sign in to comment.