Skip to content

Commit

Permalink
Hot fix 0.3.4 (#36)
Browse files Browse the repository at this point in the history
- TItkcetPrice now has a lock (multiple threads creating multiple TicketPrice's)
- Empty UpdateMessage now is possible
- reduce on __str__ methods
  • Loading branch information
rodrigondec authored Dec 25, 2019
1 parent f21fdf2 commit 81704d3
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 21 deletions.
4 changes: 4 additions & 0 deletions db/ticket.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import logging
from threading import Lock

import pendulum
from mongoengine import (
Expand All @@ -16,6 +17,7 @@


class TicketPrice(Document):
lock = Lock()
endpoint = "stake/diff"

price = FloatField(required=True)
Expand Down Expand Up @@ -49,6 +51,7 @@ def _fetch_new_ticket_price(cls):

@classmethod
def get_last(cls):
cls.lock.acquire()
last_ticket_price = cls.objects.order_by('-datetime').first()

try:
Expand All @@ -59,4 +62,5 @@ def get_last(cls):
finally:
last_ticket_price.save()

cls.lock.release()
return last_ticket_price
24 changes: 13 additions & 11 deletions db/update_message.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from json import loads
from functools import reduce

import pendulum
from mongoengine import (
Expand All @@ -19,6 +20,11 @@ class Amount(EmbeddedDocument):
def __str__(self):
return f"{self.value} DCR"

def __add__(self, other):
if not isinstance(other, Amount):
raise TypeError('Cannot add!')
return Amount(self._value + other._value)

def equal(self, other):
if not isinstance(other, Amount):
raise TypeError(f"Other must be {Amount}")
Expand All @@ -41,12 +47,9 @@ class Session(EmbeddedDocument):

def __str__(self):
string = f"{self.hash[:32]}:\t["
total = 0
for index, amount in enumerate(self.amounts):
total += amount.value
string += f"{amount}"
string += ", " if index != len(self.amounts)-1 else "]"
string += f"\nTotal: {total} DCR"
string += ", ".join([f"{amount}" for amount in self.amounts])
total = reduce(lambda a, b: a+b, self.amounts, Amount(0))
string += f"]\nTotal: {total}"
return string

def equal(self, other):
Expand All @@ -69,7 +72,7 @@ def from_data(cls, data):

class UpdateMessage(Document):
subject = ReferenceField(Subject, required=True)
sessions = EmbeddedDocumentListField(Session, required=True)
sessions = EmbeddedDocumentListField(Session)
datetime = DateTimeField(default=pendulum.now, required=True)

meta = {
Expand All @@ -81,11 +84,10 @@ class UpdateMessage(Document):

def __str__(self):
string = f"<b>{self.subject.header}</b>\n\n"
string += f"<i>Default session: {self.subject.default_session}</i>\n\n"
string += f"Ticket price: {TicketPrice.get_last()}\n\n"
for index, msg in enumerate(self.sessions):
string += f"<code>{msg}</code>"
string += "\n\n" if index != len(self.sessions) - 1 else ""
string += f"<i>Default session: {self.subject.default_session}</i>\n\n"
string += "\n\n".join([f"<code>{session}</code>"
for session in self.sessions])
return string

def equal(self, other):
Expand Down
3 changes: 1 addition & 2 deletions sws/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from threading import Thread, Lock

from websocket import WebSocketApp
from mongoengine.errors import ValidationError

from bot.jack import JackBot
from db.subject import Subject
Expand Down Expand Up @@ -80,7 +79,7 @@ def on_message(ws: WebSocketApp, data):
sws.subject.notify(msg)
sws.lock.release()
logger.info(f'{sws.name} released lock!')
except (ValidationError, DuplicatedUpdateMessageError) as e:
except DuplicatedUpdateMessageError as e:
logger.info(f"Supress {e} for creating {UpdateMessage} "
f"from {data} on {sws}")

Expand Down
36 changes: 28 additions & 8 deletions tests/db/test_update_message.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
from unittest import TestCase
from unittest import TestCase, mock

import pytest

from tests.fixtures import mongo # noqa F401
from db.update_message import UpdateMessage, Session, Amount
from db.subject import Subject
from db.ticket import TicketPrice
from utils.exceptions import DuplicatedUpdateMessageError


Expand All @@ -28,29 +29,48 @@ def setUp(self) -> None:
def test_init(self):
self.assertEqual(UpdateMessage.objects.count(), 0)

UpdateMessage(self.subject, [Session('test', [Amount(10)])]).save()
UpdateMessage(self.subject,
[Session('test', [Amount(1000000000)])]).save()
self.assertEqual(UpdateMessage.objects.count(), 1)

instance = UpdateMessage.objects.first()
self.assertEqual(instance.subject, self.subject)
self.assertIsInstance(instance, UpdateMessage)

@mock.patch('db.ticket.TicketPrice.get_last')
def test_str(self, mocked_get_last):
ticket_price = TicketPrice(10)
mocked_get_last.return_value = ticket_price

instance = UpdateMessage(self.subject,
[Session('test', [Amount(1000000000)])]).save()
self.assertEqual(instance.__str__(),
f"<b>🇧🇷 Decred Brasil</b>\n\n"
f"Ticket price: 10.00 DCR\n\n"
f"<i>Default session: dcrbr1</i>\n\n"
f"<code>test:\t[10.0 DCR]\nTotal: 10.0 DCR</code>")

def test_equal(self):
instance = UpdateMessage(self.subject, [Session('test', [Amount(10)])])
other = UpdateMessage(self.subject, [Session('test', [Amount(10)])])
instance = UpdateMessage(self.subject,
[Session('test', [Amount(1000000000)])])
other = UpdateMessage(self.subject,
[Session('test', [Amount(1000000000)])])

self.assertTrue(instance.equal(other))

def test_equal_false(self):
instance = UpdateMessage(self.subject, [Session('test', [Amount(10)])])
other = UpdateMessage(self.subject, [Session('test', [Amount(11)])])
instance = UpdateMessage(self.subject,
[Session('test', [Amount(1000000000)])])
other = UpdateMessage(self.subject,
[Session('test', [Amount(1100000000)])])

self.assertFalse(instance.equal(other))

def test_get_last_by_subject(self):
UpdateMessage(self.subject, [Session('test', [Amount(10)])]).save()
UpdateMessage(self.subject, [Session('test',
[Amount(1000000000)])]).save()
other = UpdateMessage(self.subject,
[Session('test', [Amount(11)])]).save()
[Session('test', [Amount(1100000000)])]).save()

last = UpdateMessage.get_last_by_subject(self.subject)
self.assertEqual(other, last)
Expand Down

0 comments on commit 81704d3

Please sign in to comment.