apply black with new line-length == 120

This commit is contained in:
adbenitez
2022-05-31 23:05:20 -04:00
parent d3e6cc5acb
commit 17aab01eaa
19 changed files with 86 additions and 289 deletions

View File

@@ -52,9 +52,7 @@ def run_cmdline(argv=None, account_plugins=None):
parser = argparse.ArgumentParser(prog=argv[0] if argv else None)
parser.add_argument("db", action="store", help="database file")
parser.add_argument(
"--show-ffi", action="store_true", help="show low level ffi events"
)
parser.add_argument("--show-ffi", action="store_true", help="show low level ffi events")
parser.add_argument("--email", action="store", help="email address")
parser.add_argument("--password", action="store", help="password")

View File

@@ -34,9 +34,7 @@ def local_build_flags(projdir, target):
flags["libraries"] = ["rt", "dl", "m"]
flags["extra_link_args"] = []
else:
raise NotImplementedError(
"Compilation not supported yet on Windows, can you help?"
)
raise NotImplementedError("Compilation not supported yet on Windows, can you help?")
target_dir = os.environ.get("CARGO_TARGET_DIR")
if target_dir is None:
target_dir = os.path.join(projdir, "target")
@@ -117,9 +115,7 @@ def find_header(flags):
)
finally:
os.chdir(cwd)
cc.link_executable(
objects=[obj_name], output_progname="where", output_dir=tmpdir
)
cc.link_executable(objects=[obj_name], output_progname="where", output_dir=tmpdir)
return subprocess.check_output(dst_name)
finally:
shutil.rmtree(tmpdir)

View File

@@ -37,9 +37,7 @@ def get_core_info():
path.close()
return get_dc_info_as_dict(
ffi.gc(
lib.dc_context_new(
as_dc_charpointer(""), as_dc_charpointer(path.name), ffi.NULL
),
lib.dc_context_new(as_dc_charpointer(""), as_dc_charpointer(path.name), ffi.NULL),
lib.dc_context_unref,
)
)
@@ -114,11 +112,7 @@ class Account(object):
def _check_config_key(self, name: str) -> None:
if name not in self._configkeys:
raise KeyError(
"{!r} not a valid config key, existing keys: {!r}".format(
name, self._configkeys
)
)
raise KeyError("{!r} not a valid config key, existing keys: {!r}".format(name, self._configkeys))
def get_info(self) -> Dict[str, str]:
"""return dictionary of built config parameters."""
@@ -334,9 +328,7 @@ class Account(object):
:returns: list of :class:`deltachat.contact.Contact` objects.
"""
dc_array = ffi.gc(
lib.dc_get_blocked_contacts(self._dc_context), lib.dc_array_unref
)
dc_array = ffi.gc(lib.dc_get_blocked_contacts(self._dc_context), lib.dc_array_unref)
return list(iter_array(dc_array, lambda x: Contact(self, x)))
def get_contacts(
@@ -359,9 +351,7 @@ class Account(object):
flags |= const.DC_GCL_VERIFIED_ONLY
if with_self:
flags |= const.DC_GCL_ADD_SELF
dc_array = ffi.gc(
lib.dc_get_contacts(self._dc_context, flags, query), lib.dc_array_unref
)
dc_array = ffi.gc(lib.dc_get_contacts(self._dc_context, flags, query), lib.dc_array_unref)
return list(iter_array(dc_array, lambda x: Contact(self, x)))
def get_fresh_messages(self) -> Generator[Message, None, None]:
@@ -400,9 +390,7 @@ class Account(object):
:returns: a list of :class:`deltachat.chat.Chat` objects.
"""
dc_chatlist = ffi.gc(
lib.dc_get_chatlist(self._dc_context, 0, ffi.NULL, 0), lib.dc_chatlist_unref
)
dc_chatlist = ffi.gc(lib.dc_get_chatlist(self._dc_context, 0, ffi.NULL, 0), lib.dc_chatlist_unref)
assert dc_chatlist != ffi.NULL
chatlist = []
@@ -538,9 +526,7 @@ class Account(object):
def check_qr(self, qr):
"""check qr code and return :class:`ScannedQRCode` instance representing the result"""
res = ffi.gc(
lib.dc_check_qr(self._dc_context, as_dc_charpointer(qr)), lib.dc_lot_unref
)
res = ffi.gc(lib.dc_check_qr(self._dc_context, as_dc_charpointer(qr)), lib.dc_lot_unref)
lot = DCLot(res)
if lot.state() == const.DC_QR_ERROR:
raise ValueError("invalid or unknown QR code: {}".format(lot.text1()))
@@ -575,9 +561,7 @@ class Account(object):
raise ValueError("could not join group")
return Chat(self, chat_id)
def set_location(
self, latitude: float = 0.0, longitude: float = 0.0, accuracy: float = 0.0
) -> None:
def set_location(self, latitude: float = 0.0, longitude: float = 0.0, accuracy: float = 0.0) -> None:
"""set a new location. It effects all chats where we currently
have enabled location streaming.

View File

@@ -32,10 +32,7 @@ class Chat(object):
self.id = id
def __eq__(self, other) -> bool:
return (
self.id == getattr(other, "id", None)
and self.account._dc_context == other.account._dc_context
)
return self.id == getattr(other, "id", None) and self.account._dc_context == other.account._dc_context
def __ne__(self, other) -> bool:
return not (self == other)
@@ -45,9 +42,7 @@ class Chat(object):
@property
def _dc_chat(self):
return ffi.gc(
lib.dc_get_chat(self.account._dc_context, self.id), lib.dc_chat_unref
)
return ffi.gc(lib.dc_get_chat(self.account._dc_context, self.id), lib.dc_chat_unref)
def delete(self) -> None:
"""Delete this chat and all its messages.
@@ -140,9 +135,7 @@ class Chat(object):
mute_duration = -1
else:
mute_duration = duration
ret = lib.dc_set_chat_mute_duration(
self.account._dc_context, self.id, mute_duration
)
ret = lib.dc_set_chat_mute_duration(self.account._dc_context, self.id, mute_duration)
if not bool(ret):
raise ValueError("Call to dc_set_chat_mute_duration failed")
@@ -177,9 +170,7 @@ class Chat(object):
:returns: True on success, False otherwise
"""
return bool(
lib.dc_set_chat_ephemeral_timer(self.account._dc_context, self.id, timer)
)
return bool(lib.dc_set_chat_ephemeral_timer(self.account._dc_context, self.id, timer))
def get_type(self) -> int:
"""(deprecated) return type of this chat.
@@ -402,9 +393,7 @@ class Chat(object):
:returns: None
"""
contact = self.account.get_contact(obj)
ret = lib.dc_remove_contact_from_chat(
self.account._dc_context, self.id, contact.id
)
ret = lib.dc_remove_contact_from_chat(self.account._dc_context, self.id, contact.id)
if ret != 1:
raise ValueError("could not remove contact {!r} from chat".format(contact))
@@ -489,10 +478,7 @@ class Chat(object):
"""return True if this chat is archived.
:returns: True if archived.
"""
return (
lib.dc_chat_get_visibility(self._dc_chat)
== const.DC_CHAT_VISIBILITY_ARCHIVED
)
return lib.dc_chat_get_visibility(self._dc_chat) == const.DC_CHAT_VISIBILITY_ARCHIVED
def enable_sending_locations(self, seconds):
"""enable sending locations for this chat.
@@ -523,20 +509,14 @@ class Chat(object):
else:
contact_id = contact.id
dc_array = lib.dc_get_locations(
self.account._dc_context, self.id, contact_id, time_from, time_to
)
dc_array = lib.dc_get_locations(self.account._dc_context, self.id, contact_id, time_from, time_to)
return [
Location(
latitude=lib.dc_array_get_latitude(dc_array, i),
longitude=lib.dc_array_get_longitude(dc_array, i),
accuracy=lib.dc_array_get_accuracy(dc_array, i),
timestamp=datetime.fromtimestamp(
lib.dc_array_get_timestamp(dc_array, i), timezone.utc
),
marker=from_optional_dc_charpointer(
lib.dc_array_get_marker(dc_array, i)
),
timestamp=datetime.fromtimestamp(lib.dc_array_get_timestamp(dc_array, i), timezone.utc),
marker=from_optional_dc_charpointer(lib.dc_array_get_marker(dc_array, i)),
)
for i in range(lib.dc_array_get_cnt(dc_array))
]

View File

@@ -23,24 +23,17 @@ class Contact(object):
self.id = id
def __eq__(self, other):
return (
self.account._dc_context == other.account._dc_context
and self.id == other.id
)
return self.account._dc_context == other.account._dc_context and self.id == other.id
def __ne__(self, other):
return not (self == other)
def __repr__(self):
return "<Contact id={} addr={} dc_context={}>".format(
self.id, self.addr, self.account._dc_context
)
return "<Contact id={} addr={} dc_context={}>".format(self.id, self.addr, self.account._dc_context)
@property
def _dc_contact(self):
return ffi.gc(
lib.dc_get_contact(self.account._dc_context, self.id), lib.dc_contact_unref
)
return ffi.gc(lib.dc_get_contact(self.account._dc_context, self.id), lib.dc_contact_unref)
@props.with_doc
def addr(self) -> str:
@@ -58,9 +51,7 @@ class Contact(object):
@props.with_doc
def last_seen(self) -> date:
"""Last seen timestamp."""
return datetime.fromtimestamp(
lib.dc_contact_get_last_seen(self._dc_contact), timezone.utc
)
return datetime.fromtimestamp(lib.dc_contact_get_last_seen(self._dc_contact), timezone.utc)
def is_blocked(self):
"""Return True if the contact is blocked."""

View File

@@ -182,16 +182,9 @@ class DirectImap:
self.conn.append(bytes(msg, encoding="ascii"), folder)
def get_uid_by_message_id(self, message_id) -> str:
msgs = [
msg.uid
for msg in self.conn.fetch(AND(header=Header("MESSAGE-ID", message_id)))
]
msgs = [msg.uid for msg in self.conn.fetch(AND(header=Header("MESSAGE-ID", message_id)))]
if len(msgs) == 0:
raise Exception(
"Did not find message "
+ message_id
+ ", maybe you forgot to select the correct folder?"
)
raise Exception("Did not find message " + message_id + ", maybe you forgot to select the correct folder?")
return msgs[0]

View File

@@ -135,12 +135,7 @@ class FFIEventTracker:
if current == expected_next:
return
elif current != previous:
raise Exception(
"Expected connectivity "
+ str(expected_next)
+ " but got "
+ str(current)
)
raise Exception("Expected connectivity " + str(expected_next) + " but got " + str(current))
self.get_matching("DC_EVENT_CONNECTIVITY_CHANGED")
@@ -252,12 +247,8 @@ class EventThread(threading.Thread):
lib.dc_event_unref(event)
ffi_event = FFIEvent(name=evt_name, data1=data1, data2=data2)
with self.swallow_and_log_exception(
"ac_process_ffi_event {}".format(ffi_event)
):
self.account._pm.hook.ac_process_ffi_event(
account=self, ffi_event=ffi_event
)
with self.swallow_and_log_exception("ac_process_ffi_event {}".format(ffi_event)):
self.account._pm.hook.ac_process_ffi_event(account=self, ffi_event=ffi_event)
for name, kwargs in self._map_ffi_event(ffi_event):
hook = getattr(self.account._pm.hook, name)
info = "call {} kwargs={} failed".format(name, kwargs)
@@ -271,9 +262,7 @@ class EventThread(threading.Thread):
except Exception as ex:
logfile = io.StringIO()
traceback.print_exception(*sys.exc_info(), file=logfile)
self.account.log(
"{}\nException {}\nTraceback:\n{}".format(info, ex, logfile.getvalue())
)
self.account.log("{}\nException {}\nTraceback:\n{}".format(info, ex, logfile.getvalue()))
def _map_ffi_event(self, ffi_event: FFIEvent):
name = ffi_event.name

View File

@@ -46,9 +46,7 @@ class Message(object):
@classmethod
def from_db(cls, account, id):
assert id > 0
return cls(
account, ffi.gc(lib.dc_get_msg(account._dc_context, id), lib.dc_msg_unref)
)
return cls(account, ffi.gc(lib.dc_get_msg(account._dc_context, id), lib.dc_msg_unref))
@classmethod
def new_empty(cls, account, view_type):
@@ -63,9 +61,7 @@ class Message(object):
view_type_code = get_viewtype_code_from_name(view_type)
return Message(
account,
ffi.gc(
lib.dc_msg_new(account._dc_context, view_type_code), lib.dc_msg_unref
),
ffi.gc(lib.dc_msg_new(account._dc_context, view_type_code), lib.dc_msg_unref),
)
def create_chat(self):
@@ -96,12 +92,7 @@ class Message(object):
@props.with_doc
def html(self) -> str:
"""html text of this messages (might be empty if not an html message)."""
return (
from_optional_dc_charpointer(
lib.dc_get_msg_html(self.account._dc_context, self.id)
)
or ""
)
return from_optional_dc_charpointer(lib.dc_get_msg_html(self.account._dc_context, self.id)) or ""
def has_html(self):
"""return True if this message has an html part, False otherwise."""
@@ -166,15 +157,11 @@ class Message(object):
The text is multiline and may contain eg. the raw text of the message.
"""
return from_dc_charpointer(
lib.dc_get_msg_info(self.account._dc_context, self.id)
)
return from_dc_charpointer(lib.dc_get_msg_info(self.account._dc_context, self.id))
def continue_key_transfer(self, setup_code):
"""extract key and use it as primary key for this account."""
res = lib.dc_continue_key_transfer(
self.account._dc_context, self.id, as_dc_charpointer(setup_code)
)
res = lib.dc_continue_key_transfer(self.account._dc_context, self.id, as_dc_charpointer(setup_code))
if res == 0:
raise ValueError("could not decrypt")
@@ -281,9 +268,7 @@ class Message(object):
Usually used to impersonate someone else.
"""
return from_optional_dc_charpointer(
lib.dc_msg_get_override_sender_name(self._dc_msg)
)
return from_optional_dc_charpointer(lib.dc_msg_get_override_sender_name(self._dc_msg))
def set_override_sender_name(self, name):
"""set different sender name for a message."""
@@ -315,9 +300,7 @@ class Message(object):
dc_msg = self._dc_msg
else:
# load message from db to get a fresh/current state
dc_msg = ffi.gc(
lib.dc_get_msg(self.account._dc_context, self.id), lib.dc_msg_unref
)
dc_msg = ffi.gc(lib.dc_get_msg(self.account._dc_context, self.id), lib.dc_msg_unref)
return lib.dc_msg_get_state(dc_msg)
def is_in_fresh(self):
@@ -440,8 +423,7 @@ def get_viewtype_code_from_name(view_type_name):
if code is not None:
return code
raise ValueError(
"message typecode not found for {!r}, "
"available {!r}".format(view_type_name, list(_view_type_mapping.keys()))
"message typecode not found for {!r}, " "available {!r}".format(view_type_name, list(_view_type_mapping.keys()))
)

View File

@@ -16,9 +16,7 @@ class Provider(object):
def __init__(self, account, addr) -> None:
provider = ffi.gc(
lib.dc_provider_new_from_email(
account._dc_context, as_dc_charpointer(addr)
),
lib.dc_provider_new_from_email(account._dc_context, as_dc_charpointer(addr)),
lib.dc_provider_unref,
)
if provider == ffi.NULL:
@@ -33,9 +31,7 @@ class Provider(object):
@property
def get_before_login_hints(self) -> str:
"""Should be shown to the user on login."""
return from_dc_charpointer(
lib.dc_provider_get_before_login_hint(self._provider)
)
return from_dc_charpointer(lib.dc_provider_get_before_login_hint(self._provider))
@property
def status(self) -> int:

View File

@@ -29,8 +29,7 @@ def pytest_addoption(parser):
"--liveconfig",
action="store",
default=None,
help="a file with >=2 lines where each line "
"contains NAME=VALUE config settings for one account",
help="a file with >=2 lines where each line " "contains NAME=VALUE config settings for one account",
)
group.addoption(
"--ignored",
@@ -159,9 +158,7 @@ class TestProcess:
"""
liveconfig_opt = self.pytestconfig.getoption("--liveconfig")
if not liveconfig_opt:
pytest.skip(
"specify DCC_NEW_TMP_EMAIL or --liveconfig to provide live accounts"
)
pytest.skip("specify DCC_NEW_TMP_EMAIL or --liveconfig to provide live accounts")
if not liveconfig_opt.startswith("http"):
for line in open(liveconfig_opt):
@@ -181,21 +178,13 @@ class TestProcess:
except IndexError:
res = requests.post(liveconfig_opt)
if res.status_code != 200:
pytest.fail(
"newtmpuser count={} code={}: '{}'".format(
index, res.status_code, res.text
)
)
pytest.fail("newtmpuser count={} code={}: '{}'".format(index, res.status_code, res.text))
d = res.json()
config = dict(addr=d["email"], mail_pw=d["password"])
print("newtmpuser {}: addr={}".format(index, config["addr"]))
self._configlist.append(config)
yield config
pytest.fail(
"more than {} live accounts requested.".format(
MAX_LIVE_CREATED_ACCOUNTS
)
)
pytest.fail("more than {} live accounts requested.".format(MAX_LIVE_CREATED_ACCOUNTS))
def cache_maybe_retrieve_configured_db_files(self, cache_addr, db_target_path):
db_target_path = pathlib.Path(db_target_path)
@@ -252,9 +241,7 @@ def data(request):
os.path.normpath(x)
for x in [
os.path.join(os.path.dirname(request.fspath.strpath), "data"),
os.path.join(
os.path.dirname(__file__), "..", "..", "..", "test-data"
),
os.path.join(os.path.dirname(__file__), "..", "..", "..", "test-data"),
]
]
@@ -299,9 +286,7 @@ class ACSetup:
"""add an already configured account."""
assert account.is_configured()
self._account2state[account] = self.CONFIGURED
self.log(
"added already configured account", account, account.get_config("addr")
)
self.log("added already configured account", account, account.get_config("addr"))
def start_configure(self, account, reconfigure=False):
"""add an account and start its configure process."""
@@ -452,9 +437,7 @@ class ACFactory:
# we need to use fixed database basename for maybe_cache_* functions to work
path = self.tmpdir.mkdir(logid).join("dc.db")
if try_cache_addr:
self.testprocess.cache_maybe_retrieve_configured_db_files(
try_cache_addr, path
)
self.testprocess.cache_maybe_retrieve_configured_db_files(try_cache_addr, path)
ac = Account(path.strpath, logging=self._logging)
ac._logid = logid # later instantiated FFIEventLogger needs this
ac._evtracker = ac.add_account_plugin(FFIEventTracker(ac))
@@ -476,12 +459,8 @@ class ACFactory:
except IndexError:
pass
else:
fname_pub = self.data.read_path(
"key/{name}-public.asc".format(name=keyname)
)
fname_sec = self.data.read_path(
"key/{name}-secret.asc".format(name=keyname)
)
fname_pub = self.data.read_path("key/{name}-public.asc".format(name=keyname))
fname_sec = self.data.read_path("key/{name}-secret.asc".format(name=keyname))
if fname_pub and fname_sec:
account._preconfigure_keypair(addr, fname_pub, fname_sec)
return True
@@ -638,9 +617,7 @@ class BotProcess:
# we read stdout as quickly as we can in a thread and make
# the (unicode) lines available for readers through a queue.
self.stdout_queue = queue.Queue()
self.stdout_thread = t = threading.Thread(
target=self._run_stdout_thread, name="bot-stdout-thread"
)
self.stdout_thread = t = threading.Thread(target=self._run_stdout_thread, name="bot-stdout-thread")
t.daemon = True
t.start()
@@ -663,9 +640,7 @@ class BotProcess:
self.popen.wait(timeout=timeout)
def fnmatch_lines(self, pattern_lines):
patterns = [
x.strip() for x in Source(pattern_lines.rstrip()).lines if x.strip()
]
patterns = [x.strip() for x in Source(pattern_lines.rstrip()).lines if x.strip()]
for next_pattern in patterns:
print("+++FNMATCH:", next_pattern)
ignored = []

View File

@@ -19,16 +19,12 @@ class ImexTracker:
elif ffi_event.name == "DC_EVENT_IMEX_FILE_WRITTEN":
self._imex_events.put(ffi_event.data2)
def wait_progress(
self, target_progress, progress_upper_limit=1000, progress_timeout=60
):
def wait_progress(self, target_progress, progress_upper_limit=1000, progress_timeout=60):
while True:
ev = self._imex_events.get(timeout=progress_timeout)
if isinstance(ev, int) and ev >= target_progress:
assert ev <= progress_upper_limit, (
str(ev)
+ " exceeded upper progress limit "
+ str(progress_upper_limit)
str(ev) + " exceeded upper progress limit " + str(progress_upper_limit)
)
return ev
if ev == 0: