Skip to content

Commit

Permalink
Merge pull request #47 from vincenzopalazzo/macros/lnprototest_api
Browse files Browse the repository at this point in the history
lnprototest: API improvement and introduction of test utils function
  • Loading branch information
vincenzopalazzo authored Mar 31, 2022
2 parents 433d22f + ff21cfa commit 6629da3
Show file tree
Hide file tree
Showing 11 changed files with 484 additions and 298 deletions.
2 changes: 2 additions & 0 deletions lnprototest/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
negotiated,
DualFundAccept,
Wait,
CloseChannel,
)
from .structure import Sequence, OneOf, AnyOrder, TryAll
from .runner import (
Expand Down Expand Up @@ -141,4 +142,5 @@
"dual_fund_csv",
"channel_type_csv",
"wait_for",
"CloseChannel",
]
15 changes: 13 additions & 2 deletions lnprototest/clightning/clightning.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import shutil
import logging

from datetime import date
from concurrent import futures
from ephemeral_port_reserve import reserve
from lnprototest.backend import Bitcoind
Expand Down Expand Up @@ -88,7 +89,7 @@ def __init__(self, config: Any):
k, v = o.split("/")
self.options[k] = v

def __init_sandbox_dir(self):
def __init_sandbox_dir(self) -> None:
"""Create the tmp directory for lnprotest and lightningd"""
self.lightning_dir = os.path.join(self.directory, "lightningd")
if not os.path.exists(self.lightning_dir):
Expand Down Expand Up @@ -169,12 +170,22 @@ def shutdown(self) -> None:
self.rpc.stop()
self.bitcoind.stop()

def stop(self) -> None:
def stop(self, print_logs: bool = False) -> None:
self.logger.debug("[STOP]")
self.shutdown()
self.running = False
for c in self.conns.values():
cast(CLightningConn, c).connection.connection.close()
if print_logs:
log_path = f"{self.lightning_dir}/regtest/log"
with open(log_path) as log:
self.logger.info("---------- c-lightning logging ----------------")
self.logger.info(log.read())
# now we make a backup of the log
shutil.copy(
log_path,
f'/tmp/c-lightning-log_{date.today().strftime("%b-%d-%Y_%H:%M:%S")}',
)
shutil.rmtree(os.path.join(self.lightning_dir, "regtest"))

def restart(self) -> None:
Expand Down
22 changes: 19 additions & 3 deletions lnprototest/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ def __init__(
self,
msgtypename: str,
connprivkey: Optional[str] = None,
**kwargs: Union[ResolvableStr, ResolvableInt]
**kwargs: Union[ResolvableStr, ResolvableInt],
):
super().__init__(connprivkey)
self.msgtype = namespace().get_msgtype(msgtypename)
Expand Down Expand Up @@ -286,7 +286,7 @@ def __init__(
if_match: Callable[["ExpectMsg", Message, "Runner"], None] = _default_if_match,
ignore: Optional[Callable[[Message], Optional[List[Message]]]] = None,
connprivkey: Optional[str] = None,
**kwargs: Union[str, Resolvable]
**kwargs: Union[str, Resolvable],
):
super().__init__(connprivkey)
self.msgtype = namespace().get_msgtype(msgtypename)
Expand Down Expand Up @@ -315,7 +315,9 @@ def action(self, runner: "Runner") -> bool:
while True:
binmsg = runner.get_output_message(conn, self)
if binmsg is None:
raise EventError(self, "Did not receive a message from runner")
raise EventError(
self, f"Did not receive a message {self.msgtype} from runner"
)

for e in conn.must_not_events:
if e.matches(binmsg):
Expand Down Expand Up @@ -532,6 +534,20 @@ def action(self, runner: "Runner") -> bool:
return True


class CloseChannel(Event):
"""Implementing the lnprototest event related to the
close channel operation.
BOLT 2"""

def __init__(self, channel_id: str):
super(CloseChannel, self).__init__()
self.channel_id = channel_id

def action(self, runner: "Runner") -> bool:
super().action(runner)
return runner.close_channel(self.channel_id)


def msg_to_stash(runner: "Runner", event: Event, msg: Message) -> None:
"""ExpectMsg and Msg save every field to the stash, in order"""
fields = msg.to_py()
Expand Down
9 changes: 8 additions & 1 deletion lnprototest/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,14 @@ def start(self) -> None:
pass

@abstractmethod
def stop(self) -> None:
def stop(self, print_logs: bool = False) -> None:
"""
Stop the runner, and print all the log that the ln
implementation produced.
Print the log is useful when we have a failure e we need
to debug what happens during the tests.
"""
pass

@abstractmethod
Expand Down
5 changes: 3 additions & 2 deletions lnprototest/structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,10 @@ def action(self, runner: "Runner") -> bool:
assert conn

while True:
binmsg = runner.get_output_message(conn, self.sequences[0].events[0])
event = self.sequences[0].events[0]
binmsg = runner.get_output_message(conn, event)
if binmsg is None:
raise EventError(self, "Did not receive a message from runner")
raise EventError(self, f"Did not receive a message {event} from runner")

try:
msg = Message.read(namespace(), io.BytesIO(binmsg))
Expand Down
Loading

0 comments on commit 6629da3

Please sign in to comment.