예제 #1
0
async def test_create_visitor_without_token(client, visitors):
    new_visitor = get_fake_visitor()
    new_visitor.pop("id")

    # Missing token
    res = await client.post("/visitors", json=new_visitor)
    assert res.status == 200

    body = await res.json()
    assert "data" in body
    assert isinstance(body["data"], dict)

    all_visitors = await Visitor.query.gino.all()
    assert len(all_visitors) == len(visitors) + 1
    assert profile_created_from_origin(new_visitor, all_visitors[-1].to_dict())

    # Valid
    new_user = get_fake_visitor()
    new_user.pop("id")
    res = await client.post("/visitors", json=new_user)
    assert res.status == 200

    body = await res.json()
    assert "data" in body
    assert isinstance(body["data"], dict)

    all_users = await Visitor.query.gino.all()
    assert len(all_users) == len(visitors) + 2
    assert profile_created_from_origin(new_user, all_users[-1].to_dict())

    # Create an existing user
    res = await client.post("/visitors", json=new_user)
    assert res.status == 400
예제 #2
0
async def test_get_flagged_chats_of_online_visitors(supervisor1_client):
    # Create some visitors
    visitors = []
    chats = []
    for _ in range(30):
        new_visitor = get_fake_visitor()
        new_visitor.pop("id")

        res = await supervisor1_client.post("/visitors", json=new_visitor)
        assert res.status == 200
        body = await res.json()
        visitors.append(body["data"])
        chat = await Chat.get_or_create(visitor_id=body["data"]["id"])
        chats.append(chat)

    # Flag some chats
    index = 7
    for visitor in visitors[7:26]:
        chat = await Chat.get_or_create(visitor_id=visitor["id"])
        sleep(0.001)
        updated_chat = await Chat.modify(
            {"id": chat["id"]},
            {"severity_level": DEFAULT_SEVERITY_LEVEL_OF_CHAT + 1})
        chats[index] = updated_chat
        index += 1

    # Get the first 15 flagged chats
    online_visitors = [visitor["id"] for visitor in visitors]
    flagged_chats = await get_flagged_chats_of_online_visitors(
        Visitor, Chat, in_values=online_visitors)
    assert len(flagged_chats) == 15
    for expected, visitor in zip(reversed(visitors[11:26]), flagged_chats):
        # room = flag_chat["room"]
        # visitor = flag_chat["visitor"]

        # Compare
        chat = await Chat.get(visitor_id=visitor["id"])
        # assert profile_created_from_origin(room, chat)
        # assert profile_created_from_origin(expected, visitor)
        assert profile_created_from_origin({**chat, **expected}, visitor)

    # Unflag some chats
    for chat in chats[11:25]:
        await Chat.modify({"id": chat["id"]},
                          {"severity_level": DEFAULT_SEVERITY_LEVEL_OF_CHAT})

    # Get the remained flagged chats
    flagged_chats = await get_flagged_chats_of_online_visitors(
        Visitor, Chat, in_values=online_visitors)
    assert len(flagged_chats) == 5
    for expected, visitor in zip(reversed(visitors[7:11] + visitors[25:26]),
                                 flagged_chats):
        # room = flag_chat["room"]
        # visitor = flag_chat["user"]

        # Compare
        chat = await Chat.get(visitor_id=visitor["id"])
        # assert profile_created_from_origin(room, chat)
        # assert profile_created_from_origin(expected, visitor)
        assert profile_created_from_origin({**chat, **expected}, visitor)
예제 #3
0
async def test_get_visitor_bookmark_of_staff(supervisor1_client, users):
    # Create some visitors
    visitors = []
    for _ in range(32):
        new_visitor = get_fake_visitor()
        new_visitor.pop("id")

        res = await supervisor1_client.post("/visitors", json=new_visitor)
        assert res.status == 200
        body = await res.json()
        visitors.append(body["data"])

    # Bookmark some visitors
    for visitor in visitors:
        res = await supervisor1_client.patch(
            "/visitors/{}/bookmark".format(visitor["id"]), json={"is_bookmarked": True}
        )
        assert res.status == 200

    visitors = visitors[::-1]

    # Get the bookmarked visitors
    res = await supervisor1_client.get("/visitors/bookmarked")
    body = await res.json()
    assert res.status == 200
    assert "data" in body
    assert isinstance(body["data"], list)
    assert "links" in body and "next" in body["links"]
    assert len(body["data"]) == 15
    for expected, actual in zip(visitors[:15], body["data"]):
        assert profile_created_from_origin(expected, actual)

    # Next page
    next_page_link = get_next_page_link(body)
    res = await supervisor1_client.get(next_page_link)
    body = await res.json()
    assert res.status == 200
    assert "data" in body
    assert isinstance(body["data"], list)
    assert "links" in body and "next" in body["links"]
    assert len(body["data"]) == 15
    for expected, actual in zip(visitors[15:30], body["data"]):
        assert profile_created_from_origin(expected, actual)

    # Last page
    next_page_link = get_next_page_link(body)
    res = await supervisor1_client.get(next_page_link)
    body = await res.json()
    assert res.status == 200
    assert "data" in body
    assert isinstance(body["data"], list)
    assert "links" in body and "next" in body["links"]
    assert len(body["data"]) == 2

    for expected, actual in zip(visitors[30:], body["data"]):
        assert profile_created_from_origin(expected, actual)
예제 #4
0
async def test_get_many_visitors(supervisor1_client):
    # Create some visitors
    visitors = []
    for _ in range(33):
        new_visitor = get_fake_visitor()
        new_visitor.pop("id")

        res = await supervisor1_client.post("/visitors", json=new_visitor)
        assert res.status == 200
        body = await res.json()
        visitors.append(body["data"])

    visitors = visitors[::-1]
    # Get the visitor (sorted by created order)
    res = await supervisor1_client.get("/visitors")
    assert res.status == 200
    body = await res.json()
    assert "data" in body
    assert isinstance(body["data"], list)
    assert len(body["data"]) == 15
    assert "links" in body and "next" in body["links"]

    for expected, actual in zip(visitors[:15], body["data"]):
        assert profile_created_from_origin(expected, actual)

    # Get the next page of visitors
    next_page_link = get_next_page_link(body)
    res = await supervisor1_client.get(next_page_link)
    assert res.status == 200
    body = await res.json()
    assert "data" in body
    assert isinstance(body["data"], list)
    assert len(body["data"]) == 15
    assert "links" in body and "next" in body["links"]

    for expected, actual in zip(visitors[15:30], body["data"]):
        assert profile_created_from_origin(expected, actual)

    # Get the last page of visitors
    next_page_link = get_next_page_link(body)
    res = await supervisor1_client.get(next_page_link)
    assert res.status == 200
    body = await res.json()
    assert "data" in body
    assert isinstance(body["data"], list)
    assert len(body["data"]) == 10  # = 3 (created just now) + 7 (in fixtures)
    assert "links" in body and "next" in body["links"]

    for expected, actual in zip(visitors[30:], body["data"]):
        assert profile_created_from_origin(expected, actual)
예제 #5
0
async def test_update_last_seen_message_of_staff(supervisor1_client):
    # Create a lot more visitors to test
    visitors = [get_fake_visitor() for _ in range(3)]
    for visitor in visitors:
        _visitor = deepcopy(visitor)

        # Anonymous users don't have passwords
        if "password" in _visitor:
            _visitor["password"] = hash_password(_visitor["password"])
        await Visitor(**_visitor).create()

    # Create some dummy chat messages
    created_at = 1
    chat_messages = {}
    for visitor in visitors[::-1]:
        chat = await Chat.add(visitor_id=visitor["id"])
        for sequence_num in range(4):
            content = {"content": fake.sentence(nb_words=10)}
            chat_msg = {
                "chat_id": chat["id"],
                "sequence_num": sequence_num,
                "content": content,
                "sender": None,
                "created_at": created_at,
            }
            created_at += 1
            created_msg = await ChatMessage.add(**chat_msg)
            chat_messages.setdefault(chat["id"], []).append(created_msg)

    for chat_id, value in chat_messages.items():
        chat = await Chat.get(id=chat_id)
        res = await supervisor1_client.patch(
            "/visitors/{}/last_seen".format(chat["visitor_id"]),
            json={"last_seen_msg_id": value[2]["id"]},
        )
        assert res.status == 200
        body = await res.json()
        assert "data" in body
        assert isinstance(body["data"], dict)
        assert body["data"]["last_seen_msg_id"] == value[2]["id"]
예제 #6
0
    get_fake_user,
    get_fake_organisation,
    get_fake_visitor,
    number_of_users,
    number_of_visitors,
)

organisations = [get_fake_organisation()]
user_roles = [{"id": role, "name": value} for role, value in ROLES.items()]
settings = [{"key": "max_staffs_in_chat", "value": 5}]
settings = [{
    "key": key,
    "value": value
} for key, value in DEFAULT_GLOBAL_SETTINGS.items()]

visitors = [get_fake_visitor() for _ in range(number_of_visitors)]
visitors += [
    {
        "id": generate_uuid(),
        "name": "Anonymous 1",
        "is_anonymous": True
    },
    {
        "id": generate_uuid(),
        "name": "Anonymous 2",
        "is_anonymous": True
    },
    {
        "id": generate_uuid(),
        "name": "Visitor 1",
        "email": "*****@*****.**",
예제 #7
0
async def test_get_visitors_most_recent(users, supervisor1_client):
    # Create a lot more visitors to test
    visitors = [get_fake_visitor() for _ in range(32)]
    for visitor in visitors:
        _visitor = deepcopy(visitor)

        # Anonymous users don't have passwords
        if "password" in _visitor:
            _visitor["password"] = hash_password(_visitor["password"])
        await Visitor(**_visitor).create()

    # Create some dummy chat messages
    created_at = 1
    staff = users[-5]
    for visitor in visitors[::-1]:
        chat = await Chat.add(visitor_id=visitor["id"])
        for sequence_num in range(3):
            content = {"content": fake.sentence(nb_words=10)}
            chat_msg = {
                "chat_id": chat["id"],
                "sequence_num": sequence_num,
                "content": content,
                "sender": None,
                "created_at": created_at,
            }
            created_at += 1
            await ChatMessage.add(**chat_msg)

        # Let a staff send a message, as staffs can only fetch visitors
        # that chatted with the staffs from his org
        await ChatMessage.add(
            **{
                "chat_id": chat["id"],
                "sequence_num": sequence_num + 1,
                "content": {
                    "content": fake.sentence(nb_words=10)
                },
                "sender": staff["id"],
                "created_at": created_at,
            })

    # Get the most recent visitors that chatted with the staffs from org
    res = await supervisor1_client.get("/visitors/most_recent")
    assert res.status == 200
    body = await res.json()
    assert "data" in body
    assert isinstance(body["data"], list)
    assert len(body["data"]) == 15
    assert "links" in body and "next" in body["links"]
    for expected, actual in zip(visitors, body["data"]):
        assert profile_created_from_origin(expected, actual)

    # Ensure that the next links work as well
    next_page_link = get_next_page_link(body)
    res = await supervisor1_client.get(next_page_link)
    assert res.status == 200
    body = await res.json()
    assert "data" in body
    assert isinstance(body["data"], list)
    assert len(body["data"]) == 15
    assert "links" in body and "next" in body["links"]
    for expected, actual in zip(visitors[15:], body["data"]):
        assert profile_created_from_origin(expected, actual)

    # Last page
    next_page_link = get_next_page_link(body)
    res = await supervisor1_client.get(next_page_link)
    assert res.status == 200
    assert res.status == 200
    body = await res.json()
    assert "data" in body
    assert isinstance(body["data"], list)
    assert len(body["data"]) == 2
    assert "links" in body and "next" in body["links"]
    for expected, actual in zip(visitors[30:], body["data"]):
        assert profile_created_from_origin(expected, actual)
예제 #8
0
async def test_get_unread_visitors_for_staff(supervisor1_client):
    # Create some visitors
    visitors = []
    for _ in range(30):
        new_visitor = get_fake_visitor()
        new_visitor.pop("id")

        res = await supervisor1_client.post("/visitors", json=new_visitor)
        assert res.status == 200
        body = await res.json()
        visitors.append(body["data"])

    # Create some dummy chat messages
    created_at = 1
    chat_messages = {}
    chats = []
    for visitor in visitors:
        chat = await Chat.add(visitor_id=visitor["id"])
        chats.append(chat)
        for sequence_num in range(4):
            content = {"content": fake.sentence(nb_words=10)}
            chat_msg = {
                "chat_id": chat["id"],
                "sequence_num": sequence_num,
                "content": content,
                "sender": None,
                "created_at": created_at,
            }
            created_at += 1
            created_msg = await ChatMessage.add(**chat_msg)
            chat_messages.setdefault(visitor["id"], []).append(created_msg)

    # Mark some visitors as read
    for visitor in visitors[12:17] + visitors[22:26]:
        res = await supervisor1_client.patch(
            "/visitors/{}/last_seen".format(visitor["id"]),
            json={"last_seen_msg_id": chat_messages[visitor["id"]][-1]["id"]},
        )
        assert res.status == 200

    # Mark some visitors as partially read
    for visitor in visitors[5:10]:
        res = await supervisor1_client.patch(
            "/visitors/{}/last_seen".format(visitor["id"]),
            json={"last_seen_msg_id": chat_messages[visitor["id"]][2]["id"]},
        )
        assert res.status == 200

    # Get the first unread visitors
    res = await supervisor1_client.get("/visitors/unread")
    assert res.status == 200
    body = await res.json()
    assert "data" in body
    assert "links" not in body
    assert isinstance(body["data"], list)
    assert len(body["data"]) == 15
    for expected_visitor, expected_chat, item in zip(
            reversed(visitors[:12] + visitors[17:22] + visitors[26:]),
            reversed(chats[:12] + chats[17:22] + chats[26:]),
            body["data"],
    ):
        actual_visitor = item["user"]
        actual_chat = item["room"]
        assert profile_created_from_origin(expected_visitor, actual_visitor)
        assert profile_created_from_origin(expected_chat, actual_chat)

    # Mark some visitors as fully read
    for visitor in visitors[2:8] + visitors[26:29]:
        res = await supervisor1_client.patch(
            "/visitors/{}/last_seen".format(visitor["id"]),
            json={"last_seen_msg_id": chat_messages[visitor["id"]][3]["id"]},
        )
        assert res.status == 200

    # Get the second unread visitors
    res = await supervisor1_client.get("/visitors/unread")
    assert res.status == 200
    body = await res.json()
    assert "data" in body
    assert "links" not in body
    assert isinstance(body["data"], list)
    assert len(body["data"]) == 12
    for expected_visitor, expected_chat, item in zip(
            reversed(visitors[:2] + visitors[8:12] + visitors[17:22] +
                     visitors[29:]),
            reversed(chats[:2] + chats[8:12] + chats[17:22] + chats[29:]),
            body["data"],
    ):
        actual_visitor = item["user"]
        actual_chat = item["room"]
        assert profile_created_from_origin(expected_visitor, actual_visitor)
        assert profile_created_from_origin(expected_chat, actual_chat)

    # Mark all visitors as read
    for visitor in visitors:
        res = await supervisor1_client.patch(
            "/visitors/{}/last_seen".format(visitor["id"]),
            json={"last_seen_msg_id": chat_messages[visitor["id"]][-1]["id"]},
        )
        assert res.status == 200

    # Get the last unread visitors
    res = await supervisor1_client.get("/visitors/unread")
    assert res.status == 200
    body = await res.json()
    assert "data" in body
    assert "links" not in body
    assert isinstance(body["data"], list)
    assert not body["data"]