Beispiel #1
0
def test_rec_lists():
    x = [
        [1, 4, 5],
        {"x": 234, "name": "human"},
        "cordial",
        ["a", "b", "c"]
    ]
    assert serializer(x) == x, "Elemental List Recursion level 1 should serialize to self"

    x2 = [
        [[1, 4, 6], {"x": 4.5}, "i am not", [{"x": 1}]]
    ]

    assert serializer(x2) == x2, "Elemental List with multiple recursions should serialize to self"
Beispiel #2
0
def test_rec_dict():
    x = dict(
        x=[1, 2, 3, 4],
        anomaly=dict(x=1.3, y=3.4, z=6.7),
        name="not the guy"
    )
    assert serializer(x) == x, "Elemental Dict with recursion level 1 should serialize to self"

    x2 = dict(
        w=dict(w=dict(x=dict(f=[1, 4, 6]))),
        f=[1.3, 1.5, 1.6],
        name="namaste"
    )

    assert serializer(x2) == x2, "Elemental Dict with multiple recursions should serialize to self"
Beispiel #3
0
def test_recursive_mixin():
    class Values(SerializableMixin):

        def __init__(self, values: List[int]):
            self.values = values

        def __serialize__(self):
            return dict(
                values=serializer(self.values)
            )

    class Test(SerializableMixin):

        def __init__(self, name: str, values: Values):
            self.name = name
            self.values = values

        def __serialize__(self):
            return dict(
                name=serializer(self.name),
                values=serializer(self.values)
            )

    test = Test(name="Nick", values=Values(values=[1, 4, 1]))
    result = dict(name="Nick", values=dict(values=[1, 4, 1]))
    assert serializer(test) == result, "Recursive mixin test failed"
Beispiel #4
0
    def __init__(self,
                 influxHost,
                 username,
                 password,
                 database,
                 topic,
                 influxPort=8086):
        from influxdb import InfluxDBClient
        import logging
        import traceback
        from serializer import serializer
        from status_validator import status_validate

        self.influxClient = InfluxDBClient(influxHost, influxPort, username,
                                           password)
        self.influxClient.switch_database(database)

        self.logging = logging
        self.traceback = traceback
        self.logging.basicConfig(filename="error.log")
        self.topic = topic
        switch = {"ph": "pH", "tb": "NTU", "temp": "Celsius", "do": "mg/L"}

        self.serializer = serializer(topic, switch.get(topic, "No unit"))
        self.validate = status_validate()
Beispiel #5
0
async def like_topic(connection: asyncpg.connection.Connection,topic:int,user_id:int,timeout:int = 10) -> Tuple:
    ''' 1: Like added 
        2: Like removed
        3: No such topic
        4: Cannot remove like '''
    is_topic = await check_topic(connection,topic)
    if not is_topic:
        return 3, None
    select_query = 'SELECT * FROM TopicLike WHERE topic_id = $1 and user_id = $2;'
    result = await connection.fetchrow(select_query,topic,user_id)
    if result:
        now = datetime.now()
        if (now-result['added']).seconds//60 > timeout:
            return 4, None
        else:
            delete_query = 'DELETE FROM TopicLike WHERE topic_id = $1 AND user_id = $2;'
            await connection.execute(delete_query,topic,user_id)
            update_query = 'UPDATE Topic SET number_of_likes = number_of_likes-1 WHERE id=$1;'
            await connection.execute(update_query,topic)
            return 2, None
    else:
        add_query = 'INSERT INTO TopicLike (topic_id, user_id) VALUES ($1,$2);'
        await connection.execute(add_query,topic,user_id)
        update_query = 'UPDATE Topic SET number_of_likes = number_of_likes+1 WHERE id=$1;'
        await connection.execute(update_query,topic)
        return 1, serializer({'topic_id':topic,'user_id':user_id})
Beispiel #6
0
async def create_topic(connection: asyncpg.connection.Connection, title:str, body: str, id: int):
    query = 'INSERT INTO Topic (title, body, creator_id) VALUES ($1,$2,$3);'
    await connection.execute(query,title,body,id)

    select_query = 'SELECT * FROM Topic WHERE title = $1 AND body = $2 AND creator_id = $3'
    res = await connection.fetchrow(select_query,title,body,id)
    return serializer(dict(res))
Beispiel #7
0
def test_wrapper_dataclass():
    @serializable
    class Test:
        name: str
        values: List[int]

    test = Test(name="Nick", values=[1, 4, 1])
    result = dict(name="Nick", values=[1, 4, 1])
    assert serializer(test) == result, "Simple dataclass wrapper test failed"
Beispiel #8
0
async def get_comments(connection: asyncpg.connection.Connection,topic:int, limit: int, offset: int) -> List:

    select_query = 'SELECT * FROM Comment WHERE topic_id = $1 LIMIT $2 OFFSET $3;'
    res = await connection.fetch(select_query,topic,limit,offset)
    results = []

    for topic in res:
        results.append(serializer(dict(topic)))

    return results
Beispiel #9
0
async def get_topics(connection: asyncpg.connection.Connection, limit: int, offset: int) -> List:

    select_query = 'SELECT * FROM Topic LIMIT $1 OFFSET $2;'
    res = await connection.fetch(select_query,limit,offset)
    results = []

    for topic in res:
        results.append(serializer(dict(topic)))

    return results
Beispiel #10
0
async def create_comment(connection: asyncpg.connection.Connection,topic:int,user_id:int,body:str):
    is_topic = await check_topic(connection,topic)
    if not is_topic:
        return None
    create_query = 'insert into Comment (body, creator_id, topic_id) values ($1,$2,$3);'
    await connection.execute(create_query,body,user_id,topic)
    update_query = 'UPDATE Topic SET number_of_comments = number_of_comments+1 WHERE id=$1;'
    await connection.execute(update_query,topic)
    query = 'SELECT * from Comment WHERE body = $1 AND creator_id =$2 AND topic_id = $3;'
    comment = await connection.fetchrow(query,body,user_id,topic)
    return serializer(dict(comment))
Beispiel #11
0
def test_recursive_dataclass():
    @serializable
    class Values:
        values: List[int]

    @serializable
    class Test:
        name: str
        values: Values

    test = Test(name="Nick", values=Values(values=[1, 4, 1]))
    result = dict(name="Nick", values=dict(values=[1, 4, 1]))
    assert serializer(test) == result, "Recursive dataclass test failed"
Beispiel #12
0
def test_class_mixin():
    class Test(SerializableMixin):

        def __init__(self, name: str, values: List[int]):
            self.name = name
            self.values = values

        def __serialize__(self):
            return dict(
                name=serializer(self.name),
                values=serializer(self.values)
            )

    test = Test(name="Nick", values=[1, 4, 1])
    result = dict(name="Nick", values=[1, 4, 1])
    assert serializer(test) == result, "Simple Mixin Test failed"
Beispiel #13
0
def test_recursive_dataclass2():
    @serializable
    class Role:
        role_type: str
        attributes: List[str]

    @serializable
    class Person:
        name: str
        age: int
        height: float
        weight: float
        address: str
        role: List[Role]

    @serializable
    class Values:
        values: List[int]

    @serializable
    class Test:
        humans: Dict[str, Person]
        values: Values

    persons = dict(
        john=Person(name="john", age=19, height=1.4, weight=14.8, address="here",
                    role=Role(role_type="manager", attributes=["lead_stuff", "decide"])),
        mark=Person(name="mark", age=19, height=1.4, weight=14.8, address="here",
                    role=Role(role_type="manager", attributes=["lead_stuff", "decide"])),
        devil=Person(name="devil", age=19, height=1.4, weight=14.8, address="here",
                     role=Role(role_type="manager", attributes=["lead_stuff", "decide"])),
    )
    test = Test(humans=persons, values=Values(values=[1, 4, 1]))
    result = dict(
        humans=dict(
            dict(
                john=dict(name="john", age=19, height=1.4, weight=14.8, address="here",
                          role=dict(role_type="manager", attributes=["lead_stuff", "decide"])),
                mark=dict(name="mark", age=19, height=1.4, weight=14.8, address="here",
                          role=dict(role_type="manager", attributes=["lead_stuff", "decide"])),
                devil=dict(name="devil", age=19, height=1.4, weight=14.8, address="here",
                           role=dict(role_type="manager", attributes=["lead_stuff", "decide"])),
            )
        ),
        values=dict(values=[1, 4, 1]))
    assert serializer(test) == result, "Complex Recursive dataclass test failed"
Beispiel #14
0
async def auth(connection: asyncpg.connection.Connection,username: str,password: str) -> Tuple:

    password_hash = get_password(password)

    query = 'SELECT id, username, first_name, last_name, email, date_joined FROM Users WHERE username = $1 AND password = $2;'

    result = await connection.fetchrow(query,username,password_hash)

    if not result:
        return None, None

    token = create_token(username,password_hash)

    user = serializer(dict(result))

    await update_token(connection,token,result['id'])

    return user, token
Beispiel #15
0
#encoding:utf-8
import os,sys
import signal  
from serializer import serializer
   
#发送信号,16175是前面那个绑定信号处理函数的pid,需要自行修改  
data=serializer('working/data/pids.json')
for i in data.loader():
    if i['name'] == 'get_html_a':
        print 'send term to pid:%s'%i['pid']
        os.kill(i['pid'],signal.SIGUSR1)
    #else:    
    #    print 'send kill to pid:%s'%i['pid']
    #    os.kill(i['pid'],signal.SIGKILL)  

#for i in spid:
#        print 'send kill to pid:%s'%i
#        os.kill(i,signal.SIGKILL)  

#发送信号,16175是前面那个绑定信号处理函数的pid,需要自行修改  
Beispiel #16
0
 def __serialize__(self):
     return dict(
         values=serializer(self.values)
     )
Beispiel #17
0
def test_list_serialisation():
    # Testing lists
    assert serializer([1, 2, 3]) == [1, 2, 3], "List of builtins should not be altered"
    assert serializer([1.4, 2.6, 3.9]) == [1.4, 2.6, 3.9], "List of builtins should not be altered"
    assert serializer(["aze", "azea", "azez"]) == ["aze", "azea", "azez"], "List of builtins should not be altered"
Beispiel #18
0
 def __serialize__(self):
     return dict(
         name=serializer(self.name),
         values=serializer(self.values)
     )
Beispiel #19
0
def test_builtin_serialisation():
    # Elemental python.builtins
    assert serializer(5) == 5, "Int should not be altered"
    assert serializer(5.6) == 5.6, "Float should not be altered"
    assert serializer("I am a string") == "I am a string", "String should not be altered"
    assert serializer(None) is None, "None should remain none"
Beispiel #20
0
def test_dict_serialisation():
    # Testing dicts
    assert serializer({'x': 234, 'y': 234}) == {'x': 234, 'y': 234}, "Dict of builtins should not be altered"
    assert serializer({'x': '234', 'y': 234, 'z': 567.9}) == {'x': '234', 'y': 234, 'z': 567.9}, \
        "Dict of builtins should not be altered"