Skip to content

Commit

Permalink
Merge branches 'pytest/enh/task07', 'pytest/enh/spec08', 'pytest/enh/…
Browse files Browse the repository at this point in the history
…spec09' and 'pytest/enh/spec10' into pytest/tracking/all
  • Loading branch information
miri64 committed Jul 28, 2020
4 parents 7f9205a + c0ad963 + 85a771d + 5c9a070 commit 31ef2db
Show file tree
Hide file tree
Showing 6 changed files with 921 additions and 4 deletions.
88 changes: 88 additions & 0 deletions 08-interop/test_spec08.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import re
import sys

import pexpect.replwrap
import pytest

import riotctrl.shell
from riotctrl_shell.gnrc import GNRCICMPv6Echo
from riotctrl_shell.netif import Ifconfig

from testutils.native import bridge, get_link_local, get_ping_cmd, \
interface_exists
from testutils.shell import lladdr, ping6, GNRCUDP


GNRC_APP = 'examples/gnrc_networking'
LWIP_APP = 'tests/lwip'
pytestmark = pytest.mark.rc_only()


class Shell(Ifconfig, GNRCICMPv6Echo, GNRCUDP):
pass


@pytest.mark.skipif(not interface_exists("tap0"),
reason="tap0 does not exist")
# nodes passed to riot_ctrl fixture
@pytest.mark.parametrize('nodes',
[pytest.param(['native'])],
indirect=['nodes'])
def test_task01(riot_ctrl, log_nodes):
node = riot_ctrl(0, GNRC_APP, Shell, port='tap0')
linux = pexpect.replwrap.bash()

node_iface, node_addr = lladdr(node.ifconfig_list())
assert node_addr.startswith("fe80::")
linux_iface = bridge('tap0')
linux_addr = get_link_local(linux_iface)
assert linux_addr.startswith("fe80::")
ping_cmd = get_ping_cmd()

if log_nodes:
linux.child.logfile = sys.stdout
out = linux.run_command("{ping_cmd} -c 20 -i .5 {node_addr}%{linux_iface}"
.format(ping_cmd=ping_cmd, node_addr=node_addr,
linux_iface=linux_iface), timeout=20)
m = re.search(r"\b(\d+)% packet loss", out)
assert m is not None
assert int(m.group(1)) < 1
res = ping6(node, "{}%{}".format(linux_addr, node_iface),
count=20, interval=100, packet_size=8)
assert res["stats"]["packet_loss"] < 1


@pytest.mark.iotlab_creds
# nodes passed to riot_ctrl fixture
@pytest.mark.parametrize('nodes',
[pytest.param(['iotlab-m3', 'iotlab-m3'])],
indirect=['nodes'])
def test_task08(riot_ctrl):
gnrc_node, lwip_node = (
riot_ctrl(0, GNRC_APP, Shell),
riot_ctrl(1, LWIP_APP, riotctrl.shell.ShellInteraction),
)

_, gnrc_addr = lladdr(gnrc_node.ifconfig_list())
assert gnrc_addr.startswith("fe80::")
res = lwip_node.cmd("ifconfig")
m = re.search(r"inet6\s+(?P<addr>fe80:[0-9a-f:]+)", res)
assert m is not None
lwip_addr = m.group("addr")

gnrc_node.udp_server_start(61616)

lwip_node.cmd("udp send [{gnrc_addr}]:61616 012345678abcdef"
.format(gnrc_addr=gnrc_addr))
packet_loss = gnrc_node.udp_server_check_output(count=1, delay_ms=0)
assert packet_loss == 0
gnrc_node.udp_server_stop()

lwip_node.cmd("udp server start 61617")
gnrc_node.udp_client_send(lwip_addr, 61617, "01234567")
lwip_node.riotctrl.term.expect_exact("Received UDP data from [{}]:61617"
.format(gnrc_addr))
lwip_node.riotctrl.term.expect_exact("00000000 " +
" ".join(hex(ord(c))[2:]
for c in "01234567"),
timeout=3)
132 changes: 132 additions & 0 deletions 09-coap/server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
#!/usr/bin/env python3

# This file is part of the Python aiocoap library project.
#
# Copyright (c) 2012-2014 Maciej Wasilak <http://sixpinetrees.blogspot.com/>,
# 2013-2014 Christian Amsüss <c.amsuess@energyharvesting.at>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

"""This is a usage example of aiocoap that demonstrates how to implement a
simple server. See the "Usage Examples" section in the aiocoap documentation
for some more information."""

import datetime
import logging

import asyncio

import aiocoap.resource as resource
import aiocoap


class BlockResource(resource.Resource):
"""Example resource which supports the GET and PUT methods. It sends large
responses, which trigger blockwise transfer."""

def __init__(self):
super().__init__()
self.set_content(b"This is the resource's default content. It is padded "\
b"with numbers to be large enough to trigger blockwise "\
b"transfer.\n")

def set_content(self, content):
self.content = content
while len(self.content) <= 1024:
self.content = self.content + b"0123456789\n"

async def render_get(self, request):
return aiocoap.Message(payload=self.content)

async def render_put(self, request):
print('PUT payload: %s' % request.payload)
self.set_content(request.payload)
return aiocoap.Message(code=aiocoap.CHANGED, payload=self.content)


class SeparateLargeResource(resource.Resource):
"""Example resource which supports the GET method. It uses asyncio.sleep to
simulate a long-running operation, and thus forces the protocol to send
empty ACK first. """

def get_link_description(self):
# Publish additional data in .well-known/core
return dict(**super().get_link_description(), title="A large resource")

async def render_get(self, request):
await asyncio.sleep(3)

payload = "Three rings for the elven kings under the sky, seven rings "\
"for dwarven lords in their halls of stone, nine rings for "\
"mortal men doomed to die, one ring for the dark lord on his "\
"dark throne.".encode('ascii')
return aiocoap.Message(payload=payload)

class TimeResource(resource.ObservableResource):
"""Example resource that can be observed. The `notify` method keeps
scheduling itself, and calles `update_state` to trigger sending
notifications."""

def __init__(self):
super().__init__()

self.handle = None

def notify(self):
self.updated_state()
self.reschedule()

def reschedule(self):
self.handle = asyncio.get_event_loop().call_later(5, self.notify)

def update_observation_count(self, count):
if count and self.handle is None:
print("Starting the clock")
self.reschedule()
if count == 0 and self.handle:
print("Stopping the clock")
self.handle.cancel()
self.handle = None

async def render_get(self, request):
payload = datetime.datetime.now().\
strftime("%Y-%m-%d %H:%M").encode('ascii')
return aiocoap.Message(payload=payload)

# logging setup

logging.basicConfig(level=logging.INFO)
logging.getLogger("coap-server").setLevel(logging.DEBUG)

def main():
# Resource tree creation
root = resource.Site()

root.add_resource(['.well-known', 'core'],
resource.WKCResource(root.get_resources_as_linkheader))
root.add_resource(['time'], TimeResource())
root.add_resource(['other', 'block'], BlockResource())
root.add_resource(['other', 'separate'], SeparateLargeResource())

asyncio.Task(aiocoap.Context.create_server_context(root))

asyncio.get_event_loop().run_forever()

if __name__ == "__main__":
main()
Loading

0 comments on commit 31ef2db

Please # to comment.