aboutsummaryrefslogtreecommitdiffstats
path: root/packages/meshbay-cli/tests/test_chat_files.py
blob: 4c83cbabf1c0b6f822fd926e1e0c0fa67ce0a7b4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
"""Files in the chat: where they go, and how a message names one."""

import json

from meshbay_cli.client.chat import Message, attachment_text, chat_folder, read_attachment
from meshbay_cli.commands.chat import as_json, print_message

ROOTS = {"music": {"name": "music", "writable": False},
         "share": {"name": "share", "writable": True},
         "usb": {"name": "usb", "writable": True, "available": False}}


def test_the_chat_folder_is_the_operators_choice_while_it_can_be_written():
    assert chat_folder({"chat_directory": "share/chat"}, ROOTS) == "share/chat"
    assert chat_folder({"chat_directory": "/share/chat/"}, ROOTS) == "share/chat"
    # Read-only, unplugged, gone, or never chosen: the first writable root.
    for chosen in ("music/x", "usb/x", "gone/x", ""):
        assert chat_folder({"chat_directory": chosen}, ROOTS) == "share"
    assert chat_folder({}, {"music": ROOTS["music"]}) == ""


def test_an_attachment_reads_back_as_the_application_writes_it():
    text = attachment_text("IMG 1.JPG", 1234)
    assert json.loads(text) == {"text": "", "attachment": {
        "filename": "IMG 1.JPG", "size": 1234, "type": "image"}}
    assert read_attachment(text) == ("", {"filename": "IMG 1.JPG", "size": 1234,
                                          "type": "image"})
    assert json.loads(attachment_text("clip.mkv", 1))["attachment"]["type"] == "video"
    assert json.loads(attachment_text("README", 1))["attachment"]["type"] == "file"


def test_text_that_only_looks_like_json_stays_text():
    for text in ('{"a": 1}', "{not json", '{"attachment": "x"}',
                 '{"attachment": {"filename": ""}}', "[1]", "hello"):
        assert read_attachment(text) == (text, None)


def test_the_chat_action_prints_a_file_by_name_and_size(capsys):
    m = Message(1, 1_700_000_000, "bob", "look", attachment={
        "filename": "a.pdf", "size": 2048, "type": "file"})
    print_message(m)
    out = capsys.readouterr().out.splitlines()
    assert out[0].endswith("bob: [file: a.pdf, 2.0 KB]") and out[1].strip() == "look"
    assert as_json(m)["attachment"] == {"filename": "a.pdf", "size": 2048, "type": "file"}