diff options
author | Klement Sekera <klement.sekera@gmail.com> | 2022-04-26 19:02:15 +0200 |
---|---|---|
committer | Ole Tr�an <otroan@employees.org> | 2022-05-10 18:52:08 +0000 |
commit | d9b0c6fbf7aa5bd9af84264105b39c82028a4a29 (patch) | |
tree | 4f786cfd8ebc2443cb11e11b74c8657204068898 /test | |
parent | f90348bcb4afd0af2611cefc43b17ef3042b511c (diff) |
tests: replace pycodestyle with black
Drop pycodestyle for code style checking in favor of black. Black is
much faster, stable PEP8 compliant code style checker offering also
automatic formatting. It aims to be very stable and produce smallest
diffs. It's used by many small and big projects.
Running checkstyle with black takes a few seconds with a terse output.
Thus, test-checkstyle-diff is no longer necessary.
Expand scope of checkstyle to all python files in the repo, replacing
test-checkstyle with checkstyle-python.
Also, fixstyle-python is now available for automatic style formatting.
Note: python virtualenv has been consolidated in test/Makefile,
test/requirements*.txt which will eventually be moved to a central
location. This is required to simply the automated generation of
docker executor images in the CI.
Type: improvement
Change-Id: I022a326603485f58585e879ac0f697fceefbc9c8
Signed-off-by: Klement Sekera <klement.sekera@gmail.com>
Signed-off-by: Dave Wallace <dwallacelf@gmail.com>
Diffstat (limited to 'test')
195 files changed, 36387 insertions, 27443 deletions
diff --git a/test/Makefile b/test/Makefile index 82cef838978..b416bc3f5a3 100644 --- a/test/Makefile +++ b/test/Makefile @@ -73,10 +73,10 @@ V=0 endif PYTHON_VERSION=$(shell $(PYTHON_INTERP) -c 'import sys; print(sys.version_info.major)') -PIP_VERSION=22.0.3 +PIP_VERSION=22.0.4 # Keep in sync with requirements.txt -PIP_TOOLS_VERSION=6.5.0 -PIP_SETUPTOOLS_VERSION=60.7.1 +PIP_TOOLS_VERSION=6.6.0 +PIP_SETUPTOOLS_VERSION=62.1.0 PYTHON_DEPENDS=requirements-$(PYTHON_VERSION).txt SCAPY_SOURCE=$(shell find $(VENV_PATH)/lib/python* -name site-packages) BUILD_COV_DIR=$(TEST_BR)/coverage @@ -344,37 +344,35 @@ wipe-papi: wipe-all: wipe wipe-papi wipe-cov @rm -rf $(TEST_BR) -.PHONY: checkstyle-diff -checkstyle-diff: $(PIP_INSTALL_DONE) - @bash -c "source $(VENV_PATH)/bin/activate &&\ - python3 -m pip install pycodestyle" - @bash -c "source $(VENV_PATH)/bin/activate &&\ - cd $(WS_ROOT) && git diff --name-only --no-color --relative HEAD~1 ':!*.patch' | grep '.py$$' | xargs -I XXX \ - pycodestyle --show-source --ignore=W504,E126,E241,E226,E305,E704,E741,E722 -v XXX ||\ - (echo \"*********************************************************************\" &&\ - echo \"* Test framework PEP8 compliance check FAILED (checked changed files)\" &&\ - echo \"*********************************************************************\" &&\ - false)" - @echo "*********************************************************************" - @echo "* Test framework PEP8 compliance check passed (checked changed files)" - @echo "*********************************************************************" - .PHONY: start-gdb start-gdb: sanity @bash -c "source $(VENV_PATH)/bin/activate && python3 -c 'from debug import start_vpp_in_gdb; start_vpp_in_gdb()' $(RUN_TESTS_ARGS)" -.PHONY: checkstyle -checkstyle: $(PIP_INSTALL_DONE) +.PHONY: checkstyle-python-all +checkstyle-python-all: $(PIP_INSTALL_DONE) @bash -c "source $(VENV_PATH)/bin/activate &&\ - python3 -m pip install pycodestyle" + black -t py39 --diff $(WS_ROOT) ||\ + (echo \"*************************************************************************\" &&\ + echo \"* Test framework PEP8 compliance check FAILED (maybe: make fixstyle-python)\" &&\ + echo \"*************************************************************************\" &&\ + false)" + @echo "*******************************************************************" + @echo "* Test framework PEP8 compliance check passed" + @echo "*******************************************************************" + +.PHONY: checkstyle +checkstyle: checkstyle-python-all + +.PHONY: fixstyle-python-all +fixstyle-python-all: $(PIP_INSTALL_DONE) @bash -c "source $(VENV_PATH)/bin/activate &&\ - pycodestyle --show-source --ignore=W504,E126,E241,E226,E305,E704,E741,E722 -v *.py ||\ - (echo \"*******************************************************************\" &&\ - echo \"* Test framework PEP8 compliance check FAILED (checked all files)\" &&\ - echo \"*******************************************************************\" &&\ - false)" + black -t py39 $(WS_ROOT) ||\ + (echo \"*************************************************************************\" &&\ + echo \"* Test framework PEP8 compliance check FAILED (maybe: make fixstyle-python)\" &&\ + echo \"*************************************************************************\" &&\ + false)" @echo "*******************************************************************" - @echo "* Test framework PEP8 compliance check passed (checked all files)" + @echo "* Test framework PEP8 compliance check passed" @echo "*******************************************************************" .PHONY: help @@ -397,7 +395,6 @@ help: @echo " test-wipe-all - wipe (temporary) files generated by unit tests, and coverage" @echo " test-shell - enter shell with test environment" @echo " test-shell-debug - enter shell with test environment (debug build)" - @echo " test-checkstyle - check PEP8 compliance for test framework" @echo " test-refresh-deps - refresh the Python dependencies for the tests" @echo "" @echo "Arguments controlling test runs:" @@ -456,8 +453,3 @@ help: @echo "" @echo " test-cov - generate code coverage report for test framework" @echo " test-wipe-cov - wipe code coverage report for test framework" - @echo "" - @echo "Verifying code-style:" - @echo "" - @echo " test-checkstyle - check PEP8 compliance" - @echo "" diff --git a/test/bfd.py b/test/bfd.py index bbfa5945593..4189983b430 100644 --- a/test/bfd.py +++ b/test/bfd.py @@ -5,15 +5,22 @@ from socket import AF_INET, AF_INET6, inet_pton from scapy.all import bind_layers from scapy.layers.inet import UDP from scapy.packet import Packet -from scapy.fields import BitField, BitEnumField, XByteField, FlagsField,\ - ConditionalField, StrField +from scapy.fields import ( + BitField, + BitEnumField, + XByteField, + FlagsField, + ConditionalField, + StrField, +) from vpp_object import VppObject from util import NumericConstant from vpp_papi import VppEnum class BFDDiagCode(NumericConstant): - """ BFD Diagnostic Code """ + """BFD Diagnostic Code""" + no_diagnostic = 0 control_detection_time_expired = 1 echo_function_failed = 2 @@ -38,7 +45,8 @@ class BFDDiagCode(NumericConstant): class BFDState(NumericConstant): - """ BFD State """ + """BFD State""" + admin_down = 0 down = 1 init = 2 @@ -53,7 +61,8 @@ class BFDState(NumericConstant): class BFDAuthType(NumericConstant): - """ BFD Authentication Type """ + """BFD Authentication Type""" + no_auth = 0 simple_pwd = 1 keyed_md5 = 2 @@ -72,34 +81,38 @@ class BFDAuthType(NumericConstant): def bfd_is_auth_used(pkt): - """ is packet authenticated? """ + """is packet authenticated?""" return "A" in pkt.sprintf("%BFD.flags%") def bfd_is_simple_pwd_used(pkt): - """ is simple password authentication used? """ + """is simple password authentication used?""" return bfd_is_auth_used(pkt) and pkt.auth_type == BFDAuthType.simple_pwd def bfd_is_sha1_used(pkt): - """ is sha1 authentication used? """ - return bfd_is_auth_used(pkt) and pkt.auth_type in \ - (BFDAuthType.keyed_sha1, BFDAuthType.meticulous_keyed_sha1) + """is sha1 authentication used?""" + return bfd_is_auth_used(pkt) and pkt.auth_type in ( + BFDAuthType.keyed_sha1, + BFDAuthType.meticulous_keyed_sha1, + ) def bfd_is_md5_used(pkt): - """ is md5 authentication used? """ - return bfd_is_auth_used(pkt) and pkt.auth_type in \ - (BFDAuthType.keyed_md5, BFDAuthType.meticulous_keyed_md5) + """is md5 authentication used?""" + return bfd_is_auth_used(pkt) and pkt.auth_type in ( + BFDAuthType.keyed_md5, + BFDAuthType.meticulous_keyed_md5, + ) def bfd_is_md5_or_sha1_used(pkt): - """ is md5 or sha1 used? """ + """is md5 or sha1 used?""" return bfd_is_md5_used(pkt) or bfd_is_sha1_used(pkt) class BFD(Packet): - """ BFD protocol layer for scapy """ + """BFD protocol layer for scapy""" udp_dport = 3784 #: BFD destination port per RFC 5881 udp_dport_echo = 3785 # : BFD destination port for ECHO per RFC 5881 @@ -114,7 +127,7 @@ class BFD(Packet): BitField("version", 1, 3), BitEnumField("diag", 0, 5, BFDDiagCode.desc_dict), BitEnumField("state", 0, 2, BFDState.desc_dict), - FlagsField("flags", 0, 6, ['M', 'D', 'A', 'C', 'F', 'P']), + FlagsField("flags", 0, 6, ["M", "D", "A", "C", "F", "P"]), XByteField("detect_mult", 0), BitField("length", bfd_pkt_len, 8), BitField("my_discriminator", 0, 32), @@ -123,22 +136,20 @@ class BFD(Packet): BitField("required_min_rx_interval", 0, 32), BitField("required_min_echo_rx_interval", 0, 32), ConditionalField( - BitEnumField("auth_type", 0, 8, BFDAuthType.desc_dict), - bfd_is_auth_used), + BitEnumField("auth_type", 0, 8, BFDAuthType.desc_dict), bfd_is_auth_used + ), ConditionalField(BitField("auth_len", 0, 8), bfd_is_auth_used), ConditionalField(BitField("auth_key_id", 0, 8), bfd_is_auth_used), - ConditionalField(BitField("auth_reserved", 0, 8), - bfd_is_md5_or_sha1_used), - ConditionalField( - BitField("auth_seq_num", 0, 32), bfd_is_md5_or_sha1_used), + ConditionalField(BitField("auth_reserved", 0, 8), bfd_is_md5_or_sha1_used), + ConditionalField(BitField("auth_seq_num", 0, 32), bfd_is_md5_or_sha1_used), ConditionalField(StrField("auth_key_hash", "0" * 16), bfd_is_md5_used), - ConditionalField( - StrField("auth_key_hash", "0" * 20), bfd_is_sha1_used), + ConditionalField(StrField("auth_key_hash", "0" * 20), bfd_is_sha1_used), ] def mysummary(self): - return self.sprintf("BFD(my_disc=%BFD.my_discriminator%," - "your_disc=%BFD.your_discriminator%)") + return self.sprintf( + "BFD(my_disc=%BFD.my_discriminator%, your_disc=%BFD.your_discriminator%)" + ) # glue the BFD packet class to scapy parser @@ -146,7 +157,7 @@ bind_layers(UDP, BFD, dport=BFD.udp_dport) class BFD_vpp_echo(Packet): - """ BFD echo packet as used by VPP (non-rfc, as rfc doesn't define one) """ + """BFD echo packet as used by VPP (non-rfc, as rfc doesn't define one)""" udp_dport = 3785 #: BFD echo destination port per RFC 5881 name = "BFD_VPP_ECHO" @@ -154,13 +165,14 @@ class BFD_vpp_echo(Packet): fields_desc = [ BitField("discriminator", 0, 32), BitField("expire_time_clocks", 0, 64), - BitField("checksum", 0, 64) + BitField("checksum", 0, 64), ] def mysummary(self): return self.sprintf( "BFD_VPP_ECHO(disc=%BFD_VPP_ECHO.discriminator%," - "expire_time_clocks=%BFD_VPP_ECHO.expire_time_clocks%)") + "expire_time_clocks=%BFD_VPP_ECHO.expire_time_clocks%)" + ) # glue the BFD echo packet class to scapy parser @@ -168,7 +180,7 @@ bind_layers(UDP, BFD_vpp_echo, dport=BFD_vpp_echo.udp_dport) class VppBFDAuthKey(VppObject): - """ Represents BFD authentication key in VPP """ + """Represents BFD authentication key in VPP""" def __init__(self, test, conf_key_id, auth_type, key): self._test = test @@ -179,17 +191,17 @@ class VppBFDAuthKey(VppObject): @property def test(self): - """ Test which created this key """ + """Test which created this key""" return self._test @property def auth_type(self): - """ Authentication type for this key """ + """Authentication type for this key""" return self._auth_type @property def key(self): - """ key data """ + """key data""" return self._key @key.setter @@ -198,17 +210,20 @@ class VppBFDAuthKey(VppObject): @property def conf_key_id(self): - """ configuration key ID """ + """configuration key ID""" return self._conf_key_id def add_vpp_config(self): self.test.vapi.bfd_auth_set_key( - conf_key_id=self._conf_key_id, auth_type=self._auth_type, - key=self._key, key_len=len(self._key)) + conf_key_id=self._conf_key_id, + auth_type=self._auth_type, + key=self._key, + key_len=len(self._key), + ) self._test.registry.register(self, self.test.logger) def get_bfd_auth_keys_dump_entry(self): - """ get the entry in the auth keys dump corresponding to this key """ + """get the entry in the auth keys dump corresponding to this key""" result = self.test.vapi.bfd_auth_keys_dump() for k in result: if k.conf_key_id == self._conf_key_id: @@ -226,11 +241,22 @@ class VppBFDAuthKey(VppObject): class VppBFDUDPSession(VppObject): - """ Represents BFD UDP session in VPP """ - - def __init__(self, test, interface, peer_addr, local_addr=None, af=AF_INET, - desired_min_tx=300000, required_min_rx=300000, detect_mult=3, - sha1_key=None, bfd_key_id=None, is_tunnel=False): + """Represents BFD UDP session in VPP""" + + def __init__( + self, + test, + interface, + peer_addr, + local_addr=None, + af=AF_INET, + desired_min_tx=300000, + required_min_rx=300000, + detect_mult=3, + sha1_key=None, + bfd_key_id=None, + is_tunnel=False, + ): self._test = test self._interface = interface self._af = af @@ -251,22 +277,22 @@ class VppBFDUDPSession(VppObject): @property def test(self): - """ Test which created this session """ + """Test which created this session""" return self._test @property def interface(self): - """ Interface on which this session lives """ + """Interface on which this session lives""" return self._interface @property def af(self): - """ Address family - AF_INET or AF_INET6 """ + """Address family - AF_INET or AF_INET6""" return self._af @property def local_addr(self): - """ BFD session local address (VPP address) """ + """BFD session local address (VPP address)""" if self._local_addr is None: if self.af == AF_INET: return self._interface.local_ip4 @@ -278,28 +304,32 @@ class VppBFDUDPSession(VppObject): @property def peer_addr(self): - """ BFD session peer address """ + """BFD session peer address""" return self._peer_addr def get_bfd_udp_session_dump_entry(self): - """ get the namedtuple entry from bfd udp session dump """ + """get the namedtuple entry from bfd udp session dump""" result = self.test.vapi.bfd_udp_session_dump() for s in result: self.test.logger.debug("session entry: %s" % str(s)) if s.sw_if_index == self.interface.sw_if_index: - if self.af == AF_INET \ - and self.interface.local_ip4 == str(s.local_addr) \ - and self.interface.remote_ip4 == str(s.peer_addr): + if ( + self.af == AF_INET + and self.interface.local_ip4 == str(s.local_addr) + and self.interface.remote_ip4 == str(s.peer_addr) + ): return s - if self.af == AF_INET6 \ - and self.interface.local_ip6 == str(s.local_addr) \ - and self.interface.remote_ip6 == str(s.peer_addr): + if ( + self.af == AF_INET6 + and self.interface.local_ip6 == str(s.local_addr) + and self.interface.remote_ip6 == str(s.peer_addr) + ): return s return None @property def state(self): - """ BFD session state """ + """BFD session state""" session = self.get_bfd_udp_session_dump_entry() if session is None: raise Exception("Could not find BFD session in VPP response") @@ -307,27 +337,27 @@ class VppBFDUDPSession(VppObject): @property def desired_min_tx(self): - """ desired minimum tx interval """ + """desired minimum tx interval""" return self._desired_min_tx @property def required_min_rx(self): - """ required minimum rx interval """ + """required minimum rx interval""" return self._required_min_rx @property def detect_mult(self): - """ detect multiplier """ + """detect multiplier""" return self._detect_mult @property def sha1_key(self): - """ sha1 key """ + """sha1 key""" return self._sha1_key @property def bfd_key_id(self): - """ bfd key id in use """ + """bfd key id in use""" return self._bfd_key_id @property @@ -335,7 +365,7 @@ class VppBFDUDPSession(VppObject): return self._is_tunnel def activate_auth(self, key, bfd_key_id=None, delayed=False): - """ activate authentication for this session """ + """activate authentication for this session""" self._bfd_key_id = bfd_key_id if bfd_key_id else randint(0, 255) self._sha1_key = key conf_key_id = self._sha1_key.conf_key_id @@ -346,10 +376,11 @@ class VppBFDUDPSession(VppObject): peer_addr=self.peer_addr, bfd_key_id=self._bfd_key_id, conf_key_id=conf_key_id, - is_delayed=is_delayed) + is_delayed=is_delayed, + ) def deactivate_auth(self, delayed=False): - """ deactivate authentication """ + """deactivate authentication""" self._bfd_key_id = None self._sha1_key = None is_delayed = 1 if delayed else 0 @@ -357,45 +388,48 @@ class VppBFDUDPSession(VppObject): sw_if_index=self._interface.sw_if_index, local_addr=self.local_addr, peer_addr=self.peer_addr, - is_delayed=is_delayed) + is_delayed=is_delayed, + ) - def modify_parameters(self, - detect_mult=None, - desired_min_tx=None, - required_min_rx=None): - """ modify session parameters """ + def modify_parameters( + self, detect_mult=None, desired_min_tx=None, required_min_rx=None + ): + """modify session parameters""" if detect_mult: self._detect_mult = detect_mult if desired_min_tx: self._desired_min_tx = desired_min_tx if required_min_rx: self._required_min_rx = required_min_rx - self.test.vapi.bfd_udp_mod(sw_if_index=self._interface.sw_if_index, - desired_min_tx=self.desired_min_tx, - required_min_rx=self.required_min_rx, - detect_mult=self.detect_mult, - local_addr=self.local_addr, - peer_addr=self.peer_addr) + self.test.vapi.bfd_udp_mod( + sw_if_index=self._interface.sw_if_index, + desired_min_tx=self.desired_min_tx, + required_min_rx=self.required_min_rx, + detect_mult=self.detect_mult, + local_addr=self.local_addr, + peer_addr=self.peer_addr, + ) def add_vpp_config(self): bfd_key_id = self._bfd_key_id if self._sha1_key else None conf_key_id = self._sha1_key.conf_key_id if self._sha1_key else None is_authenticated = True if self._sha1_key else False - self.test.vapi.bfd_udp_add(sw_if_index=self._interface.sw_if_index, - desired_min_tx=self.desired_min_tx, - required_min_rx=self.required_min_rx, - detect_mult=self.detect_mult, - local_addr=self.local_addr, - peer_addr=self.peer_addr, - bfd_key_id=bfd_key_id, - conf_key_id=conf_key_id, - is_authenticated=is_authenticated) + self.test.vapi.bfd_udp_add( + sw_if_index=self._interface.sw_if_index, + desired_min_tx=self.desired_min_tx, + required_min_rx=self.required_min_rx, + detect_mult=self.detect_mult, + local_addr=self.local_addr, + peer_addr=self.peer_addr, + bfd_key_id=bfd_key_id, + conf_key_id=conf_key_id, + is_authenticated=is_authenticated, + ) self._test.registry.register(self, self.test.logger) - def upd_vpp_config(self, - detect_mult=None, - desired_min_tx=None, - required_min_rx=None): + def upd_vpp_config( + self, detect_mult=None, desired_min_tx=None, required_min_rx=None + ): if desired_min_tx: self._desired_min_tx = desired_min_tx if required_min_rx: @@ -405,15 +439,17 @@ class VppBFDUDPSession(VppObject): bfd_key_id = self._bfd_key_id if self._sha1_key else None conf_key_id = self._sha1_key.conf_key_id if self._sha1_key else None is_authenticated = True if self._sha1_key else False - self.test.vapi.bfd_udp_upd(sw_if_index=self._interface.sw_if_index, - desired_min_tx=self.desired_min_tx, - required_min_rx=self.required_min_rx, - detect_mult=self.detect_mult, - local_addr=self.local_addr, - peer_addr=self.peer_addr, - bfd_key_id=bfd_key_id, - conf_key_id=conf_key_id, - is_authenticated=is_authenticated) + self.test.vapi.bfd_udp_upd( + sw_if_index=self._interface.sw_if_index, + desired_min_tx=self.desired_min_tx, + required_min_rx=self.required_min_rx, + detect_mult=self.detect_mult, + local_addr=self.local_addr, + peer_addr=self.peer_addr, + bfd_key_id=bfd_key_id, + conf_key_id=conf_key_id, + is_authenticated=is_authenticated, + ) self._test.registry.register(self, self.test.logger) def query_vpp_config(self): @@ -421,27 +457,34 @@ class VppBFDUDPSession(VppObject): return session is not None def remove_vpp_config(self): - self.test.vapi.bfd_udp_del(self._interface.sw_if_index, - local_addr=self.local_addr, - peer_addr=self.peer_addr) + self.test.vapi.bfd_udp_del( + self._interface.sw_if_index, + local_addr=self.local_addr, + peer_addr=self.peer_addr, + ) def object_id(self): - return "bfd-udp-%s-%s-%s-%s" % (self._interface.sw_if_index, - self.local_addr, - self.peer_addr, - self.af) + return "bfd-udp-%s-%s-%s-%s" % ( + self._interface.sw_if_index, + self.local_addr, + self.peer_addr, + self.af, + ) def admin_up(self): - """ set bfd session admin-up """ + """set bfd session admin-up""" self.test.vapi.bfd_udp_session_set_flags( flags=VppEnum.vl_api_if_status_flags_t.IF_STATUS_API_FLAG_ADMIN_UP, sw_if_index=self._interface.sw_if_index, local_addr=self.local_addr, - peer_addr=self.peer_addr) + peer_addr=self.peer_addr, + ) def admin_down(self): - """ set bfd session admin-down """ + """set bfd session admin-down""" self.test.vapi.bfd_udp_session_set_flags( - flags=0, sw_if_index=self._interface.sw_if_index, + flags=0, + sw_if_index=self._interface.sw_if_index, local_addr=self.local_addr, - peer_addr=self.peer_addr) + peer_addr=self.peer_addr, + ) diff --git a/test/config.py b/test/config.py index dd3b9c1f9ea..c99d1ca66a6 100644 --- a/test/config.py +++ b/test/config.py @@ -12,6 +12,7 @@ def positive_int_or_default(default): if int(v) <= 0: raise ValueError("value must be positive") return int(v) + return positive_integer @@ -22,6 +23,7 @@ def positive_float_or_default(default): if float(v) <= 0: raise ValueError("value must be positive") return float(v) + return positive_float @@ -50,6 +52,7 @@ def int_choice_or_default(options, default): if int(v) in options: return int(v) raise ValueError("invalid choice") + return choice @@ -57,14 +60,13 @@ def worker_config(v): if v is None or v == "": return 0 if v.startswith("workers "): - return(int(v.split(" ")[1])) + return int(v.split(" ")[1]) return int(v) def directory(v): if not os.path.isdir(v): - raise ValueError(f"provided path '{v}' doesn't exist " - "or is not a directory") + raise ValueError(f"provided path '{v}' doesn't exist or is not a directory") return v @@ -74,35 +76,51 @@ def directory_verify_or_create(v): return v -parser = argparse.ArgumentParser(description="VPP unit tests", - formatter_class=argparse.RawTextHelpFormatter) +parser = argparse.ArgumentParser( + description="VPP unit tests", formatter_class=argparse.RawTextHelpFormatter +) -parser.add_argument("--failfast", action="store_true", - help="stop running tests on first failure") +parser.add_argument( + "--failfast", action="store_true", help="stop running tests on first failure" +) -parser.add_argument("--test-src-dir", action="append", type=directory, - help="directory containing test files " - "(may be specified multiple times) " - "(VPP_WS_DIR/test is added automatically to the set)") +parser.add_argument( + "--test-src-dir", + action="append", + type=directory, + help="directory containing test files " + "(may be specified multiple times) " + "(VPP_WS_DIR/test is added automatically to the set)", +) default_verbose = 0 -parser.add_argument("--verbose", action="store", default=default_verbose, - type=int_choice_or_default((0, 1, 2), default_verbose), - help="verbosity setting - 0 - least verbose, " - "2 - most verbose (default: 0)") +parser.add_argument( + "--verbose", + action="store", + default=default_verbose, + type=int_choice_or_default((0, 1, 2), default_verbose), + help="verbosity setting - 0 - least verbose, 2 - most verbose (default: 0)", +) default_test_run_timeout = 600 -parser.add_argument("--timeout", action="store", - type=positive_int_or_default(default_test_run_timeout), - default=default_test_run_timeout, - metavar="TEST_RUN_TIMEOUT", - help="test run timeout in seconds - per test " - f"(default: {default_test_run_timeout})") - -parser.add_argument("--failed-dir", action="store", type=directory, - help="directory containing failed tests") +parser.add_argument( + "--timeout", + action="store", + type=positive_int_or_default(default_test_run_timeout), + default=default_test_run_timeout, + metavar="TEST_RUN_TIMEOUT", + help="test run timeout in seconds - per test " + f"(default: {default_test_run_timeout})", +) + +parser.add_argument( + "--failed-dir", + action="store", + type=directory, + help="directory containing failed tests", +) filter_help_string = """\ expression consists of 3 string selectors separated by '.' separators: @@ -126,17 +144,23 @@ examples: 4. '.*.test_add_bfd' selects all test functions named test_add_bfd from all files/classes """ -parser.add_argument("--filter", action="store", - metavar="FILTER_EXPRESSION", help=filter_help_string) +parser.add_argument( + "--filter", action="store", metavar="FILTER_EXPRESSION", help=filter_help_string +) default_retries = 0 -parser.add_argument("--retries", action="store", default=default_retries, - type=positive_int_or_default(default_retries), - help="retry failed tests RETRIES times") +parser.add_argument( + "--retries", + action="store", + default=default_retries, + type=positive_int_or_default(default_retries), + help="retry failed tests RETRIES times", +) -parser.add_argument("--step", action="store_true", default=False, - help="enable stepping through tests") +parser.add_argument( + "--step", action="store_true", default=False, help="enable stepping through tests" +) debug_help_string = """\ attach - attach to already running vpp @@ -145,80 +169,153 @@ gdb - print VPP PID and pause allowing attaching gdb gdbserver - same as above, but run gdb in gdbserver """ -parser.add_argument("--debug", action="store", - choices=["attach", "core", "gdb", "gdbserver"], - help=debug_help_string) - -parser.add_argument("--debug-framework", action="store_true", - help="enable internal test framework debugging") - -parser.add_argument("--compress-core", action="store_true", - help="compress core files if not debugging them") - -parser.add_argument("--extended", action="store_true", - help="run extended tests") - -parser.add_argument("--sanity", action="store_true", - help="perform sanity vpp run before running tests") - -parser.add_argument("--force-foreground", action="store_true", - help="force running in foreground - don't fork") - -parser.add_argument("--jobs", action="store", type=positive_int_or_auto, - default="auto", help="maximum concurrent test jobs") - -parser.add_argument("--venv-dir", action="store", - type=directory, help="path to virtual environment") +parser.add_argument( + "--debug", + action="store", + choices=["attach", "core", "gdb", "gdbserver"], + help=debug_help_string, +) + +parser.add_argument( + "--debug-framework", + action="store_true", + help="enable internal test framework debugging", +) + +parser.add_argument( + "--compress-core", + action="store_true", + help="compress core files if not debugging them", +) + +parser.add_argument("--extended", action="store_true", help="run extended tests") + +parser.add_argument( + "--sanity", action="store_true", help="perform sanity vpp run before running tests" +) + +parser.add_argument( + "--force-foreground", + action="store_true", + help="force running in foreground - don't fork", +) + +parser.add_argument( + "--jobs", + action="store", + type=positive_int_or_auto, + default="auto", + help="maximum concurrent test jobs", +) + +parser.add_argument( + "--venv-dir", action="store", type=directory, help="path to virtual environment" +) default_rnd_seed = time.time() -parser.add_argument("--rnd-seed", action="store", default=default_rnd_seed, - type=positive_float_or_default(default_rnd_seed), - help="random generator seed (default: current time)") - -parser.add_argument("--vpp-worker-count", action="store", type=worker_config, - default=0, help="number of vpp workers") - -parser.add_argument("--gcov", action="store_true", - default=False, help="running gcov tests") - -parser.add_argument("--cache-vpp-output", action="store_true", default=False, - help="cache VPP stdout/stderr and log as one block " - "after test finishes") - -parser.add_argument("--vpp-ws-dir", action="store", required=True, - type=directory, help="vpp workspace directory") - -parser.add_argument("--vpp-tag", action="store", default="vpp_debug", - metavar="VPP_TAG", required=True, - help="vpp tag (e.g. vpp, vpp_debug, vpp_gcov)") - -parser.add_argument("--vpp", action="store", help="path to vpp binary " - "(default: derive from VPP_WS_DIR and VPP_TAG)") - -parser.add_argument("--vpp-install-dir", type=directory, - action="store", help="path to vpp install directory" - "(default: derive from VPP_WS_DIR and VPP_TAG)") - -parser.add_argument("--vpp-build-dir", action="store", type=directory, - help="vpp build directory" - "(default: derive from VPP_WS_DIR and VPP_TAG)") - -parser.add_argument("--vpp-plugin-dir", action="append", type=directory, - help="directory containing vpp plugins" - "(default: derive from VPP_WS_DIR and VPP_TAG)") - -parser.add_argument("--vpp-test-plugin-dir", action="append", type=directory, - help="directory containing vpp api test plugins" - "(default: derive from VPP_WS_DIR and VPP_TAG)") - -parser.add_argument("--extern-plugin-dir", action="append", type=directory, - default=[], help="directory containing external plugins") - -parser.add_argument("--coredump-size", action="store", default="unlimited", - help="specify vpp coredump size") - -parser.add_argument("--max-vpp-cpus", action="store", type=int_or_auto, - default=0, help="max cpus used by vpp") +parser.add_argument( + "--rnd-seed", + action="store", + default=default_rnd_seed, + type=positive_float_or_default(default_rnd_seed), + help="random generator seed (default: current time)", +) + +parser.add_argument( + "--vpp-worker-count", + action="store", + type=worker_config, + default=0, + help="number of vpp workers", +) + +parser.add_argument( + "--gcov", action="store_true", default=False, help="running gcov tests" +) + +parser.add_argument( + "--cache-vpp-output", + action="store_true", + default=False, + help="cache VPP stdout/stderr and log as one block after test finishes", +) + +parser.add_argument( + "--vpp-ws-dir", + action="store", + required=True, + type=directory, + help="vpp workspace directory", +) + +parser.add_argument( + "--vpp-tag", + action="store", + default="vpp_debug", + metavar="VPP_TAG", + required=True, + help="vpp tag (e.g. vpp, vpp_debug, vpp_gcov)", +) + +parser.add_argument( + "--vpp", + action="store", + help="path to vpp binary (default: derive from VPP_WS_DIR and VPP_TAG)", +) + +parser.add_argument( + "--vpp-install-dir", + type=directory, + action="store", + help="path to vpp install directory" + "(default: derive from VPP_WS_DIR and VPP_TAG)", +) + +parser.add_argument( + "--vpp-build-dir", + action="store", + type=directory, + help="vpp build directory (default: derive from VPP_WS_DIR and VPP_TAG)", +) + +parser.add_argument( + "--vpp-plugin-dir", + action="append", + type=directory, + help="directory containing vpp plugins" + "(default: derive from VPP_WS_DIR and VPP_TAG)", +) + +parser.add_argument( + "--vpp-test-plugin-dir", + action="append", + type=directory, + help="directory containing vpp api test plugins" + "(default: derive from VPP_WS_DIR and VPP_TAG)", +) + +parser.add_argument( + "--extern-plugin-dir", + action="append", + type=directory, + default=[], + help="directory containing external plugins", +) + +parser.add_argument( + "--coredump-size", + action="store", + default="unlimited", + help="specify vpp coredump size", +) + +parser.add_argument( + "--max-vpp-cpus", + action="store", + type=int_or_auto, + default=0, + help="max cpus used by vpp", +) variant_help_string = """\ specify which march node variant to unit test @@ -228,26 +325,41 @@ specify which march node variant to unit test parser.add_argument("--variant", action="store", help=variant_help_string) -parser.add_argument("--api-fuzz", action="store", default=None, - help="specify api fuzzing parameters") - -parser.add_argument("--wipe-tmp-dir", action="store_true", default=True, - help="remove test tmp directory before running test") - -parser.add_argument("--tmp-dir", action="store", default="/tmp", - type=directory_verify_or_create, - help="directory where to store test temporary directories") - -parser.add_argument("--log-dir", action="store", - type=directory_verify_or_create, - help="directory where to store directories " - "containing log files (default: --tmp-dir)") +parser.add_argument( + "--api-fuzz", action="store", default=None, help="specify api fuzzing parameters" +) + +parser.add_argument( + "--wipe-tmp-dir", + action="store_true", + default=True, + help="remove test tmp directory before running test", +) + +parser.add_argument( + "--tmp-dir", + action="store", + default="/tmp", + type=directory_verify_or_create, + help="directory where to store test temporary directories", +) + +parser.add_argument( + "--log-dir", + action="store", + type=directory_verify_or_create, + help="directory where to store directories " + "containing log files (default: --tmp-dir)", +) default_keep_pcaps = False -parser.add_argument("--keep-pcaps", action="store_true", - default=default_keep_pcaps, - help="if set, keep all pcap files from a test run" - f" (default: {default_keep_pcaps})") +parser.add_argument( + "--keep-pcaps", + action="store_true", + default=default_keep_pcaps, + help="if set, keep all pcap files from a test run" + f" (default: {default_keep_pcaps})", +) config = parser.parse_args() @@ -268,12 +380,13 @@ libs = ["lib", "lib64"] if config.vpp_plugin_dir is None: config.vpp_plugin_dir = [ - f"{config.vpp_install_dir}/vpp/{lib}/vpp_plugins" for lib in libs] + f"{config.vpp_install_dir}/vpp/{lib}/vpp_plugins" for lib in libs + ] if config.vpp_test_plugin_dir is None: config.vpp_test_plugin_dir = [ - f"{config.vpp_install_dir}/vpp/{lib}/vpp_api_test_plugins" - for lib in libs] + f"{config.vpp_install_dir}/vpp/{lib}/vpp_api_test_plugins" for lib in libs + ] test_dirs = [f"{ws}/test"] @@ -289,7 +402,7 @@ if config.venv_dir is None: available_cpus = psutil.Process().cpu_affinity() num_cpus = len(available_cpus) -if config.max_vpp_cpus == 'auto': +if config.max_vpp_cpus == "auto": max_vpp_cpus = num_cpus elif config.max_vpp_cpus > 0: max_vpp_cpus = min(config.max_vpp_cpus, num_cpus) diff --git a/test/debug.py b/test/debug.py index 0ab143201c8..d77fd87f3e5 100644 --- a/test/debug.py +++ b/test/debug.py @@ -8,7 +8,7 @@ from sanity_run_vpp import SanityTestCase from shutil import rmtree from config import available_cpus -gdb_path = '/usr/bin/gdb' +gdb_path = "/usr/bin/gdb" def spawn_gdb(binary_path, core_path): @@ -24,8 +24,9 @@ def spawn_gdb(binary_path, core_path): if gdb.isalive(): raise Exception("GDB refused to die...") else: - sys.stderr.write("Debugger '%s' does not exist or is not " - "an executable..\n" % gdb_path) + sys.stderr.write( + "Debugger '%s' does not exist or is not an executable..\n" % gdb_path + ) def start_vpp_in_gdb(): @@ -33,8 +34,7 @@ def start_vpp_in_gdb(): # but any test case class could be used ... SanityTestCase.set_debug_flags("attach") SanityTestCase.tempdir = SanityTestCase.get_tempdir() - SanityTestCase.assign_cpus( - available_cpus[:SanityTestCase.get_cpus_required()]) + SanityTestCase.assign_cpus(available_cpus[: SanityTestCase.get_cpus_required()]) SanityTestCase.setUpConstants() vpp_cmdline = SanityTestCase.vpp_cmdline print("Hacking cmdline to make VPP interactive.") @@ -54,5 +54,6 @@ def start_vpp_in_gdb(): if gdb.isalive(): raise Exception("GDB refused to die...") else: - sys.stderr.write("Debugger '%s' does not exist or is not " - "an executable..\n" % gdb_path) + sys.stderr.write( + "Debugger '%s' does not exist or is not an executable..\n" % gdb_path + ) diff --git a/test/debug_internal.py b/test/debug_internal.py index 2cbee27ec81..fe10db7ee7f 100644 --- a/test/debug_internal.py +++ b/test/debug_internal.py @@ -4,6 +4,7 @@ import vpp_papi from vpp_papi_provider import VppPapiProvider import objgraph from pympler import tracker + tr = tracker.SummaryTracker() """ @@ -18,16 +19,16 @@ def on_tear_down_class(cls): tr.print_diff() objects = gc.get_objects() counter = 0 - with open(cls.tempdir + '/python_objects.txt', 'w') as f: + with open(cls.tempdir + "/python_objects.txt", "w") as f: interesting = [ - o for o in objects - if isinstance(o, (VppPapiProvider, vpp_papi.VPP))] + o for o in objects if isinstance(o, (VppPapiProvider, vpp_papi.VPP)) + ] del objects gc.collect() for o in interesting: - objgraph.show_backrefs([o], max_depth=5, - filename="%s/%s.png" % - (cls.tempdir, counter)) + objgraph.show_backrefs( + [o], max_depth=5, filename="%s/%s.png" % (cls.tempdir, counter) + ) counter += 1 refs = gc.get_referrers(o) pp = pprint.PrettyPrinter(indent=2) diff --git a/test/framework.py b/test/framework.py index 8065518ff7a..05e59b577cb 100644 --- a/test/framework.py +++ b/test/framework.py @@ -37,8 +37,15 @@ from vpp_papi import VppEnum import vpp_papi from vpp_papi.vpp_stats import VPPStats from vpp_papi.vpp_transport_socket import VppTransportSocketIOError -from log import RED, GREEN, YELLOW, double_line_delim, single_line_delim, \ - get_logger, colorize +from log import ( + RED, + GREEN, + YELLOW, + double_line_delim, + single_line_delim, + get_logger, + colorize, +) from vpp_object import VppObjectRegistry from util import ppp, is_core_present from scapy.layers.inet import IPerror, TCPerror, UDPerror, ICMPerror @@ -49,7 +56,7 @@ from scapy.layers.inet6 import ICMPv6EchoReply logger = logging.getLogger(__name__) # Set up an empty logger for the testcase that can be overridden as necessary -null_logger = logging.getLogger('VppTestCase') +null_logger = logging.getLogger("VppTestCase") null_logger.addHandler(logging.NullHandler()) PASS = 0 @@ -72,10 +79,13 @@ if config.debug_framework: class VppDiedError(Exception): - """ exception for reporting that the subprocess has died.""" + """exception for reporting that the subprocess has died.""" - signals_by_value = {v: k for k, v in signal.__dict__.items() if - k.startswith('SIG') and not k.startswith('SIG_')} + signals_by_value = { + v: k + for k, v in signal.__dict__.items() + if k.startswith("SIG") and not k.startswith("SIG_") + } def __init__(self, rv=None, testcase=None, method_name=None): self.rv = rv @@ -89,15 +99,16 @@ class VppDiedError(Exception): pass if testcase is None and method_name is None: - in_msg = '' + in_msg = "" else: - in_msg = ' while running %s.%s' % (testcase, method_name) + in_msg = " while running %s.%s" % (testcase, method_name) if self.rv: - msg = "VPP subprocess died unexpectedly%s with return code: %d%s."\ - % (in_msg, self.rv, ' [%s]' % - (self.signal_name if - self.signal_name is not None else '')) + msg = "VPP subprocess died unexpectedly%s with return code: %d%s." % ( + in_msg, + self.rv, + " [%s]" % (self.signal_name if self.signal_name is not None else ""), + ) else: msg = "VPP subprocess died unexpectedly%s." % in_msg @@ -110,6 +121,7 @@ class _PacketInfo(object): Help process information about the next packet. Set variables to default values. """ + #: Store the index of the packet. index = -1 #: Store the index of the source packet generator interface of the packet. @@ -133,19 +145,23 @@ class _PacketInfo(object): def pump_output(testclass): - """ pump output from vpp stdout/stderr to proper queues """ + """pump output from vpp stdout/stderr to proper queues""" stdout_fragment = "" stderr_fragment = "" while not testclass.pump_thread_stop_flag.is_set(): - readable = select.select([testclass.vpp.stdout.fileno(), - testclass.vpp.stderr.fileno(), - testclass.pump_thread_wakeup_pipe[0]], - [], [])[0] + readable = select.select( + [ + testclass.vpp.stdout.fileno(), + testclass.vpp.stderr.fileno(), + testclass.pump_thread_wakeup_pipe[0], + ], + [], + [], + )[0] if testclass.vpp.stdout.fileno() in readable: read = os.read(testclass.vpp.stdout.fileno(), 102400) if len(read) > 0: - split = read.decode('ascii', - errors='backslashreplace').splitlines(True) + split = read.decode("ascii", errors="backslashreplace").splitlines(True) if len(stdout_fragment) > 0: split[0] = "%s%s" % (stdout_fragment, split[0]) if len(split) > 0 and split[-1].endswith("\n"): @@ -156,13 +172,11 @@ def pump_output(testclass): testclass.vpp_stdout_deque.extend(split[:limit]) if not config.cache_vpp_output: for line in split[:limit]: - testclass.logger.info( - "VPP STDOUT: %s" % line.rstrip("\n")) + testclass.logger.info("VPP STDOUT: %s" % line.rstrip("\n")) if testclass.vpp.stderr.fileno() in readable: read = os.read(testclass.vpp.stderr.fileno(), 102400) if len(read) > 0: - split = read.decode('ascii', - errors='backslashreplace').splitlines(True) + split = read.decode("ascii", errors="backslashreplace").splitlines(True) if len(stderr_fragment) > 0: split[0] = "%s%s" % (stderr_fragment, split[0]) if len(split) > 0 and split[-1].endswith("\n"): @@ -174,14 +188,13 @@ def pump_output(testclass): testclass.vpp_stderr_deque.extend(split[:limit]) if not config.cache_vpp_output: for line in split[:limit]: - testclass.logger.error( - "VPP STDERR: %s" % line.rstrip("\n")) + testclass.logger.error("VPP STDERR: %s" % line.rstrip("\n")) # ignoring the dummy pipe here intentionally - the # flag will take care of properly terminating the loop def _is_platform_aarch64(): - return platform.machine() == 'aarch64' + return platform.machine() == "aarch64" is_platform_aarch64 = _is_platform_aarch64() @@ -191,6 +204,7 @@ class KeepAliveReporter(object): """ Singleton object which reports test start to parent process """ + _shared_state = {} def __init__(self): @@ -216,7 +230,7 @@ class KeepAliveReporter(object): return if isclass(test): - desc = '%s (%s)' % (desc, unittest.util.strclass(test)) + desc = "%s (%s)" % (desc, unittest.util.strclass(test)) else: desc = test.id() @@ -240,6 +254,7 @@ def create_tag_decorator(e): except AttributeError: cls.test_tags = [e] return cls + return decorator @@ -250,7 +265,7 @@ tag_fixme_asan = create_tag_decorator(TestCaseTag.FIXME_ASAN) class DummyVpp: returncode = None - pid = 0xcafebafe + pid = 0xCAFEBAFE def poll(self): pass @@ -300,7 +315,7 @@ class VppTestCase(CPUInterface, unittest.TestCase): @classmethod def has_tag(cls, tag): - """ if the test case has a given tag - return true """ + """if the test case has a given tag - return true""" try: return tag in cls.test_tags except AttributeError: @@ -309,15 +324,15 @@ class VppTestCase(CPUInterface, unittest.TestCase): @classmethod def is_tagged_run_solo(cls): - """ if the test case class is timing-sensitive - return true """ + """if the test case class is timing-sensitive - return true""" return cls.has_tag(TestCaseTag.RUN_SOLO) @classmethod def skip_fixme_asan(cls): - """ if @tag_fixme_asan & ASan is enabled - mark for skip """ + """if @tag_fixme_asan & ASan is enabled - mark for skip""" if cls.has_tag(TestCaseTag.FIXME_ASAN): - vpp_extra_cmake_args = os.environ.get('VPP_EXTRA_CMAKE_ARGS', '') - if 'DVPP_ENABLE_SANITIZE_ADDR=ON' in vpp_extra_cmake_args: + vpp_extra_cmake_args = os.environ.get("VPP_EXTRA_CMAKE_ARGS", "") + if "DVPP_ENABLE_SANITIZE_ADDR=ON" in vpp_extra_cmake_args: cls = unittest.skip("Skipping @tag_fixme_asan tests")(cls) @classmethod @@ -364,7 +379,7 @@ class VppTestCase(CPUInterface, unittest.TestCase): @classmethod def setUpConstants(cls): - """ Set-up the test case class based on environment variables """ + """Set-up the test case class based on environment variables""" cls.step = config.step cls.plugin_path = ":".join(config.vpp_plugin_dir) cls.test_plugin_path = ":".join(config.vpp_test_plugin_dir) @@ -385,34 +400,92 @@ class VppTestCase(CPUInterface, unittest.TestCase): api_fuzzing = config.api_fuzz if api_fuzzing is None: - api_fuzzing = 'off' + api_fuzzing = "off" cls.vpp_cmdline = [ config.vpp, - "unix", "{", "nodaemon", debug_cli, "full-coredump", - coredump_size, "runtime-dir", cls.tempdir, "}", - "api-trace", "{", "on", "}", - "api-segment", "{", "prefix", cls.get_api_segment_prefix(), "}", - "cpu", "{", "main-core", str(cls.cpus[0]), ] + "unix", + "{", + "nodaemon", + debug_cli, + "full-coredump", + coredump_size, + "runtime-dir", + cls.tempdir, + "}", + "api-trace", + "{", + "on", + "}", + "api-segment", + "{", + "prefix", + cls.get_api_segment_prefix(), + "}", + "cpu", + "{", + "main-core", + str(cls.cpus[0]), + ] if cls.extern_plugin_path not in (None, ""): - cls.extra_vpp_plugin_config.append( - "add-path %s" % cls.extern_plugin_path) + cls.extra_vpp_plugin_config.append("add-path %s" % cls.extern_plugin_path) if cls.get_vpp_worker_count(): - cls.vpp_cmdline.extend([ - "corelist-workers", ",".join([str(x) for x in cls.cpus[1:]])]) - cls.vpp_cmdline.extend([ - "}", - "physmem", "{", "max-size", "32m", "}", - "statseg", "{", "socket-name", cls.get_stats_sock_path(), - cls.extra_vpp_statseg_config, "}", - "socksvr", "{", "socket-name", cls.get_api_sock_path(), "}", - "node { ", default_variant, "}", - "api-fuzz {", api_fuzzing, "}", - "plugins", "{", "plugin", "dpdk_plugin.so", "{", "disable", "}", - "plugin", "rdma_plugin.so", "{", "disable", "}", - "plugin", "lisp_unittest_plugin.so", "{", "enable", "}", - "plugin", "unittest_plugin.so", "{", "enable", "}" - ] + cls.extra_vpp_plugin_config + ["}", ]) + cls.vpp_cmdline.extend( + ["corelist-workers", ",".join([str(x) for x in cls.cpus[1:]])] + ) + cls.vpp_cmdline.extend( + [ + "}", + "physmem", + "{", + "max-size", + "32m", + "}", + "statseg", + "{", + "socket-name", + cls.get_stats_sock_path(), + cls.extra_vpp_statseg_config, + "}", + "socksvr", + "{", + "socket-name", + cls.get_api_sock_path(), + "}", + "node { ", + default_variant, + "}", + "api-fuzz {", + api_fuzzing, + "}", + "plugins", + "{", + "plugin", + "dpdk_plugin.so", + "{", + "disable", + "}", + "plugin", + "rdma_plugin.so", + "{", + "disable", + "}", + "plugin", + "lisp_unittest_plugin.so", + "{", + "enable", + "}", + "plugin", + "unittest_plugin.so", + "{", + "enable", + "}", + ] + + cls.extra_vpp_plugin_config + + [ + "}", + ] + ) if cls.extra_vpp_punt_config is not None: cls.vpp_cmdline.extend(cls.extra_vpp_punt_config) @@ -435,17 +508,23 @@ class VppTestCase(CPUInterface, unittest.TestCase): print(single_line_delim) print("You can debug VPP using:") if cls.debug_gdbserver: - print(f"sudo gdb {config.vpp} " - f"-ex 'target remote localhost:{cls.gdbserver_port}'") - print("Now is the time to attach gdb by running the above " - "command, set up breakpoints etc., then resume VPP from " - "within gdb by issuing the 'continue' command") + print( + f"sudo gdb {config.vpp} " + f"-ex 'target remote localhost:{cls.gdbserver_port}'" + ) + print( + "Now is the time to attach gdb by running the above " + "command, set up breakpoints etc., then resume VPP from " + "within gdb by issuing the 'continue' command" + ) cls.gdbserver_port += 1 elif cls.debug_gdb: print(f"sudo gdb {config.vpp} -ex 'attach {cls.vpp.pid}'") - print("Now is the time to attach gdb by running the above " - "command and set up breakpoints etc., then resume VPP from" - " within gdb by issuing the 'continue' command") + print( + "Now is the time to attach gdb by running the above " + "command and set up breakpoints etc., then resume VPP from" + " within gdb by issuing the 'continue' command" + ) print(single_line_delim) input("Press ENTER to continue running the testcase...") @@ -459,31 +538,35 @@ class VppTestCase(CPUInterface, unittest.TestCase): cmdline = cls.vpp_cmdline if cls.debug_gdbserver: - gdbserver = '/usr/bin/gdbserver' - if not os.path.isfile(gdbserver) or\ - not os.access(gdbserver, os.X_OK): - raise Exception("gdbserver binary '%s' does not exist or is " - "not executable" % gdbserver) - - cmdline = [gdbserver, 'localhost:{port}' - .format(port=cls.gdbserver_port)] + cls.vpp_cmdline + gdbserver = "/usr/bin/gdbserver" + if not os.path.isfile(gdbserver) or not os.access(gdbserver, os.X_OK): + raise Exception( + "gdbserver binary '%s' does not exist or is " + "not executable" % gdbserver + ) + + cmdline = [ + gdbserver, + "localhost:{port}".format(port=cls.gdbserver_port), + ] + cls.vpp_cmdline cls.logger.info("Gdbserver cmdline is %s", " ".join(cmdline)) try: - cls.vpp = subprocess.Popen(cmdline, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE) + cls.vpp = subprocess.Popen( + cmdline, stdout=subprocess.PIPE, stderr=subprocess.PIPE + ) except subprocess.CalledProcessError as e: - cls.logger.critical("Subprocess returned with non-0 return code: (" - "%s)", e.returncode) + cls.logger.critical( + "Subprocess returned with non-0 return code: (%s)", e.returncode + ) raise except OSError as e: - cls.logger.critical("Subprocess returned with OS error: " - "(%s) %s", e.errno, e.strerror) + cls.logger.critical( + "Subprocess returned with OS error: (%s) %s", e.errno, e.strerror + ) raise except Exception as e: - cls.logger.exception("Subprocess returned unexpected from " - "%s:", cmdline) + cls.logger.exception("Subprocess returned unexpected from %s:", cmdline) raise cls.wait_for_enter() @@ -504,11 +587,11 @@ class VppTestCase(CPUInterface, unittest.TestCase): ok = True break if not ok: - cls.logger.error("Timed out waiting for coredump to complete:" - " %s", corefile) + cls.logger.error( + "Timed out waiting for coredump to complete: %s", corefile + ) else: - cls.logger.error("Coredump complete: %s, size %d", - corefile, curr_size) + cls.logger.error("Coredump complete: %s, size %d", corefile, curr_size) @classmethod def get_stats_sock_path(cls): @@ -554,21 +637,24 @@ class VppTestCase(CPUInterface, unittest.TestCase): super(VppTestCase, cls).setUpClass() cls.logger = get_logger(cls.__name__) random.seed(config.rnd_seed) - if hasattr(cls, 'parallel_handler'): + if hasattr(cls, "parallel_handler"): cls.logger.addHandler(cls.parallel_handler) cls.logger.propagate = False cls.set_debug_flags(config.debug) cls.tempdir = cls.get_tempdir() cls.create_file_handler() cls.file_handler.setFormatter( - Formatter(fmt='%(asctime)s,%(msecs)03d %(message)s', - datefmt="%H:%M:%S")) + Formatter(fmt="%(asctime)s,%(msecs)03d %(message)s", datefmt="%H:%M:%S") + ) cls.file_handler.setLevel(DEBUG) cls.logger.addHandler(cls.file_handler) cls.logger.debug("--- setUpClass() for %s called ---" % cls.__name__) os.chdir(cls.tempdir) - cls.logger.info("Temporary dir is %s, api socket is %s", - cls.tempdir, cls.get_api_sock_path()) + cls.logger.info( + "Temporary dir is %s, api socket is %s", + cls.tempdir, + cls.get_api_sock_path(), + ) cls.logger.debug("Random seed is %s", config.rnd_seed) cls.setUpConstants() cls.reset_packet_infos() @@ -586,9 +672,10 @@ class VppTestCase(CPUInterface, unittest.TestCase): cls.attach_vpp() else: cls.run_vpp() - cls.reporter.send_keep_alive(cls, 'setUpClass') + cls.reporter.send_keep_alive(cls, "setUpClass") VppTestResult.current_test_case_info = TestCaseInfo( - cls.logger, cls.tempdir, cls.vpp.pid, config.vpp) + cls.logger, cls.tempdir, cls.vpp.pid, config.vpp + ) cls.vpp_stdout_deque = deque() cls.vpp_stderr_deque = deque() if not cls.debug_attach: @@ -599,8 +686,7 @@ class VppTestCase(CPUInterface, unittest.TestCase): cls.pump_thread.start() if cls.debug_gdb or cls.debug_gdbserver or cls.debug_attach: cls.vapi_response_timeout = 0 - cls.vapi = VppPapiProvider(cls.__name__, cls, - cls.vapi_response_timeout) + cls.vapi = VppPapiProvider(cls.__name__, cls, cls.vapi_response_timeout) if cls.step: hook = hookmodule.StepHook(cls) else: @@ -613,7 +699,8 @@ class VppTestCase(CPUInterface, unittest.TestCase): cls.vpp_startup_failed = True cls.logger.critical( "VPP died shortly after startup, check the" - " output to standard error for possible cause") + " output to standard error for possible cause" + ) raise try: cls.vapi.connect() @@ -622,9 +709,14 @@ class VppTestCase(CPUInterface, unittest.TestCase): cls.vapi.disconnect() if cls.debug_gdbserver: - print(colorize("You're running VPP inside gdbserver but " - "VPP-API connection failed, did you forget " - "to 'continue' VPP from within gdb?", RED)) + print( + colorize( + "You're running VPP inside gdbserver but " + "VPP-API connection failed, did you forget " + "to 'continue' VPP from within gdb?", + RED, + ) + ) raise e if cls.debug_attach: last_line = cls.vapi.cli("show thread").split("\n")[-2] @@ -641,7 +733,7 @@ class VppTestCase(CPUInterface, unittest.TestCase): @classmethod def _debug_quit(cls): - if (cls.debug_gdbserver or cls.debug_gdb): + if cls.debug_gdbserver or cls.debug_gdb: try: cls.vpp.poll() @@ -650,8 +742,10 @@ class VppTestCase(CPUInterface, unittest.TestCase): print(double_line_delim) print("VPP or GDB server is still running") print(single_line_delim) - input("When done debugging, press ENTER to kill the " - "process and finish running the testcase...") + input( + "When done debugging, press ENTER to kill the " + "process and finish running the testcase..." + ) except AttributeError: pass @@ -663,25 +757,23 @@ class VppTestCase(CPUInterface, unittest.TestCase): cls._debug_quit() # first signal that we want to stop the pump thread, then wake it up - if hasattr(cls, 'pump_thread_stop_flag'): + if hasattr(cls, "pump_thread_stop_flag"): cls.pump_thread_stop_flag.set() - if hasattr(cls, 'pump_thread_wakeup_pipe'): - os.write(cls.pump_thread_wakeup_pipe[1], b'ding dong wake up') - if hasattr(cls, 'pump_thread'): + if hasattr(cls, "pump_thread_wakeup_pipe"): + os.write(cls.pump_thread_wakeup_pipe[1], b"ding dong wake up") + if hasattr(cls, "pump_thread"): cls.logger.debug("Waiting for pump thread to stop") cls.pump_thread.join() - if hasattr(cls, 'vpp_stderr_reader_thread'): + if hasattr(cls, "vpp_stderr_reader_thread"): cls.logger.debug("Waiting for stderr pump to stop") cls.vpp_stderr_reader_thread.join() - if hasattr(cls, 'vpp'): - if hasattr(cls, 'vapi'): + if hasattr(cls, "vpp"): + if hasattr(cls, "vapi"): cls.logger.debug(cls.vapi.vpp.get_stats()) - cls.logger.debug("Disconnecting class vapi client on %s", - cls.__name__) + cls.logger.debug("Disconnecting class vapi client on %s", cls.__name__) cls.vapi.disconnect() - cls.logger.debug("Deleting class vapi attribute on %s", - cls.__name__) + cls.logger.debug("Deleting class vapi attribute on %s", cls.__name__) del cls.vapi cls.vpp.poll() if not cls.debug_attach and cls.vpp.returncode is None: @@ -694,8 +786,7 @@ class VppTestCase(CPUInterface, unittest.TestCase): except subprocess.TimeoutExpired: cls.vpp.kill() outs, errs = cls.vpp.communicate() - cls.logger.debug("Deleting class vpp attribute on %s", - cls.__name__) + cls.logger.debug("Deleting class vpp attribute on %s", cls.__name__) if not cls.debug_attach: cls.vpp.stdout.close() cls.vpp.stderr.close() @@ -708,32 +799,31 @@ class VppTestCase(CPUInterface, unittest.TestCase): stdout_log = cls.logger.info stderr_log = cls.logger.info - if hasattr(cls, 'vpp_stdout_deque'): + if hasattr(cls, "vpp_stdout_deque"): stdout_log(single_line_delim) - stdout_log('VPP output to stdout while running %s:', cls.__name__) + stdout_log("VPP output to stdout while running %s:", cls.__name__) stdout_log(single_line_delim) vpp_output = "".join(cls.vpp_stdout_deque) - with open(cls.tempdir + '/vpp_stdout.txt', 'w') as f: + with open(cls.tempdir + "/vpp_stdout.txt", "w") as f: f.write(vpp_output) - stdout_log('\n%s', vpp_output) + stdout_log("\n%s", vpp_output) stdout_log(single_line_delim) - if hasattr(cls, 'vpp_stderr_deque'): + if hasattr(cls, "vpp_stderr_deque"): stderr_log(single_line_delim) - stderr_log('VPP output to stderr while running %s:', cls.__name__) + stderr_log("VPP output to stderr while running %s:", cls.__name__) stderr_log(single_line_delim) vpp_output = "".join(cls.vpp_stderr_deque) - with open(cls.tempdir + '/vpp_stderr.txt', 'w') as f: + with open(cls.tempdir + "/vpp_stderr.txt", "w") as f: f.write(vpp_output) - stderr_log('\n%s', vpp_output) + stderr_log("\n%s", vpp_output) stderr_log(single_line_delim) @classmethod def tearDownClass(cls): - """ Perform final cleanup after running all tests in this test-case """ - cls.logger.debug("--- tearDownClass() for %s called ---" % - cls.__name__) - cls.reporter.send_keep_alive(cls, 'tearDownClass') + """Perform final cleanup after running all tests in this test-case""" + cls.logger.debug("--- tearDownClass() for %s called ---" % cls.__name__) + cls.reporter.send_keep_alive(cls, "tearDownClass") cls.quit() cls.file_handler.close() cls.reset_packet_infos() @@ -741,14 +831,15 @@ class VppTestCase(CPUInterface, unittest.TestCase): debug_internal.on_tear_down_class(cls) def show_commands_at_teardown(self): - """ Allow subclass specific teardown logging additions.""" + """Allow subclass specific teardown logging additions.""" self.logger.info("--- No test specific show commands provided. ---") def tearDown(self): - """ Show various debug prints after each test """ - self.logger.debug("--- tearDown() for %s.%s(%s) called ---" % - (self.__class__.__name__, self._testMethodName, - self._testMethodDoc)) + """Show various debug prints after each test""" + self.logger.debug( + "--- tearDown() for %s.%s(%s) called ---" + % (self.__class__.__name__, self._testMethodName, self._testMethodDoc) + ) try: if not self.vpp_dead: @@ -769,32 +860,35 @@ class VppTestCase(CPUInterface, unittest.TestCase): tmp_api_trace = "/tmp/%s" % api_trace vpp_api_trace_log = "%s/%s" % (self.tempdir, api_trace) self.logger.info(self.vapi.ppcli("api trace save %s" % api_trace)) - self.logger.info("Moving %s to %s\n" % (tmp_api_trace, - vpp_api_trace_log)) + self.logger.info("Moving %s to %s\n" % (tmp_api_trace, vpp_api_trace_log)) os.rename(tmp_api_trace, vpp_api_trace_log) except VppTransportSocketIOError: - self.logger.debug("VppTransportSocketIOError: Vpp dead. " - "Cannot log show commands.") + self.logger.debug( + "VppTransportSocketIOError: Vpp dead. Cannot log show commands." + ) self.vpp_dead = True else: self.registry.unregister_all(self.logger) def setUp(self): - """ Clear trace before running each test""" + """Clear trace before running each test""" super(VppTestCase, self).setUp() self.reporter.send_keep_alive(self) if self.vpp_dead: - raise VppDiedError(rv=None, testcase=self.__class__.__name__, - method_name=self._testMethodName) - self.sleep(.1, "during setUp") + raise VppDiedError( + rv=None, + testcase=self.__class__.__name__, + method_name=self._testMethodName, + ) + self.sleep(0.1, "during setUp") self.vpp_stdout_deque.append( - "--- test setUp() for %s.%s(%s) starts here ---\n" % - (self.__class__.__name__, self._testMethodName, - self._testMethodDoc)) + "--- test setUp() for %s.%s(%s) starts here ---\n" + % (self.__class__.__name__, self._testMethodName, self._testMethodDoc) + ) self.vpp_stderr_deque.append( - "--- test setUp() for %s.%s(%s) starts here ---\n" % - (self.__class__.__name__, self._testMethodName, - self._testMethodDoc)) + "--- test setUp() for %s.%s(%s) starts here ---\n" + % (self.__class__.__name__, self._testMethodName, self._testMethodDoc) + ) self.vapi.cli("clear trace") # store the test instance inside the test class - so that objects # holding the class can access instance methods (like assertEqual) @@ -816,7 +910,7 @@ class VppTestCase(CPUInterface, unittest.TestCase): @classmethod def register_pcap(cls, intf, worker): - """ Register a pcap in the testclass """ + """Register a pcap in the testclass""" # add to the list of captures with current timestamp cls._pcaps.append((intf, worker)) @@ -824,14 +918,14 @@ class VppTestCase(CPUInterface, unittest.TestCase): def get_vpp_time(cls): # processes e.g. "Time now 2.190522, Wed, 11 Mar 2020 17:29:54 GMT" # returns float("2.190522") - timestr = cls.vapi.cli('show clock') - head, sep, tail = timestr.partition(',') - head, sep, tail = head.partition('Time now') + timestr = cls.vapi.cli("show clock") + head, sep, tail = timestr.partition(",") + head, sep, tail = head.partition("Time now") return float(tail) @classmethod def sleep_on_vpp_time(cls, sec): - """ Sleep according to time in VPP world """ + """Sleep according to time in VPP world""" # On a busy system with many processes # we might end up with VPP time being slower than real world # So take that into account when waiting for VPP to do something @@ -841,34 +935,31 @@ class VppTestCase(CPUInterface, unittest.TestCase): @classmethod def pg_start(cls, trace=True): - """ Enable the PG, wait till it is done, then clean up """ + """Enable the PG, wait till it is done, then clean up""" for (intf, worker) in cls._old_pcaps: - intf.handle_old_pcap_file(intf.get_in_path(worker), - intf.in_history_counter) + intf.handle_old_pcap_file(intf.get_in_path(worker), intf.in_history_counter) cls._old_pcaps = [] if trace: cls.vapi.cli("clear trace") cls.vapi.cli("trace add pg-input 1000") - cls.vapi.cli('packet-generator enable') + cls.vapi.cli("packet-generator enable") # PG, when starts, runs to completion - # so let's avoid a race condition, # and wait a little till it's done. # Then clean it up - and then be gone. deadline = time.time() + 300 - while cls.vapi.cli('show packet-generator').find("Yes") != -1: + while cls.vapi.cli("show packet-generator").find("Yes") != -1: cls.sleep(0.01) # yield if time.time() > deadline: cls.logger.error("Timeout waiting for pg to stop") break for intf, worker in cls._pcaps: - cls.vapi.cli('packet-generator delete %s' % - intf.get_cap_name(worker)) + cls.vapi.cli("packet-generator delete %s" % intf.get_cap_name(worker)) cls._old_pcaps = cls._pcaps cls._pcaps = [] @classmethod - def create_pg_interfaces_internal(cls, interfaces, gso=0, gso_size=0, - mode=None): + def create_pg_interfaces_internal(cls, interfaces, gso=0, gso_size=0, mode=None): """ Create packet-generator interfaces. @@ -887,26 +978,30 @@ class VppTestCase(CPUInterface, unittest.TestCase): @classmethod def create_pg_ip4_interfaces(cls, interfaces, gso=0, gso_size=0): pgmode = VppEnum.vl_api_pg_interface_mode_t - return cls.create_pg_interfaces_internal(interfaces, gso, gso_size, - pgmode.PG_API_MODE_IP4) + return cls.create_pg_interfaces_internal( + interfaces, gso, gso_size, pgmode.PG_API_MODE_IP4 + ) @classmethod def create_pg_ip6_interfaces(cls, interfaces, gso=0, gso_size=0): pgmode = VppEnum.vl_api_pg_interface_mode_t - return cls.create_pg_interfaces_internal(interfaces, gso, gso_size, - pgmode.PG_API_MODE_IP6) + return cls.create_pg_interfaces_internal( + interfaces, gso, gso_size, pgmode.PG_API_MODE_IP6 + ) @classmethod def create_pg_interfaces(cls, interfaces, gso=0, gso_size=0): pgmode = VppEnum.vl_api_pg_interface_mode_t - return cls.create_pg_interfaces_internal(interfaces, gso, gso_size, - pgmode.PG_API_MODE_ETHERNET) + return cls.create_pg_interfaces_internal( + interfaces, gso, gso_size, pgmode.PG_API_MODE_ETHERNET + ) @classmethod def create_pg_ethernet_interfaces(cls, interfaces, gso=0, gso_size=0): pgmode = VppEnum.vl_api_pg_interface_mode_t - return cls.create_pg_interfaces_internal(interfaces, gso, gso_size, - pgmode.PG_API_MODE_ETHERNET) + return cls.create_pg_interfaces_internal( + interfaces, gso, gso_size, pgmode.PG_API_MODE_ETHERNET + ) @classmethod def create_loopback_interfaces(cls, count): @@ -937,7 +1032,7 @@ class VppTestCase(CPUInterface, unittest.TestCase): return result @staticmethod - def extend_packet(packet, size, padding=' '): + def extend_packet(packet, size, padding=" "): """ Extend packet to given size by padding with spaces or custom padding NOTE: Currently works only when Raw layer is present. @@ -955,7 +1050,7 @@ class VppTestCase(CPUInterface, unittest.TestCase): @classmethod def reset_packet_infos(cls): - """ Reset the list of packet info objects and packet counts to zero """ + """Reset the list of packet info objects and packet counts to zero""" cls._packet_infos = {} cls._packet_count_for_dst_if_idx = {} @@ -997,11 +1092,10 @@ class VppTestCase(CPUInterface, unittest.TestCase): """ # retrieve payload, currently 18 bytes (4 x ints + 1 short) - return pack('iiiih', info.index, info.src, - info.dst, info.ip, info.proto) + return pack("iiiih", info.index, info.src, info.dst, info.ip, info.proto) @staticmethod - def payload_to_info(payload, payload_field='load'): + def payload_to_info(payload, payload_field="load"): """ Convert packet payload to _PacketInfo object @@ -1018,12 +1112,11 @@ class VppTestCase(CPUInterface, unittest.TestCase): payload_b = getattr(payload, payload_field)[:18] info = _PacketInfo() - info.index, info.src, info.dst, info.ip, info.proto \ - = unpack('iiiih', payload_b) + info.index, info.src, info.dst, info.ip, info.proto = unpack("iiiih", payload_b) # some SRv6 TCs depend on get an exception if bad values are detected if info.index > 0x4000: - raise ValueError('Index value is invalid') + raise ValueError("Index value is invalid") return info @@ -1086,32 +1179,38 @@ class VppTestCase(CPUInterface, unittest.TestCase): return try: msg = "Invalid %s: %d('%s') does not match expected value %d('%s')" - msg = msg % (getdoc(name_or_class).strip(), - real_value, str(name_or_class(real_value)), - expected_value, str(name_or_class(expected_value))) + msg = msg % ( + getdoc(name_or_class).strip(), + real_value, + str(name_or_class(real_value)), + expected_value, + str(name_or_class(expected_value)), + ) except Exception: msg = "Invalid %s: %s does not match expected value %s" % ( - name_or_class, real_value, expected_value) + name_or_class, + real_value, + expected_value, + ) self.assertEqual(real_value, expected_value, msg) - def assert_in_range(self, - real_value, - expected_min, - expected_max, - name=None): + def assert_in_range(self, real_value, expected_min, expected_max, name=None): if name is None: msg = None else: msg = "Invalid %s: %s out of range <%s,%s>" % ( - name, real_value, expected_min, expected_max) + name, + real_value, + expected_min, + expected_max, + ) self.assertTrue(expected_min <= real_value <= expected_max, msg) - def assert_packet_checksums_valid(self, packet, - ignore_zero_udp_checksums=True): + def assert_packet_checksums_valid(self, packet, ignore_zero_udp_checksums=True): received = packet.__class__(scapy.compat.raw(packet)) - udp_layers = ['UDP', 'UDPerror'] - checksum_fields = ['cksum', 'chksum'] + udp_layers = ["UDP", "UDPerror"] + checksum_fields = ["cksum", "chksum"] checksums = [] counter = 0 temp = received.__class__(scapy.compat.raw(received)) @@ -1122,9 +1221,11 @@ class VppTestCase(CPUInterface, unittest.TestCase): layer.remove_payload() for cf in checksum_fields: if hasattr(layer, cf): - if ignore_zero_udp_checksums and \ - 0 == getattr(layer, cf) and \ - layer.name in udp_layers: + if ( + ignore_zero_udp_checksums + and 0 == getattr(layer, cf) + and layer.name in udp_layers + ): continue delattr(temp.getlayer(counter), cf) checksums.append((counter, cf)) @@ -1137,71 +1238,76 @@ class VppTestCase(CPUInterface, unittest.TestCase): for layer, cf in checksums: calc_sum = getattr(temp[layer], cf) self.assert_equal( - getattr(received[layer], cf), calc_sum, - "packet checksum on layer #%d: %s" % (layer, temp[layer].name)) + getattr(received[layer], cf), + calc_sum, + "packet checksum on layer #%d: %s" % (layer, temp[layer].name), + ) self.logger.debug( - "Checksum field `%s` on `%s` layer has correct value `%s`" % - (cf, temp[layer].name, calc_sum)) - - def assert_checksum_valid(self, received_packet, layer, - field_name='chksum', - ignore_zero_checksum=False): - """ Check checksum of received packet on given layer """ + "Checksum field `%s` on `%s` layer has correct value `%s`" + % (cf, temp[layer].name, calc_sum) + ) + + def assert_checksum_valid( + self, received_packet, layer, field_name="chksum", ignore_zero_checksum=False + ): + """Check checksum of received packet on given layer""" received_packet_checksum = getattr(received_packet[layer], field_name) if ignore_zero_checksum and 0 == received_packet_checksum: return - recalculated = received_packet.__class__( - scapy.compat.raw(received_packet)) + recalculated = received_packet.__class__(scapy.compat.raw(received_packet)) delattr(recalculated[layer], field_name) recalculated = recalculated.__class__(scapy.compat.raw(recalculated)) - self.assert_equal(received_packet_checksum, - getattr(recalculated[layer], field_name), - "packet checksum on layer: %s" % layer) - - def assert_ip_checksum_valid(self, received_packet, - ignore_zero_checksum=False): - self.assert_checksum_valid(received_packet, 'IP', - ignore_zero_checksum=ignore_zero_checksum) - - def assert_tcp_checksum_valid(self, received_packet, - ignore_zero_checksum=False): - self.assert_checksum_valid(received_packet, 'TCP', - ignore_zero_checksum=ignore_zero_checksum) - - def assert_udp_checksum_valid(self, received_packet, - ignore_zero_checksum=True): - self.assert_checksum_valid(received_packet, 'UDP', - ignore_zero_checksum=ignore_zero_checksum) + self.assert_equal( + received_packet_checksum, + getattr(recalculated[layer], field_name), + "packet checksum on layer: %s" % layer, + ) + + def assert_ip_checksum_valid(self, received_packet, ignore_zero_checksum=False): + self.assert_checksum_valid( + received_packet, "IP", ignore_zero_checksum=ignore_zero_checksum + ) + + def assert_tcp_checksum_valid(self, received_packet, ignore_zero_checksum=False): + self.assert_checksum_valid( + received_packet, "TCP", ignore_zero_checksum=ignore_zero_checksum + ) + + def assert_udp_checksum_valid(self, received_packet, ignore_zero_checksum=True): + self.assert_checksum_valid( + received_packet, "UDP", ignore_zero_checksum=ignore_zero_checksum + ) def assert_embedded_icmp_checksum_valid(self, received_packet): if received_packet.haslayer(IPerror): - self.assert_checksum_valid(received_packet, 'IPerror') + self.assert_checksum_valid(received_packet, "IPerror") if received_packet.haslayer(TCPerror): - self.assert_checksum_valid(received_packet, 'TCPerror') + self.assert_checksum_valid(received_packet, "TCPerror") if received_packet.haslayer(UDPerror): - self.assert_checksum_valid(received_packet, 'UDPerror', - ignore_zero_checksum=True) + self.assert_checksum_valid( + received_packet, "UDPerror", ignore_zero_checksum=True + ) if received_packet.haslayer(ICMPerror): - self.assert_checksum_valid(received_packet, 'ICMPerror') + self.assert_checksum_valid(received_packet, "ICMPerror") def assert_icmp_checksum_valid(self, received_packet): - self.assert_checksum_valid(received_packet, 'ICMP') + self.assert_checksum_valid(received_packet, "ICMP") self.assert_embedded_icmp_checksum_valid(received_packet) def assert_icmpv6_checksum_valid(self, pkt): if pkt.haslayer(ICMPv6DestUnreach): - self.assert_checksum_valid(pkt, 'ICMPv6DestUnreach', 'cksum') + self.assert_checksum_valid(pkt, "ICMPv6DestUnreach", "cksum") self.assert_embedded_icmp_checksum_valid(pkt) if pkt.haslayer(ICMPv6EchoRequest): - self.assert_checksum_valid(pkt, 'ICMPv6EchoRequest', 'cksum') + self.assert_checksum_valid(pkt, "ICMPv6EchoRequest", "cksum") if pkt.haslayer(ICMPv6EchoReply): - self.assert_checksum_valid(pkt, 'ICMPv6EchoReply', 'cksum') + self.assert_checksum_valid(pkt, "ICMPv6EchoReply", "cksum") def get_counter(self, counter): if counter.startswith("/"): counter_value = self.statistics.get_counter(counter) else: - counters = self.vapi.cli("sh errors").split('\n') + counters = self.vapi.cli("sh errors").split("\n") counter_value = 0 for i in range(1, len(counters) - 1): results = counters[i].split() @@ -1210,8 +1316,7 @@ class VppTestCase(CPUInterface, unittest.TestCase): break return counter_value - def assert_counter_equal(self, counter, expected_value, - thread=None, index=0): + def assert_counter_equal(self, counter, expected_value, thread=None, index=0): c = self.get_counter(counter) if thread is not None: c = c[thread][index] @@ -1221,13 +1326,13 @@ class VppTestCase(CPUInterface, unittest.TestCase): def assert_packet_counter_equal(self, counter, expected_value): counter_value = self.get_counter(counter) - self.assert_equal(counter_value, expected_value, - "packet counter `%s'" % counter) + self.assert_equal( + counter_value, expected_value, "packet counter `%s'" % counter + ) def assert_error_counter_equal(self, counter, expected_value): counter_value = self.statistics[counter].sum() - self.assert_equal(counter_value, expected_value, - "error counter `%s'" % counter) + self.assert_equal(counter_value, expected_value, "error counter `%s'" % counter) @classmethod def sleep(cls, timeout, remark=None): @@ -1238,7 +1343,7 @@ class VppTestCase(CPUInterface, unittest.TestCase): # https://github.com/python/cpython/blob/6673decfa0fb078f60587f5cb5e98460eea137c2/Modules/timemodule.c#L1892 # noqa if timeout == 0: # yield quantum - if hasattr(os, 'sched_yield'): + if hasattr(os, "sched_yield"): os.sched_yield() else: time.sleep(0) @@ -1249,13 +1354,18 @@ class VppTestCase(CPUInterface, unittest.TestCase): time.sleep(timeout) after = time.time() if after - before > 2 * timeout: - cls.logger.error("unexpected self.sleep() result - " - "slept for %es instead of ~%es!", - after - before, timeout) + cls.logger.error( + "unexpected self.sleep() result - slept for %es instead of ~%es!", + after - before, + timeout, + ) cls.logger.debug( "Finished sleep (%s) - slept %es (wanted %es)", - remark, after - before, timeout) + remark, + after - before, + timeout, + ) def virtual_sleep(self, timeout, remark=None): self.logger.debug("Moving VPP time by %s (%s)", timeout, remark) @@ -1285,7 +1395,8 @@ class VppTestCase(CPUInterface, unittest.TestCase): stats_snapshot[cntr].sum() + diff, f"'{cntr}' counter value (previous value: " f"{stats_snapshot[cntr].sum()}, " - f"expected diff: {diff})") + f"expected diff: {diff})", + ) else: try: self.assert_equal( @@ -1293,7 +1404,8 @@ class VppTestCase(CPUInterface, unittest.TestCase): stats_snapshot[cntr][:, sw_if_index].sum() + diff, f"'{cntr}' counter value (previous value: " f"{stats_snapshot[cntr][:, sw_if_index].sum()}, " - f"expected diff: {diff})") + f"expected diff: {diff})", + ) except IndexError: # if diff is 0, then this most probably a case where # test declares multiple interfaces but traffic hasn't @@ -1302,8 +1414,9 @@ class VppTestCase(CPUInterface, unittest.TestCase): if 0 != diff: raise - def send_and_assert_no_replies(self, intf, pkts, remark="", timeout=None, - stats_diff=None, trace=True, msg=None): + def send_and_assert_no_replies( + self, intf, pkts, remark="", timeout=None, stats_diff=None, trace=True, msg=None + ): if stats_diff: stats_snapshot = self.snapshot_stats(stats_diff) @@ -1324,8 +1437,17 @@ class VppTestCase(CPUInterface, unittest.TestCase): if stats_diff: self.compare_stats_with_snapshot(stats_diff, stats_snapshot) - def send_and_expect(self, intf, pkts, output, n_rx=None, worker=None, - trace=True, msg=None, stats_diff=None): + def send_and_expect( + self, + intf, + pkts, + output, + n_rx=None, + worker=None, + trace=True, + msg=None, + stats_diff=None, + ): if stats_diff: stats_snapshot = self.snapshot_stats(stats_diff) @@ -1343,8 +1465,9 @@ class VppTestCase(CPUInterface, unittest.TestCase): return rx - def send_and_expect_load_balancing(self, input, pkts, outputs, - worker=None, trace=True): + def send_and_expect_load_balancing( + self, input, pkts, outputs, worker=None, trace=True + ): self.pg_send(input, pkts, worker=worker, trace=trace) rxs = [] for oo in outputs: @@ -1355,9 +1478,7 @@ class VppTestCase(CPUInterface, unittest.TestCase): self.logger.debug(self.vapi.cli("show trace")) return rxs - def send_and_expect_some(self, intf, pkts, output, - worker=None, - trace=True): + def send_and_expect_some(self, intf, pkts, output, worker=None, trace=True): self.pg_send(intf, pkts, worker=worker, trace=trace) rx = output._get_capture(1) if trace: @@ -1366,8 +1487,7 @@ class VppTestCase(CPUInterface, unittest.TestCase): self.assertTrue(len(rx) < len(pkts)) return rx - def send_and_expect_only(self, intf, pkts, output, timeout=None, - stats_diff=None): + def send_and_expect_only(self, intf, pkts, output, timeout=None, stats_diff=None): if stats_diff: stats_snapshot = self.snapshot_stats(stats_diff) @@ -1427,8 +1547,7 @@ class VppTestResult(unittest.TestResult): core_crash_test_cases_info = set() current_test_case_info = None - def __init__(self, stream=None, descriptions=None, verbosity=None, - runner=None): + def __init__(self, stream=None, descriptions=None, verbosity=None, runner=None): """ :param stream File descriptor to store where to report test results. Set to the standard error stream by default. @@ -1453,9 +1572,9 @@ class VppTestResult(unittest.TestResult): """ if self.current_test_case_info: self.current_test_case_info.logger.debug( - "--- addSuccess() %s.%s(%s) called" % (test.__class__.__name__, - test._testMethodName, - test._testMethodDoc)) + "--- addSuccess() %s.%s(%s) called" + % (test.__class__.__name__, test._testMethodName, test._testMethodDoc) + ) unittest.TestResult.addSuccess(self, test) self.result_string = colorize("OK", GREEN) @@ -1471,9 +1590,14 @@ class VppTestResult(unittest.TestResult): """ if self.current_test_case_info: self.current_test_case_info.logger.debug( - "--- addSkip() %s.%s(%s) called, reason is %s" % - (test.__class__.__name__, test._testMethodName, - test._testMethodDoc, reason)) + "--- addSkip() %s.%s(%s) called, reason is %s" + % ( + test.__class__.__name__, + test._testMethodName, + test._testMethodDoc, + reason, + ) + ) unittest.TestResult.addSkip(self, test, reason) self.result_string = colorize("SKIP", YELLOW) @@ -1488,17 +1612,18 @@ class VppTestResult(unittest.TestResult): failed_dir = config.failed_dir link_path = os.path.join( failed_dir, - '%s-FAILED' % - os.path.basename(self.current_test_case_info.tempdir)) + "%s-FAILED" % os.path.basename(self.current_test_case_info.tempdir), + ) self.current_test_case_info.logger.debug( - "creating a link to the failed test") + "creating a link to the failed test" + ) self.current_test_case_info.logger.debug( - "os.symlink(%s, %s)" % - (self.current_test_case_info.tempdir, link_path)) + "os.symlink(%s, %s)" + % (self.current_test_case_info.tempdir, link_path) + ) if os.path.exists(link_path): - self.current_test_case_info.logger.debug( - 'symlink already exists') + self.current_test_case_info.logger.debug("symlink already exists") else: os.symlink(self.current_test_case_info.tempdir, link_path) @@ -1506,7 +1631,7 @@ class VppTestResult(unittest.TestResult): self.current_test_case_info.logger.error(e) def send_result_through_pipe(self, test, result): - if hasattr(self, 'test_framework_result_pipe'): + if hasattr(self, "test_framework_result_pipe"): pipe = self.test_framework_result_pipe if pipe: pipe.send((test.id(), result)) @@ -1516,32 +1641,37 @@ class VppTestResult(unittest.TestResult): if isinstance(test, unittest.suite._ErrorHolder): test_name = test.description else: - test_name = '%s.%s(%s)' % (test.__class__.__name__, - test._testMethodName, - test._testMethodDoc) + test_name = "%s.%s(%s)" % ( + test.__class__.__name__, + test._testMethodName, + test._testMethodDoc, + ) self.current_test_case_info.logger.debug( - "--- %s() %s called, err is %s" % - (fn_name, test_name, err)) + "--- %s() %s called, err is %s" % (fn_name, test_name, err) + ) self.current_test_case_info.logger.debug( - "formatted exception is:\n%s" % - "".join(format_exception(*err))) + "formatted exception is:\n%s" % "".join(format_exception(*err)) + ) def add_error(self, test, err, unittest_fn, error_type): if error_type == FAIL: - self.log_error(test, err, 'addFailure') + self.log_error(test, err, "addFailure") error_type_str = colorize("FAIL", RED) elif error_type == ERROR: - self.log_error(test, err, 'addError') + self.log_error(test, err, "addError") error_type_str = colorize("ERROR", RED) else: - raise Exception('Error type %s cannot be used to record an ' - 'error or a failure' % error_type) + raise Exception( + "Error type %s cannot be used to record an " + "error or a failure" % error_type + ) unittest_fn(self, test, err) if self.current_test_case_info: - self.result_string = "%s [ temp dir used by test case: %s ]" % \ - (error_type_str, - self.current_test_case_info.tempdir) + self.result_string = "%s [ temp dir used by test case: %s ]" % ( + error_type_str, + self.current_test_case_info.tempdir, + ) self.symlink_failed() self.failed_test_cases_info.add(self.current_test_case_info) if is_core_present(self.current_test_case_info.tempdir): @@ -1550,12 +1680,12 @@ class VppTestResult(unittest.TestResult): test_name = str(test) else: test_name = "'{!s}' ({!s})".format( - get_testcase_doc_name(test), test.id()) + get_testcase_doc_name(test), test.id() + ) self.current_test_case_info.core_crash_test = test_name - self.core_crash_test_cases_info.add( - self.current_test_case_info) + self.core_crash_test_cases_info.add(self.current_test_case_info) else: - self.result_string = '%s [no temp dir]' % error_type_str + self.result_string = "%s [no temp dir]" % error_type_str self.send_result_through_pipe(test, error_type) @@ -1613,15 +1743,13 @@ class VppTestResult(unittest.TestResult): # This block may overwrite the colorized title above, # but we want this to stand out and be fixed if test.has_tag(TestCaseTag.FIXME_VPP_WORKERS): - test_title = colorize( - f"FIXME with VPP workers: {test_title}", RED) + test_title = colorize(f"FIXME with VPP workers: {test_title}", RED) if test.has_tag(TestCaseTag.FIXME_ASAN): - test_title = colorize( - f"FIXME with ASAN: {test_title}", RED) + test_title = colorize(f"FIXME with ASAN: {test_title}", RED) test.skip_fixme_asan() - if hasattr(test, 'vpp_worker_count'): + if hasattr(test, "vpp_worker_count"): if test.vpp_worker_count == 0: test_title += " [main thread only]" elif test.vpp_worker_count == 1: @@ -1633,7 +1761,9 @@ class VppTestResult(unittest.TestResult): test_title = colorize( f"{test_title} [skipped - not enough cpus, " f"required={test.__class__.get_cpus_required()}, " - f"available={max_vpp_cpus}]", YELLOW) + f"available={max_vpp_cpus}]", + YELLOW, + ) print(double_line_delim) print(test_title) @@ -1644,8 +1774,7 @@ class VppTestResult(unittest.TestResult): self.start_test = time.time() unittest.TestResult.startTest(self, test) if self.verbosity > 0: - self.stream.writeln( - "Starting " + self.getDescription(test) + " ...") + self.stream.writeln("Starting " + self.getDescription(test) + " ...") self.stream.writeln(single_line_delim) def stopTest(self, test): @@ -1659,14 +1788,19 @@ class VppTestResult(unittest.TestResult): if self.verbosity > 0: self.stream.writeln(single_line_delim) - self.stream.writeln("%-73s%s" % (self.getDescription(test), - self.result_string)) + self.stream.writeln( + "%-73s%s" % (self.getDescription(test), self.result_string) + ) self.stream.writeln(single_line_delim) else: - self.stream.writeln("%-68s %4.2f %s" % - (self.getDescription(test), - time.time() - self.start_test, - self.result_string)) + self.stream.writeln( + "%-68s %4.2f %s" + % ( + self.getDescription(test), + time.time() - self.start_test, + self.result_string, + ) + ) self.send_result_through_pipe(test, TEST_RUN) @@ -1676,12 +1810,12 @@ class VppTestResult(unittest.TestResult): """ if len(self.errors) > 0 or len(self.failures) > 0: self.stream.writeln() - self.printErrorList('ERROR', self.errors) - self.printErrorList('FAIL', self.failures) + self.printErrorList("ERROR", self.errors) + self.printErrorList("FAIL", self.failures) # ^^ that is the last output from unittest before summary if not self.runner.print_summary: - devnull = unittest.runner._WritelnDecorator(open(os.devnull, 'w')) + devnull = unittest.runner._WritelnDecorator(open(os.devnull, "w")) self.stream = devnull self.runner.stream = devnull @@ -1696,8 +1830,7 @@ class VppTestResult(unittest.TestResult): """ for test, err in errors: self.stream.writeln(double_line_delim) - self.stream.writeln("%s: %s" % - (flavour, self.getDescription(test))) + self.stream.writeln("%s: %s" % (flavour, self.getDescription(test))) self.stream.writeln(single_line_delim) self.stream.writeln("%s" % err) @@ -1712,14 +1845,23 @@ class VppTestRunner(unittest.TextTestRunner): """Class maintaining the results of the tests""" return VppTestResult - def __init__(self, keep_alive_pipe=None, descriptions=True, verbosity=1, - result_pipe=None, failfast=False, buffer=False, - resultclass=None, print_summary=True, **kwargs): + def __init__( + self, + keep_alive_pipe=None, + descriptions=True, + verbosity=1, + result_pipe=None, + failfast=False, + buffer=False, + resultclass=None, + print_summary=True, + **kwargs, + ): # ignore stream setting here, use hard-coded stdout to be in sync # with prints from VppTestCase methods ... - super(VppTestRunner, self).__init__(sys.stdout, descriptions, - verbosity, failfast, buffer, - resultclass, **kwargs) + super(VppTestRunner, self).__init__( + sys.stdout, descriptions, verbosity, failfast, buffer, resultclass, **kwargs + ) KeepAliveReporter.pipe = keep_alive_pipe self.orig_stream = self.stream @@ -1728,10 +1870,7 @@ class VppTestRunner(unittest.TextTestRunner): self.print_summary = print_summary def _makeResult(self): - return self.resultclass(self.stream, - self.descriptions, - self.verbosity, - self) + return self.resultclass(self.stream, self.descriptions, self.verbosity, self) def run(self, test): """ @@ -1754,91 +1893,120 @@ class Worker(Thread): super(Worker, self).__init__(*args, **kwargs) self.logger = logger self.args = executable_args - if hasattr(self, 'testcase') and self.testcase.debug_all: + if hasattr(self, "testcase") and self.testcase.debug_all: if self.testcase.debug_gdbserver: - self.args = ['/usr/bin/gdbserver', 'localhost:{port}' - .format(port=self.testcase.gdbserver_port)] + args - elif self.testcase.debug_gdb and hasattr(self, 'wait_for_gdb'): + self.args = [ + "/usr/bin/gdbserver", + "localhost:{port}".format(port=self.testcase.gdbserver_port), + ] + args + elif self.testcase.debug_gdb and hasattr(self, "wait_for_gdb"): self.args.append(self.wait_for_gdb) self.app_bin = executable_args[0] self.app_name = os.path.basename(self.app_bin) - if hasattr(self, 'role'): - self.app_name += ' {role}'.format(role=self.role) + if hasattr(self, "role"): + self.app_name += " {role}".format(role=self.role) self.process = None self.result = None env = {} if env is None else env self.env = copy.deepcopy(env) def wait_for_enter(self): - if not hasattr(self, 'testcase'): + if not hasattr(self, "testcase"): return if self.testcase.debug_all and self.testcase.debug_gdbserver: print() print(double_line_delim) - print("Spawned GDB Server for '{app}' with PID: {pid}" - .format(app=self.app_name, pid=self.process.pid)) + print( + "Spawned GDB Server for '{app}' with PID: {pid}".format( + app=self.app_name, pid=self.process.pid + ) + ) elif self.testcase.debug_all and self.testcase.debug_gdb: print() print(double_line_delim) - print("Spawned '{app}' with PID: {pid}" - .format(app=self.app_name, pid=self.process.pid)) + print( + "Spawned '{app}' with PID: {pid}".format( + app=self.app_name, pid=self.process.pid + ) + ) else: return print(single_line_delim) print("You can debug '{app}' using:".format(app=self.app_name)) if self.testcase.debug_gdbserver: - print("sudo gdb " + self.app_bin + - " -ex 'target remote localhost:{port}'" - .format(port=self.testcase.gdbserver_port)) - print("Now is the time to attach gdb by running the above " - "command, set up breakpoints etc., then resume from " - "within gdb by issuing the 'continue' command") + print( + "sudo gdb " + + self.app_bin + + " -ex 'target remote localhost:{port}'".format( + port=self.testcase.gdbserver_port + ) + ) + print( + "Now is the time to attach gdb by running the above " + "command, set up breakpoints etc., then resume from " + "within gdb by issuing the 'continue' command" + ) self.testcase.gdbserver_port += 1 elif self.testcase.debug_gdb: - print("sudo gdb " + self.app_bin + - " -ex 'attach {pid}'".format(pid=self.process.pid)) - print("Now is the time to attach gdb by running the above " - "command and set up breakpoints etc., then resume from" - " within gdb by issuing the 'continue' command") + print( + "sudo gdb " + + self.app_bin + + " -ex 'attach {pid}'".format(pid=self.process.pid) + ) + print( + "Now is the time to attach gdb by running the above " + "command and set up breakpoints etc., then resume from" + " within gdb by issuing the 'continue' command" + ) print(single_line_delim) input("Press ENTER to continue running the testcase...") def run(self): executable = self.args[0] if not os.path.exists(executable) or not os.access( - executable, os.F_OK | os.X_OK): + executable, os.F_OK | os.X_OK + ): # Exit code that means some system file did not exist, # could not be opened, or had some other kind of error. self.result = os.EX_OSFILE raise EnvironmentError( - "executable '%s' is not found or executable." % executable) - self.logger.debug("Running executable '{app}': '{cmd}'" - .format(app=self.app_name, - cmd=' '.join(self.args))) + "executable '%s' is not found or executable." % executable + ) + self.logger.debug( + "Running executable '{app}': '{cmd}'".format( + app=self.app_name, cmd=" ".join(self.args) + ) + ) env = os.environ.copy() env.update(self.env) env["CK_LOG_FILE_NAME"] = "-" self.process = subprocess.Popen( - ['stdbuf', '-o0', '-e0'] + self.args, shell=False, env=env, - preexec_fn=os.setpgrp, stdout=subprocess.PIPE, - stderr=subprocess.PIPE) + ["stdbuf", "-o0", "-e0"] + self.args, + shell=False, + env=env, + preexec_fn=os.setpgrp, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) self.wait_for_enter() out, err = self.process.communicate() self.logger.debug("Finished running `{app}'".format(app=self.app_name)) self.logger.info("Return code is `%s'" % self.process.returncode) self.logger.info(single_line_delim) - self.logger.info("Executable `{app}' wrote to stdout:" - .format(app=self.app_name)) + self.logger.info( + "Executable `{app}' wrote to stdout:".format(app=self.app_name) + ) self.logger.info(single_line_delim) - self.logger.info(out.decode('utf-8')) + self.logger.info(out.decode("utf-8")) self.logger.info(single_line_delim) - self.logger.info("Executable `{app}' wrote to stderr:" - .format(app=self.app_name)) + self.logger.info( + "Executable `{app}' wrote to stderr:".format(app=self.app_name) + ) self.logger.info(single_line_delim) - self.logger.info(err.decode('utf-8')) + self.logger.info(err.decode("utf-8")) self.logger.info(single_line_delim) self.result = self.process.returncode -if __name__ == '__main__': +if __name__ == "__main__": pass diff --git a/test/hook.py b/test/hook.py index 8033c9355cb..3429bdad1fe 100644 --- a/test/hook.py +++ b/test/hook.py @@ -33,19 +33,20 @@ class Hook: if not isinstance(val, str): return val if len(val) == 6: - return '{!s} ({!s})'.format(val, ':'.join(['{:02x}'.format( - scapy.compat.orb(x)) for x in val])) + return "{!s} ({!s})".format( + val, ":".join(["{:02x}".format(scapy.compat.orb(x)) for x in val]) + ) try: # we don't call test_type(val) because it is a packed value. - return '{!s} ({!s})'.format(val, str( - ipaddress.ip_address(val))) + return "{!s} ({!s})".format(val, str(ipaddress.ip_address(val))) except ValueError: return val - _args = ', '.join("{!s}={!r}".format(key, _friendly_format(val)) for - (key, val) in api_args.items()) - self.logger.debug("API: %s (%s)" % - (api_name, _args), extra={'color': RED}) + _args = ", ".join( + "{!s}={!r}".format(key, _friendly_format(val)) + for (key, val) in api_args.items() + ) + self.logger.debug("API: %s (%s)" % (api_name, _args), extra={"color": RED}) def after_api(self, api_name, api_args): """ @@ -63,7 +64,7 @@ class Hook: @param cli: CLI string """ - self.logger.debug("CLI: %s" % (cli), extra={'color': RED}) + self.logger.debug("CLI: %s" % (cli), extra={"color": RED}) def after_cli(self, cli): """ @@ -73,14 +74,15 @@ class Hook: class PollHook(Hook): - """ Hook which checks if the vpp subprocess is alive """ + """Hook which checks if the vpp subprocess is alive""" def __init__(self, test): super(PollHook, self).__init__(test) def on_crash(self, core_path): - self.logger.error("Core file present, debug with: gdb %s %s", - config.vpp, core_path) + self.logger.error( + "Core file present, debug with: gdb %s %s", config.vpp, core_path + ) check_core_path(self.logger, core_path) self.logger.error("Running `file %s':", core_path) try: @@ -90,17 +92,24 @@ class PollHook(Hook): self.logger.error( "Subprocess returned with error running `file' utility on " "core-file, " - "rc=%s", e.returncode) + "rc=%s", + e.returncode, + ) except OSError as e: self.logger.error( "Subprocess returned OS error running `file' utility on " "core-file, " - "oserror=(%s) %s", e.errno, e.strerror) + "oserror=(%s) %s", + e.errno, + e.strerror, + ) except Exception as e: self.logger.error( "Subprocess returned unanticipated error running `file' " "utility on core-file, " - "%s", e) + "%s", + e, + ) def poll_vpp(self): """ @@ -144,7 +153,7 @@ class PollHook(Hook): class StepHook(PollHook): - """ Hook which requires user to press ENTER before doing any API/CLI """ + """Hook which requires user to press ENTER before doing any API/CLI""" def __init__(self, test): self.skip_stack = None @@ -183,19 +192,18 @@ class StepHook(PollHook): self.skip_count += 1 return True else: - print("%d API/CLI calls skipped in specified stack " - "frame" % self.skip_count) + print("%d API/CLI calls skipped in specified stack frame" % self.skip_count) self.skip_count = 0 self.skip_stack = None self.skip_num = None return False def user_input(self): - print('number\tfunction\tfile\tcode') + print("number\tfunction\tfile\tcode") counter = 0 stack = traceback.extract_stack() for e in stack: - print('%02d.\t%s\t%s:%d\t[%s]' % (counter, e[2], e[0], e[1], e[3])) + print("%02d.\t%s\t%s:%d\t[%s]" % (counter, e[2], e[0], e[1], e[3])) counter += 1 print(single_line_delim) print("You may enter a number of stack frame chosen from above") @@ -203,9 +211,11 @@ class StepHook(PollHook): print("Alternatively, enter a test function name to stop at") print(single_line_delim) while True: - print("Enter your choice, if any, and press ENTER to continue " - "running the testcase...") - choice = sys.stdin.readline().rstrip('\r\n') + print( + "Enter your choice, if any, and press ENTER to continue " + "running the testcase..." + ) + choice = sys.stdin.readline().rstrip("\r\n") if choice == "": choice = None try: @@ -229,7 +239,7 @@ class StepHook(PollHook): self.skip_num = num def before_cli(self, cli): - """ Wait for ENTER before executing CLI """ + """Wait for ENTER before executing CLI""" if self.skip(): print("Skip pause before executing CLI: %s" % cli) else: @@ -240,14 +250,12 @@ class StepHook(PollHook): super(StepHook, self).before_cli(cli) def before_api(self, api_name, api_args): - """ Wait for ENTER before executing API """ + """Wait for ENTER before executing API""" if self.skip(): - print("Skip pause before executing API: %s (%s)" - % (api_name, api_args)) + print("Skip pause before executing API: %s (%s)" % (api_name, api_args)) else: print(double_line_delim) - print("Test paused before executing API: %s (%s)" - % (api_name, api_args)) + print("Test paused before executing API: %s (%s)" % (api_name, api_args)) print(single_line_delim) self.user_input() super(StepHook, self).before_api(api_name, api_args) diff --git a/test/ipfix.py b/test/ipfix.py index bac6dfd4c2a..bf833b36bbf 100644 --- a/test/ipfix.py +++ b/test/ipfix.py @@ -1,106 +1,114 @@ #!/usr/bin/env python3 # IPFIX support for Scapy (RFC7011) -from scapy.all import bind_layers, FieldLenField, IntField, Packet, \ - PacketListField, ShortEnumField, ShortField, StrLenField +from scapy.all import ( + bind_layers, + FieldLenField, + IntField, + Packet, + PacketListField, + ShortEnumField, + ShortField, + StrLenField, +) from scapy.layers.inet import UDP # IPFIX Information Elements http://www.iana.org/assignments/ipfix/ipfix.xhtml information_elements = { - 1: "octetDeltaCount", - 2: "packetDeltaCount", - 3: "deltaFlowCount", - 4: "protocolIdentifier", - 5: "ipClassOfService", - 6: "tcpControlBits", - 7: "sourceTransportPort", - 8: "sourceIPv4Address", - 9: "sourceIPv4PrefixLength", - 10: "ingressInterface", - 11: "destinationTransportPort", - 12: "destinationIPv4Address", - 13: "destinationIPv4PrefixLength", - 14: "egressInterface", - 15: "ipNextHopIPv4Address", - 16: "bgpSourceAsNumber", - 17: "bgpDestinationAsNumber", - 18: "bgpNextHopIPv4Address", - 19: "postMCastPacketDeltaCount", - 20: "postMCastOctetDeltaCount", - 21: "flowEndSysUpTime", - 22: "flowStartSysUpTime", - 23: "postOctetDeltaCount", - 24: "postPacketDeltaCount", - 25: "minimumIpTotalLength", - 26: "maximumIpTotalLength", - 27: "sourceIPv6Address", - 28: "destinationIPv6Address", - 29: "sourceIPv6PrefixLength", - 30: "destinationIPv6PrefixLength", - 31: "flowLabelIPv6", - 32: "icmpTypeCodeIPv4", - 33: "igmpType", - 34: "samplingInterval", - 35: "samplingAlgorithm", - 36: "flowActiveTimeout", - 37: "flowIdleTimeout", - 38: "engineType", - 39: "engineId", - 40: "exportedOctetTotalCount", - 41: "exportedMessageTotalCount", - 42: "exportedFlowRecordTotalCount", - 43: "ipv4RouterSc", - 44: "sourceIPv4Prefix", - 45: "destinationIPv4Prefix", - 46: "mplsTopLabelType", - 47: "mplsTopLabelIPv4Address", - 48: "samplerId", - 49: "samplerMode", - 50: "samplerRandomInterval", - 51: "classId", - 52: "minimumTTL", - 53: "maximumTTL", - 54: "fragmentIdentification", - 55: "postIpClassOfService", - 56: "sourceMacAddress", - 57: "postDestinationMacAddress", - 58: "vlanId", - 59: "postVlanId", - 60: "ipVersion", - 61: "flowDirection", - 62: "ipNextHopIPv6Address", - 63: "bgpNextHopIPv6Address", - 64: "ipv6ExtensionHeaders", - 70: "mplsTopLabelStackSection", - 71: "mplsLabelStackSection2", - 72: "mplsLabelStackSection3", - 73: "mplsLabelStackSection4", - 74: "mplsLabelStackSection5", - 75: "mplsLabelStackSection6", - 76: "mplsLabelStackSection7", - 77: "mplsLabelStackSection8", - 78: "mplsLabelStackSection9", - 79: "mplsLabelStackSection10", - 80: "destinationMacAddress", - 81: "postSourceMacAddress", - 82: "interfaceName", - 83: "interfaceDescription", - 84: "samplerName", - 85: "octetTotalCount", - 86: "packetTotalCount", - 87: "flagsAndSamplerId", - 88: "fragmentOffset", - 89: "forwardingStatus", - 90: "mplsVpnRouteDistinguisher", - 91: "mplsTopLabelPrefixLength", - 92: "srcTrafficIndex", - 93: "dstTrafficIndex", - 94: "applicationDescription", - 95: "applicationId", - 96: "applicationName", - 98: "postIpDiffServCodePoint", - 99: "multicastReplicationFactor", + 1: "octetDeltaCount", + 2: "packetDeltaCount", + 3: "deltaFlowCount", + 4: "protocolIdentifier", + 5: "ipClassOfService", + 6: "tcpControlBits", + 7: "sourceTransportPort", + 8: "sourceIPv4Address", + 9: "sourceIPv4PrefixLength", + 10: "ingressInterface", + 11: "destinationTransportPort", + 12: "destinationIPv4Address", + 13: "destinationIPv4PrefixLength", + 14: "egressInterface", + 15: "ipNextHopIPv4Address", + 16: "bgpSourceAsNumber", + 17: "bgpDestinationAsNumber", + 18: "bgpNextHopIPv4Address", + 19: "postMCastPacketDeltaCount", + 20: "postMCastOctetDeltaCount", + 21: "flowEndSysUpTime", + 22: "flowStartSysUpTime", + 23: "postOctetDeltaCount", + 24: "postPacketDeltaCount", + 25: "minimumIpTotalLength", + 26: "maximumIpTotalLength", + 27: "sourceIPv6Address", + 28: "destinationIPv6Address", + 29: "sourceIPv6PrefixLength", + 30: "destinationIPv6PrefixLength", + 31: "flowLabelIPv6", + 32: "icmpTypeCodeIPv4", + 33: "igmpType", + 34: "samplingInterval", + 35: "samplingAlgorithm", + 36: "flowActiveTimeout", + 37: "flowIdleTimeout", + 38: "engineType", + 39: "engineId", + 40: "exportedOctetTotalCount", + 41: "exportedMessageTotalCount", + 42: "exportedFlowRecordTotalCount", + 43: "ipv4RouterSc", + 44: "sourceIPv4Prefix", + 45: "destinationIPv4Prefix", + 46: "mplsTopLabelType", + 47: "mplsTopLabelIPv4Address", + 48: "samplerId", + 49: "samplerMode", + 50: "samplerRandomInterval", + 51: "classId", + 52: "minimumTTL", + 53: "maximumTTL", + 54: "fragmentIdentification", + 55: "postIpClassOfService", + 56: "sourceMacAddress", + 57: "postDestinationMacAddress", + 58: "vlanId", + 59: "postVlanId", + 60: "ipVersion", + 61: "flowDirection", + 62: "ipNextHopIPv6Address", + 63: "bgpNextHopIPv6Address", + 64: "ipv6ExtensionHeaders", + 70: "mplsTopLabelStackSection", + 71: "mplsLabelStackSection2", + 72: "mplsLabelStackSection3", + 73: "mplsLabelStackSection4", + 74: "mplsLabelStackSection5", + 75: "mplsLabelStackSection6", + 76: "mplsLabelStackSection7", + 77: "mplsLabelStackSection8", + 78: "mplsLabelStackSection9", + 79: "mplsLabelStackSection10", + 80: "destinationMacAddress", + 81: "postSourceMacAddress", + 82: "interfaceName", + 83: "interfaceDescription", + 84: "samplerName", + 85: "octetTotalCount", + 86: "packetTotalCount", + 87: "flagsAndSamplerId", + 88: "fragmentOffset", + 89: "forwardingStatus", + 90: "mplsVpnRouteDistinguisher", + 91: "mplsTopLabelPrefixLength", + 92: "srcTrafficIndex", + 93: "dstTrafficIndex", + 94: "applicationDescription", + 95: "applicationId", + 96: "applicationName", + 98: "postIpDiffServCodePoint", + 99: "multicastReplicationFactor", 100: "className", 101: "classificationEngineId", 102: "layer2packetSectionOffset", @@ -443,24 +451,27 @@ information_elements = { 471: "maxSessionEntries", 472: "maxBIBEntries", 473: "maxEntriesPerUser", - 475: "maxFragmentsPendingReassembly" + 475: "maxFragmentsPendingReassembly", } class IPFIX(Packet): name = "IPFIX" - fields_desc = [ShortField("version", 10), - ShortField("length", None), - IntField("exportTime", None), - IntField("sequenceNumber", 1), - IntField("observationDomainID", 1)] + fields_desc = [ + ShortField("version", 10), + ShortField("length", None), + IntField("exportTime", None), + IntField("sequenceNumber", 1), + IntField("observationDomainID", 1), + ] class FieldSpecifier(Packet): name = "Field Specifier" - fields_desc = [ShortEnumField( - "informationElement", None, information_elements), - ShortField("fieldLength", None)] + fields_desc = [ + ShortEnumField("informationElement", None, information_elements), + ShortField("fieldLength", None), + ] def extract_padding(self, s): return "", s @@ -468,16 +479,20 @@ class FieldSpecifier(Packet): class Template(Packet): name = "Template" - fields_desc = [ShortField("templateID", 256), - FieldLenField("fieldCount", None, count_of="fields"), - PacketListField("templateFields", [], FieldSpecifier, - count_from=lambda p: p.fieldCount)] + fields_desc = [ + ShortField("templateID", 256), + FieldLenField("fieldCount", None, count_of="fields"), + PacketListField( + "templateFields", [], FieldSpecifier, count_from=lambda p: p.fieldCount + ), + ] class Data(Packet): name = "Data" fields_desc = [ - StrLenField("data", "", length_from=lambda p: p.underlayer.length - 4)] + StrLenField("data", "", length_from=lambda p: p.underlayer.length - 4) + ] def extract_padding(self, s): return "", s @@ -485,8 +500,7 @@ class Data(Packet): class Set(Packet): name = "Set" - fields_desc = [ShortField("setID", 256), - ShortField("length", None)] + fields_desc = [ShortField("setID", 256), ShortField("length", None)] def guess_payload_class(self, payload): if self.setID == 2: @@ -502,7 +516,7 @@ bind_layers(UDP, IPFIX, dport=4739) class IPFIXDecoder: - """ IPFIX data set decoder """ + """IPFIX data set decoder""" def __init__(self): self._templates = [] @@ -517,11 +531,9 @@ class IPFIXDecoder: fields = [] rec_len = 0 for field in template.templateFields: - fields.append( - {'name': field.informationElement, 'len': field.fieldLength}) + fields.append({"name": field.informationElement, "len": field.fieldLength}) rec_len += field.fieldLength - self._templates.append( - {'id': templateID, 'fields': fields, 'rec_len': rec_len}) + self._templates.append({"id": templateID, "fields": fields, "rec_len": rec_len}) def decode_data_set(self, data_set): """ @@ -532,15 +544,15 @@ class IPFIXDecoder: """ data = [] for template in self._templates: - if template['id'] == data_set.setID: + if template["id"] == data_set.setID: offset = 0 d = data_set[Data].data - for i in range(len(d) // template['rec_len']): + for i in range(len(d) // template["rec_len"]): record = {} - for field in template['fields']: - f = d[offset:offset + field['len']] - offset += field['len'] - record.update({field['name']: f}) + for field in template["fields"]: + f = d[offset : offset + field["len"]] + offset += field["len"] + record.update({field["name"]: f}) data.append(record) break return data diff --git a/test/lisp.py b/test/lisp.py index bd5e1ab7c5f..9ebc86a35e3 100644 --- a/test/lisp.py +++ b/test/lisp.py @@ -5,7 +5,7 @@ from vpp_object import VppObject class VppLispLocatorSet(VppObject): - """ Represents LISP locator set in VPP """ + """Represents LISP locator set in VPP""" def __init__(self, test, ls_name): self._test = test @@ -26,7 +26,7 @@ class VppLispLocatorSet(VppObject): def get_lisp_locator_sets_dump_entry(self): result = self.test.vapi.lisp_locator_set_dump() for ls in result: - if ls.ls_name.strip('\x00') == self._ls_name: + if ls.ls_name.strip("\x00") == self._ls_name: return ls return None @@ -34,15 +34,16 @@ class VppLispLocatorSet(VppObject): return self.get_lisp_locator_sets_dump_entry() is not None def remove_vpp_config(self): - self.test.vapi.lisp_add_del_locator_set(locator_set_name=self._ls_name, - is_add=0) + self.test.vapi.lisp_add_del_locator_set( + locator_set_name=self._ls_name, is_add=0 + ) def object_id(self): - return 'lisp-locator-set-%s' % self._ls_name + return "lisp-locator-set-%s" % self._ls_name class VppLispLocator(VppObject): - """ Represents LISP locator in VPP """ + """Represents LISP locator in VPP""" def __init__(self, test, sw_if_index, ls_name, priority=1, weight=1): self._test = test @@ -53,12 +54,12 @@ class VppLispLocator(VppObject): @property def test(self): - """ Test which created this locator """ + """Test which created this locator""" return self._test @property def ls_name(self): - """ Locator set name """ + """Locator set name""" return self._ls_name @property @@ -74,15 +75,18 @@ class VppLispLocator(VppObject): return self._weight def add_vpp_config(self): - self.test.vapi.lisp_add_del_locator(locator_set_name=self._ls_name, - sw_if_index=self._sw_if_index, - priority=self._priority, - weight=self._weight) + self.test.vapi.lisp_add_del_locator( + locator_set_name=self._ls_name, + sw_if_index=self._sw_if_index, + priority=self._priority, + weight=self._weight, + ) self._test.registry.register(self, self.test.logger) def get_lisp_locator_dump_entry(self): locators = self.test.vapi.lisp_locator_dump( - is_index_set=0, ls_name=self._ls_name) + is_index_set=0, ls_name=self._ls_name + ) for locator in locators: if locator.sw_if_index == self._sw_if_index: return locator @@ -94,12 +98,16 @@ class VppLispLocator(VppObject): def remove_vpp_config(self): self.test.vapi.lisp_add_del_locator( - locator_set_name=self._ls_name, sw_if_index=self._sw_if_index, - priority=self._priority, weight=self._weight, is_add=0) + locator_set_name=self._ls_name, + sw_if_index=self._sw_if_index, + priority=self._priority, + weight=self._weight, + is_add=0, + ) self._test.registry.register(self, self.test.logger) def object_id(self): - return 'lisp-locator-%s-%d' % (self._ls_name, self._sw_if_index) + return "lisp-locator-%s-%d" % (self._ls_name, self._sw_if_index) class LispEIDType: @@ -115,7 +123,8 @@ class LispKeyIdType: class LispEID: - """ Lisp endpoint identifier """ + """Lisp endpoint identifier""" + def __init__(self, eid): self.eid = eid self._type = -1 @@ -130,7 +139,7 @@ class LispEID: self.mac = self.eid self._type = LispEIDType.MAC return - raise Exception('Unsupported EID format {!s}!'.format(eid)) + raise Exception("Unsupported EID format {!s}!".format(eid)) @property def eid_type(self): @@ -143,7 +152,7 @@ class LispEID: elif self.eid_type == LispEIDType.MAC: return self.mac elif self.eid_type == LispEIDType.NSH: - return Exception('Unimplemented') + return Exception("Unimplemented") @property def packed(self): @@ -152,11 +161,12 @@ class LispEID: elif self.eid_type == LispEIDType.MAC: return {"type": self._type, "address": {"mac": self.mac}} elif self.eid_type == LispEIDType.NSH: - return Exception('Unimplemented') + return Exception("Unimplemented") class LispKey: - """ Lisp Key """ + """Lisp Key""" + def __init__(self, key_type, key): self._key_type = key_type self._key = key @@ -167,7 +177,7 @@ class LispKey: class VppLispMapping(VppObject): - """ Represents common features for remote and local LISP mapping in VPP """ + """Represents common features for remote and local LISP mapping in VPP""" def __init__(self, test, eid, vni=0, priority=1, weight=1): self._eid = LispEID(eid) @@ -198,21 +208,36 @@ class VppLispMapping(VppObject): def get_lisp_mapping_dump_entry(self): return self.test.vapi.lisp_eid_table_dump( - eid_set=1, vni=self._vni, eid=self._eid.packed) + eid_set=1, vni=self._vni, eid=self._eid.packed + ) def query_vpp_config(self): mapping = self.get_lisp_mapping_dump_entry() return mapping def object_id(self): - return 'lisp-mapping-[%s]-%s-%s-%s' % ( - self.vni, self.eid.address, self.priority, self.weight) + return "lisp-mapping-[%s]-%s-%s-%s" % ( + self.vni, + self.eid.address, + self.priority, + self.weight, + ) class VppLocalMapping(VppLispMapping): - """ LISP Local mapping """ - def __init__(self, test, eid, ls_name, vni=0, priority=1, weight=1, - key_id=LispKeyIdType.NONE, key=''): + """LISP Local mapping""" + + def __init__( + self, + test, + eid, + ls_name, + vni=0, + priority=1, + weight=1, + key_id=LispKeyIdType.NONE, + key="", + ): super(VppLocalMapping, self).__init__(test, eid, vni, priority, weight) self._ls_name = ls_name self._key = LispKey(key_id, key) @@ -231,17 +256,23 @@ class VppLocalMapping(VppLispMapping): def add_vpp_config(self): self.test.vapi.lisp_add_del_local_eid( - locator_set_name=self._ls_name, eid=self._eid.packed, - vni=self._vni, key=self._key.packed) + locator_set_name=self._ls_name, + eid=self._eid.packed, + vni=self._vni, + key=self._key.packed, + ) self._test.registry.register(self, self.test.logger) def remove_vpp_config(self): self.test.vapi.lisp_add_del_local_eid( - locator_set_name=self._ls_name, eid=self._eid.packed, - vni=self._vni, is_add=0) + locator_set_name=self._ls_name, + eid=self._eid.packed, + vni=self._vni, + is_add=0, + ) def object_id(self): - return 'lisp-eid-local-mapping-%s[%d]' % (self._eid.address, self._vni) + return "lisp-eid-local-mapping-%s[%d]" % (self._eid.address, self._vni) class LispRemoteLocator: @@ -252,15 +283,16 @@ class LispRemoteLocator: @property def packed(self): - return {"priority": self.priority, "weight": self.weight, - "ip_address": self.addr} + return { + "priority": self.priority, + "weight": self.weight, + "ip_address": self.addr, + } class VppRemoteMapping(VppLispMapping): - def __init__(self, test, eid, rlocs=None, vni=0, priority=1, weight=1): - super(VppRemoteMapping, self).__init__(test, eid, vni, priority, - weight) + super(VppRemoteMapping, self).__init__(test, eid, vni, priority, weight) self._rlocs = rlocs @property @@ -272,27 +304,30 @@ class VppRemoteMapping(VppLispMapping): def add_vpp_config(self): self.test.vapi.lisp_add_del_remote_mapping( - rlocs=self.rlocs, deid=self._eid.packed, - vni=self._vni, rloc_num=len(self._rlocs)) + rlocs=self.rlocs, + deid=self._eid.packed, + vni=self._vni, + rloc_num=len(self._rlocs), + ) self._test.registry.register(self, self.test.logger) def remove_vpp_config(self): self.test.vapi.lisp_add_del_remote_mapping( - deid=self._eid.packed, vni=self._vni, is_add=0, rloc_num=0) + deid=self._eid.packed, vni=self._vni, is_add=0, rloc_num=0 + ) def object_id(self): - return 'lisp-eid-remote-mapping-%s[%d]' % (self._eid.address, - self._vni) + return "lisp-eid-remote-mapping-%s[%d]" % (self._eid.address, self._vni) class VppLispAdjacency(VppObject): - """ Represents LISP adjacency in VPP """ + """Represents LISP adjacency in VPP""" def __init__(self, test, leid, reid, vni=0): self._leid = LispEID(leid) self._reid = LispEID(reid) if self._leid.eid_type != self._reid.eid_type: - raise Exception('remote and local EID are different types!') + raise Exception("remote and local EID are different types!") self._vni = vni self._test = test @@ -314,7 +349,8 @@ class VppLispAdjacency(VppObject): def add_vpp_config(self): self.test.vapi.lisp_add_del_adjacency( - leid=self._leid.packed, reid=self._reid.packed, vni=self._vni) + leid=self._leid.packed, reid=self._reid.packed, vni=self._vni + ) self._test.registry.register(self, self.test.logger) @staticmethod @@ -334,15 +370,16 @@ class VppLispAdjacency(VppObject): def query_vpp_config(self): res = self.test.vapi.lisp_adjacencies_get(vni=self._vni) for adj in res.adjacencies: - if self.eid_equal(self._leid, adj.leid) and \ - self.eid_equal(self._reid, adj.reid): + if self.eid_equal(self._leid, adj.leid) and self.eid_equal( + self._reid, adj.reid + ): return True return False def remove_vpp_config(self): self.test.vapi.lisp_add_del_adjacency( - leid=self._leid.packed, reid=self._reid.packed, - vni=self._vni, is_add=0) + leid=self._leid.packed, reid=self._reid.packed, vni=self._vni, is_add=0 + ) def object_id(self): - return 'lisp-adjacency-%s-%s[%d]' % (self._leid, self._reid, self._vni) + return "lisp-adjacency-%s-%s[%d]" % (self._leid, self._reid, self._vni) diff --git a/test/log.py b/test/log.py index 9701aecc04a..f848e221044 100644 --- a/test/log.py +++ b/test/log.py @@ -7,9 +7,9 @@ import logging from config import config """ @var formatting delimiter consisting of '=' characters """ -double_line_delim = '=' * 78 +double_line_delim = "=" * 78 """ @var formatting delimiter consisting of '-' characters """ -single_line_delim = '-' * 78 +single_line_delim = "-" * 78 def colorize(msg, color): @@ -17,13 +17,12 @@ def colorize(msg, color): class ColorFormatter(logging.Formatter): - def init(self, fmt=None, datefmt=None): super(ColorFormatter, self).__init__(fmt, datefmt) def format(self, record): message = super(ColorFormatter, self).format(record) - if hasattr(record, 'color'): + if hasattr(record, "color"): message = colorize(message, record.color) return message @@ -37,8 +36,9 @@ else: log_level = 40 handler = logging.StreamHandler(sys.stdout) -color_formatter = ColorFormatter(fmt='%(asctime)s,%(msecs)03d %(message)s', - datefmt="%H:%M:%S") +color_formatter = ColorFormatter( + fmt="%(asctime)s,%(msecs)03d %(message)s", datefmt="%H:%M:%S" +) handler.setFormatter(color_formatter) handler.setLevel(log_level) @@ -56,7 +56,7 @@ def get_logger(name): def get_parallel_logger(stream): - logger = logging.getLogger('parallel_logger_{!s}'.format(stream)) + logger = logging.getLogger("parallel_logger_{!s}".format(stream)) logger.propagate = False logger.setLevel(logging.DEBUG) handler = logging.StreamHandler(stream) @@ -71,15 +71,15 @@ def get_parallel_logger(stream): # These variables (RED, GREEN, YELLOW and LPURPLE) are used to configure # the color of the text to be printed in the terminal. Variable COLOR_RESET # is used to revert the text color to the default one. -if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty(): - RED = '\033[91m' - GREEN = '\033[92m' - YELLOW = '\033[93m' - LPURPLE = '\033[94m' - COLOR_RESET = '\033[0m' +if hasattr(sys.stdout, "isatty") and sys.stdout.isatty(): + RED = "\033[91m" + GREEN = "\033[92m" + YELLOW = "\033[93m" + LPURPLE = "\033[94m" + COLOR_RESET = "\033[0m" else: - RED = '' - GREEN = '' - YELLOW = '' - LPURPLE = '' - COLOR_RESET = '' + RED = "" + GREEN = "" + YELLOW = "" + LPURPLE = "" + COLOR_RESET = "" diff --git a/test/remote_test.py b/test/remote_test.py index 19bad897cdf..707d61fa9e5 100644 --- a/test/remote_test.py +++ b/test/remote_test.py @@ -16,10 +16,11 @@ class SerializableClassCopy: """ Empty class used as a basis for a serializable copy of another class. """ + pass def __repr__(self): - return '<SerializableClassCopy dict=%s>' % self.__dict__ + return "<SerializableClassCopy dict=%s>" % self.__dict__ class RemoteClassAttr: @@ -32,7 +33,7 @@ class RemoteClassAttr: self._remote = remote def path_to_str(self): - return '.'.join(self._path) + return ".".join(self._path) def get_remote_value(self): return self._remote._remote_exec(RemoteClass.GET, self.path_to_str()) @@ -44,25 +45,24 @@ class RemoteClassAttr: return self._remote._remote_exec(RemoteClass.STR, self.path_to_str()) def __getattr__(self, attr): - if attr[0] == '_': - if not (attr.startswith('__') and attr.endswith('__')): - raise AttributeError('tried to get private attribute: %s ', - attr) + if attr[0] == "_": + if not (attr.startswith("__") and attr.endswith("__")): + raise AttributeError("tried to get private attribute: %s ", attr) self._path.append(attr) return self def __setattr__(self, attr, val): - if attr[0] == '_': - if not (attr.startswith('__') and attr.endswith('__')): + if attr[0] == "_": + if not (attr.startswith("__") and attr.endswith("__")): super(RemoteClassAttr, self).__setattr__(attr, val) return self._path.append(attr) - self._remote._remote_exec(RemoteClass.SETATTR, self.path_to_str(), - value=val) + self._remote._remote_exec(RemoteClass.SETATTR, self.path_to_str(), value=val) def __call__(self, *args, **kwargs): - return self._remote._remote_exec(RemoteClass.CALL, self.path_to_str(), - *args, **kwargs) + return self._remote._remote_exec( + RemoteClass.CALL, self.path_to_str(), *args, **kwargs + ) class RemoteClass(Process): @@ -98,12 +98,12 @@ class RemoteClass(Process): object.terminate() """ - GET = 0 # Get attribute remotely - CALL = 1 # Call method remotely - SETATTR = 2 # Set attribute remotely - REPR = 3 # Get representation of a remote object - STR = 4 # Get string representation of a remote object - QUIT = 5 # Quit remote execution + GET = 0 # Get attribute remotely + CALL = 1 # Call method remotely + SETATTR = 2 # Set attribute remotely + REPR = 3 # Get representation of a remote object + STR = 4 # Get string representation of a remote object + QUIT = 5 # Quit remote execution PIPE_PARENT = 0 # Parent end of the pipe PIPE_CHILD = 1 # Child end of the pipe @@ -128,16 +128,16 @@ class RemoteClass(Process): return self.RemoteClassAttr(self, None)() def __getattr__(self, attr): - if attr[0] == '_' or not self.is_alive(): - if not (attr.startswith('__') and attr.endswith('__')): - if hasattr(super(RemoteClass, self), '__getattr__'): + if attr[0] == "_" or not self.is_alive(): + if not (attr.startswith("__") and attr.endswith("__")): + if hasattr(super(RemoteClass, self), "__getattr__"): return super(RemoteClass, self).__getattr__(attr) - raise AttributeError('missing: %s', attr) + raise AttributeError("missing: %s", attr) return RemoteClassAttr(self, attr) def __setattr__(self, attr, val): - if attr[0] == '_' or not self.is_alive(): - if not (attr.startswith('__') and attr.endswith('__')): + if attr[0] == "_" or not self.is_alive(): + if not (attr.startswith("__") and attr.endswith("__")): super(RemoteClass, self).__setattr__(attr, val) return setattr(RemoteClassAttr(self, None), attr, val) @@ -149,13 +149,11 @@ class RemoteClass(Process): # automatically resolve remote objects in the arguments mutable_args = list(args) for i, val in enumerate(mutable_args): - if isinstance(val, RemoteClass) or \ - isinstance(val, RemoteClassAttr): + if isinstance(val, RemoteClass) or isinstance(val, RemoteClassAttr): mutable_args[i] = val.get_remote_value() args = tuple(mutable_args) for key, val in kwargs.items(): - if isinstance(val, RemoteClass) or \ - isinstance(val, RemoteClassAttr): + if isinstance(val, RemoteClass) or isinstance(val, RemoteClassAttr): kwargs[key] = val.get_remote_value() # send request args = self._make_serializable(args) @@ -163,11 +161,11 @@ class RemoteClass(Process): self._pipe[RemoteClass.PIPE_PARENT].send((op, path, args, kwargs)) timeout = self._timeout # adjust timeout specifically for the .sleep method - if path is not None and path.split('.')[-1] == 'sleep': + if path is not None and path.split(".")[-1] == "sleep": if args and isinstance(args[0], (long, int)): timeout += args[0] - elif 'timeout' in kwargs: - timeout += kwargs['timeout'] + elif "timeout" in kwargs: + timeout += kwargs["timeout"] if not self._pipe[RemoteClass.PIPE_PARENT].poll(timeout): return None try: @@ -222,7 +220,7 @@ class RemoteClass(Process): return None def _serializable(self, obj): - """ Test if the given object is serializable """ + """Test if the given object is serializable""" try: dumps(obj) return True @@ -243,7 +241,7 @@ class RemoteClass(Process): Dictionaries can hold complex values, so we split keys and values into separate lists and serialize them individually. """ - if (type(obj) is dict): + if type(obj) is dict: copy.type = type(obj) copy.k_list = list() copy.v_list = list() @@ -255,12 +253,12 @@ class RemoteClass(Process): # copy at least serializable attributes and properties for name, member in inspect.getmembers(obj): # skip private members and non-writable dunder methods. - if name[0] == '_': - if name in ['__weakref__']: + if name[0] == "_": + if name in ["__weakref__"]: continue - if name in ['__dict__']: + if name in ["__dict__"]: continue - if not (name.startswith('__') and name.endswith('__')): + if not (name.startswith("__") and name.endswith("__")): continue if callable(member) and not isinstance(member, property): continue @@ -281,13 +279,13 @@ class RemoteClass(Process): if type(obj) is tuple: rv = tuple(rv) return rv - elif (isinstance(obj, IntEnum) or isinstance(obj, IntFlag)): + elif isinstance(obj, IntEnum) or isinstance(obj, IntFlag): return obj.value else: return self._make_obj_serializable(obj) def _deserialize_obj(self, obj): - if (hasattr(obj, 'type')): + if hasattr(obj, "type"): if obj.type is dict: _obj = dict() for k, v in zip(obj.k_list, obj.v_list): @@ -307,19 +305,19 @@ class RemoteClass(Process): return self._deserialize_obj(obj) def start_remote(self): - """ Start remote execution """ + """Start remote execution""" self.start() def quit_remote(self): - """ Quit remote execution """ + """Quit remote execution""" self._remote_exec(RemoteClass.QUIT, None) def get_remote_value(self): - """ Get value of a remotely held object """ + """Get value of a remotely held object""" return RemoteClassAttr(self, None).get_remote_value() def set_request_timeout(self, timeout): - """ Change request timeout """ + """Change request timeout""" self._timeout = timeout def run(self): @@ -332,17 +330,16 @@ class RemoteClass(Process): try: rv = None # get request from the parent process - (op, path, args, - kwargs) = self._pipe[RemoteClass.PIPE_CHILD].recv() + (op, path, args, kwargs) = self._pipe[RemoteClass.PIPE_CHILD].recv() args = self._deserialize(args) kwargs = self._deserialize(kwargs) - path = path.split('.') if path else [] + path = path.split(".") if path else [] if op == RemoteClass.GET: rv = self._get_local_value(path) elif op == RemoteClass.CALL: rv = self._call_local_method(path, *args, **kwargs) - elif op == RemoteClass.SETATTR and 'value' in kwargs: - self._set_local_attr(path, kwargs['value']) + elif op == RemoteClass.SETATTR and "value" in kwargs: + self._set_local_attr(path, kwargs["value"]) elif op == RemoteClass.REPR: rv = self._get_local_repr(path) elif op == RemoteClass.STR: @@ -362,34 +359,34 @@ class RemoteClass(Process): @unittest.skip("Remote Vpp Test Case Class") class RemoteVppTestCase(VppTestCase): - """ Re-use VppTestCase to create remote VPP segment + """Re-use VppTestCase to create remote VPP segment - In your test case:: + In your test case:: - @classmethod - def setUpClass(cls): - # fork new process before client connects to VPP - cls.remote_test = RemoteClass(RemoteVppTestCase) + @classmethod + def setUpClass(cls): + # fork new process before client connects to VPP + cls.remote_test = RemoteClass(RemoteVppTestCase) - # start remote process - cls.remote_test.start_remote() + # start remote process + cls.remote_test.start_remote() - # set up your test case - super(MyTestCase, cls).setUpClass() + # set up your test case + super(MyTestCase, cls).setUpClass() - # set up remote test - cls.remote_test.setUpClass(cls.tempdir) + # set up remote test + cls.remote_test.setUpClass(cls.tempdir) - @classmethod - def tearDownClass(cls): - # tear down remote test - cls.remote_test.tearDownClass() + @classmethod + def tearDownClass(cls): + # tear down remote test + cls.remote_test.tearDownClass() - # stop remote process - cls.remote_test.quit_remote() + # stop remote process + cls.remote_test.quit_remote() - # tear down your test case - super(MyTestCase, cls).tearDownClass() + # tear down your test case + super(MyTestCase, cls).tearDownClass() """ def __init__(self): @@ -408,10 +405,10 @@ class RemoteVppTestCase(VppTestCase): def setUpClass(cls, tempdir): # disable features unsupported in remote VPP orig_env = dict(os.environ) - if 'STEP' in os.environ: - del os.environ['STEP'] - if 'DEBUG' in os.environ: - del os.environ['DEBUG'] + if "STEP" in os.environ: + del os.environ["STEP"] + if "DEBUG" in os.environ: + del os.environ["DEBUG"] cls.tempdir_prefix = os.path.basename(tempdir) + "/" super(RemoteVppTestCase, cls).setUpClass() os.environ = orig_env @@ -422,7 +419,7 @@ class RemoteVppTestCase(VppTestCase): @unittest.skip("Empty test") def emptyTest(self): - """ Do nothing """ + """Do nothing""" pass def setTestFunctionInfo(self, name, doc): diff --git a/test/requirements-3.txt b/test/requirements-3.txt index 0ccdec7fa5c..2e8f17df0c5 100644 --- a/test/requirements-3.txt +++ b/test/requirements-3.txt @@ -1,5 +1,5 @@ # -# This file is autogenerated by pip-compile with python 3.8 +# This file is autogenerated by pip-compile with python 3.7 # To update, run: # # make test-refresh-deps (or update requirements.txt) @@ -12,10 +12,35 @@ attrs==21.4.0 \ --hash=sha256:2d27e3784d7a565d36ab851fe94887c5eccd6a463168875832a1be79c82828b4 \ --hash=sha256:626ba8234211db98e869df76230a137c4c40a12d72445c45d5f5b716f076e2fd # via jsonschema -babel==2.9.1 \ - --hash=sha256:ab49e12b91d937cd11f0b67cb259a57ab4ad2b59ac7a3b41d6c06c0ac5b0def9 \ - --hash=sha256:bc0c176f9f6a994582230df350aa6e05ba2ebe4b3ac317eab29d9be5d2768da0 +babel==2.10.1 \ + --hash=sha256:3f349e85ad3154559ac4930c3918247d319f21910d5ce4b25d439ed8693b98d2 \ + --hash=sha256:98aeaca086133efb3e1e2aad0396987490c8425929ddbcfe0550184fdc54cd13 # via sphinx +black==22.3.0 \ + --hash=sha256:06f9d8846f2340dfac80ceb20200ea5d1b3f181dd0556b47af4e8e0b24fa0a6b \ + --hash=sha256:10dbe6e6d2988049b4655b2b739f98785a884d4d6b85bc35133a8fb9a2233176 \ + --hash=sha256:2497f9c2386572e28921fa8bec7be3e51de6801f7459dffd6e62492531c47e09 \ + --hash=sha256:30d78ba6bf080eeaf0b7b875d924b15cd46fec5fd044ddfbad38c8ea9171043a \ + --hash=sha256:328efc0cc70ccb23429d6be184a15ce613f676bdfc85e5fe8ea2a9354b4e9015 \ + --hash=sha256:35020b8886c022ced9282b51b5a875b6d1ab0c387b31a065b84db7c33085ca79 \ + --hash=sha256:5795a0375eb87bfe902e80e0c8cfaedf8af4d49694d69161e5bd3206c18618bb \ + --hash=sha256:5891ef8abc06576985de8fa88e95ab70641de6c1fca97e2a15820a9b69e51b20 \ + --hash=sha256:637a4014c63fbf42a692d22b55d8ad6968a946b4a6ebc385c5505d9625b6a464 \ + --hash=sha256:67c8301ec94e3bcc8906740fe071391bce40a862b7be0b86fb5382beefecd968 \ + --hash=sha256:6d2fc92002d44746d3e7db7cf9313cf4452f43e9ea77a2c939defce3b10b5c82 \ + --hash=sha256:6ee227b696ca60dd1c507be80a6bc849a5a6ab57ac7352aad1ffec9e8b805f21 \ + --hash=sha256:863714200ada56cbc366dc9ae5291ceb936573155f8bf8e9de92aef51f3ad0f0 \ + --hash=sha256:9b542ced1ec0ceeff5b37d69838106a6348e60db7b8fdd245294dc1d26136265 \ + --hash=sha256:a6342964b43a99dbc72f72812bf88cad8f0217ae9acb47c0d4f141a6416d2d7b \ + --hash=sha256:ad4efa5fad66b903b4a5f96d91461d90b9507a812b3c5de657d544215bb7877a \ + --hash=sha256:bc58025940a896d7e5356952228b68f793cf5fcb342be703c3a2669a1488cb72 \ + --hash=sha256:cc1e1de68c8e5444e8f94c3670bb48a2beef0e91dddfd4fcc29595ebd90bb9ce \ + --hash=sha256:cee3e11161dde1b2a33a904b850b0899e0424cc331b7295f2a9698e79f9a69a0 \ + --hash=sha256:e3556168e2e5c49629f7b0f377070240bd5511e45e25a4497bb0073d9dda776a \ + --hash=sha256:e8477ec6bbfe0312c128e74644ac8a02ca06bcdb8982d4ee06f209be28cdf163 \ + --hash=sha256:ee8f1f7228cce7dffc2b464f07ce769f478968bfb3dd1254a4c2eeed84928aad \ + --hash=sha256:fd57160949179ec517d32ac2ac898b5f20d68ed1a9c977346efbac9c2f1e779d + # via -r requirements.txt certifi==2021.10.8 \ --hash=sha256:78884e7c1d4b00ce3cea67b44566851c4343c120abd683433ce934a68ea58872 \ --hash=sha256:d62a0163eb4c2344ac042ab2bdf75399a71a2d8c7d47eac2e2ee91b9d6339569 @@ -72,39 +97,43 @@ cffi==1.15.0 \ --hash=sha256:fd8a250edc26254fe5b33be00402e6d287f562b6a5b2152dec302fa15bb3e997 \ --hash=sha256:ffaa5c925128e29efbde7301d8ecaf35c8c60ffbcd6a1ffd3a552177c8e5e796 # via cryptography -charset-normalizer==2.0.11 \ - --hash=sha256:2842d8f5e82a1f6aa437380934d5e1cd4fcf2003b06fed6940769c164a480a45 \ - --hash=sha256:98398a9d69ee80548c762ba991a4728bfc3836768ed226b3945908d1a688371c +charset-normalizer==2.0.12 \ + --hash=sha256:2857e29ff0d34db842cd7ca3230549d1a697f96ee6d3fb071cfa6c7393832597 \ + --hash=sha256:6881edbebdb17b39b4eaaa821b438bf6eddffb4468cf344f09f89def34a8b1df # via requests -click==8.0.3 \ - --hash=sha256:353f466495adaeb40b6b5f592f9f91cb22372351c84caeb068132442a4518ef3 \ - --hash=sha256:410e932b050f5eed773c4cda94de75971c89cdb3155a72a0831139a79e5ecb5b - # via pip-tools +click==8.1.3 \ + --hash=sha256:7682dc8afb30297001674575ea00d1814d808d6a36af415a82bd481d37ba7b8e \ + --hash=sha256:bb4d8133cb15a609f44e8213d9b391b0809795062913b383c62be0ee95b1db48 + # via + # black + # pip-tools commonmark==0.9.1 \ --hash=sha256:452f9dc859be7f06631ddcb328b6919c67984aca654e5fefb3914d54691aed60 \ --hash=sha256:da2f38c92590f83de410ba1a3cbceafbc74fee9def35f9251ba9a971d6d66fd9 # via recommonmark -cryptography==36.0.1 \ - --hash=sha256:0a817b961b46894c5ca8a66b599c745b9a3d9f822725221f0e0fe49dc043a3a3 \ - --hash=sha256:2d87cdcb378d3cfed944dac30596da1968f88fb96d7fc34fdae30a99054b2e31 \ - --hash=sha256:30ee1eb3ebe1644d1c3f183d115a8c04e4e603ed6ce8e394ed39eea4a98469ac \ - --hash=sha256:391432971a66cfaf94b21c24ab465a4cc3e8bf4a939c1ca5c3e3a6e0abebdbcf \ - --hash=sha256:39bdf8e70eee6b1c7b289ec6e5d84d49a6bfa11f8b8646b5b3dfe41219153316 \ - --hash=sha256:4caa4b893d8fad33cf1964d3e51842cd78ba87401ab1d2e44556826df849a8ca \ - --hash=sha256:53e5c1dc3d7a953de055d77bef2ff607ceef7a2aac0353b5d630ab67f7423638 \ - --hash=sha256:596f3cd67e1b950bc372c33f1a28a0692080625592ea6392987dba7f09f17a94 \ - --hash=sha256:5d59a9d55027a8b88fd9fd2826c4392bd487d74bf628bb9d39beecc62a644c12 \ - --hash=sha256:6c0c021f35b421ebf5976abf2daacc47e235f8b6082d3396a2fe3ccd537ab173 \ - --hash=sha256:73bc2d3f2444bcfeac67dd130ff2ea598ea5f20b40e36d19821b4df8c9c5037b \ - --hash=sha256:74d6c7e80609c0f4c2434b97b80c7f8fdfaa072ca4baab7e239a15d6d70ed73a \ - --hash=sha256:7be0eec337359c155df191d6ae00a5e8bbb63933883f4f5dffc439dac5348c3f \ - --hash=sha256:94ae132f0e40fe48f310bba63f477f14a43116f05ddb69d6fa31e93f05848ae2 \ - --hash=sha256:bb5829d027ff82aa872d76158919045a7c1e91fbf241aec32cb07956e9ebd3c9 \ - --hash=sha256:ca238ceb7ba0bdf6ce88c1b74a87bffcee5afbfa1e41e173b1ceb095b39add46 \ - --hash=sha256:ca28641954f767f9822c24e927ad894d45d5a1e501767599647259cbf030b903 \ - --hash=sha256:e0344c14c9cb89e76eb6a060e67980c9e35b3f36691e15e1b7a9e58a0a6c6dc3 \ - --hash=sha256:ebc15b1c22e55c4d5566e3ca4db8689470a0ca2babef8e3a9ee057a8b82ce4b1 \ - --hash=sha256:ec63da4e7e4a5f924b90af42eddf20b698a70e58d86a72d943857c4c6045b3ee +cryptography==37.0.1 \ + --hash=sha256:06bfafa6e53ccbfb7a94be4687b211a025ce0625e3f3c60bb15cd048a18f3ed8 \ + --hash=sha256:0db5cf21bd7d092baacb576482b0245102cea2d3cf09f09271ce9f69624ecb6f \ + --hash=sha256:125702572be12bcd318e3a14e9e70acd4be69a43664a75f0397e8650fe3c6cc3 \ + --hash=sha256:1858eff6246bb8bbc080eee78f3dd1528739e3f416cba5f9914e8631b8df9871 \ + --hash=sha256:315af6268de72bcfa0bb3401350ce7d921f216e6b60de12a363dad128d9d459f \ + --hash=sha256:451aaff8b8adf2dd0597cbb1fdcfc8a7d580f33f843b7cce75307a7f20112dd8 \ + --hash=sha256:58021d6e9b1d88b1105269d0da5e60e778b37dfc0e824efc71343dd003726831 \ + --hash=sha256:618391152147a1221c87b1b0b7f792cafcfd4b5a685c5c72eeea2ddd29aeceff \ + --hash=sha256:6d4daf890e674d191757d8d7d60dc3a29c58c72c7a76a05f1c0a326013f47e8b \ + --hash=sha256:74b55f67f4cf026cb84da7a1b04fc2a1d260193d4ad0ea5e9897c8b74c1e76ac \ + --hash=sha256:7ceae26f876aabe193b13a0c36d1bb8e3e7e608d17351861b437bd882f617e9f \ + --hash=sha256:930b829e8a2abaf43a19f38277ae3c5e1ffcf547b936a927d2587769ae52c296 \ + --hash=sha256:a18ff4bfa9d64914a84d7b06c46eb86e0cc03113470b3c111255aceb6dcaf81d \ + --hash=sha256:ae1cd29fbe6b716855454e44f4bf743465152e15d2d317303fe3b58ee9e5af7a \ + --hash=sha256:b1ee5c82cf03b30f6ae4e32d2bcb1e167ef74d6071cbb77c2af30f101d0b360b \ + --hash=sha256:bf585476fcbcd37bed08072e8e2db3954ce1bfc68087a2dc9c19cfe0b90979ca \ + --hash=sha256:c4a58eeafbd7409054be41a377e726a7904a17c26f45abf18125d21b1215b08b \ + --hash=sha256:cce90609e01e1b192fae9e13665058ab46b2ea53a3c05a3ea74a3eb8c3af8857 \ + --hash=sha256:d610d0ee14dd9109006215c7c0de15eee91230b70a9bce2263461cf7c3720b83 \ + --hash=sha256:e69a0e36e62279120e648e787b76d79b41e0f9e86c1c636a4f38d415595c722e \ + --hash=sha256:f095988548ec5095e3750cdb30e6962273d239b1998ba1aac66c0d5bee7111c1 \ + --hash=sha256:faf0f5456c059c7b1c29441bdd5e988f0ba75bdc3eea776520d8dcb1e30e1b5c # via # -r requirements.txt # noiseprotocol @@ -119,9 +148,9 @@ docutils==0.17.1 \ # recommonmark # sphinx # sphinx-rtd-theme -graphviz==0.19.1 \ - --hash=sha256:09ed0cde452d015fe77c4845a210eb642f28d245f5bc250d4b97808cb8f49078 \ - --hash=sha256:f34088c08be2ec16279dfa9c3b4ff3d1453c5c67597a33e2819b000e18d4c546 +graphviz==0.20 \ + --hash=sha256:62c5f48bcc534a45b4588c548ff75e419c1f1f3a33d31a91796ae80a7f581e4a \ + --hash=sha256:76bdfb73f42e72564ffe9c7299482f9d72f8e6cb8d54bce7b48ab323755e9ba5 # via objgraph idna==3.3 \ --hash=sha256:84d9dd047ffa80596e0f246e2eab0b391788b0503584e8945f2368256d2735ff \ @@ -131,17 +160,22 @@ imagesize==1.3.0 \ --hash=sha256:1db2f82529e53c3e929e8926a1fa9235aa82d0bd0c580359c67ec31b2fddaa8c \ --hash=sha256:cd1750d452385ca327479d45b64d9c7729ecf0b3969a58148298c77092261f9d # via sphinx -importlib-metadata==4.10.1 \ - --hash=sha256:899e2a40a8c4a1aec681feef45733de8a6c58f3f6a0dbed2eb6574b4387a77b6 \ - --hash=sha256:951f0d8a5b7260e9db5e41d429285b5f451e928479f19d80818878527d36e95e - # via sphinx -importlib-resources==5.4.0 \ - --hash=sha256:33a95faed5fc19b4bc16b29a6eeae248a3fe69dd55d4d229d2b480e23eeaad45 \ - --hash=sha256:d756e2f85dd4de2ba89be0b21dba2a3bbec2e871a42a3a16719258a11f87506b +importlib-metadata==4.11.3 \ + --hash=sha256:1208431ca90a8cca1a6b8af391bb53c1a2db74e5d1cef6ddced95d4b2062edc6 \ + --hash=sha256:ea4c597ebf37142f827b8f39299579e31685c31d3a438b59f469406afd0f2539 + # via + # click + # jsonschema + # pep517 + # sphinx + # sphinxcontrib-spelling +importlib-resources==5.7.1 \ + --hash=sha256:b6062987dfc51f0fcb809187cffbd60f35df7acb4589091f154214af6d0d49d3 \ + --hash=sha256:e447dc01619b1e951286f3929be820029d48c75eb25d265c28b92a16548212b8 # via jsonschema -jinja2==3.0.3 \ - --hash=sha256:077ce6014f7b40d03b47d1f1ca4b0fc8328a692bd284016f806ed0eaca390ad8 \ - --hash=sha256:611bb273cd68f3b993fabdc4064fc858c5b47a973cb5aa7999ec1ba405c87cd7 +jinja2==3.1.2 \ + --hash=sha256:31351a702a408a9e7595a8fc6150fc3f43bb6bf7e319770cbc0db9df9437e852 \ + --hash=sha256:6088930bfe239f0e6710546ab9c19c9ef35e29792895fed6e6e31a023a182a61 # via sphinx jsonschema==4.4.0 ; python_version >= "3.7" \ --hash=sha256:636694eb41b3535ed608fe04129f26542b59ed99808b4f688aa32dcf55317a83 \ @@ -150,77 +184,52 @@ jsonschema==4.4.0 ; python_version >= "3.7" \ lark-parser==0.6.7 \ --hash=sha256:062800f3823a6c733ec1d181a2089a22d1f62dbe65f90a3f6b1e6de1934b05ef # via syslog-rfc5424-parser -markupsafe==2.0.1 \ - --hash=sha256:01a9b8ea66f1658938f65b93a85ebe8bc016e6769611be228d797c9d998dd298 \ - --hash=sha256:023cb26ec21ece8dc3907c0e8320058b2e0cb3c55cf9564da612bc325bed5e64 \ - --hash=sha256:0446679737af14f45767963a1a9ef7620189912317d095f2d9ffa183a4d25d2b \ - --hash=sha256:04635854b943835a6ea959e948d19dcd311762c5c0c6e1f0e16ee57022669194 \ - --hash=sha256:0717a7390a68be14b8c793ba258e075c6f4ca819f15edfc2a3a027c823718567 \ - --hash=sha256:0955295dd5eec6cb6cc2fe1698f4c6d84af2e92de33fbcac4111913cd100a6ff \ - --hash=sha256:0d4b31cc67ab36e3392bbf3862cfbadac3db12bdd8b02a2731f509ed5b829724 \ - --hash=sha256:10f82115e21dc0dfec9ab5c0223652f7197feb168c940f3ef61563fc2d6beb74 \ - --hash=sha256:168cd0a3642de83558a5153c8bd34f175a9a6e7f6dc6384b9655d2697312a646 \ - --hash=sha256:1d609f577dc6e1aa17d746f8bd3c31aa4d258f4070d61b2aa5c4166c1539de35 \ - --hash=sha256:1f2ade76b9903f39aa442b4aadd2177decb66525062db244b35d71d0ee8599b6 \ - --hash=sha256:20dca64a3ef2d6e4d5d615a3fd418ad3bde77a47ec8a23d984a12b5b4c74491a \ - --hash=sha256:2a7d351cbd8cfeb19ca00de495e224dea7e7d919659c2841bbb7f420ad03e2d6 \ - --hash=sha256:2d7d807855b419fc2ed3e631034685db6079889a1f01d5d9dac950f764da3dad \ - --hash=sha256:2ef54abee730b502252bcdf31b10dacb0a416229b72c18b19e24a4509f273d26 \ - --hash=sha256:36bc903cbb393720fad60fc28c10de6acf10dc6cc883f3e24ee4012371399a38 \ - --hash=sha256:37205cac2a79194e3750b0af2a5720d95f786a55ce7df90c3af697bfa100eaac \ - --hash=sha256:3c112550557578c26af18a1ccc9e090bfe03832ae994343cfdacd287db6a6ae7 \ - --hash=sha256:3dd007d54ee88b46be476e293f48c85048603f5f516008bee124ddd891398ed6 \ - --hash=sha256:4296f2b1ce8c86a6aea78613c34bb1a672ea0e3de9c6ba08a960efe0b0a09047 \ - --hash=sha256:47ab1e7b91c098ab893b828deafa1203de86d0bc6ab587b160f78fe6c4011f75 \ - --hash=sha256:49e3ceeabbfb9d66c3aef5af3a60cc43b85c33df25ce03d0031a608b0a8b2e3f \ - --hash=sha256:4dc8f9fb58f7364b63fd9f85013b780ef83c11857ae79f2feda41e270468dd9b \ - --hash=sha256:4efca8f86c54b22348a5467704e3fec767b2db12fc39c6d963168ab1d3fc9135 \ - --hash=sha256:53edb4da6925ad13c07b6d26c2a852bd81e364f95301c66e930ab2aef5b5ddd8 \ - --hash=sha256:5855f8438a7d1d458206a2466bf82b0f104a3724bf96a1c781ab731e4201731a \ - --hash=sha256:594c67807fb16238b30c44bdf74f36c02cdf22d1c8cda91ef8a0ed8dabf5620a \ - --hash=sha256:5b6d930f030f8ed98e3e6c98ffa0652bdb82601e7a016ec2ab5d7ff23baa78d1 \ - --hash=sha256:5bb28c636d87e840583ee3adeb78172efc47c8b26127267f54a9c0ec251d41a9 \ - --hash=sha256:60bf42e36abfaf9aff1f50f52644b336d4f0a3fd6d8a60ca0d054ac9f713a864 \ - --hash=sha256:611d1ad9a4288cf3e3c16014564df047fe08410e628f89805e475368bd304914 \ - --hash=sha256:6300b8454aa6930a24b9618fbb54b5a68135092bc666f7b06901f897fa5c2fee \ - --hash=sha256:63f3268ba69ace99cab4e3e3b5840b03340efed0948ab8f78d2fd87ee5442a4f \ - --hash=sha256:6557b31b5e2c9ddf0de32a691f2312a32f77cd7681d8af66c2692efdbef84c18 \ - --hash=sha256:693ce3f9e70a6cf7d2fb9e6c9d8b204b6b39897a2c4a1aa65728d5ac97dcc1d8 \ - --hash=sha256:6a7fae0dd14cf60ad5ff42baa2e95727c3d81ded453457771d02b7d2b3f9c0c2 \ - --hash=sha256:6c4ca60fa24e85fe25b912b01e62cb969d69a23a5d5867682dd3e80b5b02581d \ - --hash=sha256:6fcf051089389abe060c9cd7caa212c707e58153afa2c649f00346ce6d260f1b \ - --hash=sha256:7d91275b0245b1da4d4cfa07e0faedd5b0812efc15b702576d103293e252af1b \ - --hash=sha256:89c687013cb1cd489a0f0ac24febe8c7a666e6e221b783e53ac50ebf68e45d86 \ - --hash=sha256:8d206346619592c6200148b01a2142798c989edcb9c896f9ac9722a99d4e77e6 \ - --hash=sha256:905fec760bd2fa1388bb5b489ee8ee5f7291d692638ea5f67982d968366bef9f \ - --hash=sha256:97383d78eb34da7e1fa37dd273c20ad4320929af65d156e35a5e2d89566d9dfb \ - --hash=sha256:984d76483eb32f1bcb536dc27e4ad56bba4baa70be32fa87152832cdd9db0833 \ - --hash=sha256:99df47edb6bda1249d3e80fdabb1dab8c08ef3975f69aed437cb69d0a5de1e28 \ - --hash=sha256:9f02365d4e99430a12647f09b6cc8bab61a6564363f313126f775eb4f6ef798e \ - --hash=sha256:a30e67a65b53ea0a5e62fe23682cfe22712e01f453b95233b25502f7c61cb415 \ - --hash=sha256:ab3ef638ace319fa26553db0624c4699e31a28bb2a835c5faca8f8acf6a5a902 \ - --hash=sha256:aca6377c0cb8a8253e493c6b451565ac77e98c2951c45f913e0b52facdcff83f \ - --hash=sha256:add36cb2dbb8b736611303cd3bfcee00afd96471b09cda130da3581cbdc56a6d \ - --hash=sha256:b2f4bf27480f5e5e8ce285a8c8fd176c0b03e93dcc6646477d4630e83440c6a9 \ - --hash=sha256:b7f2d075102dc8c794cbde1947378051c4e5180d52d276987b8d28a3bd58c17d \ - --hash=sha256:baa1a4e8f868845af802979fcdbf0bb11f94f1cb7ced4c4b8a351bb60d108145 \ - --hash=sha256:be98f628055368795d818ebf93da628541e10b75b41c559fdf36d104c5787066 \ - --hash=sha256:bf5d821ffabf0ef3533c39c518f3357b171a1651c1ff6827325e4489b0e46c3c \ - --hash=sha256:c47adbc92fc1bb2b3274c4b3a43ae0e4573d9fbff4f54cd484555edbf030baf1 \ - --hash=sha256:cdfba22ea2f0029c9261a4bd07e830a8da012291fbe44dc794e488b6c9bb353a \ - --hash=sha256:d6c7ebd4e944c85e2c3421e612a7057a2f48d478d79e61800d81468a8d842207 \ - --hash=sha256:d7f9850398e85aba693bb640262d3611788b1f29a79f0c93c565694658f4071f \ - --hash=sha256:d8446c54dc28c01e5a2dbac5a25f071f6653e6e40f3a8818e8b45d790fe6ef53 \ - --hash=sha256:deb993cacb280823246a026e3b2d81c493c53de6acfd5e6bfe31ab3402bb37dd \ - --hash=sha256:e0f138900af21926a02425cf736db95be9f4af72ba1bb21453432a07f6082134 \ - --hash=sha256:e9936f0b261d4df76ad22f8fee3ae83b60d7c3e871292cd42f40b81b70afae85 \ - --hash=sha256:f0567c4dc99f264f49fe27da5f735f414c4e7e7dd850cfd8e69f0862d7c74ea9 \ - --hash=sha256:f5653a225f31e113b152e56f154ccbe59eeb1c7487b39b9d9f9cdb58e6c79dc5 \ - --hash=sha256:f826e31d18b516f653fe296d967d700fddad5901ae07c622bb3705955e1faa94 \ - --hash=sha256:f8ba0e8349a38d3001fae7eadded3f6606f0da5d748ee53cc1dab1d6527b9509 \ - --hash=sha256:f9081981fe268bd86831e5c75f7de206ef275defcb82bc70740ae6dc507aee51 \ - --hash=sha256:fa130dd50c57d53368c9d59395cb5526eda596d3ffe36666cd81a44d56e48872 +markupsafe==2.1.1 \ + --hash=sha256:0212a68688482dc52b2d45013df70d169f542b7394fc744c02a57374a4207003 \ + --hash=sha256:089cf3dbf0cd6c100f02945abeb18484bd1ee57a079aefd52cffd17fba910b88 \ + --hash=sha256:10c1bfff05d95783da83491be968e8fe789263689c02724e0c691933c52994f5 \ + --hash=sha256:33b74d289bd2f5e527beadcaa3f401e0df0a89927c1559c8566c066fa4248ab7 \ + --hash=sha256:3799351e2336dc91ea70b034983ee71cf2f9533cdff7c14c90ea126bfd95d65a \ + --hash=sha256:3ce11ee3f23f79dbd06fb3d63e2f6af7b12db1d46932fe7bd8afa259a5996603 \ + --hash=sha256:421be9fbf0ffe9ffd7a378aafebbf6f4602d564d34be190fc19a193232fd12b1 \ + --hash=sha256:43093fb83d8343aac0b1baa75516da6092f58f41200907ef92448ecab8825135 \ + --hash=sha256:46d00d6cfecdde84d40e572d63735ef81423ad31184100411e6e3388d405e247 \ + --hash=sha256:4a33dea2b688b3190ee12bd7cfa29d39c9ed176bda40bfa11099a3ce5d3a7ac6 \ + --hash=sha256:4b9fe39a2ccc108a4accc2676e77da025ce383c108593d65cc909add5c3bd601 \ + --hash=sha256:56442863ed2b06d19c37f94d999035e15ee982988920e12a5b4ba29b62ad1f77 \ + --hash=sha256:671cd1187ed5e62818414afe79ed29da836dde67166a9fac6d435873c44fdd02 \ + --hash=sha256:694deca8d702d5db21ec83983ce0bb4b26a578e71fbdbd4fdcd387daa90e4d5e \ + --hash=sha256:6a074d34ee7a5ce3effbc526b7083ec9731bb3cbf921bbe1d3005d4d2bdb3a63 \ + --hash=sha256:6d0072fea50feec76a4c418096652f2c3238eaa014b2f94aeb1d56a66b41403f \ + --hash=sha256:6fbf47b5d3728c6aea2abb0589b5d30459e369baa772e0f37a0320185e87c980 \ + --hash=sha256:7f91197cc9e48f989d12e4e6fbc46495c446636dfc81b9ccf50bb0ec74b91d4b \ + --hash=sha256:86b1f75c4e7c2ac2ccdaec2b9022845dbb81880ca318bb7a0a01fbf7813e3812 \ + --hash=sha256:8dc1c72a69aa7e082593c4a203dcf94ddb74bb5c8a731e4e1eb68d031e8498ff \ + --hash=sha256:8e3dcf21f367459434c18e71b2a9532d96547aef8a871872a5bd69a715c15f96 \ + --hash=sha256:8e576a51ad59e4bfaac456023a78f6b5e6e7651dcd383bcc3e18d06f9b55d6d1 \ + --hash=sha256:96e37a3dc86e80bf81758c152fe66dbf60ed5eca3d26305edf01892257049925 \ + --hash=sha256:97a68e6ada378df82bc9f16b800ab77cbf4b2fada0081794318520138c088e4a \ + --hash=sha256:99a2a507ed3ac881b975a2976d59f38c19386d128e7a9a18b7df6fff1fd4c1d6 \ + --hash=sha256:a49907dd8420c5685cfa064a1335b6754b74541bbb3706c259c02ed65b644b3e \ + --hash=sha256:b09bf97215625a311f669476f44b8b318b075847b49316d3e28c08e41a7a573f \ + --hash=sha256:b7bd98b796e2b6553da7225aeb61f447f80a1ca64f41d83612e6139ca5213aa4 \ + --hash=sha256:b87db4360013327109564f0e591bd2a3b318547bcef31b468a92ee504d07ae4f \ + --hash=sha256:bcb3ed405ed3222f9904899563d6fc492ff75cce56cba05e32eff40e6acbeaa3 \ + --hash=sha256:d4306c36ca495956b6d568d276ac11fdd9c30a36f1b6eb928070dc5360b22e1c \ + --hash=sha256:d5ee4f386140395a2c818d149221149c54849dfcfcb9f1debfe07a8b8bd63f9a \ + --hash=sha256:dda30ba7e87fbbb7eab1ec9f58678558fd9a6b8b853530e176eabd064da81417 \ + --hash=sha256:e04e26803c9c3851c931eac40c695602c6295b8d432cbe78609649ad9bd2da8a \ + --hash=sha256:e1c0b87e09fa55a220f058d1d49d3fb8df88fbfab58558f1198e08c1e1de842a \ + --hash=sha256:e72591e9ecd94d7feb70c1cbd7be7b3ebea3f548870aa91e2732960fa4d57a37 \ + --hash=sha256:e8c843bbcda3a2f1e3c2ab25913c80a3c5376cd00c6e8c4a86a89a28c8dc5452 \ + --hash=sha256:efc1913fd2ca4f334418481c7e595c00aad186563bbc1ec76067848c7ca0a933 \ + --hash=sha256:f121a1420d4e173a5d96e47e9a0c0dcff965afdf1626d28de1460815f7c4ee7a \ + --hash=sha256:fc7b548b17d238737688817ab67deebb30e8073c95749d55538ed473130ec0c7 # via jinja2 +mypy-extensions==0.4.3 \ + --hash=sha256:090fedd75945a69ae91ce1303b5824f428daf5a028d2f6ab8a299250a846f15d \ + --hash=sha256:2d82818f5bb3e369420cb3c4060a7970edba416647068eb4c5343488a6c604a8 + # via black noiseprotocol==0.3.1 \ --hash=sha256:2e1a603a38439636cf0ffd8b3e8b12cee27d368a28b41be7dbe568b2abb23111 \ --hash=sha256:b092a871b60f6a8f07f17950dc9f7098c8fe7d715b049bd4c24ee3752b90d645 @@ -239,6 +248,10 @@ parameterized==0.8.1 \ --hash=sha256:41bbff37d6186430f77f900d777e5bb6a24928a1c46fb1de692f8b52b8833b5c \ --hash=sha256:9cbb0b69a03e8695d68b3399a8a5825200976536fe1cb79db60ed6a4c8c9efe9 # via -r requirements.txt +pathspec==0.9.0 \ + --hash=sha256:7d15c4ddb0b5c802d161efc417ec1a2558ea2653c2e8ad9c19098201dc1c993a \ + --hash=sha256:e564499435a2673d586f6b2130bb5b95f04a3ba06f81b8f895b651a3c76aabb1 + # via black pep517==0.12.0 \ --hash=sha256:931378d93d11b298cf511dd634cf5ea4cb249a28ef84160b3247ee9afb4e8ab0 \ --hash=sha256:dd884c326898e2c6e11f9e0b64940606a93eb10ea022a2e067959f3a110cf161 @@ -247,10 +260,14 @@ pexpect==4.8.0 \ --hash=sha256:0b48a55dcb3c05f3329815901ea4fc1537514d6ba867a152b581d69ae3710937 \ --hash=sha256:fc65a43959d153d0114afe13997d439c22823a27cefceb5ff35c2178c6784c0c # via -r requirements.txt -pip-tools==6.5.0 \ - --hash=sha256:9cf69a020e3c208a7a1bcc78cbfd436dab323efc187919df6182eca98efbe3f2 \ - --hash=sha256:d14ea4fc2c118db2a6af65a4345a8b9b355e792aedad6bf64dd3eb97c5fc5fee +pip-tools==6.6.0 \ + --hash=sha256:66318bc2e884b61fafa1cb2cf01b35fdd779ab9ce82cc1bce277adb8cf3ab845 \ + --hash=sha256:98aa24004440a1c0489d71a567a4e8afdf23c7782bff483d1219881e7302de83 # via -r requirements.txt +platformdirs==2.5.2 \ + --hash=sha256:027d8e83a2d7de06bbac4e5ef7e023c02b863d7ea5d079477e722bb41ab25788 \ + --hash=sha256:58c8abb07dcb441e6ee4b11d8df0ac856038f944ab98b7be6b27b2a3c7feef19 + # via black psutil==5.9.0 \ --hash=sha256:072664401ae6e7c1bfb878c65d7282d4b4391f1bc9a56d5e03b5a490403271b5 \ --hash=sha256:1070a9b287846a21a5d572d6dddd369517510b68710fca56b0e9e02fd24bed9a \ @@ -289,10 +306,6 @@ ptyprocess==0.7.0 \ --hash=sha256:4b41f3967fce3af57cc7e94b888626c18bf37a083e3651ca8feeb66d492fef35 \ --hash=sha256:5c5d0a3b48ceee0b48485e0c26037c0acd7d29765ca3fbb5cb3831d347423220 # via pexpect -pycodestyle==2.8.0 \ - --hash=sha256:720f8b39dde8b293825e7ff02c475f3077124006db4f440dcbc9a20b76548a20 \ - --hash=sha256:eddd5847ef438ea1c7870ca7eb78a9d47ce0cdb4851a5523949f2601d0cbbe7f - # via -r requirements.txt pycparser==2.21 \ --hash=sha256:8ee45429555515e1f6b185e78100aea234072576aa43ab53aefcae078162fca9 \ --hash=sha256:e644fdec12f7872f86c58ff790da456218b10f863970249516d60a5eaca77206 @@ -303,17 +316,17 @@ pyenchant==3.2.2 \ --hash=sha256:5facc821ece957208a81423af7d6ec7810dad29697cb0d77aae81e4e11c8e5a6 \ --hash=sha256:6153f521852e23a5add923dbacfbf4bebbb8d70c4e4bad609a8e0f9faeb915d1 # via sphinxcontrib-spelling -pygments==2.11.2 \ - --hash=sha256:44238f1b60a76d78fc8ca0528ee429702aae011c265fe6a8dd8b63049ae41c65 \ - --hash=sha256:4e426f72023d88d03b2fa258de560726ce890ff3b630f88c21cbb8b2503b8c6a +pygments==2.12.0 \ + --hash=sha256:5eb116118f9612ff1ee89ac96437bb6b49e8f04d8a13b514ba26f620208e26eb \ + --hash=sha256:dc9c10fb40944260f6ed4c688ece0cd2048414940f1cea51b8b226318411c519 # via sphinx pympler==1.0.1 \ --hash=sha256:993f1a3599ca3f4fcd7160c7545ad06310c9e12f70174ae7ae8d4e25f6c5d3fa \ --hash=sha256:d260dda9ae781e1eab6ea15bacb84015849833ba5555f141d2d9b7b7473b307d # via -r requirements.txt -pyparsing==3.0.7 \ - --hash=sha256:18ee9022775d270c55187733956460083db60b37d0d0fb357445f3094eed3eea \ - --hash=sha256:a6c06a88f252e6c322f65faf8f418b16213b51bdfaece0524c1c1bc30c63c484 +pyparsing==3.0.8 \ + --hash=sha256:7bf433498c016c4314268d95df76c81b842a4cb2b276fa3312cfb1e1d85f6954 \ + --hash=sha256:ef7b523f6356f763771559412c0d7134753f037822dad1b16945b7b846f7ad06 # via packaging pyrsistent==0.18.1 \ --hash=sha256:0e3e1fcc45199df76053026a51cc59ab2ea3fc7c094c6627e93b7b44cdae2c8c \ @@ -338,9 +351,9 @@ pyrsistent==0.18.1 \ --hash=sha256:f87cc2863ef33c709e237d4b5f4502a62a00fab450c9e020892e8e2ede5847f5 \ --hash=sha256:fd8da6d0124efa2f67d86fa70c851022f87c98e205f0594e1fae044e7119a5a6 # via jsonschema -pytz==2021.3 \ - --hash=sha256:3672058bc3453457b622aab7a1c3bfd5ab0bdae451512f6cf25f64ed37f5b87c \ - --hash=sha256:acad2d8b20a1af07d4e4c9d2e9285c5ed9104354062f275f3fcd88dcef4f1326 +pytz==2022.1 \ + --hash=sha256:1e760e2fe6a8163bc0b3d9a19c4f84342afa0a2affebfaa84b01b978a02ecaa7 \ + --hash=sha256:e68985985296d9a66a881eb3193b0906246245294a881e7c8afe623866ac6a5c # via babel pyyaml==6.0 \ --hash=sha256:0283c35a6a9fbf047493e3a0ce8d79ef5030852c51e9d911a27badfde0605293 \ @@ -396,9 +409,9 @@ snowballstemmer==2.2.0 \ --hash=sha256:09b16deb8547d3412ad7b590689584cd0fe25ec8db3be37788be3810cbf19cb1 \ --hash=sha256:c8e1716e83cc398ae16824e5572ae04e0d9fc2c6b985fb0f900f5f0c96ecba1a # via sphinx -sphinx==4.4.0 \ - --hash=sha256:5da895959511473857b6d0200f56865ed62c31e8f82dd338063b84ec022701fe \ - --hash=sha256:6caad9786055cb1fa22b4a365c1775816b876f91966481765d7d50e9f0dd35cc +sphinx==4.5.0 \ + --hash=sha256:7bf8ca9637a4ee15af412d1a1d9689fec70523a68ca9bb9127c2f3eeb344e2e6 \ + --hash=sha256:ebf612653238bcc8f4359627a9b7ce44ede6fdd75d9d30f68255c7383d3a6226 # via # -r requirements.txt # recommonmark @@ -432,32 +445,68 @@ sphinxcontrib-serializinghtml==1.1.5 \ --hash=sha256:352a9a00ae864471d3a7ead8d7d79f5fc0b57e8b3f95e9867eb9eb28999b92fd \ --hash=sha256:aa5f6de5dfdf809ef505c4895e51ef5c9eac17d0f287933eb49ec495280b6952 # via sphinx -sphinxcontrib-spelling==7.3.2 \ - --hash=sha256:1b99cdb1a30271c7080ec5b968dfc243c2540a960afdc4c052cd59dfe8d94c54 \ - --hash=sha256:9d66dc4990749c5ac52e7eaf17e82f4dc6b4aff6515d26bbf48821829d41bd02 +sphinxcontrib-spelling==7.3.3 \ + --hash=sha256:3819d12629d95e0c909224fa40b462a67e0adb321d50283d7fc0d11686c8ac7e \ + --hash=sha256:8809d5dc175f43f00628134a41ef9fec56db9f794f4eab701f9a5a87f8c69bb0 # via -r requirements.txt syslog-rfc5424-parser==0.3.2 \ --hash=sha256:6134ee1958da89ab7f8d32ed5370a49ddabcc99d75a950b6ec59708417f20a7a \ --hash=sha256:80a9239d4da404a271266000f4c5f00a183af3d03d53d19d7052c8272430bee9 # via -r requirements.txt -tomli==2.0.0 \ - --hash=sha256:b5bde28da1fed24b9bd1d4d2b8cba62300bfb4ec9a6187a957e8ddb9434c5224 \ - --hash=sha256:c292c34f58502a1eb2bbb9f5bbc9a5ebc37bee10ffb8c2d6bbdfa8eb13cc14e1 - # via pep517 -urllib3==1.26.8 \ - --hash=sha256:000ca7f471a233c2251c6c7023ee85305721bfdf18621ebff4fd17a8653427ed \ - --hash=sha256:0e7c33d9a63e7ddfcb86780aac87befc2fbddf46c58dbb487e0855f7ceec283c +tomli==2.0.1 \ + --hash=sha256:939de3e7a6161af0c887ef91b7d41a53e7c5a1ca976325f429cb46ea9bc30ecc \ + --hash=sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f + # via + # black + # pep517 +typed-ast==1.5.3 \ + --hash=sha256:20d5118e494478ef2d3a2702d964dae830aedd7b4d3b626d003eea526be18718 \ + --hash=sha256:27e46cdd01d6c3a0dd8f728b6a938a6751f7bd324817501c15fb056307f918c6 \ + --hash=sha256:27f25232e2dd0edfe1f019d6bfaaf11e86e657d9bdb7b0956db95f560cceb2b3 \ + --hash=sha256:3042bfc9ca118712c9809201f55355479cfcdc17449f9f8db5e744e9625c6805 \ + --hash=sha256:37e5349d1d5de2f4763d534ccb26809d1c24b180a477659a12c4bde9dd677d74 \ + --hash=sha256:4fff9fdcce59dc61ec1b317bdb319f8f4e6b69ebbe61193ae0a60c5f9333dc49 \ + --hash=sha256:542cd732351ba8235f20faa0fc7398946fe1a57f2cdb289e5497e1e7f48cfedb \ + --hash=sha256:5dc2c11ae59003d4a26dda637222d9ae924387f96acae9492df663843aefad55 \ + --hash=sha256:8831479695eadc8b5ffed06fdfb3e424adc37962a75925668deeb503f446c0a3 \ + --hash=sha256:8cdf91b0c466a6c43f36c1964772918a2c04cfa83df8001ff32a89e357f8eb06 \ + --hash=sha256:8e0b8528838ffd426fea8d18bde4c73bcb4167218998cc8b9ee0a0f2bfe678a6 \ + --hash=sha256:8ef1d96ad05a291f5c36895d86d1375c0ee70595b90f6bb5f5fdbee749b146db \ + --hash=sha256:9ad3b48cf2b487be140072fb86feff36801487d4abb7382bb1929aaac80638ea \ + --hash=sha256:9cc9e1457e1feb06b075c8ef8aeb046a28ec351b1958b42c7c31c989c841403a \ + --hash=sha256:9e237e74fd321a55c90eee9bc5d44be976979ad38a29bbd734148295c1ce7617 \ + --hash=sha256:c9f1a27592fac87daa4e3f16538713d705599b0a27dfe25518b80b6b017f0a6d \ + --hash=sha256:d64dabc6336ddc10373922a146fa2256043b3b43e61f28961caec2a5207c56d5 \ + --hash=sha256:e20d196815eeffb3d76b75223e8ffed124e65ee62097e4e73afb5fec6b993e7a \ + --hash=sha256:e34f9b9e61333ecb0f7d79c21c28aa5cd63bec15cb7e1310d7d3da6ce886bc9b \ + --hash=sha256:ed44e81517364cb5ba367e4f68fca01fba42a7a4690d40c07886586ac267d9b9 \ + --hash=sha256:ee852185964744987609b40aee1d2eb81502ae63ee8eef614558f96a56c1902d \ + --hash=sha256:f60d9de0d087454c91b3999a296d0c4558c1666771e3460621875021bf899af9 \ + --hash=sha256:f818c5b81966d4728fec14caa338e30a70dfc3da577984d38f97816c4b3071ec \ + --hash=sha256:fd5df1313915dbd70eaaa88c19030b441742e8b05e6103c631c83b75e0435ccc + # via black +typing-extensions==4.2.0 \ + --hash=sha256:6657594ee297170d19f67d55c05852a874e7eb634f4f753dbd667855e07c1708 \ + --hash=sha256:f1c24655a0da0d1b67f07e17a5e6b2a105894e6824b92096378bb3668ef02376 + # via + # black + # importlib-metadata + # jsonschema +urllib3==1.26.9 \ + --hash=sha256:44ece4d53fb1706f667c9bd1c648f5469a2ec925fcf3a776667042d645472c14 \ + --hash=sha256:aabaf16477806a5e1dd19aa41f8c2b7950dd3c746362d7e3223dbe6de6ac448e # via requests wheel==0.37.1 \ --hash=sha256:4bdcd7d840138086126cd09254dc6195fb4fc6f01c050a1d7236f2630db1d22a \ --hash=sha256:e9a504e793efbca1b8e0e9cb979a249cf4a0a7b5b8c9e8b65a5e39d49529c1c4 # via pip-tools -zipp==3.7.0 \ - --hash=sha256:9f50f446828eb9d45b267433fd3e9da8d801f614129124863f9c51ebceafb87d \ - --hash=sha256:b47250dd24f92b7dd6a0a8fc5244da14608f3ca90a5efcd37a3b1642fac9a375 +zipp==3.8.0 \ + --hash=sha256:56bf8aadb83c24db6c4b577e13de374ccfb67da2078beba1d037c17980bf43ad \ + --hash=sha256:c4f6e5bbf48e74f7a38e7cc5b0480ff42b0ae5178957d564d18932525d5cf099 # via # importlib-metadata # importlib-resources + # pep517 # WARNING: The following packages were not pinned, but pip requires them to be # pinned when the requirements file includes hashes. Consider using the --allow-unsafe flag. diff --git a/test/requirements.txt b/test/requirements.txt index 7df379367a4..a1779671e31 100644 --- a/test/requirements.txt +++ b/test/requirements.txt @@ -1,4 +1,4 @@ -pip-tools==6.5.0 # BSD Keep this in sync with Makefile's PIP_TOOLS_VERSION +pip-tools==6.6.0 # BSD Keep this in sync with Makefile's PIP_TOOLS_VERSION cryptography!=2.0 # BSD/Apache-2.0 deprecation>=2.0.6 # Apache-2.0 faulthandler; python_version < '3.3' # # BSD License (2 clause) @@ -6,7 +6,6 @@ ipaddress; python_version < '3.3' # PSF parameterized>=0.6.1 # BSD pexpect # ISC psutil # BSD -pycodestyle # MIT (Expat license) https://pypi.org/project/pycodestyle/ scapy==2.4.3; python_version >= '2.7' or python_version >= '3.4' # GPL2 https://github.com/secdev/scapy/blob/master/LICENSE six # MIT syslog_rfc5424_parser>=0.3.1 # ISC @@ -20,3 +19,4 @@ recommonmark # MIT pyyaml # MIT jsonschema; python_version >= '3.7' # MIT dataclasses; python_version == '3.6' # Apache-2.0 +black # MIT https://github.com/psf/black diff --git a/test/run_tests.py b/test/run_tests.py index 8cb631ed660..5df37efba6b 100644 --- a/test/run_tests.py +++ b/test/run_tests.py @@ -16,12 +16,28 @@ from multiprocessing.queues import Queue from multiprocessing.managers import BaseManager import framework from config import config, num_cpus, available_cpus, max_vpp_cpus -from framework import VppTestRunner, VppTestCase, \ - get_testcase_doc_name, get_test_description, PASS, FAIL, ERROR, SKIP, \ - TEST_RUN, SKIP_CPU_SHORTAGE +from framework import ( + VppTestRunner, + VppTestCase, + get_testcase_doc_name, + get_test_description, + PASS, + FAIL, + ERROR, + SKIP, + TEST_RUN, + SKIP_CPU_SHORTAGE, +) from debug import spawn_gdb, start_vpp_in_gdb -from log import get_parallel_logger, double_line_delim, RED, YELLOW, GREEN, \ - colorize, single_line_delim +from log import ( + get_parallel_logger, + double_line_delim, + RED, + YELLOW, + GREEN, + colorize, + single_line_delim, +) from discover_tests import discover_tests import sanity_run_vpp from subprocess import check_output, CalledProcessError @@ -50,7 +66,7 @@ class StreamQueueManager(BaseManager): pass -StreamQueueManager.register('StreamQueue', StreamQueue) +StreamQueueManager.register("StreamQueue", StreamQueue) class TestResult(dict): @@ -68,9 +84,11 @@ class TestResult(dict): self.testcases_by_id = testcases_by_id def was_successful(self): - return 0 == len(self[FAIL]) == len(self[ERROR]) \ - and len(self[PASS] + self[SKIP] + self[SKIP_CPU_SHORTAGE]) \ + return ( + 0 == len(self[FAIL]) == len(self[ERROR]) + and len(self[PASS] + self[SKIP] + self[SKIP_CPU_SHORTAGE]) == self.testcase_suite.countTestCases() + ) def no_tests_run(self): return 0 == len(self[TEST_RUN]) @@ -90,10 +108,11 @@ class TestResult(dict): def get_testcase_names(self, test_id): # could be tearDownClass (test_ipsec_esp.TestIpsecEsp1) setup_teardown_match = re.match( - r'((tearDownClass)|(setUpClass)) \((.+\..+)\)', test_id) + r"((tearDownClass)|(setUpClass)) \((.+\..+)\)", test_id + ) if setup_teardown_match: test_name, _, _, testcase_name = setup_teardown_match.groups() - if len(testcase_name.split('.')) == 2: + if len(testcase_name.split(".")) == 2: for key in self.testcases_by_id.keys(): if key.startswith(testcase_name): testcase_name = key @@ -107,8 +126,7 @@ class TestResult(dict): def _get_test_description(self, test_id): if test_id in self.testcases_by_id: - desc = get_test_description(descriptions, - self.testcases_by_id[test_id]) + desc = get_test_description(descriptions, self.testcases_by_id[test_id]) else: desc = test_id return desc @@ -121,17 +139,20 @@ class TestResult(dict): return doc_name -def test_runner_wrapper(suite, keep_alive_pipe, stdouterr_queue, - finished_pipe, result_pipe, logger): +def test_runner_wrapper( + suite, keep_alive_pipe, stdouterr_queue, finished_pipe, result_pipe, logger +): sys.stdout = stdouterr_queue sys.stderr = stdouterr_queue VppTestCase.parallel_handler = logger.handlers[0] - result = VppTestRunner(keep_alive_pipe=keep_alive_pipe, - descriptions=descriptions, - verbosity=config.verbose, - result_pipe=result_pipe, - failfast=config.failfast, - print_summary=False).run(suite) + result = VppTestRunner( + keep_alive_pipe=keep_alive_pipe, + descriptions=descriptions, + verbosity=config.verbose, + result_pipe=result_pipe, + failfast=config.failfast, + print_summary=False, + ).run(suite) finished_pipe.send(result.wasSuccessful()) finished_pipe.close() keep_alive_pipe.close() @@ -139,21 +160,23 @@ def test_runner_wrapper(suite, keep_alive_pipe, stdouterr_queue, class TestCaseWrapper(object): def __init__(self, testcase_suite, manager): - self.keep_alive_parent_end, self.keep_alive_child_end = Pipe( - duplex=False) + self.keep_alive_parent_end, self.keep_alive_child_end = Pipe(duplex=False) self.finished_parent_end, self.finished_child_end = Pipe(duplex=False) self.result_parent_end, self.result_child_end = Pipe(duplex=False) self.testcase_suite = testcase_suite self.stdouterr_queue = manager.StreamQueue(ctx=get_context()) self.logger = get_parallel_logger(self.stdouterr_queue) - self.child = Process(target=test_runner_wrapper, - args=(testcase_suite, - self.keep_alive_child_end, - self.stdouterr_queue, - self.finished_child_end, - self.result_child_end, - self.logger) - ) + self.child = Process( + target=test_runner_wrapper, + args=( + testcase_suite, + self.keep_alive_child_end, + self.stdouterr_queue, + self.finished_child_end, + self.result_child_end, + self.logger, + ), + ) self.child.start() self.last_test_temp_dir = None self.last_test_vpp_binary = None @@ -187,18 +210,20 @@ class TestCaseWrapper(object): if self.last_test_id in self.testcases_by_id: test = self.testcases_by_id[self.last_test_id] class_name = unittest.util.strclass(test.__class__) - test_name = "'{}' ({})".format(get_test_description(descriptions, - test), - self.last_test_id) + test_name = "'{}' ({})".format( + get_test_description(descriptions, test), self.last_test_id + ) else: test_name = self.last_test_id - class_name = re.match(r'((tearDownClass)|(setUpClass)) ' - r'\((.+\..+)\)', test_name).groups()[3] + class_name = re.match( + r"((tearDownClass)|(setUpClass)) " r"\((.+\..+)\)", test_name + ).groups()[3] if class_name not in self.testclasess_with_core: self.testclasess_with_core[class_name] = ( test_name, self.last_test_vpp_binary, - self.last_test_temp_dir) + self.last_test_temp_dir, + ) def close_pipes(self): self.keep_alive_child_end.close() @@ -219,8 +244,9 @@ class TestCaseWrapper(object): return self.testcase_suite.get_assigned_cpus() -def stdouterr_reader_wrapper(unread_testcases, finished_unread_testcases, - read_testcases): +def stdouterr_reader_wrapper( + unread_testcases, finished_unread_testcases, read_testcases +): read_testcase = None while read_testcases.is_set() or unread_testcases: if finished_unread_testcases: @@ -229,7 +255,7 @@ def stdouterr_reader_wrapper(unread_testcases, finished_unread_testcases, elif unread_testcases: read_testcase = unread_testcases.pop() if read_testcase: - data = '' + data = "" while data is not None: sys.stdout.write(data) data = read_testcase.stdouterr_queue.get() @@ -243,52 +269,62 @@ def handle_failed_suite(logger, last_test_temp_dir, vpp_pid, vpp_binary): if last_test_temp_dir: # Need to create link in case of a timeout or core dump without failure lttd = os.path.basename(last_test_temp_dir) - link_path = '%s%s-FAILED' % (config.failed_dir, lttd) + link_path = "%s%s-FAILED" % (config.failed_dir, lttd) if not os.path.exists(link_path): os.symlink(last_test_temp_dir, link_path) - logger.error("Symlink to failed testcase directory: %s -> %s" - % (link_path, lttd)) + logger.error( + "Symlink to failed testcase directory: %s -> %s" % (link_path, lttd) + ) # Report core existence core_path = get_core_path(last_test_temp_dir) if os.path.exists(core_path): logger.error( - "Core-file exists in test temporary directory: %s!" % - core_path) + "Core-file exists in test temporary directory: %s!" % core_path + ) check_core_path(logger, core_path) logger.debug("Running 'file %s':" % core_path) try: info = check_output(["file", core_path]) logger.debug(info) except CalledProcessError as e: - logger.error("Subprocess returned with return code " - "while running `file' utility on core-file " - "returned: " - "rc=%s", e.returncode) + logger.error( + "Subprocess returned with return code " + "while running `file' utility on core-file " + "returned: " + "rc=%s", + e.returncode, + ) except OSError as e: - logger.error("Subprocess returned with OS error while " - "running 'file' utility " - "on core-file: " - "(%s) %s", e.errno, e.strerror) + logger.error( + "Subprocess returned with OS error while " + "running 'file' utility " + "on core-file: " + "(%s) %s", + e.errno, + e.strerror, + ) except Exception as e: - logger.exception("Unexpected error running `file' utility " - "on core-file") + logger.exception("Unexpected error running `file' utility on core-file") logger.error(f"gdb {vpp_binary} {core_path}") if vpp_pid: # Copy api post mortem api_post_mortem_path = "/tmp/api_post_mortem.%d" % vpp_pid if os.path.isfile(api_post_mortem_path): - logger.error("Copying api_post_mortem.%d to %s" % - (vpp_pid, last_test_temp_dir)) + logger.error( + "Copying api_post_mortem.%d to %s" % (vpp_pid, last_test_temp_dir) + ) shutil.copy2(api_post_mortem_path, last_test_temp_dir) def check_and_handle_core(vpp_binary, tempdir, core_crash_test): if is_core_present(tempdir): if debug_core: - print('VPP core detected in %s. Last test running was %s' % - (tempdir, core_crash_test)) + print( + "VPP core detected in %s. Last test running was %s" + % (tempdir, core_crash_test) + ) print(single_line_delim) spawn_gdb(vpp_binary, get_core_path(tempdir)) print(single_line_delim) @@ -305,10 +341,9 @@ def handle_cores(failed_testcases): check_and_handle_core(vpp_binary, tempdir, test) -def process_finished_testsuite(wrapped_testcase_suite, - finished_testcase_suites, - failed_wrapped_testcases, - results): +def process_finished_testsuite( + wrapped_testcase_suite, finished_testcase_suites, failed_wrapped_testcases, results +): results.append(wrapped_testcase_suite.result) finished_testcase_suites.add(wrapped_testcase_suite) stop_run = False @@ -317,10 +352,12 @@ def process_finished_testsuite(wrapped_testcase_suite, if not wrapped_testcase_suite.was_successful(): failed_wrapped_testcases.add(wrapped_testcase_suite) - handle_failed_suite(wrapped_testcase_suite.logger, - wrapped_testcase_suite.last_test_temp_dir, - wrapped_testcase_suite.vpp_pid, - wrapped_testcase_suite.last_test_vpp_binary,) + handle_failed_suite( + wrapped_testcase_suite.logger, + wrapped_testcase_suite.last_test_temp_dir, + wrapped_testcase_suite.vpp_pid, + wrapped_testcase_suite.last_test_vpp_binary, + ) return stop_run @@ -355,17 +392,17 @@ def run_forked(testcase_suites): nonlocal wrapped_testcase_suites nonlocal unread_testcases nonlocal free_cpus - suite.assign_cpus(free_cpus[:suite.cpus_used]) - free_cpus = free_cpus[suite.cpus_used:] + suite.assign_cpus(free_cpus[: suite.cpus_used]) + free_cpus = free_cpus[suite.cpus_used :] wrapper = TestCaseWrapper(suite, manager) wrapped_testcase_suites.add(wrapper) unread_testcases.add(wrapper) on_suite_start(suite) def can_run_suite(suite): - return (tests_running < max_concurrent_tests and - (suite.cpus_used <= len(free_cpus) or - suite.cpus_used > max_vpp_cpus)) + return tests_running < max_concurrent_tests and ( + suite.cpus_used <= len(free_cpus) or suite.cpus_used > max_vpp_cpus + ) while free_cpus and testcase_suites: a_suite = testcase_suites[0] @@ -385,10 +422,10 @@ def run_forked(testcase_suites): read_from_testcases = threading.Event() read_from_testcases.set() - stdouterr_thread = threading.Thread(target=stdouterr_reader_wrapper, - args=(unread_testcases, - finished_unread_testcases, - read_from_testcases)) + stdouterr_thread = threading.Thread( + target=stdouterr_reader_wrapper, + args=(unread_testcases, finished_unread_testcases, read_from_testcases), + ) stdouterr_thread.start() failed_wrapped_testcases = set() @@ -400,59 +437,75 @@ def run_forked(testcase_suites): for wrapped_testcase_suite in wrapped_testcase_suites: while wrapped_testcase_suite.result_parent_end.poll(): wrapped_testcase_suite.result.process_result( - *wrapped_testcase_suite.result_parent_end.recv()) + *wrapped_testcase_suite.result_parent_end.recv() + ) wrapped_testcase_suite.last_heard = time.time() while wrapped_testcase_suite.keep_alive_parent_end.poll(): - wrapped_testcase_suite.last_test, \ - wrapped_testcase_suite.last_test_vpp_binary, \ - wrapped_testcase_suite.last_test_temp_dir, \ - wrapped_testcase_suite.vpp_pid = \ - wrapped_testcase_suite.keep_alive_parent_end.recv() + ( + wrapped_testcase_suite.last_test, + wrapped_testcase_suite.last_test_vpp_binary, + wrapped_testcase_suite.last_test_temp_dir, + wrapped_testcase_suite.vpp_pid, + ) = wrapped_testcase_suite.keep_alive_parent_end.recv() wrapped_testcase_suite.last_heard = time.time() if wrapped_testcase_suite.finished_parent_end.poll(): wrapped_testcase_suite.finished_parent_end.recv() wrapped_testcase_suite.last_heard = time.time() - stop_run = process_finished_testsuite( - wrapped_testcase_suite, - finished_testcase_suites, - failed_wrapped_testcases, - results) or stop_run + stop_run = ( + process_finished_testsuite( + wrapped_testcase_suite, + finished_testcase_suites, + failed_wrapped_testcases, + results, + ) + or stop_run + ) continue fail = False - if wrapped_testcase_suite.last_heard + config.timeout < \ - time.time(): + if wrapped_testcase_suite.last_heard + config.timeout < time.time(): fail = True wrapped_testcase_suite.logger.critical( "Child test runner process timed out " - "(last test running was `%s' in `%s')!" % - (wrapped_testcase_suite.last_test, - wrapped_testcase_suite.last_test_temp_dir)) + "(last test running was `%s' in `%s')!" + % ( + wrapped_testcase_suite.last_test, + wrapped_testcase_suite.last_test_temp_dir, + ) + ) elif not wrapped_testcase_suite.child.is_alive(): fail = True wrapped_testcase_suite.logger.critical( "Child test runner process unexpectedly died " - "(last test running was `%s' in `%s')!" % - (wrapped_testcase_suite.last_test, - wrapped_testcase_suite.last_test_temp_dir)) - elif wrapped_testcase_suite.last_test_temp_dir and \ - wrapped_testcase_suite.last_test_vpp_binary: - if is_core_present( - wrapped_testcase_suite.last_test_temp_dir): + "(last test running was `%s' in `%s')!" + % ( + wrapped_testcase_suite.last_test, + wrapped_testcase_suite.last_test_temp_dir, + ) + ) + elif ( + wrapped_testcase_suite.last_test_temp_dir + and wrapped_testcase_suite.last_test_vpp_binary + ): + if is_core_present(wrapped_testcase_suite.last_test_temp_dir): wrapped_testcase_suite.add_testclass_with_core() if wrapped_testcase_suite.core_detected_at is None: - wrapped_testcase_suite.core_detected_at = \ - time.time() - elif wrapped_testcase_suite.core_detected_at + \ - core_timeout < time.time(): + wrapped_testcase_suite.core_detected_at = time.time() + elif ( + wrapped_testcase_suite.core_detected_at + core_timeout + < time.time() + ): wrapped_testcase_suite.logger.critical( "Child test runner process unresponsive and " "core-file exists in test temporary directory " - "(last test running was `%s' in `%s')!" % - (wrapped_testcase_suite.last_test, - wrapped_testcase_suite.last_test_temp_dir)) + "(last test running was `%s' in `%s')!" + % ( + wrapped_testcase_suite.last_test, + wrapped_testcase_suite.last_test_temp_dir, + ) + ) fail = True if fail: @@ -461,19 +514,23 @@ def run_forked(testcase_suites): # terminating the child process tends to leave orphan # VPP process around if wrapped_testcase_suite.vpp_pid: - os.kill(wrapped_testcase_suite.vpp_pid, - signal.SIGTERM) + os.kill(wrapped_testcase_suite.vpp_pid, signal.SIGTERM) except OSError: # already dead pass wrapped_testcase_suite.result.crashed = True wrapped_testcase_suite.result.process_result( - wrapped_testcase_suite.last_test_id, ERROR) - stop_run = process_finished_testsuite( - wrapped_testcase_suite, - finished_testcase_suites, - failed_wrapped_testcases, - results) or stop_run + wrapped_testcase_suite.last_test_id, ERROR + ) + stop_run = ( + process_finished_testsuite( + wrapped_testcase_suite, + finished_testcase_suites, + failed_wrapped_testcases, + results, + ) + or stop_run + ) for finished_testcase in finished_testcase_suites: # Somewhat surprisingly, the join below may @@ -484,9 +541,9 @@ def run_forked(testcase_suites): join_end = time.time() if join_end - join_start >= test_finished_join_timeout: finished_testcase.logger.error( - "Timeout joining finished test: %s (pid %d)" % - (finished_testcase.last_test, - finished_testcase.child.pid)) + "Timeout joining finished test: %s (pid %d)" + % (finished_testcase.last_test, finished_testcase.child.pid) + ) finished_testcase.close_pipes() wrapped_testcase_suites.remove(finished_testcase) finished_unread_testcases.add(finished_testcase) @@ -548,7 +605,7 @@ class TestSuiteWrapper(unittest.TestSuite): class SplitToSuitesCallback: def __init__(self, filter_callback): self.suites = {} - self.suite_name = 'default' + self.suite_name = "default" self.filter_callback = filter_callback self.filtered = TestSuiteWrapper() @@ -573,28 +630,27 @@ def parse_test_filter(test_filter): filter_class_name = None filter_func_name = None if f: - if '.' in f: - parts = f.split('.') + if "." in f: + parts = f.split(".") if len(parts) > 3: - raise Exception("Unrecognized %s option: %s" % - (test_option, f)) + raise Exception("Unrecognized %s option: %s" % (test_option, f)) if len(parts) > 2: - if parts[2] not in ('*', ''): + if parts[2] not in ("*", ""): filter_func_name = parts[2] - if parts[1] not in ('*', ''): + if parts[1] not in ("*", ""): filter_class_name = parts[1] - if parts[0] not in ('*', ''): - if parts[0].startswith('test_'): + if parts[0] not in ("*", ""): + if parts[0].startswith("test_"): filter_file_name = parts[0] else: - filter_file_name = 'test_%s' % parts[0] + filter_file_name = "test_%s" % parts[0] else: - if f.startswith('test_'): + if f.startswith("test_"): filter_file_name = f else: - filter_file_name = 'test_%s' % f + filter_file_name = "test_%s" % f if filter_file_name: - filter_file_name = '%s.py' % filter_file_name + filter_file_name = "%s.py" % filter_file_name return filter_file_name, filter_class_name, filter_func_name @@ -608,7 +664,7 @@ def filter_tests(tests, filter_cb): result.addTest(x) elif isinstance(t, unittest.TestCase): # this is a single test - parts = t.id().split('.') + parts = t.id().split(".") # t.id() for common cases like this: # test_classifier.TestClassifier.test_acl_ip # apply filtering only if it is so @@ -645,11 +701,11 @@ class FilterByClassList: self.classes_with_filenames = classes_with_filenames def __call__(self, file_name, class_name, func_name): - return '.'.join([file_name, class_name]) in self.classes_with_filenames + return ".".join([file_name, class_name]) in self.classes_with_filenames def suite_from_failed(suite, failed): - failed = {x.rsplit('.', 1)[0] for x in failed} + failed = {x.rsplit(".", 1)[0] for x in failed} filter_cb = FilterByClassList(failed) suite = filter_tests(suite, filter_cb) return suite @@ -695,9 +751,9 @@ class AllResults(dict): return retval def print_results(self): - print('') + print("") print(double_line_delim) - print('TEST RESULTS:') + print("TEST RESULTS:") def indent_results(lines): lines = list(filter(None, lines)) @@ -707,62 +763,86 @@ class AllResults(dict): padding = " " * (maximum - l.index(":")) print(f"{padding}{l}") - indent_results([ - f'Scheduled tests: {self.all_testcases}', - f'Executed tests: {self[TEST_RUN]}', - f'Passed tests: {colorize(self[PASS], GREEN)}', - f'Skipped tests: {colorize(self[SKIP], YELLOW)}' - if self[SKIP] else None, - f'Not Executed tests: {colorize(self.not_executed, RED)}' - if self.not_executed else None, - f'Failures: {colorize(self[FAIL], RED)}' if self[FAIL] else None, - f'Errors: {colorize(self[ERROR], RED)}' if self[ERROR] else None, - 'Tests skipped due to lack of CPUS: ' - f'{colorize(self[SKIP_CPU_SHORTAGE], YELLOW)}' - if self[SKIP_CPU_SHORTAGE] else None - ]) + indent_results( + [ + f"Scheduled tests: {self.all_testcases}", + f"Executed tests: {self[TEST_RUN]}", + f"Passed tests: {colorize(self[PASS], GREEN)}", + f"Skipped tests: {colorize(self[SKIP], YELLOW)}" + if self[SKIP] + else None, + f"Not Executed tests: {colorize(self.not_executed, RED)}" + if self.not_executed + else None, + f"Failures: {colorize(self[FAIL], RED)}" if self[FAIL] else None, + f"Errors: {colorize(self[ERROR], RED)}" if self[ERROR] else None, + "Tests skipped due to lack of CPUS: " + f"{colorize(self[SKIP_CPU_SHORTAGE], YELLOW)}" + if self[SKIP_CPU_SHORTAGE] + else None, + ] + ) if self.all_failed > 0: - print('FAILURES AND ERRORS IN TESTS:') + print("FAILURES AND ERRORS IN TESTS:") for result in self.results_per_suite: failed_testcase_ids = result[FAIL] errored_testcase_ids = result[ERROR] old_testcase_name = None if failed_testcase_ids: for failed_test_id in failed_testcase_ids: - new_testcase_name, test_name = \ - result.get_testcase_names(failed_test_id) + new_testcase_name, test_name = result.get_testcase_names( + failed_test_id + ) if new_testcase_name != old_testcase_name: - print(' Testcase name: {}'.format( - colorize(new_testcase_name, RED))) + print( + " Testcase name: {}".format( + colorize(new_testcase_name, RED) + ) + ) old_testcase_name = new_testcase_name - print(' FAILURE: {} [{}]'.format( - colorize(test_name, RED), failed_test_id)) + print( + " FAILURE: {} [{}]".format( + colorize(test_name, RED), failed_test_id + ) + ) if errored_testcase_ids: for errored_test_id in errored_testcase_ids: - new_testcase_name, test_name = \ - result.get_testcase_names(errored_test_id) + new_testcase_name, test_name = result.get_testcase_names( + errored_test_id + ) if new_testcase_name != old_testcase_name: - print(' Testcase name: {}'.format( - colorize(new_testcase_name, RED))) + print( + " Testcase name: {}".format( + colorize(new_testcase_name, RED) + ) + ) old_testcase_name = new_testcase_name - print(' ERROR: {} [{}]'.format( - colorize(test_name, RED), errored_test_id)) + print( + " ERROR: {} [{}]".format( + colorize(test_name, RED), errored_test_id + ) + ) if self.testsuites_no_tests_run: - print('TESTCASES WHERE NO TESTS WERE SUCCESSFULLY EXECUTED:') + print("TESTCASES WHERE NO TESTS WERE SUCCESSFULLY EXECUTED:") tc_classes = set() for testsuite in self.testsuites_no_tests_run: for testcase in testsuite: tc_classes.add(get_testcase_doc_name(testcase)) for tc_class in tc_classes: - print(' {}'.format(colorize(tc_class, RED))) + print(" {}".format(colorize(tc_class, RED))) if self[SKIP_CPU_SHORTAGE]: print() - print(colorize(' SOME TESTS WERE SKIPPED BECAUSE THERE ARE NOT' - ' ENOUGH CPUS AVAILABLE', YELLOW)) + print( + colorize( + " SOME TESTS WERE SKIPPED BECAUSE THERE ARE NOT" + " ENOUGH CPUS AVAILABLE", + YELLOW, + ) + ) print(double_line_delim) - print('') + print("") @property def not_executed(self): @@ -805,7 +885,7 @@ def parse_results(results): return return_code, results_per_suite.rerun -if __name__ == '__main__': +if __name__ == "__main__": print(f"Config is: {config}") @@ -831,35 +911,41 @@ if __name__ == '__main__': print(f"OS reports {num_cpus} available cpu(s).") test_jobs = config.jobs - if test_jobs == 'auto': + if test_jobs == "auto": if run_interactive: max_concurrent_tests = 1 - print('Interactive mode required, running tests consecutively.') + print("Interactive mode required, running tests consecutively.") else: max_concurrent_tests = num_cpus - print(f"Running at most {max_concurrent_tests} python test " - "processes concurrently.") + print( + f"Running at most {max_concurrent_tests} python test " + "processes concurrently." + ) else: max_concurrent_tests = test_jobs - print(f"Running at most {max_concurrent_tests} python test processes " - "concurrently as set by 'TEST_JOBS'.") + print( + f"Running at most {max_concurrent_tests} python test processes " + "concurrently as set by 'TEST_JOBS'." + ) print(f"Using at most {max_vpp_cpus} cpus for VPP threads.") if run_interactive and max_concurrent_tests > 1: raise NotImplementedError( - 'Running tests interactively (DEBUG is gdb[server] or ATTACH or ' - 'STEP is set) in parallel (TEST_JOBS is more than 1) is not ' - 'supported') + "Running tests interactively (DEBUG is gdb[server] or ATTACH or " + "STEP is set) in parallel (TEST_JOBS is more than 1) is not " + "supported" + ) descriptions = True print("Running tests using custom test runner.") - filter_file, filter_class, filter_func = \ - parse_test_filter(config.filter) + filter_file, filter_class, filter_func = parse_test_filter(config.filter) - print("Selected filters: file=%s, class=%s, function=%s" % ( - filter_file, filter_class, filter_func)) + print( + "Selected filters: file=%s, class=%s, function=%s" + % (filter_file, filter_class, filter_func) + ) filter_cb = FilterByTestOption(filter_file, filter_class, filter_func) @@ -882,17 +968,19 @@ if __name__ == '__main__': # in stopTest() (for that to trigger, test function must run) for t in testcase_suite: for m in dir(t): - if m.startswith('test_'): + if m.startswith("test_"): setattr(t, m, lambda: t.skipTest("not enough cpus")) - setattr(t.__class__, 'setUpClass', lambda: None) - setattr(t.__class__, 'tearDownClass', lambda: None) - setattr(t, 'setUp', lambda: None) - setattr(t, 'tearDown', lambda: None) + setattr(t.__class__, "setUpClass", lambda: None) + setattr(t.__class__, "tearDownClass", lambda: None) + setattr(t, "setUp", lambda: None) + setattr(t, "tearDown", lambda: None) t.__class__.skipped_due_to_cpu_lack = True suites.append(testcase_suite) - print("%s out of %s tests match specified filters" % ( - tests_amount, tests_amount + cb.filtered.countTestCases())) + print( + "%s out of %s tests match specified filters" + % (tests_amount, tests_amount + cb.filtered.countTestCases()) + ) if not config.extended: print("Not running extended tests (some tests will be skipped)") @@ -903,49 +991,60 @@ if __name__ == '__main__': if run_interactive and suites: # don't fork if requiring interactive terminal - print('Running tests in foreground in the current process') + print("Running tests in foreground in the current process") full_suite = unittest.TestSuite() free_cpus = list(available_cpus) cpu_shortage = False for suite in suites: if suite.cpus_used <= max_vpp_cpus: - suite.assign_cpus(free_cpus[:suite.cpus_used]) + suite.assign_cpus(free_cpus[: suite.cpus_used]) else: suite.assign_cpus([]) cpu_shortage = True full_suite.addTests(suites) - result = VppTestRunner(verbosity=config.verbose, - failfast=config.failfast, - print_summary=True).run(full_suite) + result = VppTestRunner( + verbosity=config.verbose, failfast=config.failfast, print_summary=True + ).run(full_suite) was_successful = result.wasSuccessful() if not was_successful: for test_case_info in result.failed_test_cases_info: - handle_failed_suite(test_case_info.logger, - test_case_info.tempdir, - test_case_info.vpp_pid, - config.vpp) + handle_failed_suite( + test_case_info.logger, + test_case_info.tempdir, + test_case_info.vpp_pid, + config.vpp, + ) if test_case_info in result.core_crash_test_cases_info: - check_and_handle_core(test_case_info.vpp_bin_path, - test_case_info.tempdir, - test_case_info.core_crash_test) + check_and_handle_core( + test_case_info.vpp_bin_path, + test_case_info.tempdir, + test_case_info.core_crash_test, + ) if cpu_shortage: print() - print(colorize('SOME TESTS WERE SKIPPED BECAUSE THERE ARE NOT' - ' ENOUGH CPUS AVAILABLE', YELLOW)) + print( + colorize( + "SOME TESTS WERE SKIPPED BECAUSE THERE ARE NOT" + " ENOUGH CPUS AVAILABLE", + YELLOW, + ) + ) print() sys.exit(not was_successful) else: - print('Running each VPPTestCase in a separate background process' - f' with at most {max_concurrent_tests} parallel python test ' - 'process(es)') + print( + "Running each VPPTestCase in a separate background process" + f" with at most {max_concurrent_tests} parallel python test " + "process(es)" + ) exit_code = 0 while suites and attempts > 0: results = run_forked(suites) exit_code, suites = parse_results(results) attempts -= 1 if exit_code == 0: - print('Test run was successful') + print("Test run was successful") else: - print('%s attempt(s) left.' % attempts) + print("%s attempt(s) left." % attempts) sys.exit(exit_code) diff --git a/test/sanity_run_vpp.py b/test/sanity_run_vpp.py index b923c791b61..5e2b3c1f92b 100644 --- a/test/sanity_run_vpp.py +++ b/test/sanity_run_vpp.py @@ -8,7 +8,8 @@ from framework import VppDiedError, VppTestCase, KeepAliveReporter class SanityTestCase(VppTestCase): - """ Sanity test case - verify whether VPP is able to start """ + """Sanity test case - verify whether VPP is able to start""" + cpus = [0] # don't ask to debug SanityTestCase @@ -43,11 +44,11 @@ def main(): y.close() if rc == 0: - print('Sanity test case passed.') + print("Sanity test case passed.") else: - print('Sanity test case failed.') + print("Sanity test case failed.") return rc -if __name__ == '__main__': +if __name__ == "__main__": sys.exit(main()) diff --git a/test/template_bd.py b/test/template_bd.py index bebe76d765d..55aaa5a8f4c 100644 --- a/test/template_bd.py +++ b/test/template_bd.py @@ -8,51 +8,55 @@ from scapy.layers.inet import IP, UDP class BridgeDomain(metaclass=abc.ABCMeta): - """ Bridge domain abstraction """ + """Bridge domain abstraction""" @property def frame_request(self): - """ Ethernet frame modeling a generic request """ - return (Ether(src='00:00:00:00:00:01', dst='00:00:00:00:00:02') / - IP(src='1.2.3.4', dst='4.3.2.1') / - UDP(sport=10000, dport=20000) / - Raw('\xa5' * 100)) + """Ethernet frame modeling a generic request""" + return ( + Ether(src="00:00:00:00:00:01", dst="00:00:00:00:00:02") + / IP(src="1.2.3.4", dst="4.3.2.1") + / UDP(sport=10000, dport=20000) + / Raw("\xa5" * 100) + ) @property def frame_reply(self): - """ Ethernet frame modeling a generic reply """ - return (Ether(src='00:00:00:00:00:02', dst='00:00:00:00:00:01') / - IP(src='4.3.2.1', dst='1.2.3.4') / - UDP(sport=20000, dport=10000) / - Raw('\xa5' * 100)) + """Ethernet frame modeling a generic reply""" + return ( + Ether(src="00:00:00:00:00:02", dst="00:00:00:00:00:01") + / IP(src="4.3.2.1", dst="1.2.3.4") + / UDP(sport=20000, dport=10000) + / Raw("\xa5" * 100) + ) @abc.abstractmethod def ip_range(self, start, end): - """ range of remote ip's """ + """range of remote ip's""" pass @abc.abstractmethod def encap_mcast(self, pkt, src_ip, src_mac, vni): - """ Encapsulate mcast packet """ + """Encapsulate mcast packet""" pass @abc.abstractmethod def encapsulate(self, pkt, vni): - """ Encapsulate packet """ + """Encapsulate packet""" pass @abc.abstractmethod def decapsulate(self, pkt): - """ Decapsulate packet """ + """Decapsulate packet""" pass @abc.abstractmethod def check_encapsulation(self, pkt, vni, local_only=False): - """ Verify the encapsulation """ + """Verify the encapsulation""" pass def assert_eq_pkts(self, pkt1, pkt2): - """ Verify the Ether, IP, UDP, payload are equal in both + """Verify the Ether, IP, UDP, payload are equal in both packets """ self.assertEqual(pkt1[Ether].src, pkt2[Ether].src) @@ -64,15 +68,18 @@ class BridgeDomain(metaclass=abc.ABCMeta): self.assertEqual(pkt1[Raw], pkt2[Raw]) def test_decap(self): - """ Decapsulation test + """Decapsulation test Send encapsulated frames from pg0 Verify receipt of decapsulated frames on pg1 """ - encapsulated_pkt = self.encapsulate(self.frame_request, - self.single_tunnel_vni) + encapsulated_pkt = self.encapsulate(self.frame_request, self.single_tunnel_vni) - self.pg0.add_stream([encapsulated_pkt, ]) + self.pg0.add_stream( + [ + encapsulated_pkt, + ] + ) self.pg1.enable_capture() @@ -85,7 +92,7 @@ class BridgeDomain(metaclass=abc.ABCMeta): self.assert_eq_pkts(pkt, self.frame_request) def test_encap(self): - """ Encapsulation test + """Encapsulation test Send frames from pg1 Verify receipt of encapsulated frames on pg0 """ @@ -104,7 +111,7 @@ class BridgeDomain(metaclass=abc.ABCMeta): self.assert_eq_pkts(payload, self.frame_reply) def test_ucast_flood(self): - """ Unicast flood test + """Unicast flood test Send frames from pg3 Verify receipt of encapsulated frames on pg0 """ @@ -122,7 +129,7 @@ class BridgeDomain(metaclass=abc.ABCMeta): self.assert_eq_pkts(payload, self.frame_reply) def test_mcast_flood(self): - """ Multicast flood test + """Multicast flood test Send frames from pg2 Verify receipt of encapsulated frames on pg0 """ @@ -135,14 +142,15 @@ class BridgeDomain(metaclass=abc.ABCMeta): # Pick first received frame and check if it's correctly encapsulated. out = self.pg0.get_capture(1) pkt = out[0] - self.check_encapsulation(pkt, self.mcast_flood_bd, - local_only=False, mcast_pkt=True) + self.check_encapsulation( + pkt, self.mcast_flood_bd, local_only=False, mcast_pkt=True + ) payload = self.decapsulate(pkt) self.assert_eq_pkts(payload, self.frame_reply) def test_mcast_rcv(self): - """ Multicast receive test + """Multicast receive test Send 20 encapsulated frames from pg0 only 10 match unicast tunnels Verify receipt of 10 decap frames on pg2 """ @@ -151,7 +159,8 @@ class BridgeDomain(metaclass=abc.ABCMeta): ip_range_end = 30 mcast_stream = [ self.encap_mcast(self.frame_request, ip, mac, self.mcast_flood_bd) - for ip in self.ip_range(ip_range_start, ip_range_end)] + for ip in self.ip_range(ip_range_start, ip_range_end) + ] self.pg0.add_stream(mcast_stream) self.pg2.enable_capture() self.pg_start() diff --git a/test/template_classifier.py b/test/template_classifier.py index 7ce69d436f5..ec2a4143eec 100644 --- a/test/template_classifier.py +++ b/test/template_classifier.py @@ -30,13 +30,11 @@ class VarMatch: class TestClassifier(VppTestCase): - @staticmethod def _resolve_mask_match(mask_match): mask_match = binascii.unhexlify(mask_match) mask_match_len = ((len(mask_match) - 1) // 16 + 1) * 16 - mask_match = mask_match + b'\0' * \ - (mask_match_len - len(mask_match)) + mask_match = mask_match + b"\0" * (mask_match_len - len(mask_match)) return mask_match, mask_match_len @classmethod @@ -47,7 +45,7 @@ class TestClassifier(VppTestCase): variables and configure VPP. """ super(TestClassifier, cls).setUpClass() - cls.acl_active_table = '' + cls.acl_active_table = "" cls.af = AF_INET def setUp(self): @@ -113,13 +111,15 @@ class TestClassifier(VppTestCase): self.logger.info(self.vapi.cli("show ip fib")) self.logger.info(self.vapi.cli("show error")) - if self.acl_active_table.endswith('out'): + if self.acl_active_table.endswith("out"): self.output_acl_set_interface( - self.pg0, self.acl_tbl_idx.get(self.acl_active_table), 0) - elif self.acl_active_table != '': + self.pg0, self.acl_tbl_idx.get(self.acl_active_table), 0 + ) + elif self.acl_active_table != "": self.input_acl_set_interface( - self.pg0, self.acl_tbl_idx.get(self.acl_active_table), 0) - self.acl_active_table = '' + self.pg0, self.acl_tbl_idx.get(self.acl_active_table), 0 + ) + self.acl_active_table = "" for intf in self.interfaces: if self.af == AF_INET: @@ -131,7 +131,7 @@ class TestClassifier(VppTestCase): super(TestClassifier, self).tearDown() @staticmethod - def build_mac_match(dst_mac='', src_mac='', ether_type=''): + def build_mac_match(dst_mac="", src_mac="", ether_type=""): """Build MAC ACL match data with hexstring format. :param str dst_mac: source MAC address <x:x:x:x:x:x> @@ -139,15 +139,16 @@ class TestClassifier(VppTestCase): :param str ether_type: ethernet type <0-ffff> """ if dst_mac: - dst_mac = dst_mac.replace(':', '') + dst_mac = dst_mac.replace(":", "") if src_mac: - src_mac = src_mac.replace(':', '') + src_mac = src_mac.replace(":", "") - return ('{!s:0>12}{!s:0>12}{!s:0>4}'.format( - dst_mac, src_mac, ether_type)).rstrip() + return ( + "{!s:0>12}{!s:0>12}{!s:0>4}".format(dst_mac, src_mac, ether_type) + ).rstrip() @staticmethod - def build_mac_mask(dst_mac='', src_mac='', ether_type=''): + def build_mac_mask(dst_mac="", src_mac="", ether_type=""): """Build MAC ACL mask data with hexstring format. :param str dst_mac: source MAC address <0-ffffffffffff> @@ -155,12 +156,12 @@ class TestClassifier(VppTestCase): :param str ether_type: ethernet type <0-ffff> """ - return ('{!s:0>12}{!s:0>12}{!s:0>4}'.format( - dst_mac, src_mac, ether_type)).rstrip() + return ( + "{!s:0>12}{!s:0>12}{!s:0>4}".format(dst_mac, src_mac, ether_type) + ).rstrip() @staticmethod - def build_ip_mask(proto='', src_ip='', dst_ip='', - src_port='', dst_port=''): + def build_ip_mask(proto="", src_ip="", dst_ip="", src_port="", dst_port=""): """Build IP ACL mask data with hexstring format. :param str proto: protocol number <0-ff> @@ -170,12 +171,14 @@ class TestClassifier(VppTestCase): :param str dst_port: destination port number <0-ffff> """ - return ('{!s:0>20}{!s:0>12}{!s:0>8}{!s:0>4}{!s:0>4}'.format( - proto, src_ip, dst_ip, src_port, dst_port)).rstrip('0') + return ( + "{!s:0>20}{!s:0>12}{!s:0>8}{!s:0>4}{!s:0>4}".format( + proto, src_ip, dst_ip, src_port, dst_port + ) + ).rstrip("0") @staticmethod - def build_ip6_mask(nh='', src_ip='', dst_ip='', - src_port='', dst_port=''): + def build_ip6_mask(nh="", src_ip="", dst_ip="", src_port="", dst_port=""): """Build IPv6 ACL mask data with hexstring format. :param str nh: next header number <0-ff> @@ -185,24 +188,26 @@ class TestClassifier(VppTestCase): :param str dst_port: destination port number <0-ffff> """ - return ('{!s:0>14}{!s:0>34}{!s:0>32}{!s:0>4}{!s:0>4}'.format( - nh, src_ip, dst_ip, src_port, dst_port)).rstrip('0') + return ( + "{!s:0>14}{!s:0>34}{!s:0>32}{!s:0>4}{!s:0>4}".format( + nh, src_ip, dst_ip, src_port, dst_port + ) + ).rstrip("0") @staticmethod def build_payload_mask(masks): - payload_mask = '' + payload_mask = "" for mask in masks: # offset is specified in bytes, convert to hex format. length = (mask.offset * 2) + len(mask.spec) - format_spec = '{!s:0>' + str(length) + '}' + format_spec = "{!s:0>" + str(length) + "}" payload_mask += format_spec.format(mask.spec) - return payload_mask.rstrip('0') + return payload_mask.rstrip("0") @staticmethod - def build_ip_match(proto=0, src_ip='', dst_ip='', - src_port=0, dst_port=0): + def build_ip_match(proto=0, src_ip="", dst_ip="", src_port=0, dst_port=0): """Build IP ACL match data with hexstring format. :param int proto: protocol number with valid option "x" @@ -212,17 +217,18 @@ class TestClassifier(VppTestCase): :param int dst_port: destination port number "x" """ if src_ip: - src_ip = binascii.hexlify(socket.inet_aton(src_ip)).decode('ascii') + src_ip = binascii.hexlify(socket.inet_aton(src_ip)).decode("ascii") if dst_ip: - dst_ip = binascii.hexlify(socket.inet_aton(dst_ip)).decode('ascii') + dst_ip = binascii.hexlify(socket.inet_aton(dst_ip)).decode("ascii") - return ('{!s:0>20}{!s:0>12}{!s:0>8}{!s:0>4}{!s:0>4}'.format( - hex(proto)[2:], src_ip, dst_ip, hex(src_port)[2:], - hex(dst_port)[2:])).rstrip('0') + return ( + "{!s:0>20}{!s:0>12}{!s:0>8}{!s:0>4}{!s:0>4}".format( + hex(proto)[2:], src_ip, dst_ip, hex(src_port)[2:], hex(dst_port)[2:] + ) + ).rstrip("0") @staticmethod - def build_ip6_match(nh=0, src_ip='', dst_ip='', - src_port=0, dst_port=0): + def build_ip6_match(nh=0, src_ip="", dst_ip="", src_port=0, dst_port=0): """Build IPv6 ACL match data with hexstring format. :param int nh: next header number with valid option "x" @@ -234,39 +240,44 @@ class TestClassifier(VppTestCase): """ if src_ip: if sys.version_info[0] == 2: - src_ip = binascii.hexlify(socket.inet_pton( - socket.AF_INET6, src_ip)) + src_ip = binascii.hexlify(socket.inet_pton(socket.AF_INET6, src_ip)) else: src_ip = socket.inet_pton(socket.AF_INET6, src_ip).hex() if dst_ip: if sys.version_info[0] == 2: - dst_ip = binascii.hexlify(socket.inet_pton( - socket.AF_INET6, dst_ip)) + dst_ip = binascii.hexlify(socket.inet_pton(socket.AF_INET6, dst_ip)) else: dst_ip = socket.inet_pton(socket.AF_INET6, dst_ip).hex() - return ('{!s:0>14}{!s:0>34}{!s:0>32}{!s:0>4}{!s:0>4}'.format( - hex(nh)[2:], src_ip, dst_ip, hex(src_port)[2:], - hex(dst_port)[2:])).rstrip('0') + return ( + "{!s:0>14}{!s:0>34}{!s:0>32}{!s:0>4}{!s:0>4}".format( + hex(nh)[2:], src_ip, dst_ip, hex(src_port)[2:], hex(dst_port)[2:] + ) + ).rstrip("0") @staticmethod def build_payload_match(matches): - payload_match = '' + payload_match = "" for match in matches: sval = str(hex(match.value)[2:]) # offset is specified in bytes, convert to hex format. length = (match.offset + match.length) * 2 - format_spec = '{!s:0>' + str(length) + '}' + format_spec = "{!s:0>" + str(length) + "}" payload_match += format_spec.format(sval) - return payload_match.rstrip('0') + return payload_match.rstrip("0") - def create_stream(self, src_if, dst_if, packet_sizes, - proto_l=UDP(sport=1234, dport=5678), - payload_ex=None): + def create_stream( + self, + src_if, + dst_if, + packet_sizes, + proto_l=UDP(sport=1234, dport=5678), + payload_ex=None, + ): """Create input packet stream for defined interfaces. :param VppInterface src_if: Source Interface for packet stream. @@ -285,15 +296,19 @@ class TestClassifier(VppTestCase): payload += payload_ex if self.af == AF_INET: - p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - IP(src=src_if.remote_ip4, dst=dst_if.remote_ip4) / - proto_l / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / IP(src=src_if.remote_ip4, dst=dst_if.remote_ip4) + / proto_l + / Raw(payload) + ) elif self.af == AF_INET6: - p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - IPv6(src=src_if.remote_ip6, dst=dst_if.remote_ip6) / - proto_l / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / IPv6(src=src_if.remote_ip6, dst=dst_if.remote_ip6) + / proto_l + / Raw(payload) + ) info.data = p.copy() self.extend_packet(p, size) pkts.append(p) @@ -322,11 +337,12 @@ class TestClassifier(VppTestCase): packet_index = payload_info.index self.assertEqual(payload_info.dst, dst_sw_if_index) self.logger.debug( - "Got packet on port %s: src=%u (id=%u)" % - (dst_if.name, payload_info.src, packet_index)) + "Got packet on port %s: src=%u (id=%u)" + % (dst_if.name, payload_info.src, packet_index) + ) next_info = self.get_next_packet_info_for_interface2( - payload_info.src, dst_sw_if_index, - last_info[payload_info.src]) + payload_info.src, dst_sw_if_index, last_info[payload_info.src] + ) last_info[payload_info.src] = next_info self.assertTrue(next_info is not None) self.assertEqual(packet_index, next_info.index) @@ -343,13 +359,15 @@ class TestClassifier(VppTestCase): raise for i in self.interfaces: remaining_packet = self.get_next_packet_info_for_interface2( - i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index]) - self.assertTrue(remaining_packet is None, - "Interface %s: Packet expected from interface %s " - "didn't arrive" % (dst_if.name, i.name)) - - def create_classify_table(self, key, mask, data_offset=0, - next_table_index=None): + i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index] + ) + self.assertTrue( + remaining_packet is None, + "Interface %s: Packet expected from interface %s " + "didn't arrive" % (dst_if.name, i.name), + ) + + def create_classify_table(self, key, mask, data_offset=0, next_table_index=None): """Create Classify Table :param str key: key for classify table (ex, ACL name). @@ -366,12 +384,14 @@ class TestClassifier(VppTestCase): miss_next_index=0, current_data_flag=1, current_data_offset=data_offset, - next_table_index=next_table_index) - self.assertIsNotNone(r, 'No response msg for add_del_table') + next_table_index=next_table_index, + ) + self.assertIsNotNone(r, "No response msg for add_del_table") self.acl_tbl_idx[key] = r.new_table_index - def create_classify_session(self, table_index, match, pbr_option=0, - vrfid=0, is_add=1): + def create_classify_session( + self, table_index, match, pbr_option=0, vrfid=0, is_add=1 + ): """Create Classify Session :param int table_index: table index to identify classify table. @@ -389,8 +409,9 @@ class TestClassifier(VppTestCase): match_len=mask_match_len, opaque_index=0, action=pbr_option, - metadata=vrfid) - self.assertIsNotNone(r, 'No response msg for add_del_session') + metadata=vrfid, + ) + self.assertIsNotNone(r, "No response msg for add_del_session") def input_acl_set_interface(self, intf, table_index, is_add=1): """Configure Input ACL interface @@ -403,20 +424,17 @@ class TestClassifier(VppTestCase): r = None if self.af == AF_INET: r = self.vapi.input_acl_set_interface( - is_add, - intf.sw_if_index, - ip4_table_index=table_index) + is_add, intf.sw_if_index, ip4_table_index=table_index + ) elif self.af == AF_INET6: r = self.vapi.input_acl_set_interface( - is_add, - intf.sw_if_index, - ip6_table_index=table_index) + is_add, intf.sw_if_index, ip6_table_index=table_index + ) else: r = self.vapi.input_acl_set_interface( - is_add, - intf.sw_if_index, - l2_table_index=table_index) - self.assertIsNotNone(r, 'No response msg for acl_set_interface') + is_add, intf.sw_if_index, l2_table_index=table_index + ) + self.assertIsNotNone(r, "No response msg for acl_set_interface") def output_acl_set_interface(self, intf, table_index, is_add=1): """Configure Output ACL interface @@ -429,20 +447,17 @@ class TestClassifier(VppTestCase): r = None if self.af == AF_INET: r = self.vapi.output_acl_set_interface( - is_add, - intf.sw_if_index, - ip4_table_index=table_index) + is_add, intf.sw_if_index, ip4_table_index=table_index + ) elif self.af == AF_INET6: r = self.vapi.output_acl_set_interface( - is_add, - intf.sw_if_index, - ip6_table_index=table_index) + is_add, intf.sw_if_index, ip6_table_index=table_index + ) else: r = self.vapi.output_acl_set_interface( - is_add, - intf.sw_if_index, - l2_table_index=table_index) - self.assertIsNotNone(r, 'No response msg for acl_set_interface') + is_add, intf.sw_if_index, l2_table_index=table_index + ) + self.assertIsNotNone(r, "No response msg for acl_set_interface") def config_pbr_fib_entry(self, intf, is_add=1): """Configure fib entry to route traffic toward PBR VRF table @@ -451,10 +466,13 @@ class TestClassifier(VppTestCase): """ addr_len = 24 - self.vapi.ip_add_del_route(dst_address=intf.local_ip4, - dst_address_length=addr_len, - next_hop_address=intf.remote_ip4, - table_id=self.pbr_vrfid, is_add=is_add) + self.vapi.ip_add_del_route( + dst_address=intf.local_ip4, + dst_address_length=addr_len, + next_hop_address=intf.remote_ip4, + table_id=self.pbr_vrfid, + is_add=is_add, + ) def verify_vrf(self, vrf_id): """ diff --git a/test/template_ipsec.py b/test/template_ipsec.py index 8105f0ca52d..578c284f72e 100644 --- a/test/template_ipsec.py +++ b/test/template_ipsec.py @@ -6,16 +6,20 @@ from scapy.layers.inet import IP, ICMP, TCP, UDP from scapy.layers.ipsec import SecurityAssociation, ESP from scapy.layers.l2 import Ether from scapy.packet import raw, Raw -from scapy.layers.inet6 import IPv6, ICMPv6EchoRequest, IPv6ExtHdrHopByHop, \ - IPv6ExtHdrFragment, IPv6ExtHdrDestOpt +from scapy.layers.inet6 import ( + IPv6, + ICMPv6EchoRequest, + IPv6ExtHdrHopByHop, + IPv6ExtHdrFragment, + IPv6ExtHdrDestOpt, +) from framework import VppTestCase, VppTestRunner from util import ppp, reassemble4, fragment_rfc791, fragment_rfc8200 from vpp_papi import VppEnum -from vpp_ipsec import VppIpsecSpd, VppIpsecSpdEntry, \ - VppIpsecSpdItfBinding +from vpp_ipsec import VppIpsecSpd, VppIpsecSpdEntry, VppIpsecSpdItfBinding from ipaddress import ip_address from re import search from os import popen @@ -30,8 +34,8 @@ class IPsecIPv4Params: is_ipv6 = 0 def __init__(self): - self.remote_tun_if_host = '1.1.1.1' - self.remote_tun_if_host6 = '1111::1' + self.remote_tun_if_host = "1.1.1.1" + self.remote_tun_if_host6 = "1111::1" self.scapy_tun_sa_id = 100 self.scapy_tun_spi = 1000 @@ -48,20 +52,23 @@ class IPsecIPv4Params: self.outer_flow_label = 0 self.inner_flow_label = 0x12345 - self.auth_algo_vpp_id = (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_SHA1_96) - self.auth_algo = 'HMAC-SHA1-96' # scapy name - self.auth_key = b'C91KUR9GYMm5GfkEvNjX' - - self.crypt_algo_vpp_id = (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_AES_CBC_128) - self.crypt_algo = 'AES-CBC' # scapy name - self.crypt_key = b'JPjyOWBeVEQiMe7h' + self.auth_algo_vpp_id = ( + VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96 + ) + self.auth_algo = "HMAC-SHA1-96" # scapy name + self.auth_key = b"C91KUR9GYMm5GfkEvNjX" + + self.crypt_algo_vpp_id = ( + VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CBC_128 + ) + self.crypt_algo = "AES-CBC" # scapy name + self.crypt_key = b"JPjyOWBeVEQiMe7h" self.salt = 0 self.flags = 0 self.nat_header = None - self.tun_flags = (VppEnum.vl_api_tunnel_encap_decap_flags_t. - TUNNEL_API_ENCAP_DECAP_FLAG_NONE) + self.tun_flags = ( + VppEnum.vl_api_tunnel_encap_decap_flags_t.TUNNEL_API_ENCAP_DECAP_FLAG_NONE + ) self.dscp = 0 self.async_mode = False @@ -75,8 +82,8 @@ class IPsecIPv6Params: is_ipv6 = 1 def __init__(self): - self.remote_tun_if_host = '1111:1111:1111:1111:1111:1111:1111:1111' - self.remote_tun_if_host4 = '1.1.1.1' + self.remote_tun_if_host = "1111:1111:1111:1111:1111:1111:1111:1111" + self.remote_tun_if_host4 = "1.1.1.1" self.scapy_tun_sa_id = 500 self.scapy_tun_spi = 3001 @@ -93,20 +100,23 @@ class IPsecIPv6Params: self.outer_flow_label = 0 self.inner_flow_label = 0x12345 - self.auth_algo_vpp_id = (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_SHA1_96) - self.auth_algo = 'HMAC-SHA1-96' # scapy name - self.auth_key = b'C91KUR9GYMm5GfkEvNjX' - - self.crypt_algo_vpp_id = (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_AES_CBC_128) - self.crypt_algo = 'AES-CBC' # scapy name - self.crypt_key = b'JPjyOWBeVEQiMe7h' + self.auth_algo_vpp_id = ( + VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96 + ) + self.auth_algo = "HMAC-SHA1-96" # scapy name + self.auth_key = b"C91KUR9GYMm5GfkEvNjX" + + self.crypt_algo_vpp_id = ( + VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CBC_128 + ) + self.crypt_algo = "AES-CBC" # scapy name + self.crypt_key = b"JPjyOWBeVEQiMe7h" self.salt = 0 self.flags = 0 self.nat_header = None - self.tun_flags = (VppEnum.vl_api_tunnel_encap_decap_flags_t. - TUNNEL_API_ENCAP_DECAP_FLAG_NONE) + self.tun_flags = ( + VppEnum.vl_api_tunnel_encap_decap_flags_t.TUNNEL_API_ENCAP_DECAP_FLAG_NONE + ) self.dscp = 0 self.async_mode = False @@ -120,36 +130,40 @@ def mk_scapy_crypt_key(p): def config_tun_params(p, encryption_type, tun_if): ip_class_by_addr_type = {socket.AF_INET: IP, socket.AF_INET6: IPv6} - esn_en = bool(p.flags & (VppEnum.vl_api_ipsec_sad_flags_t. - IPSEC_API_SAD_FLAG_USE_ESN)) + esn_en = bool( + p.flags & (VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_USE_ESN) + ) p.tun_dst = tun_if.remote_addr[p.addr_type] p.tun_src = tun_if.local_addr[p.addr_type] crypt_key = mk_scapy_crypt_key(p) p.scapy_tun_sa = SecurityAssociation( - encryption_type, spi=p.vpp_tun_spi, + encryption_type, + spi=p.vpp_tun_spi, crypt_algo=p.crypt_algo, crypt_key=crypt_key, - auth_algo=p.auth_algo, auth_key=p.auth_key, - tunnel_header=ip_class_by_addr_type[p.addr_type]( - src=p.tun_dst, - dst=p.tun_src), + auth_algo=p.auth_algo, + auth_key=p.auth_key, + tunnel_header=ip_class_by_addr_type[p.addr_type](src=p.tun_dst, dst=p.tun_src), nat_t_header=p.nat_header, - esn_en=esn_en) + esn_en=esn_en, + ) p.vpp_tun_sa = SecurityAssociation( - encryption_type, spi=p.scapy_tun_spi, + encryption_type, + spi=p.scapy_tun_spi, crypt_algo=p.crypt_algo, crypt_key=crypt_key, - auth_algo=p.auth_algo, auth_key=p.auth_key, - tunnel_header=ip_class_by_addr_type[p.addr_type]( - dst=p.tun_dst, - src=p.tun_src), + auth_algo=p.auth_algo, + auth_key=p.auth_key, + tunnel_header=ip_class_by_addr_type[p.addr_type](dst=p.tun_dst, src=p.tun_src), nat_t_header=p.nat_header, - esn_en=esn_en) + esn_en=esn_en, + ) def config_tra_params(p, encryption_type): - esn_en = bool(p.flags & (VppEnum.vl_api_ipsec_sad_flags_t. - IPSEC_API_SAD_FLAG_USE_ESN)) + esn_en = bool( + p.flags & (VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_USE_ESN) + ) crypt_key = mk_scapy_crypt_key(p) p.scapy_tra_sa = SecurityAssociation( encryption_type, @@ -159,7 +173,8 @@ def config_tra_params(p, encryption_type): auth_algo=p.auth_algo, auth_key=p.auth_key, nat_t_header=p.nat_header, - esn_en=esn_en) + esn_en=esn_en, + ) p.vpp_tra_sa = SecurityAssociation( encryption_type, spi=p.scapy_tra_spi, @@ -168,7 +183,8 @@ def config_tra_params(p, encryption_type): auth_algo=p.auth_algo, auth_key=p.auth_key, nat_t_header=p.nat_header, - esn_en=esn_en) + esn_en=esn_en, + ) class TemplateIpsec(VppTestCase): @@ -189,11 +205,12 @@ class TemplateIpsec(VppTestCase): |tun_if| -------> |VPP| ------> |pg1| ------ --- --- """ + tun_spd_id = 1 tra_spd_id = 2 def ipsec_select_backend(self): - """ empty method to be overloaded when necessary """ + """empty method to be overloaded when necessary""" pass @classmethod @@ -205,12 +222,14 @@ class TemplateIpsec(VppTestCase): super(TemplateIpsec, cls).tearDownClass() def setup_params(self): - if not hasattr(self, 'ipv4_params'): + if not hasattr(self, "ipv4_params"): self.ipv4_params = IPsecIPv4Params() - if not hasattr(self, 'ipv6_params'): + if not hasattr(self, "ipv6_params"): self.ipv6_params = IPsecIPv6Params() - self.params = {self.ipv4_params.addr_type: self.ipv4_params, - self.ipv6_params.addr_type: self.ipv6_params} + self.params = { + self.ipv4_params.addr_type: self.ipv4_params, + self.ipv6_params.addr_type: self.ipv6_params, + } def config_interfaces(self): self.create_pg_interfaces(range(3)) @@ -227,10 +246,8 @@ class TemplateIpsec(VppTestCase): self.setup_params() - self.vpp_esp_protocol = (VppEnum.vl_api_ipsec_proto_t. - IPSEC_API_PROTO_ESP) - self.vpp_ah_protocol = (VppEnum.vl_api_ipsec_proto_t. - IPSEC_API_PROTO_AH) + self.vpp_esp_protocol = VppEnum.vl_api_ipsec_proto_t.IPSEC_API_PROTO_ESP + self.vpp_ah_protocol = VppEnum.vl_api_ipsec_proto_t.IPSEC_API_PROTO_AH self.config_interfaces() @@ -250,34 +267,39 @@ class TemplateIpsec(VppTestCase): def show_commands_at_teardown(self): self.logger.info(self.vapi.cli("show hardware")) - def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, - payload_size=54): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - sa.encrypt(IP(src=src, dst=dst) / - ICMP() / Raw(b'X' * payload_size)) - for i in range(count)] - - def gen_encrypt_pkts6(self, p, sa, sw_intf, src, dst, count=1, - payload_size=54): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - sa.encrypt(IPv6(src=src, dst=dst, - hlim=p.inner_hop_limit, - fl=p.inner_flow_label) / - ICMPv6EchoRequest(id=0, seq=1, - data='X' * payload_size)) - for i in range(count)] + def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=54): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / sa.encrypt(IP(src=src, dst=dst) / ICMP() / Raw(b"X" * payload_size)) + for i in range(count) + ] + + def gen_encrypt_pkts6(self, p, sa, sw_intf, src, dst, count=1, payload_size=54): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / sa.encrypt( + IPv6(src=src, dst=dst, hlim=p.inner_hop_limit, fl=p.inner_flow_label) + / ICMPv6EchoRequest(id=0, seq=1, data="X" * payload_size) + ) + for i in range(count) + ] def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=54): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - IP(src=src, dst=dst) / ICMP() / Raw(b'X' * payload_size) - for i in range(count)] + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / IP(src=src, dst=dst) + / ICMP() + / Raw(b"X" * payload_size) + for i in range(count) + ] def gen_pkts6(self, p, sw_intf, src, dst, count=1, payload_size=54): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - IPv6(src=src, dst=dst, - hlim=p.inner_hop_limit, fl=p.inner_flow_label) / - ICMPv6EchoRequest(id=0, seq=1, data='X' * payload_size) - for i in range(count)] + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / IPv6(src=src, dst=dst, hlim=p.inner_hop_limit, fl=p.inner_flow_label) + / ICMPv6EchoRequest(id=0, seq=1, data="X" * payload_size) + for i in range(count) + ] class IpsecTcp(object): @@ -285,10 +307,12 @@ class IpsecTcp(object): # start http cli server listener on http://0.0.0.0:80 self.vapi.cli("http cli server") p = self.params[socket.AF_INET] - send = (Ether(src=self.tun_if.remote_mac, dst=self.tun_if.local_mac) / - p.scapy_tun_sa.encrypt(IP(src=p.remote_tun_if_host, - dst=self.tun_if.local_ip4) / - TCP(flags='S', dport=80))) + send = Ether( + src=self.tun_if.remote_mac, dst=self.tun_if.local_mac + ) / p.scapy_tun_sa.encrypt( + IP(src=p.remote_tun_if_host, dst=self.tun_if.local_ip4) + / TCP(flags="S", dport=80) + ) self.logger.debug(ppp("Sending packet:", send)) recv = self.send_and_expect(self.tun_if, [send], self.tun_if) recv = recv[0] @@ -298,36 +322,40 @@ class IpsecTcp(object): class IpsecTcpTests(IpsecTcp): def test_tcp_checksum(self): - """ verify checksum correctness for vpp generated packets """ + """verify checksum correctness for vpp generated packets""" self.verify_tcp_checksum() class IpsecTra4(object): - """ verify methods for Transport v4 """ + """verify methods for Transport v4""" + def get_replay_counts(self, p): - replay_node_name = ('/err/%s/SA replayed packet' % - self.tra4_decrypt_node_name[0]) + replay_node_name = "/err/%s/SA replayed packet" % self.tra4_decrypt_node_name[0] count = self.statistics.get_err_counter(replay_node_name) if p.async_mode: - replay_post_node_name = ('/err/%s/SA replayed packet' % - self.tra4_decrypt_node_name[p.async_mode]) + replay_post_node_name = ( + "/err/%s/SA replayed packet" % self.tra4_decrypt_node_name[p.async_mode] + ) count += self.statistics.get_err_counter(replay_post_node_name) return count def get_hash_failed_counts(self, p): if ESP == self.encryption_type and p.crypt_algo == "AES-GCM": - hash_failed_node_name = ('/err/%s/ESP decryption failed' % - self.tra4_decrypt_node_name[p.async_mode]) + hash_failed_node_name = ( + "/err/%s/ESP decryption failed" + % self.tra4_decrypt_node_name[p.async_mode] + ) else: - hash_failed_node_name = ('/err/%s/Integrity check failed' % - self.tra4_decrypt_node_name[p.async_mode]) + hash_failed_node_name = ( + "/err/%s/Integrity check failed" + % self.tra4_decrypt_node_name[p.async_mode] + ) count = self.statistics.get_err_counter(hash_failed_node_name) if p.async_mode: - count += self.statistics.get_err_counter( - '/err/crypto-dispatch/bad-hmac') + count += self.statistics.get_err_counter("/err/crypto-dispatch/bad-hmac") return count @@ -337,81 +365,100 @@ class IpsecTra4(object): esn_on = p.vpp_tra_sa.esn_en ar_on = p.flags & saf.IPSEC_API_SAD_FLAG_USE_ANTI_REPLAY - seq_cycle_node_name = \ - ('/err/%s/sequence number cycled (packet dropped)' % - self.tra4_encrypt_node_name) + seq_cycle_node_name = ( + "/err/%s/sequence number cycled (packet dropped)" + % self.tra4_encrypt_node_name + ) replay_count = self.get_replay_counts(p) hash_failed_count = self.get_hash_failed_counts(p) seq_cycle_count = self.statistics.get_err_counter(seq_cycle_node_name) # a few packets so we get the rx seq number above the window size and # thus can simulate a wrap with an out of window packet - pkts = [(Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=seq)) - for seq in range(63, 80)] + pkts = [ + ( + Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac) + / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=seq, + ) + ) + for seq in range(63, 80) + ] recv_pkts = self.send_and_expect(self.tra_if, pkts, self.tra_if) # these 4 packets will all choose seq-num 0 to decrpyt since none # are out of window when first checked. however, once #200 has # decrypted it will move the window to 200 and has #81 is out of # window. this packet should be dropped. - pkts = [(Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=200)), - (Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=81)), - (Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=201)), - (Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=202))] + pkts = [ + ( + Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac) + / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=200, + ) + ), + ( + Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac) + / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=81, + ) + ), + ( + Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac) + / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=201, + ) + ), + ( + Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac) + / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=202, + ) + ), + ] # if anti-replay is off then we won't drop #81 n_rx = 3 if ar_on else 4 self.send_and_expect(self.tra_if, pkts, self.tra_if, n_rx=n_rx) # this packet is one before the wrap - pkts = [(Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=203))] + pkts = [ + ( + Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac) + / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=203, + ) + ) + ] recv_pkts = self.send_and_expect(self.tra_if, pkts, self.tra_if) # move the window over half way to a wrap - pkts = [(Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=0x80000001))] + pkts = [ + ( + Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac) + / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=0x80000001, + ) + ) + ] recv_pkts = self.send_and_expect(self.tra_if, pkts, self.tra_if) # anti-replay will drop old packets, no anti-replay will not - pkts = [(Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=0x44000001))] + pkts = [ + ( + Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac) + / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=0x44000001, + ) + ) + ] if ar_on: self.send_and_assert_no_replies(self.tra_if, pkts) @@ -427,36 +474,48 @@ class IpsecTra4(object): p.scapy_tra_sa.seq_num = 0x100000005 # send a packet that wraps the window for both AR and no AR - pkts = [(Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=0x100000005))] + pkts = [ + ( + Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac) + / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) + / ICMP(), + seq_num=0x100000005, + ) + ) + ] rxs = self.send_and_expect(self.tra_if, pkts, self.tra_if) for rx in rxs: decrypted = p.vpp_tra_sa.decrypt(rx[0][IP]) # move the window forward to half way to the next wrap - pkts = [(Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=0x180000005))] + pkts = [ + ( + Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac) + / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) + / ICMP(), + seq_num=0x180000005, + ) + ) + ] rxs = self.send_and_expect(self.tra_if, pkts, self.tra_if) # a packet less than 2^30 from the current position is: # - AR: out of window and dropped # - non-AR: accepted - pkts = [(Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=0x170000005))] + pkts = [ + ( + Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac) + / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) + / ICMP(), + seq_num=0x170000005, + ) + ) + ] if ar_on: self.send_and_assert_no_replies(self.tra_if, pkts) @@ -467,12 +526,16 @@ class IpsecTra4(object): # - AR: out of window and dropped # - non-AR: considered a wrap, but since it's not a wrap # it won't decrpyt and so will be dropped - pkts = [(Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=0x130000005))] + pkts = [ + ( + Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac) + / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) + / ICMP(), + seq_num=0x130000005, + ) + ) + ] self.send_and_assert_no_replies(self.tra_if, pkts) @@ -481,12 +544,16 @@ class IpsecTra4(object): # - AR: out of window so considered a wrap, so accepted # - non-AR: not considered a wrap, so won't decrypt p.scapy_tra_sa.seq_num = 0x260000005 - pkts = [(Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=0x260000005))] + pkts = [ + ( + Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac) + / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) + / ICMP(), + seq_num=0x260000005, + ) + ) + ] if ar_on: self.send_and_expect(self.tra_if, pkts, self.tra_if) else: @@ -502,44 +569,55 @@ class IpsecTra4(object): # - AR: accepted # - non-AR: not considered a wrap, so won't decrypt - pkts = [(Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=0x200000005)), - (Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=0x200000006))] + pkts = [ + ( + Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac) + / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) + / ICMP(), + seq_num=0x200000005, + ) + ), + ( + Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac) + / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) + / ICMP(), + seq_num=0x200000006, + ) + ), + ] self.send_and_expect(self.tra_if, pkts, self.tra_if) - pkts = [(Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=0x260000005))] + pkts = [ + ( + Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac) + / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) + / ICMP(), + seq_num=0x260000005, + ) + ) + ] self.send_and_expect(self.tra_if, pkts, self.tra_if) def verify_tra_anti_replay(self): p = self.params[socket.AF_INET] esn_en = p.vpp_tra_sa.esn_en - seq_cycle_node_name = \ - ('/err/%s/sequence number cycled (packet dropped)' % - self.tra4_encrypt_node_name) + seq_cycle_node_name = ( + "/err/%s/sequence number cycled (packet dropped)" + % self.tra4_encrypt_node_name + ) replay_count = self.get_replay_counts(p) hash_failed_count = self.get_hash_failed_counts(p) seq_cycle_count = self.statistics.get_err_counter(seq_cycle_node_name) if ESP == self.encryption_type: - undersize_node_name = ('/err/%s/undersized packet' % - self.tra4_decrypt_node_name[0]) - undersize_count = self.statistics.get_err_counter( - undersize_node_name) + undersize_node_name = ( + "/err/%s/undersized packet" % self.tra4_decrypt_node_name[0] + ) + undersize_count = self.statistics.get_err_counter(undersize_node_name) # # send packets with seq numbers 1->34 @@ -549,13 +627,16 @@ class IpsecTra4(object): # for reasons i haven't investigated Scapy won't create a packet with # seq_num=0 # - pkts = [(Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=seq)) - for seq in range(1, 34)] + pkts = [ + ( + Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac) + / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=seq, + ) + ) + for seq in range(1, 34) + ] recv_pkts = self.send_and_expect(self.tra_if, pkts, self.tra_if) # replayed packets are dropped @@ -569,14 +650,13 @@ class IpsecTra4(object): # self.vapi.cli("clear error") self.vapi.cli("clear node counters") - pkts = (Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=35)) - recv_pkts = self.send_and_expect(self.tra_if, pkts * 8, - self.tra_if, n_rx=1) + pkts = Ether( + src=self.tra_if.remote_mac, dst=self.tra_if.local_mac + ) / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=35, + ) + recv_pkts = self.send_and_expect(self.tra_if, pkts * 8, self.tra_if, n_rx=1) replay_count += 7 self.assertEqual(self.get_replay_counts(p), replay_count) @@ -584,12 +664,12 @@ class IpsecTra4(object): # now move the window over to 257 (more than one byte) and into Case A # self.vapi.cli("clear error") - pkt = (Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=257)) + pkt = Ether( + src=self.tra_if.remote_mac, dst=self.tra_if.local_mac + ) / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=257, + ) recv_pkts = self.send_and_expect(self.tra_if, [pkt], self.tra_if) # replayed packets are dropped @@ -599,27 +679,29 @@ class IpsecTra4(object): # the window size is 64 packets # in window are still accepted - pkt = (Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=200)) + pkt = Ether( + src=self.tra_if.remote_mac, dst=self.tra_if.local_mac + ) / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=200, + ) recv_pkts = self.send_and_expect(self.tra_if, [pkt], self.tra_if) # a packet that does not decrypt does not move the window forward - bogus_sa = SecurityAssociation(self.encryption_type, - p.vpp_tra_spi, - crypt_algo=p.crypt_algo, - crypt_key=mk_scapy_crypt_key(p)[::-1], - auth_algo=p.auth_algo, - auth_key=p.auth_key[::-1]) - pkt = (Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - bogus_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=350)) + bogus_sa = SecurityAssociation( + self.encryption_type, + p.vpp_tra_spi, + crypt_algo=p.crypt_algo, + crypt_key=mk_scapy_crypt_key(p)[::-1], + auth_algo=p.auth_algo, + auth_key=p.auth_key[::-1], + ) + pkt = Ether( + src=self.tra_if.remote_mac, dst=self.tra_if.local_mac + ) / bogus_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=350, + ) self.send_and_assert_no_replies(self.tra_if, pkt * 17, timeout=0.2) hash_failed_count += 17 @@ -627,28 +709,26 @@ class IpsecTra4(object): # a malformed 'runt' packet # created by a mis-constructed SA - if (ESP == self.encryption_type and p.crypt_algo != "NULL"): - bogus_sa = SecurityAssociation(self.encryption_type, - p.vpp_tra_spi) - pkt = (Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - bogus_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=350)) + if ESP == self.encryption_type and p.crypt_algo != "NULL": + bogus_sa = SecurityAssociation(self.encryption_type, p.vpp_tra_spi) + pkt = Ether( + src=self.tra_if.remote_mac, dst=self.tra_if.local_mac + ) / bogus_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=350, + ) self.send_and_assert_no_replies(self.tra_if, pkt * 17, timeout=0.2) undersize_count += 17 - self.assert_error_counter_equal(undersize_node_name, - undersize_count) + self.assert_error_counter_equal(undersize_node_name, undersize_count) # which we can determine since this packet is still in the window - pkt = (Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=234)) + pkt = Ether( + src=self.tra_if.remote_mac, dst=self.tra_if.local_mac + ) / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=234, + ) self.send_and_expect(self.tra_if, [pkt], self.tra_if) # @@ -656,12 +736,12 @@ class IpsecTra4(object): # this is Case B. So VPP will consider this to be a high seq num wrap # and so the decrypt attempt will fail # - pkt = (Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=17)) + pkt = Ether( + src=self.tra_if.remote_mac, dst=self.tra_if.local_mac + ) / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=17, + ) self.send_and_assert_no_replies(self.tra_if, pkt * 17, timeout=0.2) if esn_en: @@ -675,12 +755,12 @@ class IpsecTra4(object): self.assertEqual(self.get_replay_counts(p), replay_count) # valid packet moves the window over to 258 - pkt = (Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=258)) + pkt = Ether( + src=self.tra_if.remote_mac, dst=self.tra_if.local_mac + ) / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=258, + ) rx = self.send_and_expect(self.tra_if, [pkt], self.tra_if) decrypted = p.vpp_tra_sa.decrypt(rx[0][IP]) @@ -694,13 +774,16 @@ class IpsecTra4(object): self.logger.info(self.vapi.ppcli("show ipsec sa 0")) self.logger.info(self.vapi.ppcli("show ipsec sa 1")) - pkts = [(Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=seq)) - for seq in range(259, 280)] + pkts = [ + ( + Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac) + / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=seq, + ) + ) + for seq in range(259, 280) + ] if esn_en: rxs = self.send_and_expect(self.tra_if, pkts, self.tra_if) @@ -719,12 +802,12 @@ class IpsecTra4(object): # The low seq num we set it to will place VPP's RX window in Case A # p.scapy_tra_sa.seq_num = 0x100000005 - pkt = (Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=0x100000005)) + pkt = Ether( + src=self.tra_if.remote_mac, dst=self.tra_if.local_mac + ) / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=0x100000005, + ) rx = self.send_and_expect(self.tra_if, [pkt], self.tra_if) decrypted = p.vpp_tra_sa.decrypt(rx[0][IP]) @@ -733,13 +816,13 @@ class IpsecTra4(object): # A packet that has seq num between (2^32-64) and 5 is within # the window # - p.scapy_tra_sa.seq_num = 0xfffffffd - pkt = (Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=0xfffffffd)) + p.scapy_tra_sa.seq_num = 0xFFFFFFFD + pkt = Ether( + src=self.tra_if.remote_mac, dst=self.tra_if.local_mac + ) / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=0xFFFFFFFD, + ) rx = self.send_and_expect(self.tra_if, [pkt], self.tra_if) decrypted = p.vpp_tra_sa.decrypt(rx[0][IP]) @@ -748,14 +831,15 @@ class IpsecTra4(object): # because VPP will consider this packet to be one that moves the # window forward # - pkt = (Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=0x200000999)) - self.send_and_assert_no_replies(self.tra_if, [pkt], self.tra_if, - timeout=0.2) + pkt = Ether( + src=self.tra_if.remote_mac, dst=self.tra_if.local_mac + ) / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=0x200000999, + ) + self.send_and_assert_no_replies( + self.tra_if, [pkt], self.tra_if, timeout=0.2 + ) hash_failed_count += 1 self.assertEqual(self.get_hash_failed_counts(p), hash_failed_count) @@ -765,22 +849,22 @@ class IpsecTra4(object): # again # p.scapy_tra_sa.seq_num = 0x100000555 - pkt = (Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=0x100000555)) + pkt = Ether( + src=self.tra_if.remote_mac, dst=self.tra_if.local_mac + ) / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=0x100000555, + ) rx = self.send_and_expect(self.tra_if, [pkt], self.tra_if) decrypted = p.vpp_tra_sa.decrypt(rx[0][IP]) p.scapy_tra_sa.seq_num = 0x200000444 - pkt = (Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=0x200000444)) + pkt = Ether( + src=self.tra_if.remote_mac, dst=self.tra_if.local_mac + ) / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=0x200000444, + ) rx = self.send_and_expect(self.tra_if, [pkt], self.tra_if) decrypted = p.vpp_tra_sa.decrypt(rx[0][IP]) @@ -791,8 +875,7 @@ class IpsecTra4(object): # self.send_and_assert_no_replies(self.tra_if, pkts, timeout=0.2) seq_cycle_count += len(pkts) - self.assert_error_counter_equal(seq_cycle_node_name, - seq_cycle_count) + self.assert_error_counter_equal(seq_cycle_node_name, seq_cycle_count) # move the security-associations seq number on to the last we used self.vapi.cli("test ipsec sa %d seq 0x15f" % p.scapy_tra_sa_id) @@ -811,88 +894,109 @@ class IpsecTra4(object): # for reasons i haven't investigated Scapy won't create a packet with # seq_num=0 # - pkts = [(Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=seq)) - for seq in range(1, 3)] + pkts = [ + ( + Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac) + / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=seq, + ) + ) + for seq in range(1, 3) + ] self.send_and_expect(self.tra_if, pkts, self.tra_if) self.assertEqual(p.tra_sa_out.get_lost(), 0) # skip a sequence number - pkts = [(Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=seq)) - for seq in range(4, 6)] + pkts = [ + ( + Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac) + / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=seq, + ) + ) + for seq in range(4, 6) + ] self.send_and_expect(self.tra_if, pkts, self.tra_if) self.assertEqual(p.tra_sa_out.get_lost(), 0) # the lost packet are counted untill we get up past the first # sizeof(replay_window) packets - pkts = [(Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=seq)) - for seq in range(6, 100)] + pkts = [ + ( + Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac) + / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=seq, + ) + ) + for seq in range(6, 100) + ] self.send_and_expect(self.tra_if, pkts, self.tra_if) self.assertEqual(p.tra_sa_out.get_lost(), 1) # lost of holes in the sequence - pkts = [(Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=seq)) - for seq in range(100, 200, 2)] + pkts = [ + ( + Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac) + / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=seq, + ) + ) + for seq in range(100, 200, 2) + ] self.send_and_expect(self.tra_if, pkts, self.tra_if, n_rx=50) - pkts = [(Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=seq)) - for seq in range(200, 300)] + pkts = [ + ( + Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac) + / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=seq, + ) + ) + for seq in range(200, 300) + ] self.send_and_expect(self.tra_if, pkts, self.tra_if) self.assertEqual(p.tra_sa_out.get_lost(), 51) # a big hole in the seq number space - pkts = [(Ether(src=self.tra_if.remote_mac, - dst=self.tra_if.local_mac) / - p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4) / - ICMP(), - seq_num=seq)) - for seq in range(400, 500)] + pkts = [ + ( + Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac) + / p.scapy_tra_sa.encrypt( + IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(), + seq_num=seq, + ) + ) + for seq in range(400, 500) + ] self.send_and_expect(self.tra_if, pkts, self.tra_if) self.assertEqual(p.tra_sa_out.get_lost(), 151) def verify_tra_basic4(self, count=1, payload_size=54): - """ ipsec v4 transport basic test """ + """ipsec v4 transport basic test""" self.vapi.cli("clear errors") self.vapi.cli("clear ipsec sa") try: p = self.params[socket.AF_INET] - send_pkts = self.gen_encrypt_pkts(p, p.scapy_tra_sa, self.tra_if, - src=self.tra_if.remote_ip4, - dst=self.tra_if.local_ip4, - count=count, - payload_size=payload_size) - recv_pkts = self.send_and_expect(self.tra_if, send_pkts, - self.tra_if) + send_pkts = self.gen_encrypt_pkts( + p, + p.scapy_tra_sa, + self.tra_if, + src=self.tra_if.remote_ip4, + dst=self.tra_if.local_ip4, + count=count, + payload_size=payload_size, + ) + recv_pkts = self.send_and_expect(self.tra_if, send_pkts, self.tra_if) for rx in recv_pkts: self.assertEqual(len(rx) - len(Ether()), rx[IP].len) self.assert_packet_checksums_valid(rx) @@ -906,14 +1010,14 @@ class IpsecTra4(object): self.logger.info(self.vapi.ppcli("show error")) self.logger.info(self.vapi.ppcli("show ipsec all")) - pkts = p.tra_sa_in.get_stats()['packets'] - self.assertEqual(pkts, count, - "incorrect SA in counts: expected %d != %d" % - (count, pkts)) - pkts = p.tra_sa_out.get_stats()['packets'] - self.assertEqual(pkts, count, - "incorrect SA out counts: expected %d != %d" % - (count, pkts)) + pkts = p.tra_sa_in.get_stats()["packets"] + self.assertEqual( + pkts, count, "incorrect SA in counts: expected %d != %d" % (count, pkts) + ) + pkts = p.tra_sa_out.get_stats()["packets"] + self.assertEqual( + pkts, count, "incorrect SA out counts: expected %d != %d" % (count, pkts) + ) self.assertEqual(p.tra_sa_out.get_lost(), 0) self.assertEqual(p.tra_sa_in.get_lost(), 0) @@ -922,41 +1026,45 @@ class IpsecTra4(object): class IpsecTra4Tests(IpsecTra4): - """ UT test methods for Transport v4 """ + """UT test methods for Transport v4""" + def test_tra_anti_replay(self): - """ ipsec v4 transport anti-replay test """ + """ipsec v4 transport anti-replay test""" self.verify_tra_anti_replay() def test_tra_lost(self): - """ ipsec v4 transport lost packet test """ + """ipsec v4 transport lost packet test""" self.verify_tra_lost() def test_tra_basic(self, count=1): - """ ipsec v4 transport basic test """ + """ipsec v4 transport basic test""" self.verify_tra_basic4(count=1) def test_tra_burst(self): - """ ipsec v4 transport burst test """ + """ipsec v4 transport burst test""" self.verify_tra_basic4(count=257) class IpsecTra6(object): - """ verify methods for Transport v6 """ + """verify methods for Transport v6""" + def verify_tra_basic6(self, count=1, payload_size=54): self.vapi.cli("clear errors") self.vapi.cli("clear ipsec sa") try: p = self.params[socket.AF_INET6] - send_pkts = self.gen_encrypt_pkts6(p, p.scapy_tra_sa, self.tra_if, - src=self.tra_if.remote_ip6, - dst=self.tra_if.local_ip6, - count=count, - payload_size=payload_size) - recv_pkts = self.send_and_expect(self.tra_if, send_pkts, - self.tra_if) + send_pkts = self.gen_encrypt_pkts6( + p, + p.scapy_tra_sa, + self.tra_if, + src=self.tra_if.remote_ip6, + dst=self.tra_if.local_ip6, + count=count, + payload_size=payload_size, + ) + recv_pkts = self.send_and_expect(self.tra_if, send_pkts, self.tra_if) for rx in recv_pkts: - self.assertEqual(len(rx) - len(Ether()) - len(IPv6()), - rx[IPv6].plen) + self.assertEqual(len(rx) - len(Ether()) - len(IPv6()), rx[IPv6].plen) try: decrypted = p.vpp_tra_sa.decrypt(rx[IPv6]) self.assert_packet_checksums_valid(decrypted) @@ -967,32 +1075,38 @@ class IpsecTra6(object): self.logger.info(self.vapi.ppcli("show error")) self.logger.info(self.vapi.ppcli("show ipsec all")) - pkts = p.tra_sa_in.get_stats()['packets'] - self.assertEqual(pkts, count, - "incorrect SA in counts: expected %d != %d" % - (count, pkts)) - pkts = p.tra_sa_out.get_stats()['packets'] - self.assertEqual(pkts, count, - "incorrect SA out counts: expected %d != %d" % - (count, pkts)) + pkts = p.tra_sa_in.get_stats()["packets"] + self.assertEqual( + pkts, count, "incorrect SA in counts: expected %d != %d" % (count, pkts) + ) + pkts = p.tra_sa_out.get_stats()["packets"] + self.assertEqual( + pkts, count, "incorrect SA out counts: expected %d != %d" % (count, pkts) + ) self.assert_packet_counter_equal(self.tra6_encrypt_node_name, count) self.assert_packet_counter_equal(self.tra6_decrypt_node_name[0], count) - def gen_encrypt_pkts_ext_hdrs6(self, sa, sw_intf, src, dst, count=1, - payload_size=54): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - sa.encrypt(IPv6(src=src, dst=dst) / - ICMPv6EchoRequest(id=0, seq=1, - data='X' * payload_size)) - for i in range(count)] + def gen_encrypt_pkts_ext_hdrs6( + self, sa, sw_intf, src, dst, count=1, payload_size=54 + ): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / sa.encrypt( + IPv6(src=src, dst=dst) + / ICMPv6EchoRequest(id=0, seq=1, data="X" * payload_size) + ) + for i in range(count) + ] def gen_pkts_ext_hdrs6(self, sw_intf, src, dst, count=1, payload_size=54): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - IPv6(src=src, dst=dst) / - IPv6ExtHdrHopByHop() / - IPv6ExtHdrFragment(id=2, offset=200) / - Raw(b'\xff' * 200) - for i in range(count)] + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / IPv6(src=src, dst=dst) + / IPv6ExtHdrHopByHop() + / IPv6ExtHdrFragment(id=2, offset=200) + / Raw(b"\xff" * 200) + for i in range(count) + ] def verify_tra_encrypted6(self, p, sa, rxs): decrypted = [] @@ -1018,10 +1132,13 @@ class IpsecTra6(object): # # check we can decrypt with options # - tx = self.gen_encrypt_pkts_ext_hdrs6(p.scapy_tra_sa, self.tra_if, - src=self.tra_if.remote_ip6, - dst=self.tra_if.local_ip6, - count=count) + tx = self.gen_encrypt_pkts_ext_hdrs6( + p.scapy_tra_sa, + self.tra_if, + src=self.tra_if.remote_ip6, + dst=self.tra_if.local_ip6, + count=count, + ) self.send_and_expect(self.tra_if, tx, self.tra_if) # @@ -1030,11 +1147,12 @@ class IpsecTra6(object): # # one extension before ESP - tx = (Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) / - IPv6(src=self.tra_if.local_ip6, - dst=self.tra_if.remote_ip6) / - IPv6ExtHdrFragment(id=2, offset=200) / - Raw(b'\xff' * 200)) + tx = ( + Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) + / IPv6(src=self.tra_if.local_ip6, dst=self.tra_if.remote_ip6) + / IPv6ExtHdrFragment(id=2, offset=200) + / Raw(b"\xff" * 200) + ) rxs = self.send_and_expect(self.pg2, [tx], self.tra_if) dcs = self.verify_tra_encrypted6(p, p.vpp_tra_sa, rxs) @@ -1047,12 +1165,13 @@ class IpsecTra6(object): self.assert_equal(dc[IPv6ExtHdrFragment].id, 2) # two extensions before ESP - tx = (Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) / - IPv6(src=self.tra_if.local_ip6, - dst=self.tra_if.remote_ip6) / - IPv6ExtHdrHopByHop() / - IPv6ExtHdrFragment(id=2, offset=200) / - Raw(b'\xff' * 200)) + tx = ( + Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) + / IPv6(src=self.tra_if.local_ip6, dst=self.tra_if.remote_ip6) + / IPv6ExtHdrHopByHop() + / IPv6ExtHdrFragment(id=2, offset=200) + / Raw(b"\xff" * 200) + ) rxs = self.send_and_expect(self.pg2, [tx], self.tra_if) dcs = self.verify_tra_encrypted6(p, p.vpp_tra_sa, rxs) @@ -1063,13 +1182,14 @@ class IpsecTra6(object): self.assert_equal(dc[IPv6ExtHdrFragment].id, 2) # two extensions before ESP, one after - tx = (Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) / - IPv6(src=self.tra_if.local_ip6, - dst=self.tra_if.remote_ip6) / - IPv6ExtHdrHopByHop() / - IPv6ExtHdrFragment(id=2, offset=200) / - IPv6ExtHdrDestOpt() / - Raw(b'\xff' * 200)) + tx = ( + Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) + / IPv6(src=self.tra_if.local_ip6, dst=self.tra_if.remote_ip6) + / IPv6ExtHdrHopByHop() + / IPv6ExtHdrFragment(id=2, offset=200) + / IPv6ExtHdrDestOpt() + / Raw(b"\xff" * 200) + ) rxs = self.send_and_expect(self.pg2, [tx], self.tra_if) dcs = self.verify_tra_encrypted6(p, p.vpp_tra_sa, rxs) @@ -1082,47 +1202,54 @@ class IpsecTra6(object): class IpsecTra6Tests(IpsecTra6): - """ UT test methods for Transport v6 """ + """UT test methods for Transport v6""" + def test_tra_basic6(self): - """ ipsec v6 transport basic test """ + """ipsec v6 transport basic test""" self.verify_tra_basic6(count=1) def test_tra_burst6(self): - """ ipsec v6 transport burst test """ + """ipsec v6 transport burst test""" self.verify_tra_basic6(count=257) class IpsecTra6ExtTests(IpsecTra6): def test_tra_ext_hdrs_66(self): - """ ipsec 6o6 tra extension headers test """ + """ipsec 6o6 tra extension headers test""" self.verify_tra_66_ext_hdrs(self.params[socket.AF_INET6]) class IpsecTra46Tests(IpsecTra4Tests, IpsecTra6Tests): - """ UT test methods for Transport v6 and v4""" + """UT test methods for Transport v6 and v4""" + pass class IpsecTun4(object): - """ verify methods for Tunnel v4 """ + """verify methods for Tunnel v4""" + def verify_counters4(self, p, count, n_frags=None, worker=None): if not n_frags: n_frags = count - if (hasattr(p, "spd_policy_in_any")): - pkts = p.spd_policy_in_any.get_stats(worker)['packets'] - self.assertEqual(pkts, count, - "incorrect SPD any policy: expected %d != %d" % - (count, pkts)) - - if (hasattr(p, "tun_sa_in")): - pkts = p.tun_sa_in.get_stats(worker)['packets'] - self.assertEqual(pkts, count, - "incorrect SA in counts: expected %d != %d" % - (count, pkts)) - pkts = p.tun_sa_out.get_stats(worker)['packets'] - self.assertEqual(pkts, n_frags, - "incorrect SA out counts: expected %d != %d" % - (count, pkts)) + if hasattr(p, "spd_policy_in_any"): + pkts = p.spd_policy_in_any.get_stats(worker)["packets"] + self.assertEqual( + pkts, + count, + "incorrect SPD any policy: expected %d != %d" % (count, pkts), + ) + + if hasattr(p, "tun_sa_in"): + pkts = p.tun_sa_in.get_stats(worker)["packets"] + self.assertEqual( + pkts, count, "incorrect SA in counts: expected %d != %d" % (count, pkts) + ) + pkts = p.tun_sa_out.get_stats(worker)["packets"] + self.assertEqual( + pkts, + n_frags, + "incorrect SA out counts: expected %d != %d" % (count, pkts), + ) self.assert_packet_counter_equal(self.tun4_encrypt_node_name, n_frags) self.assert_packet_counter_equal(self.tun4_decrypt_node_name[0], count) @@ -1177,19 +1304,26 @@ class IpsecTun4(object): if not n_rx: n_rx = count try: - send_pkts = self.gen_encrypt_pkts(p, p.scapy_tun_sa, self.tun_if, - src=p.remote_tun_if_host, - dst=self.pg1.remote_ip4, - count=count, - payload_size=payload_size) + send_pkts = self.gen_encrypt_pkts( + p, + p.scapy_tun_sa, + self.tun_if, + src=p.remote_tun_if_host, + dst=self.pg1.remote_ip4, + count=count, + payload_size=payload_size, + ) recv_pkts = self.send_and_expect(self.tun_if, send_pkts, self.pg1) self.verify_decrypted(p, recv_pkts) - send_pkts = self.gen_pkts(self.pg1, src=self.pg1.remote_ip4, - dst=p.remote_tun_if_host, count=count, - payload_size=payload_size) - recv_pkts = self.send_and_expect(self.pg1, send_pkts, - self.tun_if, n_rx) + send_pkts = self.gen_pkts( + self.pg1, + src=self.pg1.remote_ip4, + dst=p.remote_tun_if_host, + count=count, + payload_size=payload_size, + ) + recv_pkts = self.send_and_expect(self.pg1, send_pkts, self.tun_if, n_rx) self.verify_encrypted(p, p.vpp_tun_sa, recv_pkts) for rx in recv_pkts: @@ -1209,15 +1343,23 @@ class IpsecTun4(object): if not n_rx: n_rx = count try: - send_pkts = self.gen_encrypt_pkts(p, p.scapy_tun_sa, self.tun_if, - src=p.remote_tun_if_host, - dst=self.pg1.remote_ip4, - count=count) + send_pkts = self.gen_encrypt_pkts( + p, + p.scapy_tun_sa, + self.tun_if, + src=p.remote_tun_if_host, + dst=self.pg1.remote_ip4, + count=count, + ) self.send_and_assert_no_replies(self.tun_if, send_pkts) - send_pkts = self.gen_pkts(self.pg1, src=self.pg1.remote_ip4, - dst=p.remote_tun_if_host, count=count, - payload_size=payload_size) + send_pkts = self.gen_pkts( + self.pg1, + src=self.pg1.remote_ip4, + dst=p.remote_tun_if_host, + count=count, + payload_size=payload_size, + ) self.send_and_assert_no_replies(self.pg1, send_pkts) finally: @@ -1227,23 +1369,27 @@ class IpsecTun4(object): def verify_tun_reass_44(self, p): self.vapi.cli("clear errors") self.vapi.ip_reassembly_enable_disable( - sw_if_index=self.tun_if.sw_if_index, enable_ip4=True) + sw_if_index=self.tun_if.sw_if_index, enable_ip4=True + ) try: - send_pkts = self.gen_encrypt_pkts(p, p.scapy_tun_sa, self.tun_if, - src=p.remote_tun_if_host, - dst=self.pg1.remote_ip4, - payload_size=1900, - count=1) + send_pkts = self.gen_encrypt_pkts( + p, + p.scapy_tun_sa, + self.tun_if, + src=p.remote_tun_if_host, + dst=self.pg1.remote_ip4, + payload_size=1900, + count=1, + ) send_pkts = fragment_rfc791(send_pkts[0], 1400) - recv_pkts = self.send_and_expect(self.tun_if, send_pkts, - self.pg1, n_rx=1) + recv_pkts = self.send_and_expect(self.tun_if, send_pkts, self.pg1, n_rx=1) self.verify_decrypted(p, recv_pkts) - send_pkts = self.gen_pkts(self.pg1, src=self.pg1.remote_ip4, - dst=p.remote_tun_if_host, count=1) - recv_pkts = self.send_and_expect(self.pg1, send_pkts, - self.tun_if) + send_pkts = self.gen_pkts( + self.pg1, src=self.pg1.remote_ip4, dst=p.remote_tun_if_host, count=1 + ) + recv_pkts = self.send_and_expect(self.pg1, send_pkts, self.tun_if) self.verify_encrypted(p, p.vpp_tun_sa, recv_pkts) finally: @@ -1252,23 +1398,33 @@ class IpsecTun4(object): self.verify_counters4(p, 1, 1) self.vapi.ip_reassembly_enable_disable( - sw_if_index=self.tun_if.sw_if_index, enable_ip4=False) + sw_if_index=self.tun_if.sw_if_index, enable_ip4=False + ) def verify_tun_64(self, p, count=1): self.vapi.cli("clear errors") self.vapi.cli("clear ipsec sa") try: - send_pkts = self.gen_encrypt_pkts6(p, p.scapy_tun_sa, self.tun_if, - src=p.remote_tun_if_host6, - dst=self.pg1.remote_ip6, - count=count) + send_pkts = self.gen_encrypt_pkts6( + p, + p.scapy_tun_sa, + self.tun_if, + src=p.remote_tun_if_host6, + dst=self.pg1.remote_ip6, + count=count, + ) recv_pkts = self.send_and_expect(self.tun_if, send_pkts, self.pg1) for recv_pkt in recv_pkts: self.assert_equal(recv_pkt[IPv6].src, p.remote_tun_if_host6) self.assert_equal(recv_pkt[IPv6].dst, self.pg1.remote_ip6) self.assert_packet_checksums_valid(recv_pkt) - send_pkts = self.gen_pkts6(p, self.pg1, src=self.pg1.remote_ip6, - dst=p.remote_tun_if_host6, count=count) + send_pkts = self.gen_pkts6( + p, + self.pg1, + src=self.pg1.remote_ip6, + dst=p.remote_tun_if_host6, + count=count, + ) recv_pkts = self.send_and_expect(self.pg1, send_pkts, self.tun_if) for recv_pkt in recv_pkts: try: @@ -1281,8 +1437,7 @@ class IpsecTun4(object): except: self.logger.error(ppp("Unexpected packet:", recv_pkt)) try: - self.logger.debug( - ppp("Decrypted packet:", decrypt_pkt)) + self.logger.debug(ppp("Decrypted packet:", decrypt_pkt)) except: pass raise @@ -1295,37 +1450,43 @@ class IpsecTun4(object): def verify_keepalive(self, p): # the sizeof Raw is calculated to pad to the minimum ehternet # frame size of 64 btyes - pkt = (Ether(src=self.tun_if.remote_mac, dst=self.tun_if.local_mac) / - IP(src=p.remote_tun_if_host, dst=self.tun_if.local_ip4) / - UDP(sport=333, dport=4500) / - Raw(b'\xff') / - Padding(0 * 21)) - self.send_and_assert_no_replies(self.tun_if, pkt*31) + pkt = ( + Ether(src=self.tun_if.remote_mac, dst=self.tun_if.local_mac) + / IP(src=p.remote_tun_if_host, dst=self.tun_if.local_ip4) + / UDP(sport=333, dport=4500) + / Raw(b"\xff") + / Padding(0 * 21) + ) + self.send_and_assert_no_replies(self.tun_if, pkt * 31) self.assert_error_counter_equal( - '/err/%s/NAT Keepalive' % self.tun4_input_node, 31) - - pkt = (Ether(src=self.tun_if.remote_mac, dst=self.tun_if.local_mac) / - IP(src=p.remote_tun_if_host, dst=self.tun_if.local_ip4) / - UDP(sport=333, dport=4500) / - Raw(b'\xfe')) - self.send_and_assert_no_replies(self.tun_if, pkt*31) - self.assert_error_counter_equal( - '/err/%s/Too Short' % self.tun4_input_node, 31) - - pkt = (Ether(src=self.tun_if.remote_mac, dst=self.tun_if.local_mac) / - IP(src=p.remote_tun_if_host, dst=self.tun_if.local_ip4) / - UDP(sport=333, dport=4500) / - Raw(b'\xfe') / - Padding(0 * 21)) - self.send_and_assert_no_replies(self.tun_if, pkt*31) - self.assert_error_counter_equal( - '/err/%s/Too Short' % self.tun4_input_node, 62) + "/err/%s/NAT Keepalive" % self.tun4_input_node, 31 + ) + + pkt = ( + Ether(src=self.tun_if.remote_mac, dst=self.tun_if.local_mac) + / IP(src=p.remote_tun_if_host, dst=self.tun_if.local_ip4) + / UDP(sport=333, dport=4500) + / Raw(b"\xfe") + ) + self.send_and_assert_no_replies(self.tun_if, pkt * 31) + self.assert_error_counter_equal("/err/%s/Too Short" % self.tun4_input_node, 31) + + pkt = ( + Ether(src=self.tun_if.remote_mac, dst=self.tun_if.local_mac) + / IP(src=p.remote_tun_if_host, dst=self.tun_if.local_ip4) + / UDP(sport=333, dport=4500) + / Raw(b"\xfe") + / Padding(0 * 21) + ) + self.send_and_assert_no_replies(self.tun_if, pkt * 31) + self.assert_error_counter_equal("/err/%s/Too Short" % self.tun4_input_node, 62) class IpsecTun4Tests(IpsecTun4): - """ UT test methods for Tunnel v4 """ + """UT test methods for Tunnel v4""" + def test_tun_basic44(self): - """ ipsec 4o4 tunnel basic test """ + """ipsec 4o4 tunnel basic test""" self.verify_tun_44(self.params[socket.AF_INET], count=1) self.tun_if.admin_down() self.tun_if.resolve_arp() @@ -1333,27 +1494,30 @@ class IpsecTun4Tests(IpsecTun4): self.verify_tun_44(self.params[socket.AF_INET], count=1) def test_tun_reass_basic44(self): - """ ipsec 4o4 tunnel basic reassembly test """ + """ipsec 4o4 tunnel basic reassembly test""" self.verify_tun_reass_44(self.params[socket.AF_INET]) def test_tun_burst44(self): - """ ipsec 4o4 tunnel burst test """ + """ipsec 4o4 tunnel burst test""" self.verify_tun_44(self.params[socket.AF_INET], count=127) class IpsecTun6(object): - """ verify methods for Tunnel v6 """ + """verify methods for Tunnel v6""" + def verify_counters6(self, p_in, p_out, count, worker=None): - if (hasattr(p_in, "tun_sa_in")): - pkts = p_in.tun_sa_in.get_stats(worker)['packets'] - self.assertEqual(pkts, count, - "incorrect SA in counts: expected %d != %d" % - (count, pkts)) - if (hasattr(p_out, "tun_sa_out")): - pkts = p_out.tun_sa_out.get_stats(worker)['packets'] - self.assertEqual(pkts, count, - "incorrect SA out counts: expected %d != %d" % - (count, pkts)) + if hasattr(p_in, "tun_sa_in"): + pkts = p_in.tun_sa_in.get_stats(worker)["packets"] + self.assertEqual( + pkts, count, "incorrect SA in counts: expected %d != %d" % (count, pkts) + ) + if hasattr(p_out, "tun_sa_out"): + pkts = p_out.tun_sa_out.get_stats(worker)["packets"] + self.assertEqual( + pkts, + count, + "incorrect SA out counts: expected %d != %d" % (count, pkts), + ) self.assert_packet_counter_equal(self.tun6_encrypt_node_name, count) self.assert_packet_counter_equal(self.tun6_decrypt_node_name[0], count) @@ -1366,8 +1530,7 @@ class IpsecTun6(object): def verify_encrypted6(self, p, sa, rxs): for rx in rxs: self.assert_packet_checksums_valid(rx) - self.assertEqual(len(rx) - len(Ether()) - len(IPv6()), - rx[IPv6].plen) + self.assertEqual(len(rx) - len(Ether()) - len(IPv6()), rx[IPv6].plen) self.assert_equal(rx[IPv6].hlim, p.outer_hop_limit) if p.outer_flow_label: self.assert_equal(rx[IPv6].fl, p.outer_flow_label) @@ -1392,9 +1555,14 @@ class IpsecTun6(object): self.vapi.cli("clear errors") self.vapi.cli("clear ipsec sa") - send_pkts = self.gen_pkts6(p_in, self.pg1, src=self.pg1.remote_ip6, - dst=p_in.remote_tun_if_host, count=count, - payload_size=payload_size) + send_pkts = self.gen_pkts6( + p_in, + self.pg1, + src=self.pg1.remote_ip6, + dst=p_in.remote_tun_if_host, + count=count, + payload_size=payload_size, + ) self.send_and_assert_no_replies(self.tun_if, send_pkts) self.logger.info(self.vapi.cli("sh punt stats")) @@ -1402,18 +1570,19 @@ class IpsecTun6(object): self.vapi.cli("clear errors") self.vapi.cli("clear ipsec sa") - send_pkts = self.gen_encrypt_pkts6(p_in, p_in.scapy_tun_sa, - self.tun_if, - src=p_in.remote_tun_if_host, - dst=self.pg1.remote_ip6, - count=count) + send_pkts = self.gen_encrypt_pkts6( + p_in, + p_in.scapy_tun_sa, + self.tun_if, + src=p_in.remote_tun_if_host, + dst=self.pg1.remote_ip6, + count=count, + ) self.send_and_assert_no_replies(self.tun_if, send_pkts) def verify_drop_tun_66(self, p_in, count=1, payload_size=64): - self.verify_drop_tun_tx_66(p_in, count=count, - payload_size=payload_size) - self.verify_drop_tun_rx_66(p_in, count=count, - payload_size=payload_size) + self.verify_drop_tun_tx_66(p_in, count=count, payload_size=payload_size) + self.verify_drop_tun_rx_66(p_in, count=count, payload_size=payload_size) def verify_tun_66(self, p_in, p_out=None, count=1, payload_size=64): self.vapi.cli("clear errors") @@ -1421,19 +1590,26 @@ class IpsecTun6(object): if not p_out: p_out = p_in try: - send_pkts = self.gen_encrypt_pkts6(p_in, p_in.scapy_tun_sa, - self.tun_if, - src=p_in.remote_tun_if_host, - dst=self.pg1.remote_ip6, - count=count, - payload_size=payload_size) + send_pkts = self.gen_encrypt_pkts6( + p_in, + p_in.scapy_tun_sa, + self.tun_if, + src=p_in.remote_tun_if_host, + dst=self.pg1.remote_ip6, + count=count, + payload_size=payload_size, + ) recv_pkts = self.send_and_expect(self.tun_if, send_pkts, self.pg1) self.verify_decrypted6(p_in, recv_pkts) - send_pkts = self.gen_pkts6(p_in, self.pg1, src=self.pg1.remote_ip6, - dst=p_out.remote_tun_if_host, - count=count, - payload_size=payload_size) + send_pkts = self.gen_pkts6( + p_in, + self.pg1, + src=self.pg1.remote_ip6, + dst=p_out.remote_tun_if_host, + count=count, + payload_size=payload_size, + ) recv_pkts = self.send_and_expect(self.pg1, send_pkts, self.tun_if) self.verify_encrypted6(p_out, p_out.vpp_tun_sa, recv_pkts) @@ -1449,50 +1625,65 @@ class IpsecTun6(object): def verify_tun_reass_66(self, p): self.vapi.cli("clear errors") self.vapi.ip_reassembly_enable_disable( - sw_if_index=self.tun_if.sw_if_index, enable_ip6=True) + sw_if_index=self.tun_if.sw_if_index, enable_ip6=True + ) try: - send_pkts = self.gen_encrypt_pkts6(p, p.scapy_tun_sa, self.tun_if, - src=p.remote_tun_if_host, - dst=self.pg1.remote_ip6, - count=1, - payload_size=1850) + send_pkts = self.gen_encrypt_pkts6( + p, + p.scapy_tun_sa, + self.tun_if, + src=p.remote_tun_if_host, + dst=self.pg1.remote_ip6, + count=1, + payload_size=1850, + ) send_pkts = fragment_rfc8200(send_pkts[0], 1, 1400, self.logger) - recv_pkts = self.send_and_expect(self.tun_if, send_pkts, - self.pg1, n_rx=1) + recv_pkts = self.send_and_expect(self.tun_if, send_pkts, self.pg1, n_rx=1) self.verify_decrypted6(p, recv_pkts) - send_pkts = self.gen_pkts6(p, self.pg1, src=self.pg1.remote_ip6, - dst=p.remote_tun_if_host, - count=1, - payload_size=64) - recv_pkts = self.send_and_expect(self.pg1, send_pkts, - self.tun_if) + send_pkts = self.gen_pkts6( + p, + self.pg1, + src=self.pg1.remote_ip6, + dst=p.remote_tun_if_host, + count=1, + payload_size=64, + ) + recv_pkts = self.send_and_expect(self.pg1, send_pkts, self.tun_if) self.verify_encrypted6(p, p.vpp_tun_sa, recv_pkts) finally: self.logger.info(self.vapi.ppcli("show error")) self.logger.info(self.vapi.ppcli("show ipsec all")) self.verify_counters6(p, p, 1) self.vapi.ip_reassembly_enable_disable( - sw_if_index=self.tun_if.sw_if_index, enable_ip6=False) + sw_if_index=self.tun_if.sw_if_index, enable_ip6=False + ) def verify_tun_46(self, p, count=1): - """ ipsec 4o6 tunnel basic test """ + """ipsec 4o6 tunnel basic test""" self.vapi.cli("clear errors") self.vapi.cli("clear ipsec sa") try: - send_pkts = self.gen_encrypt_pkts(p, p.scapy_tun_sa, self.tun_if, - src=p.remote_tun_if_host4, - dst=self.pg1.remote_ip4, - count=count) + send_pkts = self.gen_encrypt_pkts( + p, + p.scapy_tun_sa, + self.tun_if, + src=p.remote_tun_if_host4, + dst=self.pg1.remote_ip4, + count=count, + ) recv_pkts = self.send_and_expect(self.tun_if, send_pkts, self.pg1) for recv_pkt in recv_pkts: self.assert_equal(recv_pkt[IP].src, p.remote_tun_if_host4) self.assert_equal(recv_pkt[IP].dst, self.pg1.remote_ip4) self.assert_packet_checksums_valid(recv_pkt) - send_pkts = self.gen_pkts(self.pg1, src=self.pg1.remote_ip4, - dst=p.remote_tun_if_host4, - count=count) + send_pkts = self.gen_pkts( + self.pg1, + src=self.pg1.remote_ip4, + dst=p.remote_tun_if_host4, + count=count, + ) recv_pkts = self.send_and_expect(self.pg1, send_pkts, self.tun_if) for recv_pkt in recv_pkts: try: @@ -1505,8 +1696,7 @@ class IpsecTun6(object): except: self.logger.debug(ppp("Unexpected packet:", recv_pkt)) try: - self.logger.debug(ppp("Decrypted packet:", - decrypt_pkt)) + self.logger.debug(ppp("Decrypted packet:", decrypt_pkt)) except: pass raise @@ -1517,27 +1707,28 @@ class IpsecTun6(object): class IpsecTun6Tests(IpsecTun6): - """ UT test methods for Tunnel v6 """ + """UT test methods for Tunnel v6""" def test_tun_basic66(self): - """ ipsec 6o6 tunnel basic test """ + """ipsec 6o6 tunnel basic test""" self.verify_tun_66(self.params[socket.AF_INET6], count=1) def test_tun_reass_basic66(self): - """ ipsec 6o6 tunnel basic reassembly test """ + """ipsec 6o6 tunnel basic reassembly test""" self.verify_tun_reass_66(self.params[socket.AF_INET6]) def test_tun_burst66(self): - """ ipsec 6o6 tunnel burst test """ + """ipsec 6o6 tunnel burst test""" self.verify_tun_66(self.params[socket.AF_INET6], count=257) class IpsecTun6HandoffTests(IpsecTun6): - """ UT test methods for Tunnel v6 with multiple workers """ + """UT test methods for Tunnel v6 with multiple workers""" + vpp_worker_count = 2 def test_tun_handoff_66(self): - """ ipsec 6o6 tunnel worker hand-off test """ + """ipsec 6o6 tunnel worker hand-off test""" self.vapi.cli("clear errors") self.vapi.cli("clear ipsec sa") @@ -1547,31 +1738,42 @@ class IpsecTun6HandoffTests(IpsecTun6): # inject alternately on worker 0 and 1. all counts on the SA # should be against worker 0 for worker in [0, 1, 0, 1]: - send_pkts = self.gen_encrypt_pkts6(p, p.scapy_tun_sa, self.tun_if, - src=p.remote_tun_if_host, - dst=self.pg1.remote_ip6, - count=N_PKTS) - recv_pkts = self.send_and_expect(self.tun_if, send_pkts, - self.pg1, worker=worker) + send_pkts = self.gen_encrypt_pkts6( + p, + p.scapy_tun_sa, + self.tun_if, + src=p.remote_tun_if_host, + dst=self.pg1.remote_ip6, + count=N_PKTS, + ) + recv_pkts = self.send_and_expect( + self.tun_if, send_pkts, self.pg1, worker=worker + ) self.verify_decrypted6(p, recv_pkts) - send_pkts = self.gen_pkts6(p, self.pg1, src=self.pg1.remote_ip6, - dst=p.remote_tun_if_host, - count=N_PKTS) - recv_pkts = self.send_and_expect(self.pg1, send_pkts, - self.tun_if, worker=worker) + send_pkts = self.gen_pkts6( + p, + self.pg1, + src=self.pg1.remote_ip6, + dst=p.remote_tun_if_host, + count=N_PKTS, + ) + recv_pkts = self.send_and_expect( + self.pg1, send_pkts, self.tun_if, worker=worker + ) self.verify_encrypted6(p, p.vpp_tun_sa, recv_pkts) # all counts against the first worker that was used - self.verify_counters6(p, p, 4*N_PKTS, worker=0) + self.verify_counters6(p, p, 4 * N_PKTS, worker=0) class IpsecTun4HandoffTests(IpsecTun4): - """ UT test methods for Tunnel v4 with multiple workers """ + """UT test methods for Tunnel v4 with multiple workers""" + vpp_worker_count = 2 def test_tun_handooff_44(self): - """ ipsec 4o4 tunnel worker hand-off test """ + """ipsec 4o4 tunnel worker hand-off test""" self.vapi.cli("clear errors") self.vapi.cli("clear ipsec sa") @@ -1581,32 +1783,43 @@ class IpsecTun4HandoffTests(IpsecTun4): # inject alternately on worker 0 and 1. all counts on the SA # should be against worker 0 for worker in [0, 1, 0, 1]: - send_pkts = self.gen_encrypt_pkts(p, p.scapy_tun_sa, self.tun_if, - src=p.remote_tun_if_host, - dst=self.pg1.remote_ip4, - count=N_PKTS) - recv_pkts = self.send_and_expect(self.tun_if, send_pkts, - self.pg1, worker=worker) + send_pkts = self.gen_encrypt_pkts( + p, + p.scapy_tun_sa, + self.tun_if, + src=p.remote_tun_if_host, + dst=self.pg1.remote_ip4, + count=N_PKTS, + ) + recv_pkts = self.send_and_expect( + self.tun_if, send_pkts, self.pg1, worker=worker + ) self.verify_decrypted(p, recv_pkts) - send_pkts = self.gen_pkts(self.pg1, src=self.pg1.remote_ip4, - dst=p.remote_tun_if_host, - count=N_PKTS) - recv_pkts = self.send_and_expect(self.pg1, send_pkts, - self.tun_if, worker=worker) + send_pkts = self.gen_pkts( + self.pg1, + src=self.pg1.remote_ip4, + dst=p.remote_tun_if_host, + count=N_PKTS, + ) + recv_pkts = self.send_and_expect( + self.pg1, send_pkts, self.tun_if, worker=worker + ) self.verify_encrypted(p, p.vpp_tun_sa, recv_pkts) # all counts against the first worker that was used - self.verify_counters4(p, 4*N_PKTS, worker=0) + self.verify_counters4(p, 4 * N_PKTS, worker=0) class IpsecTun46Tests(IpsecTun4Tests, IpsecTun6Tests): - """ UT test methods for Tunnel v6 & v4 """ + """UT test methods for Tunnel v6 & v4""" + pass class IPSecIPv4Fwd(VppTestCase): - """ Test IPSec by capturing and verifying IPv4 forwarded pkts """ + """Test IPSec by capturing and verifying IPv4 forwarded pkts""" + @classmethod def setUpConstants(cls): super(IPSecIPv4Fwd, cls).setUpConstants() @@ -1664,9 +1877,18 @@ class IPSecIPv4Fwd(VppTestCase): else: raise Exception("Invalid policy type: %s", policy_type) - def spd_add_rem_policy(self, spd_id, src_if, dst_if, - proto, is_out, priority, policy_type, - remove=False, all_ips=False): + def spd_add_rem_policy( + self, + spd_id, + src_if, + dst_if, + proto, + is_out, + priority, + policy_type, + remove=False, + all_ips=False, + ): spd = VppIpsecSpd(self, spd_id) if all_ips: @@ -1680,17 +1902,21 @@ class IPSecIPv4Fwd(VppTestCase): dst_range_low = dst_if.remote_ip4 dst_range_high = dst_if.remote_ip4 - spdEntry = VppIpsecSpdEntry(self, spd, 0, - src_range_low, - src_range_high, - dst_range_low, - dst_range_high, - proto, - priority=priority, - policy=self.get_policy(policy_type), - is_outbound=is_out) - - if(remove is False): + spdEntry = VppIpsecSpdEntry( + self, + spd, + 0, + src_range_low, + src_range_high, + dst_range_low, + dst_range_high, + proto, + priority=priority, + policy=self.get_policy(policy_type), + is_outbound=is_out, + ) + + if remove is False: spdEntry.add_vpp_config() self.spd_policies.append(spdEntry) else: @@ -1699,8 +1925,7 @@ class IPSecIPv4Fwd(VppTestCase): self.logger.info(self.vapi.ppcli("show ipsec all")) return spdEntry - def create_stream(self, src_if, dst_if, pkt_count, - src_prt=1234, dst_prt=5678): + def create_stream(self, src_if, dst_if, pkt_count, src_prt=1234, dst_prt=5678): packets = [] for i in range(pkt_count): # create packet info stored in the test case instance @@ -1708,10 +1933,12 @@ class IPSecIPv4Fwd(VppTestCase): # convert the info into packet payload payload = self.info_to_payload(info) # create the packet itself - p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - IP(src=src_if.remote_ip4, dst=dst_if.remote_ip4) / - UDP(sport=src_prt, dport=dst_prt) / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / IP(src=src_if.remote_ip4, dst=dst_if.remote_ip4) + / UDP(sport=src_prt, dport=dst_prt) + / Raw(payload) + ) # store a copy of the packet in the packet info info.data = p.copy() # append the packet to the list @@ -1728,43 +1955,41 @@ class IPSecIPv4Fwd(VppTestCase): # convert the payload to packet info object payload_info = self.payload_to_info(packet) # make sure the indexes match - self.assert_equal(payload_info.src, src_if.sw_if_index, - "source sw_if_index") - self.assert_equal(payload_info.dst, dst_if.sw_if_index, - "destination sw_if_index") + self.assert_equal( + payload_info.src, src_if.sw_if_index, "source sw_if_index" + ) + self.assert_equal( + payload_info.dst, dst_if.sw_if_index, "destination sw_if_index" + ) packet_info = self.get_next_packet_info_for_interface2( - src_if.sw_if_index, - dst_if.sw_if_index, - packet_info) + src_if.sw_if_index, dst_if.sw_if_index, packet_info + ) # make sure we didn't run out of saved packets self.assertIsNotNone(packet_info) - self.assert_equal(payload_info.index, packet_info.index, - "packet info index") + self.assert_equal( + payload_info.index, packet_info.index, "packet info index" + ) saved_packet = packet_info.data # fetch the saved packet # assert the values match - self.assert_equal(ip.src, saved_packet[IP].src, - "IP source address") + self.assert_equal(ip.src, saved_packet[IP].src, "IP source address") # ... more assertions here - self.assert_equal(udp.sport, saved_packet[UDP].sport, - "UDP source port") + self.assert_equal(udp.sport, saved_packet[UDP].sport, "UDP source port") except Exception as e: - self.logger.error(ppp("Unexpected or invalid packet:", - packet)) + self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise remaining_packet = self.get_next_packet_info_for_interface2( - src_if.sw_if_index, - dst_if.sw_if_index, - packet_info) - self.assertIsNone(remaining_packet, - "Interface %s: Packet expected from interface " - "%s didn't arrive" % (dst_if.name, src_if.name)) + src_if.sw_if_index, dst_if.sw_if_index, packet_info + ) + self.assertIsNone( + remaining_packet, + "Interface %s: Packet expected from interface " + "%s didn't arrive" % (dst_if.name, src_if.name), + ) def verify_policy_match(self, pkt_count, spdEntry): - self.logger.info( - "XXXX %s %s", str(spdEntry), str(spdEntry.get_stats())) - matched_pkts = spdEntry.get_stats().get('packets') - self.logger.info( - "Policy %s matched: %d pkts", str(spdEntry), matched_pkts) + self.logger.info("XXXX %s %s", str(spdEntry), str(spdEntry.get_stats())) + matched_pkts = spdEntry.get_stats().get("packets") + self.logger.info("Policy %s matched: %d pkts", str(spdEntry), matched_pkts) self.assert_equal(pkt_count, matched_pkts) @@ -1786,43 +2011,52 @@ class SpdFlowCacheTemplate(IPSecIPv4Fwd): super(SpdFlowCacheTemplate, self).tearDown() def get_spd_flow_cache_entries(self, outbound): - """ 'show ipsec spd' output: + """'show ipsec spd' output: ipv4-inbound-spd-flow-cache-entries: 0 ipv4-outbound-spd-flow-cache-entries: 0 """ show_ipsec_reply = self.vapi.cli("show ipsec spd") # match the relevant section of 'show ipsec spd' output - if(outbound): + if outbound: regex_match = re.search( - 'ipv4-outbound-spd-flow-cache-entries: (.*)', - show_ipsec_reply, re.DOTALL) + "ipv4-outbound-spd-flow-cache-entries: (.*)", + show_ipsec_reply, + re.DOTALL, + ) else: regex_match = re.search( - 'ipv4-inbound-spd-flow-cache-entries: (.*)', - show_ipsec_reply, re.DOTALL) + "ipv4-inbound-spd-flow-cache-entries: (.*)", show_ipsec_reply, re.DOTALL + ) if regex_match is None: - raise Exception("Unable to find spd flow cache entries \ - in \'show ipsec spd\' CLI output - regex failed to match") + raise Exception( + "Unable to find spd flow cache entries \ + in 'show ipsec spd' CLI output - regex failed to match" + ) else: try: num_entries = int(regex_match.group(1)) except ValueError: - raise Exception("Unable to get spd flow cache entries \ - from \'show ipsec spd\' string: %s", regex_match.group(0)) + raise Exception( + "Unable to get spd flow cache entries \ + from 'show ipsec spd' string: %s", + regex_match.group(0), + ) self.logger.info("%s", regex_match.group(0)) return num_entries def verify_num_outbound_flow_cache_entries(self, expected_elements): - self.assertEqual(self.get_spd_flow_cache_entries(outbound=True), - expected_elements) + self.assertEqual( + self.get_spd_flow_cache_entries(outbound=True), expected_elements + ) def verify_num_inbound_flow_cache_entries(self, expected_elements): - self.assertEqual(self.get_spd_flow_cache_entries(outbound=False), - expected_elements) + self.assertEqual( + self.get_spd_flow_cache_entries(outbound=False), expected_elements + ) def crc32_supported(self): # lscpu is part of util-linux package, available on all Linux Distros - stream = os.popen('lscpu') + stream = os.popen("lscpu") cpu_info = stream.read() # feature/flag "crc32" on Aarch64 and "sse4_2" on x86 # see vppinfra/crc32.h @@ -1833,5 +2067,6 @@ class SpdFlowCacheTemplate(IPSecIPv4Fwd): self.logger.info("\ncrc32 NOT supported:\n" + cpu_info) return False -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_abf.py b/test/test_abf.py index 097476b879a..856d02a8185 100644 --- a/test/test_abf.py +++ b/test/test_abf.py @@ -5,8 +5,13 @@ import unittest from framework import VppTestCase, VppTestRunner from vpp_ip import DpoProto -from vpp_ip_route import VppIpRoute, VppRoutePath, VppMplsLabel, \ - VppIpTable, FibPathProto +from vpp_ip_route import ( + VppIpRoute, + VppRoutePath, + VppMplsLabel, + VppIpTable, + FibPathProto, +) from vpp_acl import AclRule, VppAcl from scapy.packet import Raw @@ -31,19 +36,13 @@ def find_abf_policy(test, id): def find_abf_itf_attach(test, id, sw_if_index): attachs = test.vapi.abf_itf_attach_dump() for a in attachs: - if id == a.attach.policy_id and \ - sw_if_index == a.attach.sw_if_index: + if id == a.attach.policy_id and sw_if_index == a.attach.sw_if_index: return True return False class VppAbfPolicy(VppObject): - - def __init__(self, - test, - policy_id, - acl, - paths): + def __init__(self, test, policy_id, acl, paths): self._test = test self.policy_id = policy_id self.acl = acl @@ -55,35 +54,35 @@ class VppAbfPolicy(VppObject): def add_vpp_config(self): self._test.vapi.abf_policy_add_del( 1, - {'policy_id': self.policy_id, - 'acl_index': self.acl.acl_index, - 'n_paths': len(self.paths), - 'paths': self.encoded_paths}) + { + "policy_id": self.policy_id, + "acl_index": self.acl.acl_index, + "n_paths": len(self.paths), + "paths": self.encoded_paths, + }, + ) self._test.registry.register(self, self._test.logger) def remove_vpp_config(self): self._test.vapi.abf_policy_add_del( 0, - {'policy_id': self.policy_id, - 'acl_index': self.acl.acl_index, - 'n_paths': len(self.paths), - 'paths': self.encoded_paths}) + { + "policy_id": self.policy_id, + "acl_index": self.acl.acl_index, + "n_paths": len(self.paths), + "paths": self.encoded_paths, + }, + ) def query_vpp_config(self): return find_abf_policy(self._test, self.policy_id) def object_id(self): - return ("abf-policy-%d" % self.policy_id) + return "abf-policy-%d" % self.policy_id class VppAbfAttach(VppObject): - - def __init__(self, - test, - policy_id, - sw_if_index, - priority, - is_ipv6=0): + def __init__(self, test, policy_id, sw_if_index, priority, is_ipv6=0): self._test = test self.policy_id = policy_id self.sw_if_index = sw_if_index @@ -93,31 +92,35 @@ class VppAbfAttach(VppObject): def add_vpp_config(self): self._test.vapi.abf_itf_attach_add_del( 1, - {'policy_id': self.policy_id, - 'sw_if_index': self.sw_if_index, - 'priority': self.priority, - 'is_ipv6': self.is_ipv6}) + { + "policy_id": self.policy_id, + "sw_if_index": self.sw_if_index, + "priority": self.priority, + "is_ipv6": self.is_ipv6, + }, + ) self._test.registry.register(self, self._test.logger) def remove_vpp_config(self): self._test.vapi.abf_itf_attach_add_del( 0, - {'policy_id': self.policy_id, - 'sw_if_index': self.sw_if_index, - 'priority': self.priority, - 'is_ipv6': self.is_ipv6}) + { + "policy_id": self.policy_id, + "sw_if_index": self.sw_if_index, + "priority": self.priority, + "is_ipv6": self.is_ipv6, + }, + ) def query_vpp_config(self): - return find_abf_itf_attach(self._test, - self.policy_id, - self.sw_if_index) + return find_abf_itf_attach(self._test, self.policy_id, self.sw_if_index) def object_id(self): - return ("abf-attach-%d-%d" % (self.policy_id, self.sw_if_index)) + return "abf-attach-%d-%d" % (self.policy_id, self.sw_if_index) class TestAbf(VppTestCase): - """ ABF Test Case """ + """ABF Test Case""" @classmethod def setUpClass(cls): @@ -147,8 +150,7 @@ class TestAbf(VppTestCase): super(TestAbf, self).tearDown() def test_abf4(self): - """ IPv4 ACL Based Forwarding - """ + """IPv4 ACL Based Forwarding""" # # We are not testing the various matching capabilities @@ -163,18 +165,22 @@ class TestAbf(VppTestCase): # # Rule 1 # - rule_1 = AclRule(is_permit=1, proto=17, ports=1234, - src_prefix=IPv4Network("1.1.1.1/32"), - dst_prefix=IPv4Network("1.1.1.2/32")) + rule_1 = AclRule( + is_permit=1, + proto=17, + ports=1234, + src_prefix=IPv4Network("1.1.1.1/32"), + dst_prefix=IPv4Network("1.1.1.2/32"), + ) acl_1 = VppAcl(self, rules=[rule_1]) acl_1.add_vpp_config() # # ABF policy for ACL 1 - path via interface 1 # - abf_1 = VppAbfPolicy(self, 10, acl_1, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index)]) + abf_1 = VppAbfPolicy( + self, 10, acl_1, [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)] + ) abf_1.add_vpp_config() # @@ -187,42 +193,43 @@ class TestAbf(VppTestCase): # fire in packet matching the ACL src,dst. If it's forwarded # then the ABF was successful, since default routing will drop it # - p_1 = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src="1.1.1.1", dst="1.1.1.2") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - self.send_and_expect(self.pg0, p_1*NUM_PKTS, self.pg1) + p_1 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src="1.1.1.1", dst="1.1.1.2") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + self.send_and_expect(self.pg0, p_1 * NUM_PKTS, self.pg1) # # Attach a 'better' priority policy to the same interface # - abf_2 = VppAbfPolicy(self, 11, acl_1, - [VppRoutePath(self.pg2.remote_ip4, - self.pg2.sw_if_index)]) + abf_2 = VppAbfPolicy( + self, 11, acl_1, [VppRoutePath(self.pg2.remote_ip4, self.pg2.sw_if_index)] + ) abf_2.add_vpp_config() attach_2 = VppAbfAttach(self, 11, self.pg0.sw_if_index, 40) attach_2.add_vpp_config() - self.send_and_expect(self.pg0, p_1*NUM_PKTS, self.pg2) + self.send_and_expect(self.pg0, p_1 * NUM_PKTS, self.pg2) # # Attach a policy with priority in the middle # - abf_3 = VppAbfPolicy(self, 12, acl_1, - [VppRoutePath(self.pg3.remote_ip4, - self.pg3.sw_if_index)]) + abf_3 = VppAbfPolicy( + self, 12, acl_1, [VppRoutePath(self.pg3.remote_ip4, self.pg3.sw_if_index)] + ) abf_3.add_vpp_config() attach_3 = VppAbfAttach(self, 12, self.pg0.sw_if_index, 45) attach_3.add_vpp_config() - self.send_and_expect(self.pg0, p_1*NUM_PKTS, self.pg2) + self.send_and_expect(self.pg0, p_1 * NUM_PKTS, self.pg2) # # remove the best priority # attach_2.remove_vpp_config() - self.send_and_expect(self.pg0, p_1*NUM_PKTS, self.pg3) + self.send_and_expect(self.pg0, p_1 * NUM_PKTS, self.pg3) # # Attach one of the same policies to Pg1 @@ -230,11 +237,12 @@ class TestAbf(VppTestCase): attach_4 = VppAbfAttach(self, 12, self.pg1.sw_if_index, 45) attach_4.add_vpp_config() - p_2 = (Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) / - IP(src="1.1.1.1", dst="1.1.1.2") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p_2 = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src="1.1.1.1", dst="1.1.1.2") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) self.send_and_expect(self.pg1, p_2 * NUM_PKTS, self.pg3) # @@ -255,22 +263,27 @@ class TestAbf(VppTestCase): self.pg4.config_ip4() self.pg4.resolve_arp() - abf_13 = VppAbfPolicy(self, 13, acl_1, - [VppRoutePath(self.pg4.remote_ip4, - 0xffffffff, - nh_table_id=table_20.table_id)]) + abf_13 = VppAbfPolicy( + self, + 13, + acl_1, + [ + VppRoutePath( + self.pg4.remote_ip4, 0xFFFFFFFF, nh_table_id=table_20.table_id + ) + ], + ) abf_13.add_vpp_config() attach_5 = VppAbfAttach(self, 13, self.pg0.sw_if_index, 30) attach_5.add_vpp_config() - self.send_and_expect(self.pg0, p_1*NUM_PKTS, self.pg4) + self.send_and_expect(self.pg0, p_1 * NUM_PKTS, self.pg4) self.pg4.unconfig_ip4() self.pg4.set_table_ip4(0) def test_abf6(self): - """ IPv6 ACL Based Forwarding - """ + """IPv6 ACL Based Forwarding""" # # Simple test for matching IPv6 packets @@ -279,32 +292,34 @@ class TestAbf(VppTestCase): # # Rule 1 # - rule_1 = AclRule(is_permit=1, proto=17, ports=1234, - src_prefix=IPv6Network("2001::2/128"), - dst_prefix=IPv6Network("2001::1/128")) + rule_1 = AclRule( + is_permit=1, + proto=17, + ports=1234, + src_prefix=IPv6Network("2001::2/128"), + dst_prefix=IPv6Network("2001::1/128"), + ) acl_1 = VppAcl(self, rules=[rule_1]) acl_1.add_vpp_config() # # ABF policy for ACL 1 - path via interface 1 # - abf_1 = VppAbfPolicy(self, 10, acl_1, - [VppRoutePath("3001::1", - 0xffffffff)]) + abf_1 = VppAbfPolicy(self, 10, acl_1, [VppRoutePath("3001::1", 0xFFFFFFFF)]) abf_1.add_vpp_config() - attach_1 = VppAbfAttach(self, 10, self.pg0.sw_if_index, - 45, is_ipv6=True) + attach_1 = VppAbfAttach(self, 10, self.pg0.sw_if_index, 45, is_ipv6=True) attach_1.add_vpp_config() # # a packet matching the rule # - p = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(src="2001::2", dst="2001::1") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src="2001::2", dst="2001::1") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) # # packets are dropped because there is no route to the policy's @@ -315,9 +330,12 @@ class TestAbf(VppTestCase): # # add a route resolving the next-hop # - route = VppIpRoute(self, "3001::1", 32, - [VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index)]) + route = VppIpRoute( + self, + "3001::1", + 32, + [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)], + ) route.add_vpp_config() # @@ -326,5 +344,5 @@ class TestAbf(VppTestCase): self.send_and_expect(self.pg0, p * NUM_PKTS, self.pg1) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_acl_plugin.py b/test/test_acl_plugin.py index 53d96215949..32ecedba2a6 100644 --- a/test/test_acl_plugin.py +++ b/test/test_acl_plugin.py @@ -22,7 +22,7 @@ from vpp_ip import INVALID_INDEX @tag_fixme_vpp_workers class TestACLplugin(VppTestCase): - """ ACL plugin Test Case """ + """ACL plugin Test Case""" # traffic types IP = 0 @@ -39,7 +39,7 @@ class TestACLplugin(VppTestCase): # supported protocols proto = [[6, 17], [1, 58]] - proto_map = {1: 'ICMP', 58: 'ICMPv6EchoRequest', 6: 'TCP', 17: 'UDP'} + proto_map = {1: "ICMP", 58: "ICMPv6EchoRequest", 6: "TCP", 17: "UDP"} ICMPv4 = 0 ICMPv6 = 1 TCP = 0 @@ -105,11 +105,11 @@ class TestACLplugin(VppTestCase): # Create BD with MAC learning and unknown unicast flooding disabled # and put interfaces to this BD - cls.vapi.bridge_domain_add_del(bd_id=cls.bd_id, uu_flood=1, - learn=1) + cls.vapi.bridge_domain_add_del(bd_id=cls.bd_id, uu_flood=1, learn=1) for pg_if in cls.pg_interfaces: cls.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=pg_if.sw_if_index, bd_id=cls.bd_id) + rx_sw_if_index=pg_if.sw_if_index, bd_id=cls.bd_id + ) # Set up all interfaces for i in cls.pg_interfaces: @@ -135,14 +135,16 @@ class TestACLplugin(VppTestCase): for pg_if in cls.pg_interfaces: i += 1 start_nr = macs_per_if * i + start - end_nr = count + start if i == (n_int - 1) \ - else macs_per_if * (i + 1) + start + end_nr = ( + count + start if i == (n_int - 1) else macs_per_if * (i + 1) + start + ) hosts = cls.hosts_by_pg_idx[pg_if.sw_if_index] for j in range(int(start_nr), int(end_nr)): host = Host( "00:00:00:ff:%02x:%02x" % (pg_if.sw_if_index, j), "172.17.1%02x.%u" % (pg_if.sw_if_index, j), - "2017:dead:%02x::%u" % (pg_if.sw_if_index, j)) + "2017:dead:%02x::%u" % (pg_if.sw_if_index, j), + ) hosts.append(host) except Exception: @@ -176,20 +178,32 @@ class TestACLplugin(VppTestCase): self.logger.info(self.vapi.ppcli("show acl-plugin acl")) self.logger.info(self.vapi.ppcli("show acl-plugin interface")) self.logger.info(self.vapi.ppcli("show acl-plugin tables")) - self.logger.info(self.vapi.ppcli("show bridge-domain %s detail" - % self.bd_id)) - - def create_rule(self, ip=0, permit_deny=0, ports=PORTS_ALL, proto=-1, - s_prefix=0, s_ip=0, - d_prefix=0, d_ip=0): + self.logger.info(self.vapi.ppcli("show bridge-domain %s detail" % self.bd_id)) + + def create_rule( + self, + ip=0, + permit_deny=0, + ports=PORTS_ALL, + proto=-1, + s_prefix=0, + s_ip=0, + d_prefix=0, + d_ip=0, + ): if ip: src_prefix = IPv6Network((s_ip, s_prefix)) dst_prefix = IPv6Network((d_ip, d_prefix)) else: src_prefix = IPv4Network((s_ip, s_prefix)) dst_prefix = IPv4Network((d_ip, d_prefix)) - return AclRule(is_permit=permit_deny, ports=ports, proto=proto, - src_prefix=src_prefix, dst_prefix=dst_prefix) + return AclRule( + is_permit=permit_deny, + ports=ports, + proto=proto, + src_prefix=src_prefix, + dst_prefix=dst_prefix, + ) def apply_rules(self, rules, tag=None): acl = VppAcl(self, rules, tag=tag) @@ -198,7 +212,8 @@ class TestACLplugin(VppTestCase): # Apply a ACL on the interface as inbound for i in self.pg_interfaces: acl_if = VppAclInterface( - self, sw_if_index=i.sw_if_index, n_input=1, acls=[acl]) + self, sw_if_index=i.sw_if_index, n_input=1, acls=[acl] + ) acl_if.add_vpp_config() return acl.acl_index @@ -207,8 +222,7 @@ class TestACLplugin(VppTestCase): acl.add_vpp_config() self.logger.info("Dumped ACL: " + str(acl.dump())) # Apply a ACL on the interface as inbound - acl_if = VppAclInterface(self, sw_if_index=sw_if_index, n_input=1, - acls=[acl]) + acl_if = VppAclInterface(self, sw_if_index=sw_if_index, n_input=1, acls=[acl]) return acl.acl_index def etype_whitelist(self, whitelist, n_input, add=True): @@ -216,9 +230,14 @@ class TestACLplugin(VppTestCase): if add: self._wl = [] for i in self.pg_interfaces: - self._wl.append(VppEtypeWhitelist( - self, sw_if_index=i.sw_if_index, whitelist=whitelist, - n_input=n_input).add_vpp_config()) + self._wl.append( + VppEtypeWhitelist( + self, + sw_if_index=i.sw_if_index, + whitelist=whitelist, + n_input=n_input, + ).add_vpp_config() + ) else: if hasattr(self, "_wl"): for wl in self._wl: @@ -226,27 +245,36 @@ class TestACLplugin(VppTestCase): def create_upper_layer(self, packet_index, proto, ports=0): p = self.proto_map[proto] - if p == 'UDP': + if p == "UDP": if ports == 0: - return UDP(sport=random.randint(self.udp_sport_from, - self.udp_sport_to), - dport=random.randint(self.udp_dport_from, - self.udp_dport_to)) + return UDP( + sport=random.randint(self.udp_sport_from, self.udp_sport_to), + dport=random.randint(self.udp_dport_from, self.udp_dport_to), + ) else: return UDP(sport=ports, dport=ports) - elif p == 'TCP': + elif p == "TCP": if ports == 0: - return TCP(sport=random.randint(self.tcp_sport_from, - self.tcp_sport_to), - dport=random.randint(self.tcp_dport_from, - self.tcp_dport_to)) + return TCP( + sport=random.randint(self.tcp_sport_from, self.tcp_sport_to), + dport=random.randint(self.tcp_dport_from, self.tcp_dport_to), + ) else: return TCP(sport=ports, dport=ports) - return '' - - def create_stream(self, src_if, packet_sizes, traffic_type=0, ipv6=0, - proto=-1, ports=0, fragments=False, - pkt_raw=True, etype=-1): + return "" + + def create_stream( + self, + src_if, + packet_sizes, + traffic_type=0, + ipv6=0, + proto=-1, + ports=0, + fragments=False, + pkt_raw=True, + etype=-1, + ): """ Create input packet stream for defined interface using hosts or deleted_hosts list. @@ -279,26 +307,25 @@ class TestACLplugin(VppTestCase): payload = self.info_to_payload(pkt_info) p = Ether(dst=dst_host.mac, src=src_host.mac) if etype > 0: - p = Ether(dst=dst_host.mac, - src=src_host.mac, - type=etype) + p = Ether(dst=dst_host.mac, src=src_host.mac, type=etype) if pkt_info.ip: p /= IPv6(dst=dst_host.ip6, src=src_host.ip6) if fragments: p /= IPv6ExtHdrFragment(offset=64, m=1) else: if fragments: - p /= IP(src=src_host.ip4, dst=dst_host.ip4, - flags=1, frag=64) + p /= IP( + src=src_host.ip4, dst=dst_host.ip4, flags=1, frag=64 + ) else: p /= IP(src=src_host.ip4, dst=dst_host.ip4) if traffic_type == self.ICMP: if pkt_info.ip: - p /= ICMPv6EchoRequest(type=self.icmp6_type, - code=self.icmp6_code) + p /= ICMPv6EchoRequest( + type=self.icmp6_type, code=self.icmp6_code + ) else: - p /= ICMP(type=self.icmp4_type, - code=self.icmp4_code) + p /= ICMP(type=self.icmp4_type, code=self.icmp4_code) else: p /= self.create_upper_layer(i, pkt_info.proto, ports) if pkt_raw: @@ -310,8 +337,7 @@ class TestACLplugin(VppTestCase): pkts.append(p) return pkts - def verify_capture(self, pg_if, capture, - traffic_type=0, ip_type=0, etype=-1): + def verify_capture(self, pg_if, capture, traffic_type=0, ip_type=0, etype=-1): """ Verify captured input packet stream for defined interface. @@ -326,22 +352,23 @@ class TestACLplugin(VppTestCase): for packet in capture: if etype > 0: if packet[Ether].type != etype: - self.logger.error(ppp("Unexpected ethertype in packet:", - packet)) + self.logger.error(ppp("Unexpected ethertype in packet:", packet)) else: continue try: # Raw data for ICMPv6 are stored in ICMPv6EchoRequest.data if traffic_type == self.ICMP and ip_type == self.IPV6: payload_info = self.payload_to_info( - packet[ICMPv6EchoRequest], 'data') + packet[ICMPv6EchoRequest], "data" + ) payload = packet[ICMPv6EchoRequest] else: payload_info = self.payload_to_info(packet[Raw]) payload = packet[self.proto_map[payload_info.proto]] except: - self.logger.error(ppp("Unexpected or invalid packet " - "(outside network):", packet)) + self.logger.error( + ppp("Unexpected or invalid packet (outside network):", packet) + ) raise if ip_type != 0: @@ -355,8 +382,9 @@ class TestACLplugin(VppTestCase): self.assertEqual(payload.type, self.icmp6_type) self.assertEqual(payload.code, self.icmp6_code) except: - self.logger.error(ppp("Unexpected or invalid packet " - "(outside network):", packet)) + self.logger.error( + ppp("Unexpected or invalid packet (outside network):", packet) + ) raise else: try: @@ -366,12 +394,13 @@ class TestACLplugin(VppTestCase): packet_index = payload_info.index self.assertEqual(payload_info.dst, dst_sw_if_index) - self.logger.debug("Got packet on port %s: src=%u (id=%u)" % - (pg_if.name, payload_info.src, - packet_index)) + self.logger.debug( + "Got packet on port %s: src=%u (id=%u)" + % (pg_if.name, payload_info.src, packet_index) + ) next_info = self.get_next_packet_info_for_interface2( - payload_info.src, dst_sw_if_index, - last_info[payload_info.src]) + payload_info.src, dst_sw_if_index, last_info[payload_info.src] + ) last_info[payload_info.src] = next_info self.assertTrue(next_info is not None) self.assertEqual(packet_index, next_info.index) @@ -380,29 +409,26 @@ class TestACLplugin(VppTestCase): self.assertEqual(ip.src, saved_packet[ip_version].src) self.assertEqual(ip.dst, saved_packet[ip_version].dst) p = self.proto_map[payload_info.proto] - if p == 'TCP': + if p == "TCP": tcp = packet[TCP] - self.assertEqual(tcp.sport, saved_packet[ - TCP].sport) - self.assertEqual(tcp.dport, saved_packet[ - TCP].dport) - elif p == 'UDP': + self.assertEqual(tcp.sport, saved_packet[TCP].sport) + self.assertEqual(tcp.dport, saved_packet[TCP].dport) + elif p == "UDP": udp = packet[UDP] - self.assertEqual(udp.sport, saved_packet[ - UDP].sport) - self.assertEqual(udp.dport, saved_packet[ - UDP].dport) + self.assertEqual(udp.sport, saved_packet[UDP].sport) + self.assertEqual(udp.dport, saved_packet[UDP].dport) except: - self.logger.error(ppp("Unexpected or invalid packet:", - packet)) + self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise for i in self.pg_interfaces: remaining_packet = self.get_next_packet_info_for_interface2( - i, dst_sw_if_index, last_info[i.sw_if_index]) + i, dst_sw_if_index, last_info[i.sw_if_index] + ) self.assertTrue( remaining_packet is None, - "Port %u: Packet expected from source %u didn't arrive" % - (dst_sw_if_index, i.sw_if_index)) + "Port %u: Packet expected from source %u didn't arrive" + % (dst_sw_if_index, i.sw_if_index), + ) def run_traffic_no_check(self): # Test @@ -417,16 +443,32 @@ class TestACLplugin(VppTestCase): self.pg_enable_capture(self.pg_interfaces) self.pg_start() - def run_verify_test(self, traffic_type=0, ip_type=0, proto=-1, ports=0, - frags=False, pkt_raw=True, etype=-1): + def run_verify_test( + self, + traffic_type=0, + ip_type=0, + proto=-1, + ports=0, + frags=False, + pkt_raw=True, + etype=-1, + ): # Test # Create incoming packet streams for packet-generator interfaces pkts_cnt = 0 for i in self.pg_interfaces: if self.flows.__contains__(i): - pkts = self.create_stream(i, self.pg_if_packet_sizes, - traffic_type, ip_type, proto, ports, - frags, pkt_raw, etype) + pkts = self.create_stream( + i, + self.pg_if_packet_sizes, + traffic_type, + ip_type, + proto, + ports, + frags, + pkt_raw, + etype, + ) if len(pkts) > 0: i.add_stream(pkts) pkts_cnt += len(pkts) @@ -442,21 +484,28 @@ class TestACLplugin(VppTestCase): if self.flows.__contains__(src_if): for dst_if in self.flows[src_if]: capture = dst_if.get_capture(pkts_cnt) - self.logger.info("Verifying capture on interface %s" % - dst_if.name) - self.verify_capture(dst_if, capture, - traffic_type, ip_type, etype) + self.logger.info("Verifying capture on interface %s" % dst_if.name) + self.verify_capture(dst_if, capture, traffic_type, ip_type, etype) - def run_verify_negat_test(self, traffic_type=0, ip_type=0, proto=-1, - ports=0, frags=False, etype=-1): + def run_verify_negat_test( + self, traffic_type=0, ip_type=0, proto=-1, ports=0, frags=False, etype=-1 + ): # Test pkts_cnt = 0 self.reset_packet_infos() for i in self.pg_interfaces: if self.flows.__contains__(i): - pkts = self.create_stream(i, self.pg_if_packet_sizes, - traffic_type, ip_type, proto, ports, - frags, True, etype) + pkts = self.create_stream( + i, + self.pg_if_packet_sizes, + traffic_type, + ip_type, + proto, + ports, + frags, + True, + etype, + ) if len(pkts) > 0: i.add_stream(pkts) pkts_cnt += len(pkts) @@ -471,24 +520,22 @@ class TestACLplugin(VppTestCase): for src_if in self.pg_interfaces: if self.flows.__contains__(src_if): for dst_if in self.flows[src_if]: - self.logger.info("Verifying capture on interface %s" % - dst_if.name) + self.logger.info("Verifying capture on interface %s" % dst_if.name) capture = dst_if.get_capture(0) self.assertEqual(len(capture), 0) def test_0000_warmup_test(self): - """ ACL plugin version check; learn MACs - """ + """ACL plugin version check; learn MACs""" reply = self.vapi.papi.acl_plugin_get_version() self.assertEqual(reply.major, 1) - self.logger.info("Working with ACL plugin version: %d.%d" % ( - reply.major, reply.minor)) + self.logger.info( + "Working with ACL plugin version: %d.%d" % (reply.major, reply.minor) + ) # minor version changes are non breaking # self.assertEqual(reply.minor, 0) def test_0001_acl_create(self): - """ ACL create/delete test - """ + """ACL create/delete test""" self.logger.info("ACLP_TEST_START_0001") # Create a permit-1234 ACL @@ -510,12 +557,13 @@ class TestACLplugin(VppTestCase): for i_rule in range(0, len(r) - 1): encoded_rule = r[i_rule].encode() for rule_key in encoded_rule: - self.assertEqual(rr[0].r[i_rule][rule_key], - encoded_rule[rule_key]) + self.assertEqual(rr[0].r[i_rule][rule_key], encoded_rule[rule_key]) # Create a deny-1234 ACL - r_deny = [AclRule(is_permit=0, proto=17, ports=1234, sport_to=1235), - AclRule(is_permit=1, proto=17, ports=0)] + r_deny = [ + AclRule(is_permit=0, proto=17, ports=1234, sport_to=1235), + AclRule(is_permit=1, proto=17, ports=0), + ] second_acl = VppAcl(self, rules=r_deny, tag="deny 1234;permit all") second_acl.add_vpp_config() self.assertTrue(second_acl.query_vpp_config()) @@ -528,8 +576,8 @@ class TestACLplugin(VppTestCase): # apply an ACL on an interface inbound, try to delete ACL, must fail acl_if_list = VppAclInterface( - self, sw_if_index=self.pg0.sw_if_index, n_input=1, - acls=[first_acl]) + self, sw_if_index=self.pg0.sw_if_index, n_input=1, acls=[first_acl] + ) acl_if_list.add_vpp_config() first_acl.remove_vpp_config(expect_error=True) # Unapply an ACL and then try to delete it - must be ok @@ -538,8 +586,8 @@ class TestACLplugin(VppTestCase): # apply an ACL on an interface inbound, try to delete ACL, must fail acl_if_list = VppAclInterface( - self, sw_if_index=self.pg0.sw_if_index, n_input=0, - acls=[second_acl]) + self, sw_if_index=self.pg0.sw_if_index, n_input=0, acls=[second_acl] + ) acl_if_list.add_vpp_config() second_acl.remove_vpp_config(expect_error=True) # Unapply an ACL and then try to delete it - must be ok @@ -548,22 +596,23 @@ class TestACLplugin(VppTestCase): # try to apply a nonexistent ACL - must fail acl_if_list = VppAclInterface( - self, sw_if_index=self.pg0.sw_if_index, n_input=0, - acls=[invalid_acl]) + self, sw_if_index=self.pg0.sw_if_index, n_input=0, acls=[invalid_acl] + ) acl_if_list.add_vpp_config(expect_error=True) self.logger.info("ACLP_TEST_FINISH_0001") def test_0002_acl_permit_apply(self): - """ permit ACL apply test - """ + """permit ACL apply test""" self.logger.info("ACLP_TEST_START_0002") rules = [] - rules.append(self.create_rule(self.IPV4, self.PERMIT, - 0, self.proto[self.IP][self.UDP])) - rules.append(self.create_rule(self.IPV4, self.PERMIT, - 0, self.proto[self.IP][self.TCP])) + rules.append( + self.create_rule(self.IPV4, self.PERMIT, 0, self.proto[self.IP][self.UDP]) + ) + rules.append( + self.create_rule(self.IPV4, self.PERMIT, 0, self.proto[self.IP][self.TCP]) + ) # Apply rules acl_idx = self.apply_rules(rules, "permit per-flow") @@ -574,14 +623,14 @@ class TestACLplugin(VppTestCase): # Traffic should still pass self.run_verify_test(self.IP, self.IPV4, -1) - matches = self.statistics.get_counter('/acl/%d/matches' % acl_idx) + matches = self.statistics.get_counter("/acl/%d/matches" % acl_idx) self.logger.info("stat segment counters: %s" % repr(matches)) cli = "show acl-plugin acl" self.logger.info(self.vapi.ppcli(cli)) cli = "show acl-plugin tables" self.logger.info(self.vapi.ppcli(cli)) - total_hits = matches[0][0]['packets'] + matches[0][1]['packets'] + total_hits = matches[0][0]["packets"] + matches[0][1]["packets"] self.assertEqual(total_hits, 64) # disable counters @@ -590,17 +639,17 @@ class TestACLplugin(VppTestCase): self.logger.info("ACLP_TEST_FINISH_0002") def test_0003_acl_deny_apply(self): - """ deny ACL apply test - """ + """deny ACL apply test""" self.logger.info("ACLP_TEST_START_0003") # Add a deny-flows ACL rules = [] - rules.append(self.create_rule( - self.IPV4, self.DENY, self.PORTS_ALL, - self.proto[self.IP][self.UDP])) + rules.append( + self.create_rule( + self.IPV4, self.DENY, self.PORTS_ALL, self.proto[self.IP][self.UDP] + ) + ) # Permit ip any any in the end - rules.append(self.create_rule(self.IPV4, self.PERMIT, - self.PORTS_ALL, 0)) + rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_ALL, 0)) # Apply rules acl_idx = self.apply_rules(rules, "deny per-flow;permit all") @@ -609,30 +658,34 @@ class TestACLplugin(VppTestCase): reply = self.vapi.papi.acl_stats_intf_counters_enable(enable=1) # Traffic should not pass - self.run_verify_negat_test(self.IP, self.IPV4, - self.proto[self.IP][self.UDP]) + self.run_verify_negat_test(self.IP, self.IPV4, self.proto[self.IP][self.UDP]) - matches = self.statistics.get_counter('/acl/%d/matches' % acl_idx) + matches = self.statistics.get_counter("/acl/%d/matches" % acl_idx) self.logger.info("stat segment counters: %s" % repr(matches)) cli = "show acl-plugin acl" self.logger.info(self.vapi.ppcli(cli)) cli = "show acl-plugin tables" self.logger.info(self.vapi.ppcli(cli)) - self.assertEqual(matches[0][0]['packets'], 64) + self.assertEqual(matches[0][0]["packets"], 64) # disable counters reply = self.vapi.papi.acl_stats_intf_counters_enable(enable=0) self.logger.info("ACLP_TEST_FINISH_0003") # self.assertEqual(, 0) def test_0004_vpp624_permit_icmpv4(self): - """ VPP_624 permit ICMPv4 - """ + """VPP_624 permit ICMPv4""" self.logger.info("ACLP_TEST_START_0004") # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_RANGE, - self.proto[self.ICMP][self.ICMPv4])) + rules.append( + self.create_rule( + self.IPV4, + self.PERMIT, + self.PORTS_RANGE, + self.proto[self.ICMP][self.ICMPv4], + ) + ) # deny ip any any in the end rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0)) @@ -640,20 +693,24 @@ class TestACLplugin(VppTestCase): self.apply_rules(rules, "permit icmpv4") # Traffic should still pass - self.run_verify_test(self.ICMP, self.IPV4, - self.proto[self.ICMP][self.ICMPv4]) + self.run_verify_test(self.ICMP, self.IPV4, self.proto[self.ICMP][self.ICMPv4]) self.logger.info("ACLP_TEST_FINISH_0004") def test_0005_vpp624_permit_icmpv6(self): - """ VPP_624 permit ICMPv6 - """ + """VPP_624 permit ICMPv6""" self.logger.info("ACLP_TEST_START_0005") # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_RANGE, - self.proto[self.ICMP][self.ICMPv6])) + rules.append( + self.create_rule( + self.IPV6, + self.PERMIT, + self.PORTS_RANGE, + self.proto[self.ICMP][self.ICMPv6], + ) + ) # deny ip any any in the end rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_ALL, 0)) @@ -661,22 +718,25 @@ class TestACLplugin(VppTestCase): self.apply_rules(rules, "permit icmpv6") # Traffic should still pass - self.run_verify_test(self.ICMP, self.IPV6, - self.proto[self.ICMP][self.ICMPv6]) + self.run_verify_test(self.ICMP, self.IPV6, self.proto[self.ICMP][self.ICMPv6]) self.logger.info("ACLP_TEST_FINISH_0005") def test_0006_vpp624_deny_icmpv4(self): - """ VPP_624 deny ICMPv4 - """ + """VPP_624 deny ICMPv4""" self.logger.info("ACLP_TEST_START_0006") # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_RANGE, - self.proto[self.ICMP][self.ICMPv4])) + rules.append( + self.create_rule( + self.IPV4, + self.DENY, + self.PORTS_RANGE, + self.proto[self.ICMP][self.ICMPv4], + ) + ) # permit ip any any in the end - rules.append(self.create_rule(self.IPV4, self.PERMIT, - self.PORTS_ALL, 0)) + rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_ALL, 0)) # Apply rules self.apply_rules(rules, "deny icmpv4") @@ -687,16 +747,20 @@ class TestACLplugin(VppTestCase): self.logger.info("ACLP_TEST_FINISH_0006") def test_0007_vpp624_deny_icmpv6(self): - """ VPP_624 deny ICMPv6 - """ + """VPP_624 deny ICMPv6""" self.logger.info("ACLP_TEST_START_0007") # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_RANGE, - self.proto[self.ICMP][self.ICMPv6])) + rules.append( + self.create_rule( + self.IPV6, + self.DENY, + self.PORTS_RANGE, + self.proto[self.ICMP][self.ICMPv6], + ) + ) # deny ip any any in the end - rules.append(self.create_rule(self.IPV6, self.PERMIT, - self.PORTS_ALL, 0)) + rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_ALL, 0)) # Apply rules self.apply_rules(rules, "deny icmpv6") @@ -707,14 +771,16 @@ class TestACLplugin(VppTestCase): self.logger.info("ACLP_TEST_FINISH_0007") def test_0008_tcp_permit_v4(self): - """ permit TCPv4 - """ + """permit TCPv4""" self.logger.info("ACLP_TEST_START_0008") # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_RANGE, - self.proto[self.IP][self.TCP])) + rules.append( + self.create_rule( + self.IPV4, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.TCP] + ) + ) # deny ip any any in the end rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0)) @@ -727,14 +793,16 @@ class TestACLplugin(VppTestCase): self.logger.info("ACLP_TEST_FINISH_0008") def test_0009_tcp_permit_v6(self): - """ permit TCPv6 - """ + """permit TCPv6""" self.logger.info("ACLP_TEST_START_0009") # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_RANGE, - self.proto[self.IP][self.TCP])) + rules.append( + self.create_rule( + self.IPV6, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.TCP] + ) + ) # deny ip any any in the end rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_ALL, 0)) @@ -747,14 +815,16 @@ class TestACLplugin(VppTestCase): self.logger.info("ACLP_TEST_FINISH_0008") def test_0010_udp_permit_v4(self): - """ permit UDPv4 - """ + """permit UDPv4""" self.logger.info("ACLP_TEST_START_0010") # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_RANGE, - self.proto[self.IP][self.UDP])) + rules.append( + self.create_rule( + self.IPV4, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.UDP] + ) + ) # deny ip any any in the end rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0)) @@ -767,14 +837,16 @@ class TestACLplugin(VppTestCase): self.logger.info("ACLP_TEST_FINISH_0010") def test_0011_udp_permit_v6(self): - """ permit UDPv6 - """ + """permit UDPv6""" self.logger.info("ACLP_TEST_START_0011") # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_RANGE, - self.proto[self.IP][self.UDP])) + rules.append( + self.create_rule( + self.IPV6, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.UDP] + ) + ) # deny ip any any in the end rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_ALL, 0)) @@ -787,81 +859,89 @@ class TestACLplugin(VppTestCase): self.logger.info("ACLP_TEST_FINISH_0011") def test_0012_tcp_deny(self): - """ deny TCPv4/v6 - """ + """deny TCPv4/v6""" self.logger.info("ACLP_TEST_START_0012") # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_RANGE, - self.proto[self.IP][self.TCP])) - rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_RANGE, - self.proto[self.IP][self.TCP])) + rules.append( + self.create_rule( + self.IPV4, self.DENY, self.PORTS_RANGE, self.proto[self.IP][self.TCP] + ) + ) + rules.append( + self.create_rule( + self.IPV6, self.DENY, self.PORTS_RANGE, self.proto[self.IP][self.TCP] + ) + ) # permit ip any any in the end - rules.append(self.create_rule(self.IPV4, self.PERMIT, - self.PORTS_ALL, 0)) - rules.append(self.create_rule(self.IPV6, self.PERMIT, - self.PORTS_ALL, 0)) + rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_ALL, 0)) + rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_ALL, 0)) # Apply rules self.apply_rules(rules, "deny ip4/ip6 tcp") # Traffic should not pass - self.run_verify_negat_test(self.IP, self.IPRANDOM, - self.proto[self.IP][self.TCP]) + self.run_verify_negat_test( + self.IP, self.IPRANDOM, self.proto[self.IP][self.TCP] + ) self.logger.info("ACLP_TEST_FINISH_0012") def test_0013_udp_deny(self): - """ deny UDPv4/v6 - """ + """deny UDPv4/v6""" self.logger.info("ACLP_TEST_START_0013") # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_RANGE, - self.proto[self.IP][self.UDP])) - rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_RANGE, - self.proto[self.IP][self.UDP])) + rules.append( + self.create_rule( + self.IPV4, self.DENY, self.PORTS_RANGE, self.proto[self.IP][self.UDP] + ) + ) + rules.append( + self.create_rule( + self.IPV6, self.DENY, self.PORTS_RANGE, self.proto[self.IP][self.UDP] + ) + ) # permit ip any any in the end - rules.append(self.create_rule(self.IPV4, self.PERMIT, - self.PORTS_ALL, 0)) - rules.append(self.create_rule(self.IPV6, self.PERMIT, - self.PORTS_ALL, 0)) + rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_ALL, 0)) + rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_ALL, 0)) # Apply rules self.apply_rules(rules, "deny ip4/ip6 udp") # Traffic should not pass - self.run_verify_negat_test(self.IP, self.IPRANDOM, - self.proto[self.IP][self.UDP]) + self.run_verify_negat_test( + self.IP, self.IPRANDOM, self.proto[self.IP][self.UDP] + ) self.logger.info("ACLP_TEST_FINISH_0013") def test_0014_acl_dump(self): - """ verify add/dump acls - """ + """verify add/dump acls""" self.logger.info("ACLP_TEST_START_0014") - r = [[self.IPV4, self.PERMIT, 1234, self.proto[self.IP][self.TCP]], - [self.IPV4, self.PERMIT, 2345, self.proto[self.IP][self.UDP]], - [self.IPV4, self.PERMIT, 0, self.proto[self.IP][self.TCP]], - [self.IPV4, self.PERMIT, 0, self.proto[self.IP][self.UDP]], - [self.IPV4, self.PERMIT, 5, self.proto[self.ICMP][self.ICMPv4]], - [self.IPV6, self.PERMIT, 4321, self.proto[self.IP][self.TCP]], - [self.IPV6, self.PERMIT, 5432, self.proto[self.IP][self.UDP]], - [self.IPV6, self.PERMIT, 0, self.proto[self.IP][self.TCP]], - [self.IPV6, self.PERMIT, 0, self.proto[self.IP][self.UDP]], - [self.IPV6, self.PERMIT, 6, self.proto[self.ICMP][self.ICMPv6]], - [self.IPV4, self.DENY, self.PORTS_ALL, 0], - [self.IPV4, self.DENY, 1234, self.proto[self.IP][self.TCP]], - [self.IPV4, self.DENY, 2345, self.proto[self.IP][self.UDP]], - [self.IPV4, self.DENY, 5, self.proto[self.ICMP][self.ICMPv4]], - [self.IPV6, self.DENY, 4321, self.proto[self.IP][self.TCP]], - [self.IPV6, self.DENY, 5432, self.proto[self.IP][self.UDP]], - [self.IPV6, self.DENY, 6, self.proto[self.ICMP][self.ICMPv6]], - [self.IPV6, self.DENY, self.PORTS_ALL, 0] - ] + r = [ + [self.IPV4, self.PERMIT, 1234, self.proto[self.IP][self.TCP]], + [self.IPV4, self.PERMIT, 2345, self.proto[self.IP][self.UDP]], + [self.IPV4, self.PERMIT, 0, self.proto[self.IP][self.TCP]], + [self.IPV4, self.PERMIT, 0, self.proto[self.IP][self.UDP]], + [self.IPV4, self.PERMIT, 5, self.proto[self.ICMP][self.ICMPv4]], + [self.IPV6, self.PERMIT, 4321, self.proto[self.IP][self.TCP]], + [self.IPV6, self.PERMIT, 5432, self.proto[self.IP][self.UDP]], + [self.IPV6, self.PERMIT, 0, self.proto[self.IP][self.TCP]], + [self.IPV6, self.PERMIT, 0, self.proto[self.IP][self.UDP]], + [self.IPV6, self.PERMIT, 6, self.proto[self.ICMP][self.ICMPv6]], + [self.IPV4, self.DENY, self.PORTS_ALL, 0], + [self.IPV4, self.DENY, 1234, self.proto[self.IP][self.TCP]], + [self.IPV4, self.DENY, 2345, self.proto[self.IP][self.UDP]], + [self.IPV4, self.DENY, 5, self.proto[self.ICMP][self.ICMPv4]], + [self.IPV6, self.DENY, 4321, self.proto[self.IP][self.TCP]], + [self.IPV6, self.DENY, 5432, self.proto[self.IP][self.UDP]], + [self.IPV6, self.DENY, 6, self.proto[self.ICMP][self.ICMPv6]], + [self.IPV6, self.DENY, self.PORTS_ALL, 0], + ] # Add and verify new ACLs rules = [] @@ -886,37 +966,47 @@ class TestACLplugin(VppTestCase): self.assertEqual(dr.srcport_or_icmptype_last, 65535) else: if dr.proto == self.proto[self.IP][self.TCP]: - self.assertGreater(dr.srcport_or_icmptype_first, - self.tcp_sport_from-1) - self.assertLess(dr.srcport_or_icmptype_first, - self.tcp_sport_to+1) - self.assertGreater(dr.dstport_or_icmpcode_last, - self.tcp_dport_from-1) - self.assertLess(dr.dstport_or_icmpcode_last, - self.tcp_dport_to+1) + self.assertGreater( + dr.srcport_or_icmptype_first, self.tcp_sport_from - 1 + ) + self.assertLess( + dr.srcport_or_icmptype_first, self.tcp_sport_to + 1 + ) + self.assertGreater( + dr.dstport_or_icmpcode_last, self.tcp_dport_from - 1 + ) + self.assertLess( + dr.dstport_or_icmpcode_last, self.tcp_dport_to + 1 + ) elif dr.proto == self.proto[self.IP][self.UDP]: - self.assertGreater(dr.srcport_or_icmptype_first, - self.udp_sport_from-1) - self.assertLess(dr.srcport_or_icmptype_first, - self.udp_sport_to+1) - self.assertGreater(dr.dstport_or_icmpcode_last, - self.udp_dport_from-1) - self.assertLess(dr.dstport_or_icmpcode_last, - self.udp_dport_to+1) + self.assertGreater( + dr.srcport_or_icmptype_first, self.udp_sport_from - 1 + ) + self.assertLess( + dr.srcport_or_icmptype_first, self.udp_sport_to + 1 + ) + self.assertGreater( + dr.dstport_or_icmpcode_last, self.udp_dport_from - 1 + ) + self.assertLess( + dr.dstport_or_icmpcode_last, self.udp_dport_to + 1 + ) i += 1 self.logger.info("ACLP_TEST_FINISH_0014") def test_0015_tcp_permit_port_v4(self): - """ permit single TCPv4 - """ + """permit single TCPv4""" self.logger.info("ACLP_TEST_START_0015") port = random.randint(16384, 65535) # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV4, self.PERMIT, port, - self.proto[self.IP][self.TCP])) + rules.append( + self.create_rule( + self.IPV4, self.PERMIT, port, self.proto[self.IP][self.TCP] + ) + ) # deny ip any any in the end rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0)) @@ -924,21 +1014,22 @@ class TestACLplugin(VppTestCase): self.apply_rules(rules, "permit ip4 tcp %d" % port) # Traffic should still pass - self.run_verify_test(self.IP, self.IPV4, - self.proto[self.IP][self.TCP], port) + self.run_verify_test(self.IP, self.IPV4, self.proto[self.IP][self.TCP], port) self.logger.info("ACLP_TEST_FINISH_0015") def test_0016_udp_permit_port_v4(self): - """ permit single UDPv4 - """ + """permit single UDPv4""" self.logger.info("ACLP_TEST_START_0016") port = random.randint(16384, 65535) # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV4, self.PERMIT, port, - self.proto[self.IP][self.UDP])) + rules.append( + self.create_rule( + self.IPV4, self.PERMIT, port, self.proto[self.IP][self.UDP] + ) + ) # deny ip any any in the end rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0)) @@ -946,21 +1037,22 @@ class TestACLplugin(VppTestCase): self.apply_rules(rules, "permit ip4 tcp %d" % port) # Traffic should still pass - self.run_verify_test(self.IP, self.IPV4, - self.proto[self.IP][self.UDP], port) + self.run_verify_test(self.IP, self.IPV4, self.proto[self.IP][self.UDP], port) self.logger.info("ACLP_TEST_FINISH_0016") def test_0017_tcp_permit_port_v6(self): - """ permit single TCPv6 - """ + """permit single TCPv6""" self.logger.info("ACLP_TEST_START_0017") port = random.randint(16384, 65535) # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV6, self.PERMIT, port, - self.proto[self.IP][self.TCP])) + rules.append( + self.create_rule( + self.IPV6, self.PERMIT, port, self.proto[self.IP][self.TCP] + ) + ) # deny ip any any in the end rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_ALL, 0)) @@ -968,90 +1060,89 @@ class TestACLplugin(VppTestCase): self.apply_rules(rules, "permit ip4 tcp %d" % port) # Traffic should still pass - self.run_verify_test(self.IP, self.IPV6, - self.proto[self.IP][self.TCP], port) + self.run_verify_test(self.IP, self.IPV6, self.proto[self.IP][self.TCP], port) self.logger.info("ACLP_TEST_FINISH_0017") def test_0018_udp_permit_port_v6(self): - """ permit single UDPv6 - """ + """permit single UDPv6""" self.logger.info("ACLP_TEST_START_0018") port = random.randint(16384, 65535) # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV6, self.PERMIT, port, - self.proto[self.IP][self.UDP])) + rules.append( + self.create_rule( + self.IPV6, self.PERMIT, port, self.proto[self.IP][self.UDP] + ) + ) # deny ip any any in the end - rules.append(self.create_rule(self.IPV6, self.DENY, - self.PORTS_ALL, 0)) + rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_ALL, 0)) # Apply rules self.apply_rules(rules, "permit ip4 tcp %d" % port) # Traffic should still pass - self.run_verify_test(self.IP, self.IPV6, - self.proto[self.IP][self.UDP], port) + self.run_verify_test(self.IP, self.IPV6, self.proto[self.IP][self.UDP], port) self.logger.info("ACLP_TEST_FINISH_0018") def test_0019_udp_deny_port(self): - """ deny single TCPv4/v6 - """ + """deny single TCPv4/v6""" self.logger.info("ACLP_TEST_START_0019") port = random.randint(16384, 65535) # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV4, self.DENY, port, - self.proto[self.IP][self.TCP])) - rules.append(self.create_rule(self.IPV6, self.DENY, port, - self.proto[self.IP][self.TCP])) + rules.append( + self.create_rule(self.IPV4, self.DENY, port, self.proto[self.IP][self.TCP]) + ) + rules.append( + self.create_rule(self.IPV6, self.DENY, port, self.proto[self.IP][self.TCP]) + ) # Permit ip any any in the end - rules.append(self.create_rule(self.IPV4, self.PERMIT, - self.PORTS_ALL, 0)) - rules.append(self.create_rule(self.IPV6, self.PERMIT, - self.PORTS_ALL, 0)) + rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_ALL, 0)) + rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_ALL, 0)) # Apply rules self.apply_rules(rules, "deny ip4/ip6 udp %d" % port) # Traffic should not pass - self.run_verify_negat_test(self.IP, self.IPRANDOM, - self.proto[self.IP][self.TCP], port) + self.run_verify_negat_test( + self.IP, self.IPRANDOM, self.proto[self.IP][self.TCP], port + ) self.logger.info("ACLP_TEST_FINISH_0019") def test_0020_udp_deny_port(self): - """ deny single UDPv4/v6 - """ + """deny single UDPv4/v6""" self.logger.info("ACLP_TEST_START_0020") port = random.randint(16384, 65535) # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV4, self.DENY, port, - self.proto[self.IP][self.UDP])) - rules.append(self.create_rule(self.IPV6, self.DENY, port, - self.proto[self.IP][self.UDP])) + rules.append( + self.create_rule(self.IPV4, self.DENY, port, self.proto[self.IP][self.UDP]) + ) + rules.append( + self.create_rule(self.IPV6, self.DENY, port, self.proto[self.IP][self.UDP]) + ) # Permit ip any any in the end - rules.append(self.create_rule(self.IPV4, self.PERMIT, - self.PORTS_ALL, 0)) - rules.append(self.create_rule(self.IPV6, self.PERMIT, - self.PORTS_ALL, 0)) + rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_ALL, 0)) + rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_ALL, 0)) # Apply rules self.apply_rules(rules, "deny ip4/ip6 udp %d" % port) # Traffic should not pass - self.run_verify_negat_test(self.IP, self.IPRANDOM, - self.proto[self.IP][self.UDP], port) + self.run_verify_negat_test( + self.IP, self.IPRANDOM, self.proto[self.IP][self.UDP], port + ) self.logger.info("ACLP_TEST_FINISH_0020") def test_0021_udp_deny_port_verify_fragment_deny(self): - """ deny single UDPv4/v6, permit ip any, verify non-initial fragment + """deny single UDPv4/v6, permit ip any, verify non-initial fragment blocked """ self.logger.info("ACLP_TEST_START_0021") @@ -1059,37 +1150,40 @@ class TestACLplugin(VppTestCase): port = random.randint(16384, 65535) # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV4, self.DENY, port, - self.proto[self.IP][self.UDP])) - rules.append(self.create_rule(self.IPV6, self.DENY, port, - self.proto[self.IP][self.UDP])) + rules.append( + self.create_rule(self.IPV4, self.DENY, port, self.proto[self.IP][self.UDP]) + ) + rules.append( + self.create_rule(self.IPV6, self.DENY, port, self.proto[self.IP][self.UDP]) + ) # deny ip any any in the end - rules.append(self.create_rule(self.IPV4, self.PERMIT, - self.PORTS_ALL, 0)) - rules.append(self.create_rule(self.IPV6, self.PERMIT, - self.PORTS_ALL, 0)) + rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_ALL, 0)) + rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_ALL, 0)) # Apply rules self.apply_rules(rules, "deny ip4/ip6 udp %d" % port) # Traffic should not pass - self.run_verify_negat_test(self.IP, self.IPRANDOM, - self.proto[self.IP][self.UDP], port, True) + self.run_verify_negat_test( + self.IP, self.IPRANDOM, self.proto[self.IP][self.UDP], port, True + ) self.logger.info("ACLP_TEST_FINISH_0021") def test_0022_zero_length_udp_ipv4(self): - """ VPP-687 zero length udp ipv4 packet""" + """VPP-687 zero length udp ipv4 packet""" self.logger.info("ACLP_TEST_START_0022") port = random.randint(16384, 65535) # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV4, self.PERMIT, port, - self.proto[self.IP][self.UDP])) - # deny ip any any in the end rules.append( - self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0)) + self.create_rule( + self.IPV4, self.PERMIT, port, self.proto[self.IP][self.UDP] + ) + ) + # deny ip any any in the end + rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0)) # Apply rules self.apply_rules(rules, "permit empty udp ip4 %d" % port) @@ -1097,10 +1191,16 @@ class TestACLplugin(VppTestCase): # Traffic should still pass # Create incoming packet streams for packet-generator interfaces pkts_cnt = 0 - pkts = self.create_stream(self.pg0, self.pg_if_packet_sizes, - self.IP, self.IPV4, - self.proto[self.IP][self.UDP], port, - False, False) + pkts = self.create_stream( + self.pg0, + self.pg_if_packet_sizes, + self.IP, + self.IPV4, + self.proto[self.IP][self.UDP], + port, + False, + False, + ) if len(pkts) > 0: self.pg0.add_stream(pkts) pkts_cnt += len(pkts) @@ -1114,14 +1214,17 @@ class TestACLplugin(VppTestCase): self.logger.info("ACLP_TEST_FINISH_0022") def test_0023_zero_length_udp_ipv6(self): - """ VPP-687 zero length udp ipv6 packet""" + """VPP-687 zero length udp ipv6 packet""" self.logger.info("ACLP_TEST_START_0023") port = random.randint(16384, 65535) # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV6, self.PERMIT, port, - self.proto[self.IP][self.UDP])) + rules.append( + self.create_rule( + self.IPV6, self.PERMIT, port, self.proto[self.IP][self.UDP] + ) + ) # deny ip any any in the end rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_ALL, 0)) @@ -1131,10 +1234,16 @@ class TestACLplugin(VppTestCase): # Traffic should still pass # Create incoming packet streams for packet-generator interfaces pkts_cnt = 0 - pkts = self.create_stream(self.pg0, self.pg_if_packet_sizes, - self.IP, self.IPV6, - self.proto[self.IP][self.UDP], port, - False, False) + pkts = self.create_stream( + self.pg0, + self.pg_if_packet_sizes, + self.IP, + self.IPV6, + self.proto[self.IP][self.UDP], + port, + False, + False, + ) if len(pkts) > 0: self.pg0.add_stream(pkts) pkts_cnt += len(pkts) @@ -1149,16 +1258,21 @@ class TestACLplugin(VppTestCase): self.logger.info("ACLP_TEST_FINISH_0023") def test_0108_tcp_permit_v4(self): - """ permit TCPv4 + non-match range - """ + """permit TCPv4 + non-match range""" self.logger.info("ACLP_TEST_START_0108") # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_RANGE_2, - self.proto[self.IP][self.TCP])) - rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_RANGE, - self.proto[self.IP][self.TCP])) + rules.append( + self.create_rule( + self.IPV4, self.DENY, self.PORTS_RANGE_2, self.proto[self.IP][self.TCP] + ) + ) + rules.append( + self.create_rule( + self.IPV4, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.TCP] + ) + ) # deny ip any any in the end rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0)) @@ -1171,16 +1285,21 @@ class TestACLplugin(VppTestCase): self.logger.info("ACLP_TEST_FINISH_0108") def test_0109_tcp_permit_v6(self): - """ permit TCPv6 + non-match range - """ + """permit TCPv6 + non-match range""" self.logger.info("ACLP_TEST_START_0109") # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_RANGE_2, - self.proto[self.IP][self.TCP])) - rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_RANGE, - self.proto[self.IP][self.TCP])) + rules.append( + self.create_rule( + self.IPV6, self.DENY, self.PORTS_RANGE_2, self.proto[self.IP][self.TCP] + ) + ) + rules.append( + self.create_rule( + self.IPV6, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.TCP] + ) + ) # deny ip any any in the end rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_ALL, 0)) @@ -1193,16 +1312,21 @@ class TestACLplugin(VppTestCase): self.logger.info("ACLP_TEST_FINISH_0109") def test_0110_udp_permit_v4(self): - """ permit UDPv4 + non-match range - """ + """permit UDPv4 + non-match range""" self.logger.info("ACLP_TEST_START_0110") # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_RANGE_2, - self.proto[self.IP][self.UDP])) - rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_RANGE, - self.proto[self.IP][self.UDP])) + rules.append( + self.create_rule( + self.IPV4, self.DENY, self.PORTS_RANGE_2, self.proto[self.IP][self.UDP] + ) + ) + rules.append( + self.create_rule( + self.IPV4, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.UDP] + ) + ) # deny ip any any in the end rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0)) @@ -1215,16 +1339,21 @@ class TestACLplugin(VppTestCase): self.logger.info("ACLP_TEST_FINISH_0110") def test_0111_udp_permit_v6(self): - """ permit UDPv6 + non-match range - """ + """permit UDPv6 + non-match range""" self.logger.info("ACLP_TEST_START_0111") # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_RANGE_2, - self.proto[self.IP][self.UDP])) - rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_RANGE, - self.proto[self.IP][self.UDP])) + rules.append( + self.create_rule( + self.IPV6, self.DENY, self.PORTS_RANGE_2, self.proto[self.IP][self.UDP] + ) + ) + rules.append( + self.create_rule( + self.IPV6, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.UDP] + ) + ) # deny ip any any in the end rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_ALL, 0)) @@ -1237,80 +1366,113 @@ class TestACLplugin(VppTestCase): self.logger.info("ACLP_TEST_FINISH_0111") def test_0112_tcp_deny(self): - """ deny TCPv4/v6 + non-match range - """ + """deny TCPv4/v6 + non-match range""" self.logger.info("ACLP_TEST_START_0112") # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV4, self.PERMIT, - self.PORTS_RANGE_2, - self.proto[self.IP][self.TCP])) - rules.append(self.create_rule(self.IPV6, self.PERMIT, - self.PORTS_RANGE_2, - self.proto[self.IP][self.TCP])) - rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_RANGE, - self.proto[self.IP][self.TCP])) - rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_RANGE, - self.proto[self.IP][self.TCP])) + rules.append( + self.create_rule( + self.IPV4, + self.PERMIT, + self.PORTS_RANGE_2, + self.proto[self.IP][self.TCP], + ) + ) + rules.append( + self.create_rule( + self.IPV6, + self.PERMIT, + self.PORTS_RANGE_2, + self.proto[self.IP][self.TCP], + ) + ) + rules.append( + self.create_rule( + self.IPV4, self.DENY, self.PORTS_RANGE, self.proto[self.IP][self.TCP] + ) + ) + rules.append( + self.create_rule( + self.IPV6, self.DENY, self.PORTS_RANGE, self.proto[self.IP][self.TCP] + ) + ) # permit ip any any in the end - rules.append(self.create_rule(self.IPV4, self.PERMIT, - self.PORTS_ALL, 0)) - rules.append(self.create_rule(self.IPV6, self.PERMIT, - self.PORTS_ALL, 0)) + rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_ALL, 0)) + rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_ALL, 0)) # Apply rules self.apply_rules(rules, "deny ip4/ip6 tcp") # Traffic should not pass - self.run_verify_negat_test(self.IP, self.IPRANDOM, - self.proto[self.IP][self.TCP]) + self.run_verify_negat_test( + self.IP, self.IPRANDOM, self.proto[self.IP][self.TCP] + ) self.logger.info("ACLP_TEST_FINISH_0112") def test_0113_udp_deny(self): - """ deny UDPv4/v6 + non-match range - """ + """deny UDPv4/v6 + non-match range""" self.logger.info("ACLP_TEST_START_0113") # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV4, self.PERMIT, - self.PORTS_RANGE_2, - self.proto[self.IP][self.UDP])) - rules.append(self.create_rule(self.IPV6, self.PERMIT, - self.PORTS_RANGE_2, - self.proto[self.IP][self.UDP])) - rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_RANGE, - self.proto[self.IP][self.UDP])) - rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_RANGE, - self.proto[self.IP][self.UDP])) + rules.append( + self.create_rule( + self.IPV4, + self.PERMIT, + self.PORTS_RANGE_2, + self.proto[self.IP][self.UDP], + ) + ) + rules.append( + self.create_rule( + self.IPV6, + self.PERMIT, + self.PORTS_RANGE_2, + self.proto[self.IP][self.UDP], + ) + ) + rules.append( + self.create_rule( + self.IPV4, self.DENY, self.PORTS_RANGE, self.proto[self.IP][self.UDP] + ) + ) + rules.append( + self.create_rule( + self.IPV6, self.DENY, self.PORTS_RANGE, self.proto[self.IP][self.UDP] + ) + ) # permit ip any any in the end - rules.append(self.create_rule(self.IPV4, self.PERMIT, - self.PORTS_ALL, 0)) - rules.append(self.create_rule(self.IPV6, self.PERMIT, - self.PORTS_ALL, 0)) + rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_ALL, 0)) + rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_ALL, 0)) # Apply rules self.apply_rules(rules, "deny ip4/ip6 udp") # Traffic should not pass - self.run_verify_negat_test(self.IP, self.IPRANDOM, - self.proto[self.IP][self.UDP]) + self.run_verify_negat_test( + self.IP, self.IPRANDOM, self.proto[self.IP][self.UDP] + ) self.logger.info("ACLP_TEST_FINISH_0113") def test_0300_tcp_permit_v4_etype_aaaa(self): - """ permit TCPv4, send 0xAAAA etype - """ + """permit TCPv4, send 0xAAAA etype""" self.logger.info("ACLP_TEST_START_0300") # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_RANGE_2, - self.proto[self.IP][self.TCP])) - rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_RANGE, - self.proto[self.IP][self.TCP])) + rules.append( + self.create_rule( + self.IPV4, self.DENY, self.PORTS_RANGE_2, self.proto[self.IP][self.TCP] + ) + ) + rules.append( + self.create_rule( + self.IPV4, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.TCP] + ) + ) # deny ip any any in the end rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0)) @@ -1318,33 +1480,39 @@ class TestACLplugin(VppTestCase): self.apply_rules(rules, "permit ipv4 tcp") # Traffic should still pass also for an odd ethertype - self.run_verify_test(self.IP, self.IPV4, self.proto[self.IP][self.TCP], - 0, False, True, 0xaaaa) + self.run_verify_test( + self.IP, self.IPV4, self.proto[self.IP][self.TCP], 0, False, True, 0xAAAA + ) self.logger.info("ACLP_TEST_FINISH_0300") def test_0305_tcp_permit_v4_etype_blacklist_aaaa(self): - """ permit TCPv4, whitelist 0x0BBB ethertype, send 0xAAAA-blocked - """ + """permit TCPv4, whitelist 0x0BBB ethertype, send 0xAAAA-blocked""" self.logger.info("ACLP_TEST_START_0305") # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_RANGE_2, - self.proto[self.IP][self.TCP])) - rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_RANGE, - self.proto[self.IP][self.TCP])) + rules.append( + self.create_rule( + self.IPV4, self.DENY, self.PORTS_RANGE_2, self.proto[self.IP][self.TCP] + ) + ) + rules.append( + self.create_rule( + self.IPV4, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.TCP] + ) + ) # deny ip any any in the end rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0)) # Apply rules self.apply_rules(rules, "permit ipv4 tcp") # whitelist the 0xbbbb etype - so the 0xaaaa should be blocked - self.etype_whitelist([0xbbb], 1) + self.etype_whitelist([0xBBB], 1) # The oddball ethertype should be blocked - self.run_verify_negat_test(self.IP, self.IPV4, - self.proto[self.IP][self.TCP], - 0, False, 0xaaaa) + self.run_verify_negat_test( + self.IP, self.IPV4, self.proto[self.IP][self.TCP], 0, False, 0xAAAA + ) # remove the whitelist self.etype_whitelist([], 0, add=False) @@ -1352,27 +1520,33 @@ class TestACLplugin(VppTestCase): self.logger.info("ACLP_TEST_FINISH_0305") def test_0306_tcp_permit_v4_etype_blacklist_aaaa(self): - """ permit TCPv4, whitelist 0x0BBB ethertype, send 0x0BBB - pass - """ + """permit TCPv4, whitelist 0x0BBB ethertype, send 0x0BBB - pass""" self.logger.info("ACLP_TEST_START_0306") # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_RANGE_2, - self.proto[self.IP][self.TCP])) - rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_RANGE, - self.proto[self.IP][self.TCP])) + rules.append( + self.create_rule( + self.IPV4, self.DENY, self.PORTS_RANGE_2, self.proto[self.IP][self.TCP] + ) + ) + rules.append( + self.create_rule( + self.IPV4, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.TCP] + ) + ) # deny ip any any in the end rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0)) # Apply rules self.apply_rules(rules, "permit ipv4 tcp") # whitelist the 0xbbbb etype - so the 0xaaaa should be blocked - self.etype_whitelist([0xbbb], 1) + self.etype_whitelist([0xBBB], 1) # The whitelisted traffic, should pass - self.run_verify_test(self.IP, self.IPV4, self.proto[self.IP][self.TCP], - 0, False, True, 0x0bbb) + self.run_verify_test( + self.IP, self.IPV4, self.proto[self.IP][self.TCP], 0, False, True, 0x0BBB + ) # remove the whitelist, the previously blocked 0xAAAA should pass now self.etype_whitelist([], 0, add=False) @@ -1380,16 +1554,21 @@ class TestACLplugin(VppTestCase): self.logger.info("ACLP_TEST_FINISH_0306") def test_0307_tcp_permit_v4_etype_blacklist_aaaa(self): - """ permit TCPv4, whitelist 0x0BBB, remove, send 0xAAAA - pass - """ + """permit TCPv4, whitelist 0x0BBB, remove, send 0xAAAA - pass""" self.logger.info("ACLP_TEST_START_0307") # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_RANGE_2, - self.proto[self.IP][self.TCP])) - rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_RANGE, - self.proto[self.IP][self.TCP])) + rules.append( + self.create_rule( + self.IPV4, self.DENY, self.PORTS_RANGE_2, self.proto[self.IP][self.TCP] + ) + ) + rules.append( + self.create_rule( + self.IPV4, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.TCP] + ) + ) # deny ip any any in the end rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0)) @@ -1397,27 +1576,33 @@ class TestACLplugin(VppTestCase): self.apply_rules(rules, "permit ipv4 tcp") # whitelist the 0xbbbb etype - so the 0xaaaa should be blocked - self.etype_whitelist([0xbbb], 1) + self.etype_whitelist([0xBBB], 1) # remove the whitelist, the previously blocked 0xAAAA should pass now self.etype_whitelist([], 0, add=False) # The whitelisted traffic, should pass - self.run_verify_test(self.IP, self.IPV4, self.proto[self.IP][self.TCP], - 0, False, True, 0xaaaa) + self.run_verify_test( + self.IP, self.IPV4, self.proto[self.IP][self.TCP], 0, False, True, 0xAAAA + ) self.logger.info("ACLP_TEST_FINISH_0306") def test_0315_del_intf(self): - """ apply an acl and delete the interface - """ + """apply an acl and delete the interface""" self.logger.info("ACLP_TEST_START_0315") # Add an ACL rules = [] - rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_RANGE_2, - self.proto[self.IP][self.TCP])) - rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_RANGE, - self.proto[self.IP][self.TCP])) + rules.append( + self.create_rule( + self.IPV4, self.DENY, self.PORTS_RANGE_2, self.proto[self.IP][self.TCP] + ) + ) + rules.append( + self.create_rule( + self.IPV4, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.TCP] + ) + ) # deny ip any any in the end rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0)) @@ -1434,5 +1619,5 @@ class TestACLplugin(VppTestCase): self.logger.info("ACLP_TEST_FINISH_0315") -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_acl_plugin_conns.py b/test/test_acl_plugin_conns.py index cbf0ab37cf8..1b41698d6c0 100644 --- a/test/test_acl_plugin_conns.py +++ b/test/test_acl_plugin_conns.py @@ -39,14 +39,16 @@ def to_acl_rule(self, is_permit, wildcard_sport=False): rule_l4_sport_first = rule_l4_sport rule_l4_sport_last = rule_l4_sport - new_rule = AclRule(is_permit=is_permit, proto=rule_l4_proto, - src_prefix=ip_network( - (p[rule_l3_layer].src, rule_prefix_len)), - dst_prefix=ip_network( - (p[rule_l3_layer].dst, rule_prefix_len)), - sport_from=rule_l4_sport_first, - sport_to=rule_l4_sport_last, - dport_from=rule_l4_dport, dport_to=rule_l4_dport) + new_rule = AclRule( + is_permit=is_permit, + proto=rule_l4_proto, + src_prefix=ip_network((p[rule_l3_layer].src, rule_prefix_len)), + dst_prefix=ip_network((p[rule_l3_layer].dst, rule_prefix_len)), + sport_from=rule_l4_sport_first, + sport_to=rule_l4_sport_last, + dport_from=rule_l4_dport, + dport_to=rule_l4_dport, + ) return new_rule @@ -54,7 +56,7 @@ def to_acl_rule(self, is_permit, wildcard_sport=False): Packet.to_acl_rule = to_acl_rule -class IterateWithSleep(): +class IterateWithSleep: def __init__(self, testcase, n_iters, description, sleep_sec): self.curr = 0 self.testcase = testcase @@ -87,21 +89,27 @@ class Conn(L4_Conn): deny_acl.add_vpp_config() if reflect_side == acl_side: - acl_if0 = VppAclInterface(self.testcase, - self.ifs[acl_side].sw_if_index, - [reflect_acl, deny_acl], n_input=1) - acl_if1 = VppAclInterface(self.testcase, - self.ifs[1-acl_side].sw_if_index, [], - n_input=0) + acl_if0 = VppAclInterface( + self.testcase, + self.ifs[acl_side].sw_if_index, + [reflect_acl, deny_acl], + n_input=1, + ) + acl_if1 = VppAclInterface( + self.testcase, self.ifs[1 - acl_side].sw_if_index, [], n_input=0 + ) acl_if0.add_vpp_config() acl_if1.add_vpp_config() else: - acl_if0 = VppAclInterface(self.testcase, - self.ifs[acl_side].sw_if_index, - [deny_acl, reflect_acl], n_input=1) - acl_if1 = VppAclInterface(self.testcase, - self.ifs[1-acl_side].sw_if_index, [], - n_input=0) + acl_if0 = VppAclInterface( + self.testcase, + self.ifs[acl_side].sw_if_index, + [deny_acl, reflect_acl], + n_input=1, + ) + acl_if1 = VppAclInterface( + self.testcase, self.ifs[1 - acl_side].sw_if_index, [], n_input=0 + ) acl_if0.add_vpp_config() acl_if1.add_vpp_config() @@ -109,19 +117,22 @@ class Conn(L4_Conn): any_addr = ["0.0.0.0", "::"] rule_family = self.address_family is_ip6 = 1 if rule_family == AF_INET6 else 0 - new_rule = AclRule(is_permit=is_permit, proto=0, - src_prefix=ip_network( - (any_addr[is_ip6], 0)), - dst_prefix=ip_network( - (any_addr[is_ip6], 0)), - sport_from=0, sport_to=65535, dport_from=0, - dport_to=65535) + new_rule = AclRule( + is_permit=is_permit, + proto=0, + src_prefix=ip_network((any_addr[is_ip6], 0)), + dst_prefix=ip_network((any_addr[is_ip6], 0)), + sport_from=0, + sport_to=65535, + dport_from=0, + dport_to=65535, + ) return new_rule @unittest.skipUnless(config.extended, "part of extended tests") class ACLPluginConnTestCase(VppTestCase): - """ ACL plugin connection-oriented extended testcases """ + """ACL plugin connection-oriented extended testcases""" @classmethod def setUpClass(cls): @@ -142,8 +153,7 @@ class ACLPluginConnTestCase(VppTestCase): super(ACLPluginConnTestCase, cls).tearDownClass() def tearDown(self): - """Run standard test teardown and log various show commands - """ + """Run standard test teardown and log various show commands""" super(ACLPluginConnTestCase, self).tearDown() def show_commands_at_teardown(self): @@ -156,7 +166,7 @@ class ACLPluginConnTestCase(VppTestCase): self.logger.info(self.vapi.cli("show event-logger all")) def run_basic_conn_test(self, af, acl_side): - """ Basic conn timeout test """ + """Basic conn timeout test""" conn1 = Conn(self, self.pg0, self.pg1, af, UDP, 42001, 4242) conn1.apply_acls(0, acl_side) conn1.send_through(0) @@ -178,8 +188,8 @@ class ACLPluginConnTestCase(VppTestCase): self.assert_equal(p2, None, "packet on long-idle conn") def run_active_conn_test(self, af, acl_side): - """ Idle connection behind active connection test """ - base = 10000 + 1000*acl_side + """Idle connection behind active connection test""" + base = 10000 + 1000 * acl_side conn1 = Conn(self, self.pg0, self.pg1, af, UDP, base + 1, 2323) conn2 = Conn(self, self.pg0, self.pg1, af, UDP, base + 2, 2323) conn3 = Conn(self, self.pg0, self.pg1, af, UDP, base + 3, 2323) @@ -206,7 +216,7 @@ class ACLPluginConnTestCase(VppTestCase): self.assert_equal(p2, None, "packet on long-idle conn") def run_clear_conn_test(self, af, acl_side): - """ Clear the connections via CLI """ + """Clear the connections via CLI""" conn1 = Conn(self, self.pg0, self.pg1, af, UDP, 42001, 4242) conn1.apply_acls(0, acl_side) conn1.send_through(0) @@ -229,9 +239,9 @@ class ACLPluginConnTestCase(VppTestCase): def run_tcp_transient_setup_conn_test(self, af, acl_side): conn1 = Conn(self, self.pg0, self.pg1, af, TCP, 53001, 5151) conn1.apply_acls(0, acl_side) - conn1.send_through(0, 'S') + conn1.send_through(0, "S") # the return packets should pass - conn1.send_through(1, 'SA') + conn1.send_through(1, "SA") # allow the conn to time out for i in IterateWithSleep(self, 30, "Wait for timeout", 0.1): pass @@ -247,17 +257,17 @@ class ACLPluginConnTestCase(VppTestCase): def run_tcp_established_conn_test(self, af, acl_side): conn1 = Conn(self, self.pg0, self.pg1, af, TCP, 53002, 5052) conn1.apply_acls(0, acl_side) - conn1.send_through(0, 'S') + conn1.send_through(0, "S") # the return packets should pass - conn1.send_through(1, 'SA') + conn1.send_through(1, "SA") # complete the threeway handshake # (NB: sequence numbers not tracked, so not set!) - conn1.send_through(0, 'A') + conn1.send_through(0, "A") # allow the conn to time out if it's in embryonic timer for i in IterateWithSleep(self, 30, "Wait for transient timeout", 0.1): pass # Try to send the packet from the "forbidden" side - it must pass - conn1.send_through(1, 'A') + conn1.send_through(1, "A") # ensure conn times out for real for i in IterateWithSleep(self, 130, "Wait for timeout", 0.1): pass @@ -272,19 +282,19 @@ class ACLPluginConnTestCase(VppTestCase): def run_tcp_transient_teardown_conn_test(self, af, acl_side): conn1 = Conn(self, self.pg0, self.pg1, af, TCP, 53002, 5052) conn1.apply_acls(0, acl_side) - conn1.send_through(0, 'S') + conn1.send_through(0, "S") # the return packets should pass - conn1.send_through(1, 'SA') + conn1.send_through(1, "SA") # complete the threeway handshake # (NB: sequence numbers not tracked, so not set!) - conn1.send_through(0, 'A') + conn1.send_through(0, "A") # allow the conn to time out if it's in embryonic timer for i in IterateWithSleep(self, 30, "Wait for transient timeout", 0.1): pass # Try to send the packet from the "forbidden" side - it must pass - conn1.send_through(1, 'A') + conn1.send_through(1, "A") # Send the FIN to bounce the session out of established - conn1.send_through(1, 'FA') + conn1.send_through(1, "FA") # If conn landed on transient timer it will time out here for i in IterateWithSleep(self, 30, "Wait for transient timeout", 0.1): pass @@ -298,59 +308,59 @@ class ACLPluginConnTestCase(VppTestCase): self.assert_equal(p2, None, "packet on supposedly deleted conn") def test_0000_conn_prepare_test(self): - """ Prepare the settings """ + """Prepare the settings""" self.vapi.ppcli("set acl-plugin session timeout udp idle 1") def test_0001_basic_conn_test(self): - """ IPv4: Basic conn timeout test reflect on ingress """ + """IPv4: Basic conn timeout test reflect on ingress""" self.run_basic_conn_test(AF_INET, 0) def test_0002_basic_conn_test(self): - """ IPv4: Basic conn timeout test reflect on egress """ + """IPv4: Basic conn timeout test reflect on egress""" self.run_basic_conn_test(AF_INET, 1) def test_0005_clear_conn_test(self): - """ IPv4: reflect egress, clear conn """ + """IPv4: reflect egress, clear conn""" self.run_clear_conn_test(AF_INET, 1) def test_0006_clear_conn_test(self): - """ IPv4: reflect ingress, clear conn """ + """IPv4: reflect ingress, clear conn""" self.run_clear_conn_test(AF_INET, 0) def test_0011_active_conn_test(self): - """ IPv4: Idle conn behind active conn, reflect on ingress """ + """IPv4: Idle conn behind active conn, reflect on ingress""" self.run_active_conn_test(AF_INET, 0) def test_0012_active_conn_test(self): - """ IPv4: Idle conn behind active conn, reflect on egress """ + """IPv4: Idle conn behind active conn, reflect on egress""" self.run_active_conn_test(AF_INET, 1) def test_1001_basic_conn_test(self): - """ IPv6: Basic conn timeout test reflect on ingress """ + """IPv6: Basic conn timeout test reflect on ingress""" self.run_basic_conn_test(AF_INET6, 0) def test_1002_basic_conn_test(self): - """ IPv6: Basic conn timeout test reflect on egress """ + """IPv6: Basic conn timeout test reflect on egress""" self.run_basic_conn_test(AF_INET6, 1) def test_1005_clear_conn_test(self): - """ IPv6: reflect egress, clear conn """ + """IPv6: reflect egress, clear conn""" self.run_clear_conn_test(AF_INET6, 1) def test_1006_clear_conn_test(self): - """ IPv6: reflect ingress, clear conn """ + """IPv6: reflect ingress, clear conn""" self.run_clear_conn_test(AF_INET6, 0) def test_1011_active_conn_test(self): - """ IPv6: Idle conn behind active conn, reflect on ingress """ + """IPv6: Idle conn behind active conn, reflect on ingress""" self.run_active_conn_test(AF_INET6, 0) def test_1012_active_conn_test(self): - """ IPv6: Idle conn behind active conn, reflect on egress """ + """IPv6: Idle conn behind active conn, reflect on egress""" self.run_active_conn_test(AF_INET6, 1) def test_2000_prepare_for_tcp_test(self): - """ Prepare for TCP session tests """ + """Prepare for TCP session tests""" # ensure the session hangs on if it gets treated as UDP self.vapi.ppcli("set acl-plugin session timeout udp idle 200") # let the TCP connection time out at 5 seconds @@ -358,49 +368,49 @@ class ACLPluginConnTestCase(VppTestCase): self.vapi.ppcli("set acl-plugin session timeout tcp transient 1") def test_2001_tcp_transient_conn_test(self): - """ IPv4: transient TCP session (incomplete 3WHS), ref. on ingress """ + """IPv4: transient TCP session (incomplete 3WHS), ref. on ingress""" self.run_tcp_transient_setup_conn_test(AF_INET, 0) def test_2002_tcp_transient_conn_test(self): - """ IPv4: transient TCP session (incomplete 3WHS), ref. on egress """ + """IPv4: transient TCP session (incomplete 3WHS), ref. on egress""" self.run_tcp_transient_setup_conn_test(AF_INET, 1) def test_2003_tcp_transient_conn_test(self): - """ IPv4: established TCP session (complete 3WHS), ref. on ingress """ + """IPv4: established TCP session (complete 3WHS), ref. on ingress""" self.run_tcp_established_conn_test(AF_INET, 0) def test_2004_tcp_transient_conn_test(self): - """ IPv4: established TCP session (complete 3WHS), ref. on egress """ + """IPv4: established TCP session (complete 3WHS), ref. on egress""" self.run_tcp_established_conn_test(AF_INET, 1) def test_2005_tcp_transient_teardown_conn_test(self): - """ IPv4: transient TCP session (3WHS,ACK,FINACK), ref. on ingress """ + """IPv4: transient TCP session (3WHS,ACK,FINACK), ref. on ingress""" self.run_tcp_transient_teardown_conn_test(AF_INET, 0) def test_2006_tcp_transient_teardown_conn_test(self): - """ IPv4: transient TCP session (3WHS,ACK,FINACK), ref. on egress """ + """IPv4: transient TCP session (3WHS,ACK,FINACK), ref. on egress""" self.run_tcp_transient_teardown_conn_test(AF_INET, 1) def test_3001_tcp_transient_conn_test(self): - """ IPv6: transient TCP session (incomplete 3WHS), ref. on ingress """ + """IPv6: transient TCP session (incomplete 3WHS), ref. on ingress""" self.run_tcp_transient_setup_conn_test(AF_INET6, 0) def test_3002_tcp_transient_conn_test(self): - """ IPv6: transient TCP session (incomplete 3WHS), ref. on egress """ + """IPv6: transient TCP session (incomplete 3WHS), ref. on egress""" self.run_tcp_transient_setup_conn_test(AF_INET6, 1) def test_3003_tcp_transient_conn_test(self): - """ IPv6: established TCP session (complete 3WHS), ref. on ingress """ + """IPv6: established TCP session (complete 3WHS), ref. on ingress""" self.run_tcp_established_conn_test(AF_INET6, 0) def test_3004_tcp_transient_conn_test(self): - """ IPv6: established TCP session (complete 3WHS), ref. on egress """ + """IPv6: established TCP session (complete 3WHS), ref. on egress""" self.run_tcp_established_conn_test(AF_INET6, 1) def test_3005_tcp_transient_teardown_conn_test(self): - """ IPv6: transient TCP session (3WHS,ACK,FINACK), ref. on ingress """ + """IPv6: transient TCP session (3WHS,ACK,FINACK), ref. on ingress""" self.run_tcp_transient_teardown_conn_test(AF_INET6, 0) def test_3006_tcp_transient_teardown_conn_test(self): - """ IPv6: transient TCP session (3WHS,ACK,FINACK), ref. on egress """ + """IPv6: transient TCP session (3WHS,ACK,FINACK), ref. on egress""" self.run_tcp_transient_teardown_conn_test(AF_INET6, 1) diff --git a/test/test_acl_plugin_l2l3.py b/test/test_acl_plugin_l2l3.py index 48faafb7398..343e611751b 100644 --- a/test/test_acl_plugin_l2l3.py +++ b/test/test_acl_plugin_l2l3.py @@ -76,12 +76,16 @@ class TestACLpluginL2L3(VppTestCase): # Create BD with MAC learning enabled and put interfaces to this BD cls.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=cls.loop0.sw_if_index, bd_id=cls.bd_id, - port_type=L2_PORT_TYPE.BVI) - cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=cls.pg0.sw_if_index, - bd_id=cls.bd_id) - cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=cls.pg1.sw_if_index, - bd_id=cls.bd_id) + rx_sw_if_index=cls.loop0.sw_if_index, + bd_id=cls.bd_id, + port_type=L2_PORT_TYPE.BVI, + ) + cls.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=cls.pg0.sw_if_index, bd_id=cls.bd_id + ) + cls.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=cls.pg1.sw_if_index, bd_id=cls.bd_id + ) # Configure IPv4 addresses on loopback interface and routed interface cls.loop0.config_ip4() @@ -125,8 +129,7 @@ class TestACLpluginL2L3(VppTestCase): self.logger.info(self.vapi.cli("show l2patch")) self.logger.info(self.vapi.cli("show classify tables")) self.logger.info(self.vapi.cli("show l2fib verbose")) - self.logger.info(self.vapi.cli("show bridge-domain %s detail" % - self.bd_id)) + self.logger.info(self.vapi.cli("show bridge-domain %s detail" % self.bd_id)) self.logger.info(self.vapi.cli("show ip neighbors")) cmd = "show acl-plugin sessions verbose 1" self.logger.info(self.vapi.cli(cmd)) @@ -134,23 +137,33 @@ class TestACLpluginL2L3(VppTestCase): self.logger.info(self.vapi.cli("show acl-plugin interface")) self.logger.info(self.vapi.cli("show acl-plugin tables")) - def create_stream(self, src_ip_if, dst_ip_if, reverse, packet_sizes, - is_ip6, expect_blocked, expect_established, - add_extension_header, icmp_stateful=False): + def create_stream( + self, + src_ip_if, + dst_ip_if, + reverse, + packet_sizes, + is_ip6, + expect_blocked, + expect_established, + add_extension_header, + icmp_stateful=False, + ): pkts = [] rules = [] permit_rules = [] permit_and_reflect_rules = [] total_packet_count = 8 for i in range(0, total_packet_count): - modulo = (i//2) % 2 + modulo = (i // 2) % 2 icmp_type_delta = i % 2 icmp_code = i - is_udp_packet = (modulo == 0) + is_udp_packet = modulo == 0 if is_udp_packet and icmp_stateful: continue - is_reflectable_icmp = (icmp_stateful and icmp_type_delta == 0 and - not is_udp_packet) + is_reflectable_icmp = ( + icmp_stateful and icmp_type_delta == 0 and not is_udp_packet + ) is_reflected_icmp = is_reflectable_icmp and expect_established can_reflect_this_packet = is_udp_packet or is_reflectable_icmp is_permit = i % 2 @@ -161,9 +174,9 @@ class TestACLpluginL2L3(VppTestCase): payload = self.info_to_payload(info) else: to_be_blocked = False - if (expect_blocked and not expect_established): + if expect_blocked and not expect_established: to_be_blocked = True - if (not can_reflect_this_packet): + if not can_reflect_this_packet: to_be_blocked = True if to_be_blocked: payload = "to be blocked" @@ -171,7 +184,7 @@ class TestACLpluginL2L3(VppTestCase): info = self.create_packet_info(src_ip_if, dst_ip_if) payload = self.info_to_payload(info) if reverse: - dst_mac = 'de:ad:00:00:00:00' + dst_mac = "de:ad:00:00:00:00" src_mac = remote_dst_host._mac dst_ip6 = src_ip_if.remote_ip6 src_ip6 = remote_dst_host.ip6 @@ -201,42 +214,53 @@ class TestACLpluginL2L3(VppTestCase): ulp_l4 = UDP(sport=src_l4, dport=dst_l4) if add_extension_header: # prepend some extension headers - ulp = (IPv6ExtHdrRouting() / IPv6ExtHdrRouting() / - IPv6ExtHdrFragment(offset=0, m=1) / ulp_l4) + ulp = ( + IPv6ExtHdrRouting() + / IPv6ExtHdrRouting() + / IPv6ExtHdrFragment(offset=0, m=1) + / ulp_l4 + ) # uncomment below to test invalid ones # ulp = IPv6ExtHdrRouting(len = 200) / ulp_l4 else: ulp = ulp_l4 - p = (Ether(dst=dst_mac, src=src_mac) / - IPv6(src=src_ip6, dst=dst_ip6) / - ulp / - Raw(payload)) + p = ( + Ether(dst=dst_mac, src=src_mac) + / IPv6(src=src_ip6, dst=dst_ip6) + / ulp + / Raw(payload) + ) else: ulp_l4 = UDP(sport=src_l4, dport=dst_l4) # IPv4 does not allow extension headers, # but we rather make it a first fragment flags = 1 if add_extension_header else 0 ulp = ulp_l4 - p = (Ether(dst=dst_mac, src=src_mac) / - IP(src=src_ip4, dst=dst_ip4, frag=0, flags=flags) / - ulp / - Raw(payload)) + p = ( + Ether(dst=dst_mac, src=src_mac) + / IP(src=src_ip4, dst=dst_ip4, frag=0, flags=flags) + / ulp + / Raw(payload) + ) elif modulo == 1: if is_ip6: - ulp_l4 = ICMPv6Unknown(type=128 + icmp_type_delta, - code=icmp_code) + ulp_l4 = ICMPv6Unknown(type=128 + icmp_type_delta, code=icmp_code) ulp = ulp_l4 - p = (Ether(dst=dst_mac, src=src_mac) / - IPv6(src=src_ip6, dst=dst_ip6) / - ulp / - Raw(payload)) + p = ( + Ether(dst=dst_mac, src=src_mac) + / IPv6(src=src_ip6, dst=dst_ip6) + / ulp + / Raw(payload) + ) else: - ulp_l4 = ICMP(type=8 - 8*icmp_type_delta, code=icmp_code) + ulp_l4 = ICMP(type=8 - 8 * icmp_type_delta, code=icmp_code) ulp = ulp_l4 - p = (Ether(dst=dst_mac, src=src_mac) / - IP(src=src_ip4, dst=dst_ip4) / - ulp / - Raw(payload)) + p = ( + Ether(dst=dst_mac, src=src_mac) + / IP(src=src_ip4, dst=dst_ip4) + / ulp + / Raw(payload) + ) if i % 2 == 1: info.data = p.copy() @@ -259,19 +283,20 @@ class TestACLpluginL2L3(VppTestCase): rule_l4_sport = p[ICMPv6Unknown].type rule_l4_dport = p[ICMPv6Unknown].code if p.haslayer(IPv6): - rule_l4_proto = ulp_l4.overload_fields[IPv6]['nh'] + rule_l4_proto = ulp_l4.overload_fields[IPv6]["nh"] else: rule_l4_proto = p[IP].proto - new_rule = AclRule(is_permit=is_permit, proto=rule_l4_proto, - src_prefix=ip_network( - (p[rule_l3_layer].src, rule_prefix_len)), - dst_prefix=ip_network( - (p[rule_l3_layer].dst, rule_prefix_len)), - sport_from=rule_l4_sport, - sport_to=rule_l4_sport, - dport_from=rule_l4_dport, - dport_to=rule_l4_dport) + new_rule = AclRule( + is_permit=is_permit, + proto=rule_l4_proto, + src_prefix=ip_network((p[rule_l3_layer].src, rule_prefix_len)), + dst_prefix=ip_network((p[rule_l3_layer].dst, rule_prefix_len)), + sport_from=rule_l4_sport, + sport_to=rule_l4_sport, + dport_from=rule_l4_dport, + dport_to=rule_l4_dport, + ) rules.append(new_rule) new_rule_permit = copy.copy(new_rule) @@ -287,10 +312,12 @@ class TestACLpluginL2L3(VppTestCase): permit_and_reflect_rules.append(new_rule_permit_and_reflect) self.logger.info("create_stream pkt#%d: %s" % (i, payload)) - return {'stream': pkts, - 'rules': rules, - 'permit_rules': permit_rules, - 'permit_and_reflect_rules': permit_and_reflect_rules} + return { + "stream": pkts, + "rules": rules, + "permit_rules": permit_rules, + "permit_and_reflect_rules": permit_and_reflect_rules, + } def verify_capture(self, dst_ip_if, src_ip_if, capture, reverse): last_info = dict() @@ -316,11 +343,13 @@ class TestACLpluginL2L3(VppTestCase): data = scapy.compat.raw(packet[UDP][Raw]) else: if l3 == IP: - data = scapy.compat.raw(ICMP( - scapy.compat.raw(packet[l3].payload))[Raw]) + data = scapy.compat.raw( + ICMP(scapy.compat.raw(packet[l3].payload))[Raw] + ) else: - data = scapy.compat.raw(ICMPv6Unknown( - scapy.compat.raw(packet[l3].payload)).msgbody) + data = scapy.compat.raw( + ICMPv6Unknown(scapy.compat.raw(packet[l3].payload)).msgbody + ) udp_or_icmp = packet[l3].payload data_obj = Raw(data) # FIXME: make framework believe we are on object @@ -330,8 +359,8 @@ class TestACLpluginL2L3(VppTestCase): self.assertEqual(payload_info.dst, dst_ip_sw_if_index) next_info = self.get_next_packet_info_for_interface2( - payload_info.src, dst_ip_sw_if_index, - last_info[payload_info.src]) + payload_info.src, dst_ip_sw_if_index, last_info[payload_info.src] + ) last_info[payload_info.src] = next_info self.assertTrue(next_info is not None) self.assertEqual(packet_index, next_info.index) @@ -400,13 +429,13 @@ class TestACLpluginL2L3(VppTestCase): # change the ACLs a few times for i in range(1, 10): shuffle(all_rules) - acl1.modify_vpp_config(all_rules[::1+(i % 2)]) + acl1.modify_vpp_config(all_rules[:: 1 + (i % 2)]) shuffle(all_rules) - acl2.modify_vpp_config(all_rules[::1+(i % 3)]) + acl2.modify_vpp_config(all_rules[:: 1 + (i % 3)]) shuffle(all_rules) - acl3.modify_vpp_config(all_rules[::1+(i % 5)]) + acl3.modify_vpp_config(all_rules[:: 1 + (i % 5)]) # restore to how it was before and clean up acl_if.n_input = saved_n_input @@ -417,143 +446,200 @@ class TestACLpluginL2L3(VppTestCase): acl2.remove_vpp_config() acl3.remove_vpp_config() - def create_acls_for_a_stream(self, stream_dict, - test_l2_action, is_reflect): - r = stream_dict['rules'] - r_permit = stream_dict['permit_rules'] - r_permit_reflect = stream_dict['permit_and_reflect_rules'] + def create_acls_for_a_stream(self, stream_dict, test_l2_action, is_reflect): + r = stream_dict["rules"] + r_permit = stream_dict["permit_rules"] + r_permit_reflect = stream_dict["permit_and_reflect_rules"] r_action = r_permit_reflect if is_reflect else r action_acl = VppAcl(self, rules=r_action, tag="act. acl") action_acl.add_vpp_config() permit_acl = VppAcl(self, rules=r_permit, tag="perm. acl") permit_acl.add_vpp_config() - return {'L2': action_acl if test_l2_action else permit_acl, - 'L3': permit_acl if test_l2_action else action_acl, - 'permit': permit_acl, 'action': action_acl} - - def apply_acl_ip46_x_to_y(self, bridged_to_routed, test_l2_deny, - is_ip6, is_reflect, add_eh): - """ Apply the ACLs - """ + return { + "L2": action_acl if test_l2_action else permit_acl, + "L3": permit_acl if test_l2_action else action_acl, + "permit": permit_acl, + "action": action_acl, + } + + def apply_acl_ip46_x_to_y( + self, bridged_to_routed, test_l2_deny, is_ip6, is_reflect, add_eh + ): + """Apply the ACLs""" self.reset_packet_infos() stream_dict = self.create_stream( - self.pg2, self.loop0, + self.pg2, + self.loop0, bridged_to_routed, - self.pg_if_packet_sizes, is_ip6, - not is_reflect, False, add_eh) - stream = stream_dict['stream'] - acl_idx = self.create_acls_for_a_stream(stream_dict, test_l2_deny, - is_reflect) + self.pg_if_packet_sizes, + is_ip6, + not is_reflect, + False, + add_eh, + ) + stream = stream_dict["stream"] + acl_idx = self.create_acls_for_a_stream(stream_dict, test_l2_deny, is_reflect) n_input_l3 = 0 if bridged_to_routed else 1 n_input_l2 = 1 if bridged_to_routed else 0 - acl_if_pg2 = VppAclInterface(self, sw_if_index=self.pg2.sw_if_index, - n_input=n_input_l3, acls=[acl_idx['L3']]) + acl_if_pg2 = VppAclInterface( + self, + sw_if_index=self.pg2.sw_if_index, + n_input=n_input_l3, + acls=[acl_idx["L3"]], + ) acl_if_pg2.add_vpp_config() - acl_if_pg0 = VppAclInterface(self, sw_if_index=self.pg0.sw_if_index, - n_input=n_input_l2, acls=[acl_idx['L2']]) + acl_if_pg0 = VppAclInterface( + self, + sw_if_index=self.pg0.sw_if_index, + n_input=n_input_l2, + acls=[acl_idx["L2"]], + ) acl_if_pg0.add_vpp_config() - acl_if_pg1 = VppAclInterface(self, sw_if_index=self.pg1.sw_if_index, - n_input=n_input_l2, acls=[acl_idx['L2']]) + acl_if_pg1 = VppAclInterface( + self, + sw_if_index=self.pg1.sw_if_index, + n_input=n_input_l2, + acls=[acl_idx["L2"]], + ) acl_if_pg1.add_vpp_config() self.applied_acl_shuffle(acl_if_pg0) self.applied_acl_shuffle(acl_if_pg1) - return {'L2': acl_idx['L2'], 'L3': acl_idx['L3']} + return {"L2": acl_idx["L2"], "L3": acl_idx["L3"]} - def apply_acl_ip46_both_directions_reflect(self, - primary_is_bridged_to_routed, - reflect_on_l2, is_ip6, add_eh, - stateful_icmp): + def apply_acl_ip46_both_directions_reflect( + self, primary_is_bridged_to_routed, reflect_on_l2, is_ip6, add_eh, stateful_icmp + ): primary_is_routed_to_bridged = not primary_is_bridged_to_routed self.reset_packet_infos() - stream_dict_fwd = self.create_stream(self.pg2, self.loop0, - primary_is_bridged_to_routed, - self.pg_if_packet_sizes, is_ip6, - False, False, add_eh, - stateful_icmp) - acl_idx_fwd = self.create_acls_for_a_stream(stream_dict_fwd, - reflect_on_l2, True) - - stream_dict_rev = self.create_stream(self.pg2, self.loop0, - not primary_is_bridged_to_routed, - self.pg_if_packet_sizes, is_ip6, - True, True, add_eh, stateful_icmp) + stream_dict_fwd = self.create_stream( + self.pg2, + self.loop0, + primary_is_bridged_to_routed, + self.pg_if_packet_sizes, + is_ip6, + False, + False, + add_eh, + stateful_icmp, + ) + acl_idx_fwd = self.create_acls_for_a_stream( + stream_dict_fwd, reflect_on_l2, True + ) + + stream_dict_rev = self.create_stream( + self.pg2, + self.loop0, + not primary_is_bridged_to_routed, + self.pg_if_packet_sizes, + is_ip6, + True, + True, + add_eh, + stateful_icmp, + ) # We want the primary action to be "deny" rather than reflect - acl_idx_rev = self.create_acls_for_a_stream(stream_dict_rev, - reflect_on_l2, False) + acl_idx_rev = self.create_acls_for_a_stream( + stream_dict_rev, reflect_on_l2, False + ) if primary_is_bridged_to_routed: - inbound_l2_acl = acl_idx_fwd['L2'] + inbound_l2_acl = acl_idx_fwd["L2"] else: - inbound_l2_acl = acl_idx_rev['L2'] + inbound_l2_acl = acl_idx_rev["L2"] if primary_is_routed_to_bridged: - outbound_l2_acl = acl_idx_fwd['L2'] + outbound_l2_acl = acl_idx_fwd["L2"] else: - outbound_l2_acl = acl_idx_rev['L2'] + outbound_l2_acl = acl_idx_rev["L2"] if primary_is_routed_to_bridged: - inbound_l3_acl = acl_idx_fwd['L3'] + inbound_l3_acl = acl_idx_fwd["L3"] else: - inbound_l3_acl = acl_idx_rev['L3'] + inbound_l3_acl = acl_idx_rev["L3"] if primary_is_bridged_to_routed: - outbound_l3_acl = acl_idx_fwd['L3'] + outbound_l3_acl = acl_idx_fwd["L3"] else: - outbound_l3_acl = acl_idx_rev['L3'] - - acl_if_pg2 = VppAclInterface(self, sw_if_index=self.pg2.sw_if_index, - n_input=1, - acls=[inbound_l3_acl, outbound_l3_acl]) + outbound_l3_acl = acl_idx_rev["L3"] + + acl_if_pg2 = VppAclInterface( + self, + sw_if_index=self.pg2.sw_if_index, + n_input=1, + acls=[inbound_l3_acl, outbound_l3_acl], + ) acl_if_pg2.add_vpp_config() - acl_if_pg0 = VppAclInterface(self, sw_if_index=self.pg0.sw_if_index, - n_input=1, - acls=[inbound_l2_acl, outbound_l2_acl]) + acl_if_pg0 = VppAclInterface( + self, + sw_if_index=self.pg0.sw_if_index, + n_input=1, + acls=[inbound_l2_acl, outbound_l2_acl], + ) acl_if_pg0.add_vpp_config() - acl_if_pg1 = VppAclInterface(self, sw_if_index=self.pg1.sw_if_index, - n_input=1, - acls=[inbound_l2_acl, outbound_l2_acl]) + acl_if_pg1 = VppAclInterface( + self, + sw_if_index=self.pg1.sw_if_index, + n_input=1, + acls=[inbound_l2_acl, outbound_l2_acl], + ) acl_if_pg1.add_vpp_config() self.applied_acl_shuffle(acl_if_pg0) self.applied_acl_shuffle(acl_if_pg2) - def apply_acl_ip46_routed_to_bridged(self, test_l2_deny, is_ip6, - is_reflect, add_eh): - return self.apply_acl_ip46_x_to_y(False, test_l2_deny, is_ip6, - is_reflect, add_eh) + def apply_acl_ip46_routed_to_bridged( + self, test_l2_deny, is_ip6, is_reflect, add_eh + ): + return self.apply_acl_ip46_x_to_y( + False, test_l2_deny, is_ip6, is_reflect, add_eh + ) - def apply_acl_ip46_bridged_to_routed(self, test_l2_deny, is_ip6, - is_reflect, add_eh): - return self.apply_acl_ip46_x_to_y(True, test_l2_deny, is_ip6, - is_reflect, add_eh) + def apply_acl_ip46_bridged_to_routed( + self, test_l2_deny, is_ip6, is_reflect, add_eh + ): + return self.apply_acl_ip46_x_to_y( + True, test_l2_deny, is_ip6, is_reflect, add_eh + ) def verify_acl_packet_count(self, acl_idx, packet_count): - matches = self.statistics.get_counter('/acl/%d/matches' % acl_idx) + matches = self.statistics.get_counter("/acl/%d/matches" % acl_idx) self.logger.info("stat seg for ACL %d: %s" % (acl_idx, repr(matches))) total_count = 0 for m in matches: for p in m: - total_count = total_count + p['packets'] + total_count = total_count + p["packets"] self.assertEqual(total_count, packet_count) - def run_traffic_ip46_x_to_y(self, bridged_to_routed, - test_l2_deny, is_ip6, - is_reflect, is_established, add_eh, - stateful_icmp=False): + def run_traffic_ip46_x_to_y( + self, + bridged_to_routed, + test_l2_deny, + is_ip6, + is_reflect, + is_established, + add_eh, + stateful_icmp=False, + ): self.reset_packet_infos() - stream_dict = self.create_stream(self.pg2, self.loop0, - bridged_to_routed, - self.pg_if_packet_sizes, is_ip6, - not is_reflect, is_established, - add_eh, stateful_icmp) - stream = stream_dict['stream'] + stream_dict = self.create_stream( + self.pg2, + self.loop0, + bridged_to_routed, + self.pg_if_packet_sizes, + is_ip6, + not is_reflect, + is_established, + add_eh, + stateful_icmp, + ) + stream = stream_dict["stream"] tx_if = self.pg0 if bridged_to_routed else self.pg2 rx_if = self.pg2 if bridged_to_routed else self.pg0 @@ -566,68 +652,90 @@ class TestACLpluginL2L3(VppTestCase): self.verify_capture(self.loop0, self.pg2, rcvd1, bridged_to_routed) return len(stream) - def run_traffic_ip46_routed_to_bridged(self, test_l2_deny, is_ip6, - is_reflect, is_established, add_eh, - stateful_icmp=False): - return self.run_traffic_ip46_x_to_y(False, test_l2_deny, is_ip6, - is_reflect, is_established, add_eh, - stateful_icmp) - - def run_traffic_ip46_bridged_to_routed(self, test_l2_deny, is_ip6, - is_reflect, is_established, add_eh, - stateful_icmp=False): - return self.run_traffic_ip46_x_to_y(True, test_l2_deny, is_ip6, - is_reflect, is_established, add_eh, - stateful_icmp) - - def run_test_ip46_routed_to_bridged(self, test_l2_deny, - is_ip6, is_reflect, add_eh): - acls = self.apply_acl_ip46_routed_to_bridged(test_l2_deny, - is_ip6, is_reflect, - add_eh) - pkts = self.run_traffic_ip46_routed_to_bridged(test_l2_deny, is_ip6, - is_reflect, False, - add_eh) - self.verify_acl_packet_count(acls['L3'].acl_index, pkts) - - def run_test_ip46_bridged_to_routed(self, test_l2_deny, - is_ip6, is_reflect, add_eh): - acls = self.apply_acl_ip46_bridged_to_routed(test_l2_deny, - is_ip6, is_reflect, - add_eh) - pkts = self.run_traffic_ip46_bridged_to_routed(test_l2_deny, is_ip6, - is_reflect, False, - add_eh) - self.verify_acl_packet_count(acls['L2'].acl_index, pkts) - - def run_test_ip46_routed_to_bridged_and_back(self, test_l2_action, - is_ip6, add_eh, - stateful_icmp=False): - self.apply_acl_ip46_both_directions_reflect(False, test_l2_action, - is_ip6, add_eh, - stateful_icmp) - self.run_traffic_ip46_routed_to_bridged(test_l2_action, is_ip6, - True, False, add_eh, - stateful_icmp) - self.run_traffic_ip46_bridged_to_routed(test_l2_action, is_ip6, - False, True, add_eh, - stateful_icmp) - - def run_test_ip46_bridged_to_routed_and_back(self, test_l2_action, - is_ip6, add_eh, - stateful_icmp=False): - self.apply_acl_ip46_both_directions_reflect(True, test_l2_action, - is_ip6, add_eh, - stateful_icmp) - self.run_traffic_ip46_bridged_to_routed(test_l2_action, is_ip6, - True, False, add_eh, - stateful_icmp) - self.run_traffic_ip46_routed_to_bridged(test_l2_action, is_ip6, - False, True, add_eh, - stateful_icmp) + def run_traffic_ip46_routed_to_bridged( + self, + test_l2_deny, + is_ip6, + is_reflect, + is_established, + add_eh, + stateful_icmp=False, + ): + return self.run_traffic_ip46_x_to_y( + False, + test_l2_deny, + is_ip6, + is_reflect, + is_established, + add_eh, + stateful_icmp, + ) + + def run_traffic_ip46_bridged_to_routed( + self, + test_l2_deny, + is_ip6, + is_reflect, + is_established, + add_eh, + stateful_icmp=False, + ): + return self.run_traffic_ip46_x_to_y( + True, + test_l2_deny, + is_ip6, + is_reflect, + is_established, + add_eh, + stateful_icmp, + ) + + def run_test_ip46_routed_to_bridged(self, test_l2_deny, is_ip6, is_reflect, add_eh): + acls = self.apply_acl_ip46_routed_to_bridged( + test_l2_deny, is_ip6, is_reflect, add_eh + ) + pkts = self.run_traffic_ip46_routed_to_bridged( + test_l2_deny, is_ip6, is_reflect, False, add_eh + ) + self.verify_acl_packet_count(acls["L3"].acl_index, pkts) + + def run_test_ip46_bridged_to_routed(self, test_l2_deny, is_ip6, is_reflect, add_eh): + acls = self.apply_acl_ip46_bridged_to_routed( + test_l2_deny, is_ip6, is_reflect, add_eh + ) + pkts = self.run_traffic_ip46_bridged_to_routed( + test_l2_deny, is_ip6, is_reflect, False, add_eh + ) + self.verify_acl_packet_count(acls["L2"].acl_index, pkts) + + def run_test_ip46_routed_to_bridged_and_back( + self, test_l2_action, is_ip6, add_eh, stateful_icmp=False + ): + self.apply_acl_ip46_both_directions_reflect( + False, test_l2_action, is_ip6, add_eh, stateful_icmp + ) + self.run_traffic_ip46_routed_to_bridged( + test_l2_action, is_ip6, True, False, add_eh, stateful_icmp + ) + self.run_traffic_ip46_bridged_to_routed( + test_l2_action, is_ip6, False, True, add_eh, stateful_icmp + ) + + def run_test_ip46_bridged_to_routed_and_back( + self, test_l2_action, is_ip6, add_eh, stateful_icmp=False + ): + self.apply_acl_ip46_both_directions_reflect( + True, test_l2_action, is_ip6, add_eh, stateful_icmp + ) + self.run_traffic_ip46_bridged_to_routed( + test_l2_action, is_ip6, True, False, add_eh, stateful_icmp + ) + self.run_traffic_ip46_routed_to_bridged( + test_l2_action, is_ip6, False, True, add_eh, stateful_icmp + ) def test_0000_ip6_irb_1(self): - """ ACL plugin prepare""" + """ACL plugin prepare""" if not self.vpp_dead: cmd = "set acl-plugin session timeout udp idle 2000" self.logger.info(self.vapi.ppcli(cmd)) @@ -646,219 +754,188 @@ class TestACLpluginL2L3(VppTestCase): # "set acl-plugin l2-datapath old")) def test_0001_ip6_irb_1(self): - """ ACL IPv6 routed -> bridged, L2 ACL deny""" - self.run_test_ip46_routed_to_bridged(True, True, False, - self.WITHOUT_EH) + """ACL IPv6 routed -> bridged, L2 ACL deny""" + self.run_test_ip46_routed_to_bridged(True, True, False, self.WITHOUT_EH) def test_0002_ip6_irb_1(self): - """ ACL IPv6 routed -> bridged, L3 ACL deny""" - self.run_test_ip46_routed_to_bridged(False, True, False, - self.WITHOUT_EH) + """ACL IPv6 routed -> bridged, L3 ACL deny""" + self.run_test_ip46_routed_to_bridged(False, True, False, self.WITHOUT_EH) def test_0003_ip4_irb_1(self): - """ ACL IPv4 routed -> bridged, L2 ACL deny""" - self.run_test_ip46_routed_to_bridged(True, False, False, - self.WITHOUT_EH) + """ACL IPv4 routed -> bridged, L2 ACL deny""" + self.run_test_ip46_routed_to_bridged(True, False, False, self.WITHOUT_EH) def test_0004_ip4_irb_1(self): - """ ACL IPv4 routed -> bridged, L3 ACL deny""" - self.run_test_ip46_routed_to_bridged(False, False, False, - self.WITHOUT_EH) + """ACL IPv4 routed -> bridged, L3 ACL deny""" + self.run_test_ip46_routed_to_bridged(False, False, False, self.WITHOUT_EH) def test_0005_ip6_irb_1(self): - """ ACL IPv6 bridged -> routed, L2 ACL deny """ - self.run_test_ip46_bridged_to_routed(True, True, False, - self.WITHOUT_EH) + """ACL IPv6 bridged -> routed, L2 ACL deny""" + self.run_test_ip46_bridged_to_routed(True, True, False, self.WITHOUT_EH) def test_0006_ip6_irb_1(self): - """ ACL IPv6 bridged -> routed, L3 ACL deny """ - self.run_test_ip46_bridged_to_routed(False, True, False, - self.WITHOUT_EH) + """ACL IPv6 bridged -> routed, L3 ACL deny""" + self.run_test_ip46_bridged_to_routed(False, True, False, self.WITHOUT_EH) def test_0007_ip6_irb_1(self): - """ ACL IPv4 bridged -> routed, L2 ACL deny """ - self.run_test_ip46_bridged_to_routed(True, False, False, - self.WITHOUT_EH) + """ACL IPv4 bridged -> routed, L2 ACL deny""" + self.run_test_ip46_bridged_to_routed(True, False, False, self.WITHOUT_EH) def test_0008_ip6_irb_1(self): - """ ACL IPv4 bridged -> routed, L3 ACL deny """ - self.run_test_ip46_bridged_to_routed(False, False, False, - self.WITHOUT_EH) + """ACL IPv4 bridged -> routed, L3 ACL deny""" + self.run_test_ip46_bridged_to_routed(False, False, False, self.WITHOUT_EH) # Stateful ACL tests def test_0101_ip6_irb_1(self): - """ ACL IPv6 routed -> bridged, L2 ACL permit+reflect""" - self.run_test_ip46_routed_to_bridged_and_back(True, True, - self.WITHOUT_EH) + """ACL IPv6 routed -> bridged, L2 ACL permit+reflect""" + self.run_test_ip46_routed_to_bridged_and_back(True, True, self.WITHOUT_EH) def test_0102_ip6_irb_1(self): - """ ACL IPv6 bridged -> routed, L2 ACL permit+reflect""" - self.run_test_ip46_bridged_to_routed_and_back(True, True, - self.WITHOUT_EH) + """ACL IPv6 bridged -> routed, L2 ACL permit+reflect""" + self.run_test_ip46_bridged_to_routed_and_back(True, True, self.WITHOUT_EH) def test_0103_ip6_irb_1(self): - """ ACL IPv4 routed -> bridged, L2 ACL permit+reflect""" - self.run_test_ip46_routed_to_bridged_and_back(True, False, - self.WITHOUT_EH) + """ACL IPv4 routed -> bridged, L2 ACL permit+reflect""" + self.run_test_ip46_routed_to_bridged_and_back(True, False, self.WITHOUT_EH) def test_0104_ip6_irb_1(self): - """ ACL IPv4 bridged -> routed, L2 ACL permit+reflect""" - self.run_test_ip46_bridged_to_routed_and_back(True, False, - self.WITHOUT_EH) + """ACL IPv4 bridged -> routed, L2 ACL permit+reflect""" + self.run_test_ip46_bridged_to_routed_and_back(True, False, self.WITHOUT_EH) def test_0111_ip6_irb_1(self): - """ ACL IPv6 routed -> bridged, L3 ACL permit+reflect""" - self.run_test_ip46_routed_to_bridged_and_back(False, True, - self.WITHOUT_EH) + """ACL IPv6 routed -> bridged, L3 ACL permit+reflect""" + self.run_test_ip46_routed_to_bridged_and_back(False, True, self.WITHOUT_EH) def test_0112_ip6_irb_1(self): - """ ACL IPv6 bridged -> routed, L3 ACL permit+reflect""" - self.run_test_ip46_bridged_to_routed_and_back(False, True, - self.WITHOUT_EH) + """ACL IPv6 bridged -> routed, L3 ACL permit+reflect""" + self.run_test_ip46_bridged_to_routed_and_back(False, True, self.WITHOUT_EH) def test_0113_ip6_irb_1(self): - """ ACL IPv4 routed -> bridged, L3 ACL permit+reflect""" - self.run_test_ip46_routed_to_bridged_and_back(False, False, - self.WITHOUT_EH) + """ACL IPv4 routed -> bridged, L3 ACL permit+reflect""" + self.run_test_ip46_routed_to_bridged_and_back(False, False, self.WITHOUT_EH) def test_0114_ip6_irb_1(self): - """ ACL IPv4 bridged -> routed, L3 ACL permit+reflect""" - self.run_test_ip46_bridged_to_routed_and_back(False, False, - self.WITHOUT_EH) + """ACL IPv4 bridged -> routed, L3 ACL permit+reflect""" + self.run_test_ip46_bridged_to_routed_and_back(False, False, self.WITHOUT_EH) # A block of tests with extension headers def test_1001_ip6_irb_1(self): - """ ACL IPv6+EH routed -> bridged, L2 ACL deny""" - self.run_test_ip46_routed_to_bridged(True, True, False, - self.WITH_EH) + """ACL IPv6+EH routed -> bridged, L2 ACL deny""" + self.run_test_ip46_routed_to_bridged(True, True, False, self.WITH_EH) def test_1002_ip6_irb_1(self): - """ ACL IPv6+EH routed -> bridged, L3 ACL deny""" - self.run_test_ip46_routed_to_bridged(False, True, False, - self.WITH_EH) + """ACL IPv6+EH routed -> bridged, L3 ACL deny""" + self.run_test_ip46_routed_to_bridged(False, True, False, self.WITH_EH) def test_1005_ip6_irb_1(self): - """ ACL IPv6+EH bridged -> routed, L2 ACL deny """ - self.run_test_ip46_bridged_to_routed(True, True, False, - self.WITH_EH) + """ACL IPv6+EH bridged -> routed, L2 ACL deny""" + self.run_test_ip46_bridged_to_routed(True, True, False, self.WITH_EH) def test_1006_ip6_irb_1(self): - """ ACL IPv6+EH bridged -> routed, L3 ACL deny """ - self.run_test_ip46_bridged_to_routed(False, True, False, - self.WITH_EH) + """ACL IPv6+EH bridged -> routed, L3 ACL deny""" + self.run_test_ip46_bridged_to_routed(False, True, False, self.WITH_EH) def test_1101_ip6_irb_1(self): - """ ACL IPv6+EH routed -> bridged, L2 ACL permit+reflect""" - self.run_test_ip46_routed_to_bridged_and_back(True, True, - self.WITH_EH) + """ACL IPv6+EH routed -> bridged, L2 ACL permit+reflect""" + self.run_test_ip46_routed_to_bridged_and_back(True, True, self.WITH_EH) def test_1102_ip6_irb_1(self): - """ ACL IPv6+EH bridged -> routed, L2 ACL permit+reflect""" - self.run_test_ip46_bridged_to_routed_and_back(True, True, - self.WITH_EH) + """ACL IPv6+EH bridged -> routed, L2 ACL permit+reflect""" + self.run_test_ip46_bridged_to_routed_and_back(True, True, self.WITH_EH) def test_1111_ip6_irb_1(self): - """ ACL IPv6+EH routed -> bridged, L3 ACL permit+reflect""" - self.run_test_ip46_routed_to_bridged_and_back(False, True, - self.WITH_EH) + """ACL IPv6+EH routed -> bridged, L3 ACL permit+reflect""" + self.run_test_ip46_routed_to_bridged_and_back(False, True, self.WITH_EH) def test_1112_ip6_irb_1(self): - """ ACL IPv6+EH bridged -> routed, L3 ACL permit+reflect""" - self.run_test_ip46_bridged_to_routed_and_back(False, True, - self.WITH_EH) + """ACL IPv6+EH bridged -> routed, L3 ACL permit+reflect""" + self.run_test_ip46_bridged_to_routed_and_back(False, True, self.WITH_EH) # IPv4 with "MF" bit set def test_1201_ip6_irb_1(self): - """ ACL IPv4+MF routed -> bridged, L2 ACL deny""" - self.run_test_ip46_routed_to_bridged(True, False, False, - self.WITH_EH) + """ACL IPv4+MF routed -> bridged, L2 ACL deny""" + self.run_test_ip46_routed_to_bridged(True, False, False, self.WITH_EH) def test_1202_ip6_irb_1(self): - """ ACL IPv4+MF routed -> bridged, L3 ACL deny""" - self.run_test_ip46_routed_to_bridged(False, False, False, - self.WITH_EH) + """ACL IPv4+MF routed -> bridged, L3 ACL deny""" + self.run_test_ip46_routed_to_bridged(False, False, False, self.WITH_EH) def test_1205_ip6_irb_1(self): - """ ACL IPv4+MF bridged -> routed, L2 ACL deny """ - self.run_test_ip46_bridged_to_routed(True, False, False, - self.WITH_EH) + """ACL IPv4+MF bridged -> routed, L2 ACL deny""" + self.run_test_ip46_bridged_to_routed(True, False, False, self.WITH_EH) def test_1206_ip6_irb_1(self): - """ ACL IPv4+MF bridged -> routed, L3 ACL deny """ - self.run_test_ip46_bridged_to_routed(False, False, False, - self.WITH_EH) + """ACL IPv4+MF bridged -> routed, L3 ACL deny""" + self.run_test_ip46_bridged_to_routed(False, False, False, self.WITH_EH) def test_1301_ip6_irb_1(self): - """ ACL IPv4+MF routed -> bridged, L2 ACL permit+reflect""" - self.run_test_ip46_routed_to_bridged_and_back(True, False, - self.WITH_EH) + """ACL IPv4+MF routed -> bridged, L2 ACL permit+reflect""" + self.run_test_ip46_routed_to_bridged_and_back(True, False, self.WITH_EH) def test_1302_ip6_irb_1(self): - """ ACL IPv4+MF bridged -> routed, L2 ACL permit+reflect""" - self.run_test_ip46_bridged_to_routed_and_back(True, False, - self.WITH_EH) + """ACL IPv4+MF bridged -> routed, L2 ACL permit+reflect""" + self.run_test_ip46_bridged_to_routed_and_back(True, False, self.WITH_EH) def test_1311_ip6_irb_1(self): - """ ACL IPv4+MF routed -> bridged, L3 ACL permit+reflect""" - self.run_test_ip46_routed_to_bridged_and_back(False, False, - self.WITH_EH) + """ACL IPv4+MF routed -> bridged, L3 ACL permit+reflect""" + self.run_test_ip46_routed_to_bridged_and_back(False, False, self.WITH_EH) def test_1312_ip6_irb_1(self): - """ ACL IPv4+MF bridged -> routed, L3 ACL permit+reflect""" - self.run_test_ip46_bridged_to_routed_and_back(False, False, - self.WITH_EH) + """ACL IPv4+MF bridged -> routed, L3 ACL permit+reflect""" + self.run_test_ip46_bridged_to_routed_and_back(False, False, self.WITH_EH) + # Stateful ACL tests with stateful ICMP def test_1401_ip6_irb_1(self): - """ IPv6 routed -> bridged, L2 ACL permit+reflect, ICMP reflect""" - self.run_test_ip46_routed_to_bridged_and_back(True, True, - self.WITHOUT_EH, - self.STATEFUL_ICMP) + """IPv6 routed -> bridged, L2 ACL permit+reflect, ICMP reflect""" + self.run_test_ip46_routed_to_bridged_and_back( + True, True, self.WITHOUT_EH, self.STATEFUL_ICMP + ) def test_1402_ip6_irb_1(self): - """ IPv6 bridged -> routed, L2 ACL permit+reflect, ICMP reflect""" - self.run_test_ip46_bridged_to_routed_and_back(True, True, - self.WITHOUT_EH, - self.STATEFUL_ICMP) + """IPv6 bridged -> routed, L2 ACL permit+reflect, ICMP reflect""" + self.run_test_ip46_bridged_to_routed_and_back( + True, True, self.WITHOUT_EH, self.STATEFUL_ICMP + ) def test_1403_ip4_irb_1(self): - """ IPv4 routed -> bridged, L2 ACL permit+reflect, ICMP reflect""" - self.run_test_ip46_routed_to_bridged_and_back(True, False, - self.WITHOUT_EH, - self.STATEFUL_ICMP) + """IPv4 routed -> bridged, L2 ACL permit+reflect, ICMP reflect""" + self.run_test_ip46_routed_to_bridged_and_back( + True, False, self.WITHOUT_EH, self.STATEFUL_ICMP + ) def test_1404_ip4_irb_1(self): - """ IPv4 bridged -> routed, L2 ACL permit+reflect, ICMP reflect""" - self.run_test_ip46_bridged_to_routed_and_back(True, False, - self.WITHOUT_EH, - self.STATEFUL_ICMP) + """IPv4 bridged -> routed, L2 ACL permit+reflect, ICMP reflect""" + self.run_test_ip46_bridged_to_routed_and_back( + True, False, self.WITHOUT_EH, self.STATEFUL_ICMP + ) def test_1411_ip6_irb_1(self): - """ IPv6 routed -> bridged, L3 ACL permit+reflect, ICMP reflect""" - self.run_test_ip46_routed_to_bridged_and_back(False, True, - self.WITHOUT_EH, - self.STATEFUL_ICMP) + """IPv6 routed -> bridged, L3 ACL permit+reflect, ICMP reflect""" + self.run_test_ip46_routed_to_bridged_and_back( + False, True, self.WITHOUT_EH, self.STATEFUL_ICMP + ) def test_1412_ip6_irb_1(self): - """ IPv6 bridged -> routed, L3 ACL permit+reflect, ICMP reflect""" - self.run_test_ip46_bridged_to_routed_and_back(False, True, - self.WITHOUT_EH, - self.STATEFUL_ICMP) + """IPv6 bridged -> routed, L3 ACL permit+reflect, ICMP reflect""" + self.run_test_ip46_bridged_to_routed_and_back( + False, True, self.WITHOUT_EH, self.STATEFUL_ICMP + ) def test_1413_ip4_irb_1(self): - """ IPv4 routed -> bridged, L3 ACL permit+reflect, ICMP reflect""" - self.run_test_ip46_routed_to_bridged_and_back(False, False, - self.WITHOUT_EH, - self.STATEFUL_ICMP) + """IPv4 routed -> bridged, L3 ACL permit+reflect, ICMP reflect""" + self.run_test_ip46_routed_to_bridged_and_back( + False, False, self.WITHOUT_EH, self.STATEFUL_ICMP + ) def test_1414_ip4_irb_1(self): - """ IPv4 bridged -> routed, L3 ACL permit+reflect, ICMP reflect""" - self.run_test_ip46_bridged_to_routed_and_back(False, False, - self.WITHOUT_EH, - self.STATEFUL_ICMP) + """IPv4 bridged -> routed, L3 ACL permit+reflect, ICMP reflect""" + self.run_test_ip46_bridged_to_routed_and_back( + False, False, self.WITHOUT_EH, self.STATEFUL_ICMP + ) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_acl_plugin_macip.py b/test/test_acl_plugin_macip.py index 5353c16d331..6a1ba589182 100644 --- a/test/test_acl_plugin_macip.py +++ b/test/test_acl_plugin_macip.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 from __future__ import print_function + """ACL plugin - MACIP tests """ import binascii @@ -20,10 +21,21 @@ from scapy.layers.inet6 import IPv6 from framework import VppTestCase, VppTestRunner from vpp_lo_interface import VppLoInterface from vpp_l2 import L2_PORT_TYPE -from vpp_sub_interface import L2_VTR_OP, VppSubInterface, VppDot1QSubint, \ - VppDot1ADSubint -from vpp_acl import AclRule, VppAcl, VppAclInterface, VppEtypeWhitelist, \ - VppMacipAclInterface, VppMacipAcl, MacipRule +from vpp_sub_interface import ( + L2_VTR_OP, + VppSubInterface, + VppDot1QSubint, + VppDot1ADSubint, +) +from vpp_acl import ( + AclRule, + VppAcl, + VppAclInterface, + VppEtypeWhitelist, + VppMacipAclInterface, + VppMacipAcl, + MacipRule, +) from vpp_papi import MACAddress @@ -79,16 +91,13 @@ class MethodHolder(VppTestCase): VppDot1QSubint(cls, cls.pg1, 10), VppDot1ADSubint(cls, cls.pg2, 20, 300, 400), VppDot1QSubint(cls, cls.pg3, 30), - VppDot1ADSubint(cls, cls.pg3, 40, 600, 700)] + VppDot1ADSubint(cls, cls.pg3, 40, 600, 700), + ] - cls.subifs[0].set_vtr(L2_VTR_OP.L2_POP_1, - inner=10, push1q=1) - cls.subifs[1].set_vtr(L2_VTR_OP.L2_POP_2, - outer=300, inner=400, push1q=1) - cls.subifs[2].set_vtr(L2_VTR_OP.L2_POP_1, - inner=30, push1q=1) - cls.subifs[3].set_vtr(L2_VTR_OP.L2_POP_2, - outer=600, inner=700, push1q=1) + cls.subifs[0].set_vtr(L2_VTR_OP.L2_POP_1, inner=10, push1q=1) + cls.subifs[1].set_vtr(L2_VTR_OP.L2_POP_2, outer=300, inner=400, push1q=1) + cls.subifs[2].set_vtr(L2_VTR_OP.L2_POP_1, inner=30, push1q=1) + cls.subifs[3].set_vtr(L2_VTR_OP.L2_POP_2, outer=600, inner=700, push1q=1) cls.interfaces = list(cls.pg_interfaces) cls.interfaces.extend(cls.lo_interfaces) @@ -99,16 +108,22 @@ class MethodHolder(VppTestCase): # Create BD with MAC learning enabled and put interfaces to this BD cls.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=cls.loop0.sw_if_index, bd_id=cls.bd_id, - port_type=L2_PORT_TYPE.BVI) + rx_sw_if_index=cls.loop0.sw_if_index, + bd_id=cls.bd_id, + port_type=L2_PORT_TYPE.BVI, + ) cls.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=cls.pg0.sw_if_index, bd_id=cls.bd_id) + rx_sw_if_index=cls.pg0.sw_if_index, bd_id=cls.bd_id + ) cls.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=cls.pg1.sw_if_index, bd_id=cls.bd_id) + rx_sw_if_index=cls.pg1.sw_if_index, bd_id=cls.bd_id + ) cls.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=cls.subifs[0].sw_if_index, bd_id=cls.bd_id) + rx_sw_if_index=cls.subifs[0].sw_if_index, bd_id=cls.bd_id + ) cls.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=cls.subifs[1].sw_if_index, bd_id=cls.bd_id) + rx_sw_if_index=cls.subifs[1].sw_if_index, bd_id=cls.bd_id + ) # Configure IPv4/6 addresses on loop interface and routed interface cls.loop0.config_ip4() @@ -122,7 +137,7 @@ class MethodHolder(VppTestCase): cls.loop0.generate_remote_hosts(cls.remote_hosts_count) # Modify host mac addresses to have different OUI parts for i in range(2, cls.remote_hosts_count + 2): - mac = cls.loop0.remote_hosts[i-2]._mac.split(':') + mac = cls.loop0.remote_hosts[i - 2]._mac.split(":") mac[2] = format(int(mac[2], 16) + i, "02x") cls.loop0.remote_hosts[i - 2]._mac = ":".join(mac) @@ -198,18 +213,19 @@ class MethodHolder(VppTestCase): """ return acls - def create_rules(self, mac_type=EXACT_MAC, ip_type=EXACT_IP, - acl_count=1, rules_count=None): + def create_rules( + self, mac_type=EXACT_MAC, ip_type=EXACT_IP, acl_count=1, rules_count=None + ): acls = [] if rules_count is None: rules_count = [1] src_mac = int("220000dead00", 16) - for acl in range(2, (acl_count+1) * 2): + for acl in range(2, (acl_count + 1) * 2): rules = [] host = random.choice(self.loop0.remote_hosts) is_ip6 = acl % 2 - ip4 = host.ip4.split('.') - ip6 = list(unpack('<16B', inet_pton(AF_INET6, host.ip6))) + ip4 = host.ip4.split(".") + ip6 = list(unpack("<16B", inet_pton(AF_INET6, host.ip6))) if ip_type == self.EXACT_IP: prefix_len4 = 32 @@ -241,11 +257,12 @@ class MethodHolder(VppTestCase): if mac_type == self.WILD_MAC: mac = "00:00:00:00:00:00" elif mac_type == self.OUI_MAC: - mac = ':'.join(re.findall('..', '{:02x}'.format( - src_mac))[:3])+":00:00:00" + mac = ( + ":".join(re.findall("..", "{:02x}".format(src_mac))[:3]) + + ":00:00:00" + ) else: - mac = ':'.join(re.findall( - '..', '{:02x}'.format(src_mac))) + mac = ":".join(re.findall("..", "{:02x}".format(src_mac))) if ip_type == self.EXACT_IP: ip4[3] = random.randint(100, 200) @@ -255,14 +272,16 @@ class MethodHolder(VppTestCase): ip4[3] = 0 ip6[7] = random.randint(100, 200) ip6[15] = 0 - ip_pack = b'' + ip_pack = b"" for j in range(0, len(ip)): - ip_pack += pack('<B', int(ip[j])) - - rule = MacipRule(is_permit=self.PERMIT, - src_prefix=ip_network((ip_pack, ip_len)), - src_mac=MACAddress(mac).packed, - src_mac_mask=MACAddress(mask).packed) + ip_pack += pack("<B", int(ip[j])) + + rule = MacipRule( + is_permit=self.PERMIT, + src_prefix=ip_network((ip_pack, ip_len)), + src_mac=MACAddress(mac).packed, + src_mac_mask=MACAddress(mask).packed, + ) rules.append(rule) if ip_type == self.WILD_IP: break @@ -281,8 +300,8 @@ class MethodHolder(VppTestCase): def verify_macip_acls(self, acl_count, rules_count, expected_count=2): reply = self.macip_acl_dump_debug() - for acl in range(2, (acl_count+1) * 2): - self.assertEqual(reply[acl - 2].count, rules_count[acl//2-1]) + for acl in range(2, (acl_count + 1) * 2): + self.assertEqual(reply[acl - 2].count, rules_count[acl // 2 - 1]) self.vapi.macip_acl_interface_get() @@ -292,8 +311,17 @@ class MethodHolder(VppTestCase): reply = self.vapi.macip_acl_interface_get() self.assertEqual(reply.count, expected_count) - def create_stream(self, mac_type, ip_type, packet_count, - src_if, dst_if, traffic, is_ip6, tags=PERMIT_TAGS): + def create_stream( + self, + mac_type, + ip_type, + packet_count, + src_if, + dst_if, + traffic, + is_ip6, + tags=PERMIT_TAGS, + ): # exact MAC and exact IP # exact MAC and subnet of IPs # exact MAC and wildcard IP @@ -329,7 +357,7 @@ class MethodHolder(VppTestCase): if traffic == self.BRIDGED: if is_permit: src_mac = remote_dst_host._mac - dst_mac = 'de:ad:00:00:00:00' + dst_mac = "de:ad:00:00:00:00" src_ip4 = remote_dst_host.ip4 dst_ip4 = src_if.remote_ip4 src_ip6 = remote_dst_host.ip6 @@ -337,8 +365,8 @@ class MethodHolder(VppTestCase): ip_permit = src_ip6 if is_ip6 else src_ip4 mac_permit = src_mac if denyMAC: - mac = src_mac.split(':') - mac[0] = format(int(mac[0], 16)+1, "02x") + mac = src_mac.split(":") + mac[0] = format(int(mac[0], 16) + 1, "02x") src_mac = ":".join(mac) if is_ip6: src_ip6 = ip_permit @@ -362,7 +390,7 @@ class MethodHolder(VppTestCase): ip_permit = src_ip6 if is_ip6 else src_ip4 mac_permit = src_mac if denyMAC: - mac = src_mac.split(':') + mac = src_mac.split(":") mac[0] = format(int(mac[0], 16) + 1, "02x") src_mac = ":".join(mac) if is_ip6: @@ -385,7 +413,7 @@ class MethodHolder(VppTestCase): payload = "to be blocked" if mac_type == self.WILD_MAC: - mac = src_mac.split(':') + mac = src_mac.split(":") for i in range(1, 5): mac[i] = format(random.randint(0, 255), "02x") src_mac = ":".join(mac) @@ -395,7 +423,7 @@ class MethodHolder(VppTestCase): ip_rule = src_ip6 if is_ip6 else src_ip4 if is_ip6: if ip_type != self.EXACT_IP: - sub_ip = list(unpack('<16B', inet_pton(AF_INET6, ip_rule))) + sub_ip = list(unpack("<16B", inet_pton(AF_INET6, ip_rule))) if ip_type == self.WILD_IP: sub_ip[0] = random.randint(240, 254) sub_ip[1] = random.randint(230, 239) @@ -406,13 +434,12 @@ class MethodHolder(VppTestCase): sub_ip[2] = int(sub_ip[2]) + 1 sub_ip[14] = random.randint(100, 199) sub_ip[15] = random.randint(200, 255) - packed_src_ip6 = b''.join( - [scapy.compat.chb(x) for x in sub_ip]) + packed_src_ip6 = b"".join([scapy.compat.chb(x) for x in sub_ip]) src_ip6 = inet_ntop(AF_INET6, packed_src_ip6) packet /= IPv6(src=src_ip6, dst=dst_ip6) else: if ip_type != self.EXACT_IP: - sub_ip = ip_rule.split('.') + sub_ip = ip_rule.split(".") if ip_type == self.WILD_IP: sub_ip[0] = random.randint(1, 49) sub_ip[1] = random.randint(50, 99) @@ -420,15 +447,15 @@ class MethodHolder(VppTestCase): sub_ip[3] = random.randint(200, 255) elif ip_type == self.SUBNET_IP: if denyIP: - sub_ip[1] = int(sub_ip[1])+1 + sub_ip[1] = int(sub_ip[1]) + 1 sub_ip[2] = random.randint(100, 199) sub_ip[3] = random.randint(200, 255) - src_ip4 = '.'.join(['{!s}'.format(x) for x in sub_ip]) + src_ip4 = ".".join(["{!s}".format(x) for x in sub_ip]) packet /= IP(src=src_ip4, dst=dst_ip4, frag=0, flags=0) - packet /= UDP(sport=src_port, dport=dst_port)/Raw(payload) + packet /= UDP(sport=src_port, dport=dst_port) / Raw(payload) - packet[Raw].load += b" mac:%s" % src_mac.encode('utf-8') + packet[Raw].load += b" mac:%s" % src_mac.encode("utf-8") size = self.pg_if_packet_sizes[p % len(self.pg_if_packet_sizes)] if isinstance(src_if, VppSubInterface): @@ -466,8 +493,8 @@ class MethodHolder(VppTestCase): mac_rule = "00:00:00:00:00:00" mac_mask = "00:00:00:00:00:00" elif mac_type == self.OUI_MAC: - mac = src_mac.split(':') - mac[3] = mac[4] = mac[5] = '00' + mac = src_mac.split(":") + mac[3] = mac[4] = mac[5] = "00" mac_rule = ":".join(mac) mac_mask = "ff:ff:ff:00:00:00" @@ -477,11 +504,10 @@ class MethodHolder(VppTestCase): else: ip = src_ip6 if ip_type == self.SUBNET_IP: - sub_ip = list(unpack('<16B', inet_pton(AF_INET6, ip))) + sub_ip = list(unpack("<16B", inet_pton(AF_INET6, ip))) for i in range(8, 16): sub_ip[i] = 0 - packed_ip = b''.join( - [scapy.compat.chb(x) for x in sub_ip]) + packed_ip = b"".join([scapy.compat.chb(x) for x in sub_ip]) ip = inet_ntop(AF_INET6, packed_ip) else: if ip_type == self.WILD_IP: @@ -489,8 +515,8 @@ class MethodHolder(VppTestCase): else: ip = src_ip4 if ip_type == self.SUBNET_IP: - sub_ip = ip.split('.') - sub_ip[2] = sub_ip[3] = '0' + sub_ip = ip.split(".") + sub_ip[2] = sub_ip[3] = "0" ip = ".".join(sub_ip) prefix_len = 128 if is_ip6 else 32 @@ -508,21 +534,22 @@ class MethodHolder(VppTestCase): rule_prefix_len = 128 if packet.haslayer(IPv6) else 32 rule_l3_layer = IPv6 if packet.haslayer(IPv6) else IP if packet.haslayer(IPv6): - rule_l4_proto = packet[UDP].overload_fields[IPv6]['nh'] + rule_l4_proto = packet[UDP].overload_fields[IPv6]["nh"] else: rule_l4_proto = packet[IP].proto - src_network = ip_network( - (packet[rule_l3_layer].src, rule_prefix_len)) - dst_network = ip_network( - (packet[rule_l3_layer].dst, rule_prefix_len)) - acl_rule = AclRule(is_permit=is_permit, proto=rule_l4_proto, - src_prefix=src_network, - dst_prefix=dst_network, - sport_from=rule_l4_sport, - sport_to=rule_l4_sport, - dport_from=rule_l4_dport, - dport_to=rule_l4_dport) + src_network = ip_network((packet[rule_l3_layer].src, rule_prefix_len)) + dst_network = ip_network((packet[rule_l3_layer].dst, rule_prefix_len)) + acl_rule = AclRule( + is_permit=is_permit, + proto=rule_l4_proto, + src_prefix=src_network, + dst_prefix=dst_network, + sport_from=rule_l4_sport, + sport_to=rule_l4_sport, + dport_from=rule_l4_dport, + dport_to=rule_l4_dport, + ) acl_rules.append(acl_rule) if mac_type == self.WILD_MAC and ip_type == self.WILD_IP and p > 0: @@ -531,10 +558,10 @@ class MethodHolder(VppTestCase): if is_permit: macip_rule = MacipRule( is_permit=is_permit, - src_prefix=ip_network( - (ip_rule, prefix_len)), + src_prefix=ip_network((ip_rule, prefix_len)), src_mac=MACAddress(mac_rule).packed, - src_mac_mask=MACAddress(mac_mask).packed) + src_mac_mask=MACAddress(mac_mask).packed, + ) macip_rules.append(macip_rule) # deny all other packets @@ -544,16 +571,22 @@ class MethodHolder(VppTestCase): is_permit=0, src_prefix=network, src_mac=MACAddress("00:00:00:00:00:00").packed, - src_mac_mask=MACAddress("00:00:00:00:00:00").packed) + src_mac_mask=MACAddress("00:00:00:00:00:00").packed, + ) macip_rules.append(macip_rule) network = IPv6Network((0, 0)) if is_ip6 else IPv4Network((0, 0)) - acl_rule = AclRule(is_permit=0, src_prefix=network, dst_prefix=network, - sport_from=0, sport_to=0, dport_from=0, dport_to=0) + acl_rule = AclRule( + is_permit=0, + src_prefix=network, + dst_prefix=network, + sport_from=0, + sport_to=0, + dport_from=0, + dport_to=0, + ) acl_rules.append(acl_rule) - return {'stream': packets, - 'macip_rules': macip_rules, - 'acl_rules': acl_rules} + return {"stream": packets, "macip_rules": macip_rules, "acl_rules": acl_rules} def verify_capture(self, stream, capture, is_ip6): """ @@ -582,10 +615,20 @@ class MethodHolder(VppTestCase): # data = p[Raw].load.split(':',1)[1]) # print(p[p_l3].src, data) - def run_traffic(self, mac_type, ip_type, traffic, is_ip6, packets, - do_not_expected_capture=False, tags=None, - apply_rules=True, isMACIP=True, permit_tags=PERMIT_TAGS, - try_replace=False): + def run_traffic( + self, + mac_type, + ip_type, + traffic, + is_ip6, + packets, + do_not_expected_capture=False, + tags=None, + apply_rules=True, + isMACIP=True, + permit_tags=PERMIT_TAGS, + try_replace=False, + ): self.reset_packet_infos() if tags is None: @@ -619,21 +662,28 @@ class MethodHolder(VppTestCase): else: return - test_dict = self.create_stream(mac_type, ip_type, packets, - src_if, dst_if, - traffic, is_ip6, - tags=permit_tags) + test_dict = self.create_stream( + mac_type, + ip_type, + packets, + src_if, + dst_if, + traffic, + is_ip6, + tags=permit_tags, + ) if apply_rules: if isMACIP: - self.acl = VppMacipAcl(self, rules=test_dict['macip_rules']) + self.acl = VppMacipAcl(self, rules=test_dict["macip_rules"]) else: - self.acl = VppAcl(self, rules=test_dict['acl_rules']) + self.acl = VppAcl(self, rules=test_dict["acl_rules"]) self.acl.add_vpp_config() if isMACIP: self.acl_if = VppMacipAclInterface( - self, sw_if_index=tx_if.sw_if_index, acls=[self.acl]) + self, sw_if_index=tx_if.sw_if_index, acls=[self.acl] + ) self.acl_if.add_vpp_config() dump = self.acl_if.dump() @@ -641,45 +691,51 @@ class MethodHolder(VppTestCase): self.assertEqual(dump[0].acls[0], self.acl.acl_index) else: self.acl_if = VppAclInterface( - self, sw_if_index=tx_if.sw_if_index, n_input=1, - acls=[self.acl]) + self, sw_if_index=tx_if.sw_if_index, n_input=1, acls=[self.acl] + ) self.acl_if.add_vpp_config() else: if hasattr(self, "acl_if"): self.acl_if.remove_vpp_config() if try_replace and hasattr(self, "acl"): if isMACIP: - self.acl.modify_vpp_config(test_dict['macip_rules']) + self.acl.modify_vpp_config(test_dict["macip_rules"]) else: - self.acl.modify_vpp_config(test_dict['acl_rules']) + self.acl.modify_vpp_config(test_dict["acl_rules"]) if not isinstance(src_if, VppSubInterface): - tx_if.add_stream(test_dict['stream']) + tx_if.add_stream(test_dict["stream"]) else: - tx_if.parent.add_stream(test_dict['stream']) + tx_if.parent.add_stream(test_dict["stream"]) self.pg_enable_capture(self.pg_interfaces) self.pg_start() if do_not_expected_capture: rx_if.get_capture(0) else: - if traffic == self.BRIDGED and mac_type == self.WILD_MAC and \ - ip_type == self.WILD_IP: + if ( + traffic == self.BRIDGED + and mac_type == self.WILD_MAC + and ip_type == self.WILD_IP + ): capture = rx_if.get_capture(packets) else: capture = rx_if.get_capture( - self.get_packet_count_for_if_idx(dst_if.sw_if_index)) - self.verify_capture(test_dict['stream'], capture, is_ip6) + self.get_packet_count_for_if_idx(dst_if.sw_if_index) + ) + self.verify_capture(test_dict["stream"], capture, is_ip6) if not isMACIP: if hasattr(self, "acl_if"): self.acl_if.remove_vpp_config() if hasattr(self, "acl"): self.acl.remove_vpp_config() - def run_test_acls(self, mac_type, ip_type, acl_count, - rules_count, traffic=None, ip=None): - self.apply_macip_rules(self.create_rules(mac_type, ip_type, acl_count, - rules_count)) + def run_test_acls( + self, mac_type, ip_type, acl_count, rules_count, traffic=None, ip=None + ): + self.apply_macip_rules( + self.create_rules(mac_type, ip_type, acl_count, rules_count) + ) self.verify_macip_acls(acl_count, rules_count) if traffic is not None: @@ -698,134 +754,104 @@ class TestMACIP_IP4(MethodHolder): super(TestMACIP_IP4, cls).tearDownClass() def test_acl_bridged_ip4_exactMAC_exactIP(self): - """ IP4 MACIP exactMAC|exactIP ACL bridged traffic - """ - self.run_traffic(self.EXACT_MAC, self.EXACT_IP, - self.BRIDGED, self.IS_IP4, 9) + """IP4 MACIP exactMAC|exactIP ACL bridged traffic""" + self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.BRIDGED, self.IS_IP4, 9) def test_acl_bridged_ip4_exactMAC_subnetIP(self): - """ IP4 MACIP exactMAC|subnetIP ACL bridged traffic - """ + """IP4 MACIP exactMAC|subnetIP ACL bridged traffic""" - self.run_traffic(self.EXACT_MAC, self.SUBNET_IP, - self.BRIDGED, self.IS_IP4, 9) + self.run_traffic(self.EXACT_MAC, self.SUBNET_IP, self.BRIDGED, self.IS_IP4, 9) def test_acl_bridged_ip4_exactMAC_wildIP(self): - """ IP4 MACIP exactMAC|wildIP ACL bridged traffic - """ + """IP4 MACIP exactMAC|wildIP ACL bridged traffic""" - self.run_traffic(self.EXACT_MAC, self.WILD_IP, - self.BRIDGED, self.IS_IP4, 9) + self.run_traffic(self.EXACT_MAC, self.WILD_IP, self.BRIDGED, self.IS_IP4, 9) def test_acl_bridged_ip4_ouiMAC_exactIP(self): - """ IP4 MACIP ouiMAC|exactIP ACL bridged traffic - """ + """IP4 MACIP ouiMAC|exactIP ACL bridged traffic""" - self.run_traffic(self.OUI_MAC, self.EXACT_IP, - self.BRIDGED, self.IS_IP4, 3) + self.run_traffic(self.OUI_MAC, self.EXACT_IP, self.BRIDGED, self.IS_IP4, 3) def test_acl_bridged_ip4_ouiMAC_subnetIP(self): - """ IP4 MACIP ouiMAC|subnetIP ACL bridged traffic - """ + """IP4 MACIP ouiMAC|subnetIP ACL bridged traffic""" - self.run_traffic(self.OUI_MAC, self.SUBNET_IP, - self.BRIDGED, self.IS_IP4, 9) + self.run_traffic(self.OUI_MAC, self.SUBNET_IP, self.BRIDGED, self.IS_IP4, 9) def test_acl_bridged_ip4_ouiMAC_wildIP(self): - """ IP4 MACIP ouiMAC|wildIP ACL bridged traffic - """ + """IP4 MACIP ouiMAC|wildIP ACL bridged traffic""" - self.run_traffic(self.OUI_MAC, self.WILD_IP, - self.BRIDGED, self.IS_IP4, 9) + self.run_traffic(self.OUI_MAC, self.WILD_IP, self.BRIDGED, self.IS_IP4, 9) def test_ac_bridgedl_ip4_wildMAC_exactIP(self): - """ IP4 MACIP wildcardMAC|exactIP ACL bridged traffic - """ + """IP4 MACIP wildcardMAC|exactIP ACL bridged traffic""" - self.run_traffic(self.WILD_MAC, self.EXACT_IP, - self.BRIDGED, self.IS_IP4, 9) + self.run_traffic(self.WILD_MAC, self.EXACT_IP, self.BRIDGED, self.IS_IP4, 9) def test_acl_bridged_ip4_wildMAC_subnetIP(self): - """ IP4 MACIP wildcardMAC|subnetIP ACL bridged traffic - """ + """IP4 MACIP wildcardMAC|subnetIP ACL bridged traffic""" - self.run_traffic(self.WILD_MAC, self.SUBNET_IP, - self.BRIDGED, self.IS_IP4, 9) + self.run_traffic(self.WILD_MAC, self.SUBNET_IP, self.BRIDGED, self.IS_IP4, 9) def test_acl_bridged_ip4_wildMAC_wildIP(self): - """ IP4 MACIP wildcardMAC|wildIP ACL bridged traffic - """ + """IP4 MACIP wildcardMAC|wildIP ACL bridged traffic""" - self.run_traffic(self.WILD_MAC, self.WILD_IP, - self.BRIDGED, self.IS_IP4, 9) + self.run_traffic(self.WILD_MAC, self.WILD_IP, self.BRIDGED, self.IS_IP4, 9) def test_acl_routed_ip4_exactMAC_exactIP(self): - """ IP4 MACIP exactMAC|exactIP ACL routed traffic - """ - self.run_traffic(self.EXACT_MAC, self.EXACT_IP, - self.ROUTED, self.IS_IP4, 9) + """IP4 MACIP exactMAC|exactIP ACL routed traffic""" + self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.ROUTED, self.IS_IP4, 9) def test_acl_routed_ip4_exactMAC_subnetIP(self): - """ IP4 MACIP exactMAC|subnetIP ACL routed traffic - """ - self.run_traffic(self.EXACT_MAC, self.SUBNET_IP, - self.ROUTED, self.IS_IP4, 9) + """IP4 MACIP exactMAC|subnetIP ACL routed traffic""" + self.run_traffic(self.EXACT_MAC, self.SUBNET_IP, self.ROUTED, self.IS_IP4, 9) def test_acl_routed_ip4_exactMAC_wildIP(self): - """ IP4 MACIP exactMAC|wildIP ACL routed traffic - """ - self.run_traffic(self.EXACT_MAC, self.WILD_IP, - self.ROUTED, self.IS_IP4, 9) + """IP4 MACIP exactMAC|wildIP ACL routed traffic""" + self.run_traffic(self.EXACT_MAC, self.WILD_IP, self.ROUTED, self.IS_IP4, 9) def test_acl_routed_ip4_ouiMAC_exactIP(self): - """ IP4 MACIP ouiMAC|exactIP ACL routed traffic - """ + """IP4 MACIP ouiMAC|exactIP ACL routed traffic""" - self.run_traffic(self.OUI_MAC, self.EXACT_IP, - self.ROUTED, self.IS_IP4, 9) + self.run_traffic(self.OUI_MAC, self.EXACT_IP, self.ROUTED, self.IS_IP4, 9) def test_acl_routed_ip4_ouiMAC_subnetIP(self): - """ IP4 MACIP ouiMAC|subnetIP ACL routed traffic - """ + """IP4 MACIP ouiMAC|subnetIP ACL routed traffic""" - self.run_traffic(self.OUI_MAC, self.SUBNET_IP, - self.ROUTED, self.IS_IP4, 9) + self.run_traffic(self.OUI_MAC, self.SUBNET_IP, self.ROUTED, self.IS_IP4, 9) def test_acl_routed_ip4_ouiMAC_wildIP(self): - """ IP4 MACIP ouiMAC|wildIP ACL routed traffic - """ + """IP4 MACIP ouiMAC|wildIP ACL routed traffic""" - self.run_traffic(self.OUI_MAC, self.WILD_IP, - self.ROUTED, self.IS_IP4, 9) + self.run_traffic(self.OUI_MAC, self.WILD_IP, self.ROUTED, self.IS_IP4, 9) def test_acl_routed_ip4_wildMAC_exactIP(self): - """ IP4 MACIP wildcardMAC|exactIP ACL routed traffic - """ + """IP4 MACIP wildcardMAC|exactIP ACL routed traffic""" - self.run_traffic(self.WILD_MAC, self.EXACT_IP, - self.ROUTED, self.IS_IP4, 9) + self.run_traffic(self.WILD_MAC, self.EXACT_IP, self.ROUTED, self.IS_IP4, 9) def test_acl_routed_ip4_wildMAC_subnetIP(self): - """ IP4 MACIP wildcardMAC|subnetIP ACL routed traffic - """ + """IP4 MACIP wildcardMAC|subnetIP ACL routed traffic""" - self.run_traffic(self.WILD_MAC, self.SUBNET_IP, - self.ROUTED, self.IS_IP4, 9) + self.run_traffic(self.WILD_MAC, self.SUBNET_IP, self.ROUTED, self.IS_IP4, 9) def test_acl_routed_ip4_wildMAC_wildIP(self): - """ IP4 MACIP wildcardMAC|wildIP ACL - """ + """IP4 MACIP wildcardMAC|wildIP ACL""" - self.run_traffic(self.WILD_MAC, self.WILD_IP, - self.ROUTED, self.IS_IP4, 9) + self.run_traffic(self.WILD_MAC, self.WILD_IP, self.ROUTED, self.IS_IP4, 9) def test_acl_replace_traffic_ip4(self): - """ MACIP replace ACL with IP4 traffic - """ - self.run_traffic(self.OUI_MAC, self.SUBNET_IP, - self.BRIDGED, self.IS_IP4, 9, try_replace=True) - self.run_traffic(self.EXACT_MAC, self.EXACT_IP, - self.BRIDGED, self.IS_IP4, 9, try_replace=True) + """MACIP replace ACL with IP4 traffic""" + self.run_traffic( + self.OUI_MAC, self.SUBNET_IP, self.BRIDGED, self.IS_IP4, 9, try_replace=True + ) + self.run_traffic( + self.EXACT_MAC, + self.EXACT_IP, + self.BRIDGED, + self.IS_IP4, + 9, + try_replace=True, + ) class TestMACIP_IP6(MethodHolder): @@ -840,138 +866,108 @@ class TestMACIP_IP6(MethodHolder): super(TestMACIP_IP6, cls).tearDownClass() def test_acl_bridged_ip6_exactMAC_exactIP(self): - """ IP6 MACIP exactMAC|exactIP ACL bridged traffic - """ + """IP6 MACIP exactMAC|exactIP ACL bridged traffic""" - self.run_traffic(self.EXACT_MAC, self.EXACT_IP, - self.BRIDGED, self.IS_IP6, 9) + self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.BRIDGED, self.IS_IP6, 9) def test_acl_bridged_ip6_exactMAC_subnetIP(self): - """ IP6 MACIP exactMAC|subnetIP ACL bridged traffic - """ + """IP6 MACIP exactMAC|subnetIP ACL bridged traffic""" - self.run_traffic(self.EXACT_MAC, self.SUBNET_IP, - self.BRIDGED, self.IS_IP6, 9) + self.run_traffic(self.EXACT_MAC, self.SUBNET_IP, self.BRIDGED, self.IS_IP6, 9) def test_acl_bridged_ip6_exactMAC_wildIP(self): - """ IP6 MACIP exactMAC|wildIP ACL bridged traffic - """ + """IP6 MACIP exactMAC|wildIP ACL bridged traffic""" - self.run_traffic(self.EXACT_MAC, self.WILD_IP, - self.BRIDGED, self.IS_IP6, 9) + self.run_traffic(self.EXACT_MAC, self.WILD_IP, self.BRIDGED, self.IS_IP6, 9) def test_acl_bridged_ip6_ouiMAC_exactIP(self): - """ IP6 MACIP oui_MAC|exactIP ACL bridged traffic - """ + """IP6 MACIP oui_MAC|exactIP ACL bridged traffic""" - self.run_traffic(self.OUI_MAC, self.EXACT_IP, - self.BRIDGED, self.IS_IP6, 9) + self.run_traffic(self.OUI_MAC, self.EXACT_IP, self.BRIDGED, self.IS_IP6, 9) def test_acl_bridged_ip6_ouiMAC_subnetIP(self): - """ IP6 MACIP ouiMAC|subnetIP ACL bridged traffic - """ + """IP6 MACIP ouiMAC|subnetIP ACL bridged traffic""" - self.run_traffic(self.OUI_MAC, self.SUBNET_IP, - self.BRIDGED, self.IS_IP6, 9) + self.run_traffic(self.OUI_MAC, self.SUBNET_IP, self.BRIDGED, self.IS_IP6, 9) def test_acl_bridged_ip6_ouiMAC_wildIP(self): - """ IP6 MACIP ouiMAC|wildIP ACL bridged traffic - """ + """IP6 MACIP ouiMAC|wildIP ACL bridged traffic""" - self.run_traffic(self.OUI_MAC, self.WILD_IP, - self.BRIDGED, self.IS_IP6, 9) + self.run_traffic(self.OUI_MAC, self.WILD_IP, self.BRIDGED, self.IS_IP6, 9) def test_acl_bridged_ip6_wildMAC_exactIP(self): - """ IP6 MACIP wildcardMAC|exactIP ACL bridged traffic - """ + """IP6 MACIP wildcardMAC|exactIP ACL bridged traffic""" - self.run_traffic(self.WILD_MAC, self.EXACT_IP, - self.BRIDGED, self.IS_IP6, 9) + self.run_traffic(self.WILD_MAC, self.EXACT_IP, self.BRIDGED, self.IS_IP6, 9) def test_acl_bridged_ip6_wildMAC_subnetIP(self): - """ IP6 MACIP wildcardMAC|subnetIP ACL bridged traffic - """ + """IP6 MACIP wildcardMAC|subnetIP ACL bridged traffic""" - self.run_traffic(self.WILD_MAC, self.SUBNET_IP, - self.BRIDGED, self.IS_IP6, 9) + self.run_traffic(self.WILD_MAC, self.SUBNET_IP, self.BRIDGED, self.IS_IP6, 9) def test_acl_bridged_ip6_wildMAC_wildIP(self): - """ IP6 MACIP wildcardMAC|wildIP ACL bridged traffic - """ + """IP6 MACIP wildcardMAC|wildIP ACL bridged traffic""" - self.run_traffic(self.WILD_MAC, self.WILD_IP, - self.BRIDGED, self.IS_IP6, 9) + self.run_traffic(self.WILD_MAC, self.WILD_IP, self.BRIDGED, self.IS_IP6, 9) def test_acl_routed_ip6_exactMAC_exactIP(self): - """ IP6 MACIP exactMAC|exactIP ACL routed traffic - """ + """IP6 MACIP exactMAC|exactIP ACL routed traffic""" - self.run_traffic(self.EXACT_MAC, self.EXACT_IP, - self.ROUTED, self.IS_IP6, 9) + self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.ROUTED, self.IS_IP6, 9) def test_acl_routed_ip6_exactMAC_subnetIP(self): - """ IP6 MACIP exactMAC|subnetIP ACL routed traffic - """ + """IP6 MACIP exactMAC|subnetIP ACL routed traffic""" - self.run_traffic(self.EXACT_MAC, self.SUBNET_IP, - self.ROUTED, self.IS_IP6, 9) + self.run_traffic(self.EXACT_MAC, self.SUBNET_IP, self.ROUTED, self.IS_IP6, 9) def test_acl_routed_ip6_exactMAC_wildIP(self): - """ IP6 MACIP exactMAC|wildIP ACL routed traffic - """ + """IP6 MACIP exactMAC|wildIP ACL routed traffic""" - self.run_traffic(self.EXACT_MAC, self.WILD_IP, - self.ROUTED, self.IS_IP6, 9) + self.run_traffic(self.EXACT_MAC, self.WILD_IP, self.ROUTED, self.IS_IP6, 9) def test_acl_routed_ip6_ouiMAC_exactIP(self): - """ IP6 MACIP ouiMAC|exactIP ACL routed traffic - """ + """IP6 MACIP ouiMAC|exactIP ACL routed traffic""" - self.run_traffic(self.OUI_MAC, self.EXACT_IP, - self.ROUTED, self.IS_IP6, 9) + self.run_traffic(self.OUI_MAC, self.EXACT_IP, self.ROUTED, self.IS_IP6, 9) def test_acl_routed_ip6_ouiMAC_subnetIP(self): - """ IP6 MACIP ouiMAC|subnetIP ACL routed traffic - """ + """IP6 MACIP ouiMAC|subnetIP ACL routed traffic""" - self.run_traffic(self.OUI_MAC, self.SUBNET_IP, - self.ROUTED, self.IS_IP6, 9) + self.run_traffic(self.OUI_MAC, self.SUBNET_IP, self.ROUTED, self.IS_IP6, 9) def test_acl_routed_ip6_ouiMAC_wildIP(self): - """ IP6 MACIP ouiMAC|wildIP ACL routed traffic - """ + """IP6 MACIP ouiMAC|wildIP ACL routed traffic""" - self.run_traffic(self.OUI_MAC, self.WILD_IP, - self.ROUTED, self.IS_IP6, 9) + self.run_traffic(self.OUI_MAC, self.WILD_IP, self.ROUTED, self.IS_IP6, 9) def test_acl_routed_ip6_wildMAC_exactIP(self): - """ IP6 MACIP wildcardMAC|exactIP ACL routed traffic - """ + """IP6 MACIP wildcardMAC|exactIP ACL routed traffic""" - self.run_traffic(self.WILD_MAC, self.EXACT_IP, - self.ROUTED, self.IS_IP6, 9) + self.run_traffic(self.WILD_MAC, self.EXACT_IP, self.ROUTED, self.IS_IP6, 9) def test_acl_routed_ip6_wildMAC_subnetIP(self): - """ IP6 MACIP wildcardMAC|subnetIP ACL routed traffic - """ + """IP6 MACIP wildcardMAC|subnetIP ACL routed traffic""" - self.run_traffic(self.WILD_MAC, self.SUBNET_IP, - self.ROUTED, self.IS_IP6, 9) + self.run_traffic(self.WILD_MAC, self.SUBNET_IP, self.ROUTED, self.IS_IP6, 9) def test_acl_routed_ip6_wildMAC_wildIP(self): - """ IP6 MACIP wildcardMAC|wildIP ACL - """ + """IP6 MACIP wildcardMAC|wildIP ACL""" - self.run_traffic(self.WILD_MAC, self.WILD_IP, - self.ROUTED, self.IS_IP6, 9) + self.run_traffic(self.WILD_MAC, self.WILD_IP, self.ROUTED, self.IS_IP6, 9) def test_acl_replace_traffic_ip6(self): - """ MACIP replace ACL with IP6 traffic - """ - self.run_traffic(self.OUI_MAC, self.SUBNET_IP, - self.BRIDGED, self.IS_IP6, 9, try_replace=True) - self.run_traffic(self.EXACT_MAC, self.EXACT_IP, - self.BRIDGED, self.IS_IP6, 9, try_replace=True) + """MACIP replace ACL with IP6 traffic""" + self.run_traffic( + self.OUI_MAC, self.SUBNET_IP, self.BRIDGED, self.IS_IP6, 9, try_replace=True + ) + self.run_traffic( + self.EXACT_MAC, + self.EXACT_IP, + self.BRIDGED, + self.IS_IP6, + 9, + try_replace=True, + ) class TestMACIP(MethodHolder): @@ -986,73 +982,76 @@ class TestMACIP(MethodHolder): super(TestMACIP, cls).tearDownClass() def test_acl_1_2(self): - """ MACIP ACL with 2 entries - """ + """MACIP ACL with 2 entries""" self.run_test_acls(self.EXACT_MAC, self.WILD_IP, 1, [2]) def test_acl_1_5(self): - """ MACIP ACL with 5 entries - """ + """MACIP ACL with 5 entries""" self.run_test_acls(self.EXACT_MAC, self.SUBNET_IP, 1, [5]) def test_acl_1_10(self): - """ MACIP ACL with 10 entries - """ + """MACIP ACL with 10 entries""" self.run_test_acls(self.EXACT_MAC, self.EXACT_IP, 1, [10]) def test_acl_1_20(self): - """ MACIP ACL with 20 entries - """ + """MACIP ACL with 20 entries""" self.run_test_acls(self.OUI_MAC, self.WILD_IP, 1, [20]) def test_acl_1_50(self): - """ MACIP ACL with 50 entries - """ + """MACIP ACL with 50 entries""" self.run_test_acls(self.OUI_MAC, self.SUBNET_IP, 1, [50]) def test_acl_1_100(self): - """ MACIP ACL with 100 entries - """ + """MACIP ACL with 100 entries""" self.run_test_acls(self.OUI_MAC, self.EXACT_IP, 1, [100]) def test_acl_2_X(self): - """ MACIP 2 ACLs each with 100+ entries - """ + """MACIP 2 ACLs each with 100+ entries""" self.run_test_acls(self.OUI_MAC, self.SUBNET_IP, 2, [100, 200]) def test_acl_10_X(self): - """ MACIP 10 ACLs each with 100+ entries - """ + """MACIP 10 ACLs each with 100+ entries""" - self.run_test_acls(self.EXACT_MAC, self.EXACT_IP, 10, - [100, 120, 140, 160, 180, 200, 210, 220, 230, 240]) + self.run_test_acls( + self.EXACT_MAC, + self.EXACT_IP, + 10, + [100, 120, 140, 160, 180, 200, 210, 220, 230, 240], + ) def test_acl_10_X_traffic_ip4(self): - """ MACIP 10 ACLs each with 100+ entries with IP4 traffic - """ + """MACIP 10 ACLs each with 100+ entries with IP4 traffic""" - self.run_test_acls(self.EXACT_MAC, self.EXACT_IP, 10, - [100, 120, 140, 160, 180, 200, 210, 220, 230, 240], - self.BRIDGED, self.IS_IP4) + self.run_test_acls( + self.EXACT_MAC, + self.EXACT_IP, + 10, + [100, 120, 140, 160, 180, 200, 210, 220, 230, 240], + self.BRIDGED, + self.IS_IP4, + ) def test_acl_10_X_traffic_ip6(self): - """ MACIP 10 ACLs each with 100+ entries with IP6 traffic - """ + """MACIP 10 ACLs each with 100+ entries with IP6 traffic""" - self.run_test_acls(self.EXACT_MAC, self.EXACT_IP, 10, - [100, 120, 140, 160, 180, 200, 210, 220, 230, 240], - self.BRIDGED, self.IS_IP6) + self.run_test_acls( + self.EXACT_MAC, + self.EXACT_IP, + 10, + [100, 120, 140, 160, 180, 200, 210, 220, 230, 240], + self.BRIDGED, + self.IS_IP6, + ) def test_acl_replace(self): - """ MACIP replace ACL - """ + """MACIP replace ACL""" r1 = self.create_rules(acl_count=3, rules_count=[2, 2, 2]) r2 = self.create_rules(mac_type=self.OUI_MAC, ip_type=self.SUBNET_IP) @@ -1069,17 +1068,15 @@ class TestMACIP(MethodHolder): # verify changes self.assertEqual(len(acls_before), len(acls_after)) for acl1, acl2 in zip( - acls_before[:2]+acls_before[4:], - acls_after[:2]+acls_after[4:]): + acls_before[:2] + acls_before[4:], acls_after[:2] + acls_after[4:] + ): self.assertEqual(len(acl1), len(acl2)) self.assertEqual(len(acl1.r), len(acl2.r)) for r1, r2 in zip(acl1.r, acl2.r): self.assertEqual(len(acl1.r), len(acl2.r)) self.assertEqual(acl1.r, acl2.r) - for acl1, acl2 in zip( - acls_before[2:4], - acls_after[2:4]): + for acl1, acl2 in zip(acls_before[2:4], acls_after[2:4]): self.assertEqual(len(acl1), len(acl2)) self.assertNotEqual(len(acl1.r), len(acl2.r)) @@ -1088,38 +1085,40 @@ class TestMACIP(MethodHolder): self.assertNotEqual(acl1.r, acl2.r) def test_delete_intf(self): - """ MACIP ACL delete intf with acl - """ + """MACIP ACL delete intf with acl""" - intf_count = len(self.interfaces)+1 + intf_count = len(self.interfaces) + 1 intf = [] macip_alcs = self.apply_macip_rules( - self.create_rules(acl_count=3, rules_count=[3, 5, 4])) + self.create_rules(acl_count=3, rules_count=[3, 5, 4]) + ) intf.append(VppLoInterface(self)) intf.append(VppLoInterface(self)) sw_if_index0 = intf[0].sw_if_index macip_acl_if0 = VppMacipAclInterface( - self, sw_if_index=sw_if_index0, acls=[macip_alcs[1]]) + self, sw_if_index=sw_if_index0, acls=[macip_alcs[1]] + ) macip_acl_if0.add_vpp_config() reply = self.vapi.macip_acl_interface_get() - self.assertEqual(reply.count, intf_count+1) + self.assertEqual(reply.count, intf_count + 1) self.assertEqual(reply.acls[sw_if_index0], 1) sw_if_index1 = intf[1].sw_if_index macip_acl_if1 = VppMacipAclInterface( - self, sw_if_index=sw_if_index1, acls=[macip_alcs[0]]) + self, sw_if_index=sw_if_index1, acls=[macip_alcs[0]] + ) macip_acl_if1.add_vpp_config() reply = self.vapi.macip_acl_interface_get() - self.assertEqual(reply.count, intf_count+2) + self.assertEqual(reply.count, intf_count + 2) self.assertEqual(reply.acls[sw_if_index1], 0) intf[0].remove_vpp_config() reply = self.vapi.macip_acl_interface_get() - self.assertEqual(reply.count, intf_count+2) + self.assertEqual(reply.count, intf_count + 2) self.assertEqual(reply.acls[sw_if_index0], 4294967295) self.assertEqual(reply.acls[sw_if_index1], 0) @@ -1128,14 +1127,16 @@ class TestMACIP(MethodHolder): sw_if_index2 = intf[2].sw_if_index sw_if_index3 = intf[3].sw_if_index macip_acl_if2 = VppMacipAclInterface( - self, sw_if_index=sw_if_index2, acls=[macip_alcs[1]]) + self, sw_if_index=sw_if_index2, acls=[macip_alcs[1]] + ) macip_acl_if2.add_vpp_config() macip_acl_if3 = VppMacipAclInterface( - self, sw_if_index=sw_if_index3, acls=[macip_alcs[1]]) + self, sw_if_index=sw_if_index3, acls=[macip_alcs[1]] + ) macip_acl_if3.add_vpp_config() reply = self.vapi.macip_acl_interface_get() - self.assertEqual(reply.count, intf_count+3) + self.assertEqual(reply.count, intf_count + 3) self.assertEqual(reply.acls[sw_if_index1], 0) self.assertEqual(reply.acls[sw_if_index2], 1) self.assertEqual(reply.acls[sw_if_index3], 1) @@ -1150,7 +1151,7 @@ class TestMACIP(MethodHolder): intf[1].remove_vpp_config() reply = self.vapi.macip_acl_interface_get() - self.assertEqual(reply.count, intf_count+3) + self.assertEqual(reply.count, intf_count + 3) self.assertEqual(reply.acls[sw_if_index0], 4294967295) self.assertEqual(reply.acls[sw_if_index1], 4294967295) self.assertEqual(reply.acls[sw_if_index2], 4294967295) @@ -1174,14 +1175,28 @@ class TestACL_dot1q_bridged(MethodHolder): super(TestACL_dot1q_bridged, cls).tearDownClass() def test_acl_bridged_ip4_subif_dot1q(self): - """ IP4 ACL SubIf Dot1Q bridged traffic""" - self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.BRIDGED, - self.IS_IP4, 9, tags=self.DOT1Q, isMACIP=False) + """IP4 ACL SubIf Dot1Q bridged traffic""" + self.run_traffic( + self.EXACT_MAC, + self.EXACT_IP, + self.BRIDGED, + self.IS_IP4, + 9, + tags=self.DOT1Q, + isMACIP=False, + ) def test_acl_bridged_ip6_subif_dot1q(self): - """ IP6 ACL SubIf Dot1Q bridged traffic""" - self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.BRIDGED, - self.IS_IP6, 9, tags=self.DOT1Q, isMACIP=False) + """IP6 ACL SubIf Dot1Q bridged traffic""" + self.run_traffic( + self.EXACT_MAC, + self.EXACT_IP, + self.BRIDGED, + self.IS_IP6, + 9, + tags=self.DOT1Q, + isMACIP=False, + ) class TestACL_dot1ad_bridged(MethodHolder): @@ -1196,14 +1211,28 @@ class TestACL_dot1ad_bridged(MethodHolder): super(TestACL_dot1ad_bridged, cls).tearDownClass() def test_acl_bridged_ip4_subif_dot1ad(self): - """ IP4 ACL SubIf Dot1AD bridged traffic""" - self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.BRIDGED, - self.IS_IP4, 9, tags=self.DOT1AD, isMACIP=False) + """IP4 ACL SubIf Dot1AD bridged traffic""" + self.run_traffic( + self.EXACT_MAC, + self.EXACT_IP, + self.BRIDGED, + self.IS_IP4, + 9, + tags=self.DOT1AD, + isMACIP=False, + ) def test_acl_bridged_ip6_subif_dot1ad(self): - """ IP6 ACL SubIf Dot1AD bridged traffic""" - self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.BRIDGED, - self.IS_IP6, 9, tags=self.DOT1AD, isMACIP=False) + """IP6 ACL SubIf Dot1AD bridged traffic""" + self.run_traffic( + self.EXACT_MAC, + self.EXACT_IP, + self.BRIDGED, + self.IS_IP6, + 9, + tags=self.DOT1AD, + isMACIP=False, + ) class TestACL_dot1q_routed(MethodHolder): @@ -1218,26 +1247,56 @@ class TestACL_dot1q_routed(MethodHolder): super(TestACL_dot1q_routed, cls).tearDownClass() def test_acl_routed_ip4_subif_dot1q(self): - """ IP4 ACL SubIf Dot1Q routed traffic""" - self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.ROUTED, - self.IS_IP4, 9, tags=self.DOT1Q, isMACIP=False) + """IP4 ACL SubIf Dot1Q routed traffic""" + self.run_traffic( + self.EXACT_MAC, + self.EXACT_IP, + self.ROUTED, + self.IS_IP4, + 9, + tags=self.DOT1Q, + isMACIP=False, + ) def test_acl_routed_ip6_subif_dot1q(self): - """ IP6 ACL SubIf Dot1Q routed traffic""" - self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.ROUTED, - self.IS_IP6, 9, tags=self.DOT1Q, isMACIP=False) + """IP6 ACL SubIf Dot1Q routed traffic""" + self.run_traffic( + self.EXACT_MAC, + self.EXACT_IP, + self.ROUTED, + self.IS_IP6, + 9, + tags=self.DOT1Q, + isMACIP=False, + ) def test_acl_routed_ip4_subif_dot1q_deny_by_tags(self): - """ IP4 ACL SubIf wrong tags Dot1Q routed traffic""" - self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.ROUTED, - self.IS_IP4, 9, True, tags=self.DOT1Q, isMACIP=False, - permit_tags=self.DENY_TAGS) + """IP4 ACL SubIf wrong tags Dot1Q routed traffic""" + self.run_traffic( + self.EXACT_MAC, + self.EXACT_IP, + self.ROUTED, + self.IS_IP4, + 9, + True, + tags=self.DOT1Q, + isMACIP=False, + permit_tags=self.DENY_TAGS, + ) def test_acl_routed_ip6_subif_dot1q_deny_by_tags(self): - """ IP6 ACL SubIf wrong tags Dot1Q routed traffic""" - self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.ROUTED, - self.IS_IP6, 9, True, tags=self.DOT1Q, isMACIP=False, - permit_tags=self.DENY_TAGS) + """IP6 ACL SubIf wrong tags Dot1Q routed traffic""" + self.run_traffic( + self.EXACT_MAC, + self.EXACT_IP, + self.ROUTED, + self.IS_IP6, + 9, + True, + tags=self.DOT1Q, + isMACIP=False, + permit_tags=self.DENY_TAGS, + ) class TestACL_dot1ad_routed(MethodHolder): @@ -1252,27 +1311,57 @@ class TestACL_dot1ad_routed(MethodHolder): super(TestACL_dot1ad_routed, cls).tearDownClass() def test_acl_routed_ip6_subif_dot1ad(self): - """ IP6 ACL SubIf Dot1AD routed traffic""" - self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.ROUTED, - self.IS_IP6, 9, tags=self.DOT1AD, isMACIP=False) + """IP6 ACL SubIf Dot1AD routed traffic""" + self.run_traffic( + self.EXACT_MAC, + self.EXACT_IP, + self.ROUTED, + self.IS_IP6, + 9, + tags=self.DOT1AD, + isMACIP=False, + ) def test_acl_routed_ip4_subif_dot1ad(self): - """ IP4 ACL SubIf Dot1AD routed traffic""" - self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.ROUTED, - self.IS_IP4, 9, tags=self.DOT1AD, isMACIP=False) + """IP4 ACL SubIf Dot1AD routed traffic""" + self.run_traffic( + self.EXACT_MAC, + self.EXACT_IP, + self.ROUTED, + self.IS_IP4, + 9, + tags=self.DOT1AD, + isMACIP=False, + ) def test_acl_routed_ip6_subif_dot1ad_deny_by_tags(self): - """ IP6 ACL SubIf wrong tags Dot1AD routed traffic""" - self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.ROUTED, - self.IS_IP6, 9, True, tags=self.DOT1AD, isMACIP=False, - permit_tags=self.DENY_TAGS) + """IP6 ACL SubIf wrong tags Dot1AD routed traffic""" + self.run_traffic( + self.EXACT_MAC, + self.EXACT_IP, + self.ROUTED, + self.IS_IP6, + 9, + True, + tags=self.DOT1AD, + isMACIP=False, + permit_tags=self.DENY_TAGS, + ) def test_acl_routed_ip4_subif_dot1ad_deny_by_tags(self): - """ IP4 ACL SubIf wrong tags Dot1AD routed traffic""" - self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.ROUTED, - self.IS_IP4, 9, True, tags=self.DOT1AD, isMACIP=False, - permit_tags=self.DENY_TAGS) - - -if __name__ == '__main__': + """IP4 ACL SubIf wrong tags Dot1AD routed traffic""" + self.run_traffic( + self.EXACT_MAC, + self.EXACT_IP, + self.ROUTED, + self.IS_IP4, + 9, + True, + tags=self.DOT1AD, + isMACIP=False, + permit_tags=self.DENY_TAGS, + ) + + +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_adl.py b/test/test_adl.py index 0463e258013..f58147d2d58 100644 --- a/test/test_adl.py +++ b/test/test_adl.py @@ -7,7 +7,7 @@ from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath class TestAdl(VppTestCase): - """ Allow/Deny Plugin Unit Test Cases """ + """Allow/Deny Plugin Unit Test Cases""" @classmethod def setUpClass(cls): @@ -24,80 +24,86 @@ class TestAdl(VppTestCase): super(TestAdl, self).tearDown() def test_adl1_unittest(self): - """ Plugin API Test """ - cmds = ["loop create\n", - "set int ip address loop0 192.168.1.1/24\n", - "set int ip6 table loop0 0\n", - "set int ip address loop0 2001:db01::1/64\n", - "set int state loop0 up\n", - "packet-generator new {\n" - " name ip4\n" - " limit 100\n" - " rate 0\n" - " size 128-128\n" - " interface loop0\n" - " node adl-input\n" - " data { IP4: 1.2.40 -> 3cfd.fed0.b6c8\n" - " UDP: 192.168.1.2-192.168.1.10 -> 192.168.2.1\n" - " UDP: 1234 -> 2345\n" - " incrementing 114\n" - " }\n" - " }\n", - "packet-generator new {\n" - " name ip6-allow\n" - " limit 50\n" - " rate 0\n" - " size 128-128\n" - " interface loop0\n" - " node adl-input\n" - " data { IP6: 1.2.40 -> 3cfd.fed0.b6c8\n" - " UDP: 2001:db01::2 -> 2001:db01::1\n" - " UDP: 1234 -> 2345\n" - " incrementing 80\n" - " }\n" - " }\n", - "packet-generator new {\n" - " name ip6-drop\n" - " limit 50\n" - " rate 0\n" - " size 128-128\n" - " interface loop0\n" - " node adl-input\n" - " data { IP6: 1.2.40 -> 3cfd.fed0.b6c8\n" - " UDP: 2001:db01::3 -> 2001:db01::1\n" - " UDP: 1234 -> 2345\n" - " incrementing 80\n" - " }\n" - " }\n", - "ip table 1\n", - "ip route add 192.168.2.1/32 via drop\n", - "ip route add table 1 192.168.1.2/32 via local\n", - "ip6 table 1\n", - "ip route add 2001:db01::1/128 via drop\n", - "ip route add table 1 2001:db01::2/128 via local\n", - "bin adl_interface_enable_disable loop0\n", - "bin adl_allowlist_enable_disable loop0 fib-id 1 ip4 ip6\n", - "pa en\n"] + """Plugin API Test""" + cmds = [ + "loop create\n", + "set int ip address loop0 192.168.1.1/24\n", + "set int ip6 table loop0 0\n", + "set int ip address loop0 2001:db01::1/64\n", + "set int state loop0 up\n", + "packet-generator new {\n" + " name ip4\n" + " limit 100\n" + " rate 0\n" + " size 128-128\n" + " interface loop0\n" + " node adl-input\n" + " data { IP4: 1.2.40 -> 3cfd.fed0.b6c8\n" + " UDP: 192.168.1.2-192.168.1.10 -> 192.168.2.1\n" + " UDP: 1234 -> 2345\n" + " incrementing 114\n" + " }\n" + " }\n", + "packet-generator new {\n" + " name ip6-allow\n" + " limit 50\n" + " rate 0\n" + " size 128-128\n" + " interface loop0\n" + " node adl-input\n" + " data { IP6: 1.2.40 -> 3cfd.fed0.b6c8\n" + " UDP: 2001:db01::2 -> 2001:db01::1\n" + " UDP: 1234 -> 2345\n" + " incrementing 80\n" + " }\n" + " }\n", + "packet-generator new {\n" + " name ip6-drop\n" + " limit 50\n" + " rate 0\n" + " size 128-128\n" + " interface loop0\n" + " node adl-input\n" + " data { IP6: 1.2.40 -> 3cfd.fed0.b6c8\n" + " UDP: 2001:db01::3 -> 2001:db01::1\n" + " UDP: 1234 -> 2345\n" + " incrementing 80\n" + " }\n" + " }\n", + "ip table 1\n", + "ip route add 192.168.2.1/32 via drop\n", + "ip route add table 1 192.168.1.2/32 via local\n", + "ip6 table 1\n", + "ip route add 2001:db01::1/128 via drop\n", + "ip route add table 1 2001:db01::2/128 via local\n", + "bin adl_interface_enable_disable loop0\n", + "bin adl_allowlist_enable_disable loop0 fib-id 1 ip4 ip6\n", + "pa en\n", + ] for cmd in cmds: r = self.vapi.cli_return_response(cmd) if r.retval != 0: - if hasattr(r, 'reply'): + if hasattr(r, "reply"): self.logger.info(cmd + " FAIL reply " + r.reply) else: self.logger.info(cmd + " FAIL retval " + str(r.retval)) total_pkts = self.statistics.get_err_counter( - "/err/adl-input/Allow/Deny packets processed") + "/err/adl-input/Allow/Deny packets processed" + ) self.assertEqual(total_pkts, 200) ip4_allow = self.statistics.get_err_counter( - "/err/ip4-adl-allowlist/ip4 allowlist allowed") + "/err/ip4-adl-allowlist/ip4 allowlist allowed" + ) self.assertEqual(ip4_allow, 12) ip6_allow = self.statistics.get_err_counter( - "/err/ip6-adl-allowlist/ip6 allowlist allowed") + "/err/ip6-adl-allowlist/ip6 allowlist allowed" + ) self.assertEqual(ip6_allow, 50) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_api_client.py b/test/test_api_client.py index ec44be7e370..200835b0878 100644 --- a/test/test_api_client.py +++ b/test/test_api_client.py @@ -7,14 +7,15 @@ from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath class TestAPIClient(VppTestCase): - """ API Internal client Test Cases """ + """API Internal client Test Cases""" def test_client_unittest(self): - """ Internal API client """ + """Internal API client""" error = self.vapi.cli("test api internal") if error: self.logger.critical(error) - self.assertNotIn('failed', error) + self.assertNotIn("failed", error) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_api_trace.py b/test/test_api_trace.py index 6524878a10d..ae70666d66c 100644 --- a/test/test_api_trace.py +++ b/test/test_api_trace.py @@ -6,7 +6,7 @@ import json class TestJsonApiTrace(VppTestCase): - """ JSON API trace related tests """ + """JSON API trace related tests""" @classmethod def setUpClass(cls): @@ -24,24 +24,24 @@ class TestJsonApiTrace(VppTestCase): def test_json_api_trace_save(self): self.vapi.show_version() - fname = 'test_api_trace-%d.json' % self.vpp.pid + fname = "test_api_trace-%d.json" % self.vpp.pid tmp_api_trace = "/tmp/%s" % fname - fpath = '%s/%s' % (self.tempdir, fname) + fpath = "%s/%s" % (self.tempdir, fname) self.vapi.cli("api trace save-json {}".format(fname)) os.rename(tmp_api_trace, fpath) - with open(fpath, encoding='utf-8') as f: + with open(fpath, encoding="utf-8") as f: s = f.read() trace = json.loads(s) found = False for o in trace: - if o['_msgname'] == 'show_version': + if o["_msgname"] == "show_version": found = True break self.assertTrue(found) - self.assertEquals(o['_msgname'], 'show_version') + self.assertEquals(o["_msgname"], "show_version") def test_json_api_trace_replay(self): - fname = '/tmp/create_loop.json' + fname = "/tmp/create_loop.json" req = """ [ { @@ -50,14 +50,13 @@ class TestJsonApiTrace(VppTestCase): "mac_address": "00:00:00:00:00:00" }] """ - with open(fname, 'w') as f: + with open(fname, "w") as f: f.write(req) self.vapi.cli("api trace replay-json {}".format(fname)) - r = self.vapi.sw_interface_dump(name_filter='loop', - name_filter_valid=True) + r = self.vapi.sw_interface_dump(name_filter="loop", name_filter_valid=True) self.assertEqual(len(r), 1) - self.assertEqual(r[0].interface_name, 'loop0') + self.assertEqual(r[0].interface_name, "loop0") -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_arping.py b/test/test_arping.py index bd8b6250a54..a3e7e041ba1 100644 --- a/test/test_arping.py +++ b/test/test_arping.py @@ -11,7 +11,7 @@ Basic test for sanity check of arping. class TestArping(VppTestCase): - """ Arping Test Case """ + """Arping Test Case""" @classmethod def setUpClass(cls): @@ -65,7 +65,7 @@ class TestArping(VppTestCase): self.assertEqual(src, ipv6.src) def test_arping_ip4_arp_request_cli(self): - """ arping IP4 arp request CLI test """ + """arping IP4 arp request CLI test""" try: self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -81,19 +81,19 @@ class TestArping(VppTestCase): out = self.pg1.get_capture(6) for p in out: - self.verify_arping_request(p, self.pg1.local_ip4, - self.pg1.remote_ip4) + self.verify_arping_request(p, self.pg1.local_ip4, self.pg1.remote_ip4) finally: self.vapi.cli("show error") def test_arping_ip4_garp_cli(self): - """ arping ip4 gratuitous arp CLI test """ + """arping ip4 gratuitous arp CLI test""" try: self.pg_enable_capture(self.pg_interfaces) self.pg_start() - ping_cmd = ("arping gratuitous" + self.pg1.local_ip4 + - "pg1 repeat 5 interval 0.1") + ping_cmd = ( + "arping gratuitous" + self.pg1.local_ip4 + "pg1 repeat 5 interval 0.1" + ) ret = self.vapi.cli(ping_cmd) self.logger.info(ret) @@ -103,60 +103,65 @@ class TestArping(VppTestCase): out = self.pg1.get_capture(6) for p in out: - self.verify_arping_request(p, self.pg1.local_ip4, - self.pg1.local_ip4) + self.verify_arping_request(p, self.pg1.local_ip4, self.pg1.local_ip4) finally: self.vapi.cli("show error") def test_arping_ip4_arp_request_api(self): - """ arping ip4 arp request API test """ + """arping ip4 arp request API test""" try: self.pg_enable_capture(self.pg_interfaces) self.pg_start() remote_ip4 = self.pg1.remote_ip4 - ret = self.vapi.arping(address=remote_ip4, - sw_if_index=self.pg1.sw_if_index, - is_garp=0, repeat=5, interval=0.1) + ret = self.vapi.arping( + address=remote_ip4, + sw_if_index=self.pg1.sw_if_index, + is_garp=0, + repeat=5, + interval=0.1, + ) self.logger.info(ret) - ret = self.vapi.arping(address=remote_ip4, - sw_if_index=self.pg1.sw_if_index, - is_garp=0) + ret = self.vapi.arping( + address=remote_ip4, sw_if_index=self.pg1.sw_if_index, is_garp=0 + ) self.logger.info(ret) out = self.pg1.get_capture(6) for p in out: - self.verify_arping_request(p, self.pg1.local_ip4, - self.pg1.remote_ip4) + self.verify_arping_request(p, self.pg1.local_ip4, self.pg1.remote_ip4) finally: self.vapi.cli("show error") def test_arping_ip4_garp_api(self): - """ arping ip4 gratuitous arp API test """ + """arping ip4 gratuitous arp API test""" try: self.pg_enable_capture(self.pg_interfaces) self.pg_start() - ret = self.vapi.arping(address=self.pg1.local_ip4, - sw_if_index=self.pg1.sw_if_index, - is_garp=1, repeat=5, interval=0.1) + ret = self.vapi.arping( + address=self.pg1.local_ip4, + sw_if_index=self.pg1.sw_if_index, + is_garp=1, + repeat=5, + interval=0.1, + ) self.logger.info(ret) - ret = self.vapi.arping(address=self.pg1.local_ip4, - sw_if_index=self.pg1.sw_if_index, - is_garp=1) + ret = self.vapi.arping( + address=self.pg1.local_ip4, sw_if_index=self.pg1.sw_if_index, is_garp=1 + ) self.logger.info(ret) out = self.pg1.get_capture(6) for p in out: - self.verify_arping_request(p, self.pg1.local_ip4, - self.pg1.local_ip4) + self.verify_arping_request(p, self.pg1.local_ip4, self.pg1.local_ip4) finally: self.vapi.cli("show error") def test_arping_ip6_ns_cli(self): - """ arping IP6 neighbor solicitation CLI test """ + """arping IP6 neighbor solicitation CLI test""" try: self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -172,43 +177,46 @@ class TestArping(VppTestCase): out = self.pg1.get_capture(6) for p in out: - self.verify_arping_ip6_ns(p, self.pg1.local_ip6, - self.pg1.remote_ip6) + self.verify_arping_ip6_ns(p, self.pg1.local_ip6, self.pg1.remote_ip6) finally: self.vapi.cli("show error") def test_arping_ip6_ns_api(self): - """ arping ip6 neighbor solicitation API test """ + """arping ip6 neighbor solicitation API test""" try: self.pg_enable_capture(self.pg_interfaces) self.pg_start() remote_ip6 = self.pg1.remote_ip6 - ret = self.vapi.arping(address=remote_ip6, - sw_if_index=self.pg1.sw_if_index, - is_garp=0, repeat=5, interval=0.1) + ret = self.vapi.arping( + address=remote_ip6, + sw_if_index=self.pg1.sw_if_index, + is_garp=0, + repeat=5, + interval=0.1, + ) self.logger.info(ret) - ret = self.vapi.arping(address=remote_ip6, - sw_if_index=self.pg1.sw_if_index, - is_garp=0) + ret = self.vapi.arping( + address=remote_ip6, sw_if_index=self.pg1.sw_if_index, is_garp=0 + ) self.logger.info(ret) out = self.pg1.get_capture(6) for p in out: - self.verify_arping_ip6_ns(p, self.pg1.local_ip6, - self.pg1.remote_ip6) + self.verify_arping_ip6_ns(p, self.pg1.local_ip6, self.pg1.remote_ip6) finally: self.vapi.cli("show error") def test_arping_ip6_na_cli(self): - """ arping ip6 neighbor advertisement CLI test """ + """arping ip6 neighbor advertisement CLI test""" try: self.pg_enable_capture(self.pg_interfaces) self.pg_start() - ping_cmd = ("arping gratuitous" + self.pg1.local_ip6 + - "pg1 repeat 5 interval 0.1") + ping_cmd = ( + "arping gratuitous" + self.pg1.local_ip6 + "pg1 repeat 5 interval 0.1" + ) ret = self.vapi.cli(ping_cmd) self.logger.info(ret) @@ -218,34 +226,36 @@ class TestArping(VppTestCase): out = self.pg1.get_capture(6) for p in out: - self.verify_arping_ip6_na(p, self.pg1.local_ip6, - self.pg1.local_ip6) + self.verify_arping_ip6_na(p, self.pg1.local_ip6, self.pg1.local_ip6) finally: self.vapi.cli("show error") def test_arping_ip6_na_api(self): - """ arping ip6 neighbor advertisement API test """ + """arping ip6 neighbor advertisement API test""" try: self.pg_enable_capture(self.pg_interfaces) self.pg_start() - ret = self.vapi.arping(address=self.pg1.local_ip6, - sw_if_index=self.pg1.sw_if_index, - is_garp=1, repeat=5, interval=0.1) + ret = self.vapi.arping( + address=self.pg1.local_ip6, + sw_if_index=self.pg1.sw_if_index, + is_garp=1, + repeat=5, + interval=0.1, + ) self.logger.info(ret) - ret = self.vapi.arping(address=self.pg1.local_ip6, - sw_if_index=self.pg1.sw_if_index, - is_garp=1) + ret = self.vapi.arping( + address=self.pg1.local_ip6, sw_if_index=self.pg1.sw_if_index, is_garp=1 + ) self.logger.info(ret) out = self.pg1.get_capture(6) for p in out: - self.verify_arping_ip6_na(p, self.pg1.local_ip6, - self.pg1.local_ip6) + self.verify_arping_ip6_na(p, self.pg1.local_ip6, self.pg1.local_ip6) finally: self.vapi.cli("show error") -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_bfd.py b/test/test_bfd.py index d1c7b92d89d..c7ea79abfd0 100644 --- a/test/test_bfd.py +++ b/test/test_bfd.py @@ -21,8 +21,15 @@ from scapy.layers.l2 import Ether, GRE from scapy.packet import Raw from config import config -from bfd import VppBFDAuthKey, BFD, BFDAuthType, VppBFDUDPSession, \ - BFDDiagCode, BFDState, BFD_vpp_echo +from bfd import ( + VppBFDAuthKey, + BFD, + BFDAuthType, + VppBFDUDPSession, + BFDDiagCode, + BFDState, + BFD_vpp_echo, +) from framework import tag_fixme_vpp_workers from framework import VppTestCase, VppTestRunner from framework import tag_run_solo @@ -30,8 +37,7 @@ from util import ppp from vpp_ip import DpoProto from vpp_ip_route import VppIpRoute, VppRoutePath from vpp_lo_interface import VppLoInterface -from vpp_papi_provider import UnexpectedApiReturnValueError, \ - CliFailedCommandError +from vpp_papi_provider import UnexpectedApiReturnValueError, CliFailedCommandError from vpp_pg_interface import CaptureTimeoutError, is_ipv6_misc from vpp_gre_interface import VppGreInterface from vpp_papi import VppEnum @@ -46,15 +52,17 @@ class AuthKeyFactory(object): self._conf_key_ids = {} def create_random_key(self, test, auth_type=BFDAuthType.keyed_sha1): - """ create a random key with unique conf key id """ + """create a random key with unique conf key id""" conf_key_id = randint(0, 0xFFFFFFFF) while conf_key_id in self._conf_key_ids: conf_key_id = randint(0, 0xFFFFFFFF) self._conf_key_ids[conf_key_id] = 1 key = scapy.compat.raw( - bytearray([randint(0, 255) for _ in range(randint(1, 20))])) - return VppBFDAuthKey(test=test, auth_type=auth_type, - conf_key_id=conf_key_id, key=key) + bytearray([randint(0, 255) for _ in range(randint(1, 20))]) + ) + return VppBFDAuthKey( + test=test, auth_type=auth_type, conf_key_id=conf_key_id, key=key + ) class BFDAPITestCase(VppTestCase): @@ -87,7 +95,7 @@ class BFDAPITestCase(VppTestCase): self.factory = AuthKeyFactory() def test_add_bfd(self): - """ create a BFD session """ + """create a BFD session""" session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4) session.add_vpp_config() self.logger.debug("Session state is %s", session.state) @@ -97,7 +105,7 @@ class BFDAPITestCase(VppTestCase): session.remove_vpp_config() def test_double_add(self): - """ create the same BFD session twice (negative case) """ + """create the same BFD session twice (negative case)""" session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4) session.add_vpp_config() @@ -107,9 +115,8 @@ class BFDAPITestCase(VppTestCase): session.remove_vpp_config() def test_add_bfd6(self): - """ create IPv6 BFD session """ - session = VppBFDUDPSession( - self, self.pg0, self.pg0.remote_ip6, af=AF_INET6) + """create IPv6 BFD session""" + session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip6, af=AF_INET6) session.add_vpp_config() self.logger.debug("Session state is %s", session.state) session.remove_vpp_config() @@ -118,65 +125,76 @@ class BFDAPITestCase(VppTestCase): session.remove_vpp_config() def test_mod_bfd(self): - """ modify BFD session parameters """ - session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4, - desired_min_tx=50000, - required_min_rx=10000, - detect_mult=1) + """modify BFD session parameters""" + session = VppBFDUDPSession( + self, + self.pg0, + self.pg0.remote_ip4, + desired_min_tx=50000, + required_min_rx=10000, + detect_mult=1, + ) session.add_vpp_config() s = session.get_bfd_udp_session_dump_entry() - self.assert_equal(session.desired_min_tx, - s.desired_min_tx, - "desired min transmit interval") - self.assert_equal(session.required_min_rx, - s.required_min_rx, - "required min receive interval") + self.assert_equal( + session.desired_min_tx, s.desired_min_tx, "desired min transmit interval" + ) + self.assert_equal( + session.required_min_rx, s.required_min_rx, "required min receive interval" + ) self.assert_equal(session.detect_mult, s.detect_mult, "detect mult") - session.modify_parameters(desired_min_tx=session.desired_min_tx * 2, - required_min_rx=session.required_min_rx * 2, - detect_mult=session.detect_mult * 2) + session.modify_parameters( + desired_min_tx=session.desired_min_tx * 2, + required_min_rx=session.required_min_rx * 2, + detect_mult=session.detect_mult * 2, + ) s = session.get_bfd_udp_session_dump_entry() - self.assert_equal(session.desired_min_tx, - s.desired_min_tx, - "desired min transmit interval") - self.assert_equal(session.required_min_rx, - s.required_min_rx, - "required min receive interval") + self.assert_equal( + session.desired_min_tx, s.desired_min_tx, "desired min transmit interval" + ) + self.assert_equal( + session.required_min_rx, s.required_min_rx, "required min receive interval" + ) self.assert_equal(session.detect_mult, s.detect_mult, "detect mult") def test_upd_bfd(self): - """ Create/Modify w/ Update BFD session parameters """ - session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4, - desired_min_tx=50000, - required_min_rx=10000, - detect_mult=1) + """Create/Modify w/ Update BFD session parameters""" + session = VppBFDUDPSession( + self, + self.pg0, + self.pg0.remote_ip4, + desired_min_tx=50000, + required_min_rx=10000, + detect_mult=1, + ) session.upd_vpp_config() s = session.get_bfd_udp_session_dump_entry() - self.assert_equal(session.desired_min_tx, - s.desired_min_tx, - "desired min transmit interval") - self.assert_equal(session.required_min_rx, - s.required_min_rx, - "required min receive interval") + self.assert_equal( + session.desired_min_tx, s.desired_min_tx, "desired min transmit interval" + ) + self.assert_equal( + session.required_min_rx, s.required_min_rx, "required min receive interval" + ) self.assert_equal(session.detect_mult, s.detect_mult, "detect mult") - session.upd_vpp_config(desired_min_tx=session.desired_min_tx * 2, - required_min_rx=session.required_min_rx * 2, - detect_mult=session.detect_mult * 2) + session.upd_vpp_config( + desired_min_tx=session.desired_min_tx * 2, + required_min_rx=session.required_min_rx * 2, + detect_mult=session.detect_mult * 2, + ) s = session.get_bfd_udp_session_dump_entry() - self.assert_equal(session.desired_min_tx, - s.desired_min_tx, - "desired min transmit interval") - self.assert_equal(session.required_min_rx, - s.required_min_rx, - "required min receive interval") + self.assert_equal( + session.desired_min_tx, s.desired_min_tx, "desired min transmit interval" + ) + self.assert_equal( + session.required_min_rx, s.required_min_rx, "required min receive interval" + ) self.assert_equal(session.detect_mult, s.detect_mult, "detect mult") def test_add_sha1_keys(self): - """ add SHA1 keys """ + """add SHA1 keys""" key_count = 10 - keys = [self.factory.create_random_key( - self) for i in range(0, key_count)] + keys = [self.factory.create_random_key(self) for i in range(0, key_count)] for key in keys: self.assertFalse(key.query_vpp_config()) for key in keys: @@ -211,11 +229,10 @@ class BFDAPITestCase(VppTestCase): self.assertFalse(key.query_vpp_config()) def test_add_bfd_sha1(self): - """ create a BFD session (SHA1) """ + """create a BFD session (SHA1)""" key = self.factory.create_random_key(self) key.add_vpp_config() - session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4, - sha1_key=key) + session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4, sha1_key=key) session.add_vpp_config() self.logger.debug("Session state is %s", session.state) session.remove_vpp_config() @@ -224,51 +241,56 @@ class BFDAPITestCase(VppTestCase): session.remove_vpp_config() def test_double_add_sha1(self): - """ create the same BFD session twice (negative case) (SHA1) """ + """create the same BFD session twice (negative case) (SHA1)""" key = self.factory.create_random_key(self) key.add_vpp_config() - session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4, - sha1_key=key) + session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4, sha1_key=key) session.add_vpp_config() with self.assertRaises(Exception): session.add_vpp_config() def test_add_auth_nonexistent_key(self): - """ create BFD session using non-existent SHA1 (negative case) """ + """create BFD session using non-existent SHA1 (negative case)""" session = VppBFDUDPSession( - self, self.pg0, self.pg0.remote_ip4, - sha1_key=self.factory.create_random_key(self)) + self, + self.pg0, + self.pg0.remote_ip4, + sha1_key=self.factory.create_random_key(self), + ) with self.assertRaises(Exception): session.add_vpp_config() def test_shared_sha1_key(self): - """ single SHA1 key shared by multiple BFD sessions """ + """single SHA1 key shared by multiple BFD sessions""" key = self.factory.create_random_key(self) key.add_vpp_config() sessions = [ - VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4, - sha1_key=key), - VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip6, - sha1_key=key, af=AF_INET6), - VppBFDUDPSession(self, self.pg1, self.pg1.remote_ip4, - sha1_key=key), - VppBFDUDPSession(self, self.pg1, self.pg1.remote_ip6, - sha1_key=key, af=AF_INET6)] + VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4, sha1_key=key), + VppBFDUDPSession( + self, self.pg0, self.pg0.remote_ip6, sha1_key=key, af=AF_INET6 + ), + VppBFDUDPSession(self, self.pg1, self.pg1.remote_ip4, sha1_key=key), + VppBFDUDPSession( + self, self.pg1, self.pg1.remote_ip6, sha1_key=key, af=AF_INET6 + ), + ] for s in sessions: s.add_vpp_config() removed = 0 for s in sessions: e = key.get_bfd_auth_keys_dump_entry() - self.assert_equal(e.use_count, len(sessions) - removed, - "Use count for shared key") + self.assert_equal( + e.use_count, len(sessions) - removed, "Use count for shared key" + ) s.remove_vpp_config() removed += 1 e = key.get_bfd_auth_keys_dump_entry() - self.assert_equal(e.use_count, len(sessions) - removed, - "Use count for shared key") + self.assert_equal( + e.use_count, len(sessions) - removed, "Use count for shared key" + ) def test_activate_auth(self): - """ activate SHA1 authentication """ + """activate SHA1 authentication""" key = self.factory.create_random_key(self) key.add_vpp_config() session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4) @@ -276,7 +298,7 @@ class BFDAPITestCase(VppTestCase): session.activate_auth(key) def test_deactivate_auth(self): - """ deactivate SHA1 authentication """ + """deactivate SHA1 authentication""" key = self.factory.create_random_key(self) key.add_vpp_config() session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4) @@ -285,20 +307,19 @@ class BFDAPITestCase(VppTestCase): session.deactivate_auth() def test_change_key(self): - """ change SHA1 key """ + """change SHA1 key""" key1 = self.factory.create_random_key(self) key2 = self.factory.create_random_key(self) while key2.conf_key_id == key1.conf_key_id: key2 = self.factory.create_random_key(self) key1.add_vpp_config() key2.add_vpp_config() - session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4, - sha1_key=key1) + session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4, sha1_key=key1) session.add_vpp_config() session.activate_auth(key2) def test_set_del_udp_echo_source(self): - """ set/del udp echo source """ + """set/del udp echo source""" self.create_loopback_interfaces(1) self.loopback0 = self.lo_interfaces[0] self.loopback0.admin_up() @@ -307,8 +328,7 @@ class BFDAPITestCase(VppTestCase): self.assertFalse(echo_source.have_usable_ip4) self.assertFalse(echo_source.have_usable_ip6) - self.vapi.bfd_udp_set_echo_source( - sw_if_index=self.loopback0.sw_if_index) + self.vapi.bfd_udp_set_echo_source(sw_if_index=self.loopback0.sw_if_index) echo_source = self.vapi.bfd_udp_get_echo_source() self.assertTrue(echo_source.is_set) self.assertEqual(echo_source.sw_if_index, self.loopback0.sw_if_index) @@ -316,8 +336,9 @@ class BFDAPITestCase(VppTestCase): self.assertFalse(echo_source.have_usable_ip6) self.loopback0.config_ip4() - echo_ip4 = ipaddress.IPv4Address(int(ipaddress.IPv4Address( - self.loopback0.local_ip4)) ^ 1).packed + echo_ip4 = ipaddress.IPv4Address( + int(ipaddress.IPv4Address(self.loopback0.local_ip4)) ^ 1 + ).packed echo_source = self.vapi.bfd_udp_get_echo_source() self.assertTrue(echo_source.is_set) self.assertEqual(echo_source.sw_if_index, self.loopback0.sw_if_index) @@ -326,8 +347,9 @@ class BFDAPITestCase(VppTestCase): self.assertFalse(echo_source.have_usable_ip6) self.loopback0.config_ip6() - echo_ip6 = ipaddress.IPv6Address(int(ipaddress.IPv6Address( - self.loopback0.local_ip6)) ^ 1).packed + echo_ip6 = ipaddress.IPv6Address( + int(ipaddress.IPv6Address(self.loopback0.local_ip6)) ^ 1 + ).packed echo_source = self.vapi.bfd_udp_get_echo_source() self.assertTrue(echo_source.is_set) @@ -345,11 +367,20 @@ class BFDAPITestCase(VppTestCase): class BFDTestSession(object): - """ BFD session as seen from test framework side """ - - def __init__(self, test, interface, af, detect_mult=3, sha1_key=None, - bfd_key_id=None, our_seq_number=None, - tunnel_header=None, phy_interface=None): + """BFD session as seen from test framework side""" + + def __init__( + self, + test, + interface, + af, + detect_mult=3, + sha1_key=None, + bfd_key_id=None, + our_seq_number=None, + tunnel_header=None, + phy_interface=None, + ): self.test = test self.af = af self.sha1_key = sha1_key @@ -381,17 +412,25 @@ class BFDTestSession(object): self.rx_packets_echo = 0 def inc_seq_num(self): - """ increment sequence number, wrapping if needed """ + """increment sequence number, wrapping if needed""" if self.our_seq_number == 0xFFFFFFFF: self.our_seq_number = 0 else: self.our_seq_number += 1 - def update(self, my_discriminator=None, your_discriminator=None, - desired_min_tx=None, required_min_rx=None, - required_min_echo_rx=None, detect_mult=None, - diag=None, state=None, auth_type=None): - """ update BFD parameters associated with session """ + def update( + self, + my_discriminator=None, + your_discriminator=None, + desired_min_tx=None, + required_min_rx=None, + required_min_echo_rx=None, + detect_mult=None, + diag=None, + state=None, + auth_type=None, + ): + """update BFD parameters associated with session""" if my_discriminator is not None: self.my_discriminator = my_discriminator if your_discriminator is not None: @@ -412,34 +451,37 @@ class BFDTestSession(object): self.auth_type = auth_type def fill_packet_fields(self, packet): - """ set packet fields with known values in packet """ + """set packet fields with known values in packet""" bfd = packet[BFD] if self.my_discriminator: - self.test.logger.debug("BFD: setting packet.my_discriminator=%s", - self.my_discriminator) + self.test.logger.debug( + "BFD: setting packet.my_discriminator=%s", self.my_discriminator + ) bfd.my_discriminator = self.my_discriminator if self.your_discriminator: - self.test.logger.debug("BFD: setting packet.your_discriminator=%s", - self.your_discriminator) + self.test.logger.debug( + "BFD: setting packet.your_discriminator=%s", self.your_discriminator + ) bfd.your_discriminator = self.your_discriminator if self.required_min_rx: self.test.logger.debug( - "BFD: setting packet.required_min_rx_interval=%s", - self.required_min_rx) + "BFD: setting packet.required_min_rx_interval=%s", self.required_min_rx + ) bfd.required_min_rx_interval = self.required_min_rx if self.required_min_echo_rx: self.test.logger.debug( - "BFD: setting packet.required_min_echo_rx=%s", - self.required_min_echo_rx) + "BFD: setting packet.required_min_echo_rx=%s", self.required_min_echo_rx + ) bfd.required_min_echo_rx_interval = self.required_min_echo_rx if self.desired_min_tx: self.test.logger.debug( - "BFD: setting packet.desired_min_tx_interval=%s", - self.desired_min_tx) + "BFD: setting packet.desired_min_tx_interval=%s", self.desired_min_tx + ) bfd.desired_min_tx_interval = self.desired_min_tx if self.detect_mult: self.test.logger.debug( - "BFD: setting packet.detect_mult=%s", self.detect_mult) + "BFD: setting packet.detect_mult=%s", self.detect_mult + ) bfd.detect_mult = self.detect_mult if self.diag: self.test.logger.debug("BFD: setting packet.diag=%s", self.diag) @@ -449,12 +491,11 @@ class BFDTestSession(object): bfd.state = self.state if self.auth_type: # this is used by a negative test-case - self.test.logger.debug("BFD: setting packet.auth_type=%s", - self.auth_type) + self.test.logger.debug("BFD: setting packet.auth_type=%s", self.auth_type) bfd.auth_type = self.auth_type def create_packet(self): - """ create a BFD packet, reflecting the current state of session """ + """create a BFD packet, reflecting the current state of session""" if self.sha1_key: bfd = BFD(flags="A") bfd.auth_type = self.sha1_key.auth_type @@ -464,37 +505,48 @@ class BFDTestSession(object): bfd.length = BFD.sha1_auth_len + BFD.bfd_pkt_len else: bfd = BFD() - packet = Ether(src=self.phy_interface.remote_mac, - dst=self.phy_interface.local_mac) + packet = Ether( + src=self.phy_interface.remote_mac, dst=self.phy_interface.local_mac + ) if self.tunnel_header: packet = packet / self.tunnel_header if self.af == AF_INET6: - packet = (packet / - IPv6(src=self.interface.remote_ip6, - dst=self.interface.local_ip6, - hlim=255) / - UDP(sport=self.udp_sport, dport=BFD.udp_dport) / - bfd) + packet = ( + packet + / IPv6( + src=self.interface.remote_ip6, + dst=self.interface.local_ip6, + hlim=255, + ) + / UDP(sport=self.udp_sport, dport=BFD.udp_dport) + / bfd + ) else: - packet = (packet / - IP(src=self.interface.remote_ip4, - dst=self.interface.local_ip4, - ttl=255) / - UDP(sport=self.udp_sport, dport=BFD.udp_dport) / - bfd) + packet = ( + packet + / IP( + src=self.interface.remote_ip4, dst=self.interface.local_ip4, ttl=255 + ) + / UDP(sport=self.udp_sport, dport=BFD.udp_dport) + / bfd + ) self.test.logger.debug("BFD: Creating packet") self.fill_packet_fields(packet) if self.sha1_key: - hash_material = scapy.compat.raw( - packet[BFD])[:32] + self.sha1_key.key + \ - b"\0" * (20 - len(self.sha1_key.key)) - self.test.logger.debug("BFD: Calculated SHA1 hash: %s" % - hashlib.sha1(hash_material).hexdigest()) + hash_material = ( + scapy.compat.raw(packet[BFD])[:32] + + self.sha1_key.key + + b"\0" * (20 - len(self.sha1_key.key)) + ) + self.test.logger.debug( + "BFD: Calculated SHA1 hash: %s" + % hashlib.sha1(hash_material).hexdigest() + ) packet[BFD].auth_key_hash = hashlib.sha1(hash_material).digest() return packet def send_packet(self, packet=None, interface=None): - """ send packet on interface, creating the packet if needed """ + """send packet on interface, creating the packet if needed""" if packet is None: packet = self.create_packet() if interface is None: @@ -505,82 +557,95 @@ class BFDTestSession(object): self.test.pg_start() def verify_sha1_auth(self, packet): - """ Verify correctness of authentication in BFD layer. """ + """Verify correctness of authentication in BFD layer.""" bfd = packet[BFD] self.test.assert_equal(bfd.auth_len, 28, "Auth section length") - self.test.assert_equal(bfd.auth_type, self.sha1_key.auth_type, - BFDAuthType) + self.test.assert_equal(bfd.auth_type, self.sha1_key.auth_type, BFDAuthType) self.test.assert_equal(bfd.auth_key_id, self.bfd_key_id, "Key ID") self.test.assert_equal(bfd.auth_reserved, 0, "Reserved") if self.vpp_seq_number is None: self.vpp_seq_number = bfd.auth_seq_num - self.test.logger.debug("Received initial sequence number: %s" % - self.vpp_seq_number) + self.test.logger.debug( + "Received initial sequence number: %s" % self.vpp_seq_number + ) else: recvd_seq_num = bfd.auth_seq_num - self.test.logger.debug("Received followup sequence number: %s" % - recvd_seq_num) - if self.vpp_seq_number < 0xffffffff: - if self.sha1_key.auth_type == \ - BFDAuthType.meticulous_keyed_sha1: - self.test.assert_equal(recvd_seq_num, - self.vpp_seq_number + 1, - "BFD sequence number") + self.test.logger.debug( + "Received followup sequence number: %s" % recvd_seq_num + ) + if self.vpp_seq_number < 0xFFFFFFFF: + if self.sha1_key.auth_type == BFDAuthType.meticulous_keyed_sha1: + self.test.assert_equal( + recvd_seq_num, self.vpp_seq_number + 1, "BFD sequence number" + ) else: - self.test.assert_in_range(recvd_seq_num, - self.vpp_seq_number, - self.vpp_seq_number + 1, - "BFD sequence number") + self.test.assert_in_range( + recvd_seq_num, + self.vpp_seq_number, + self.vpp_seq_number + 1, + "BFD sequence number", + ) else: - if self.sha1_key.auth_type == \ - BFDAuthType.meticulous_keyed_sha1: - self.test.assert_equal(recvd_seq_num, 0, - "BFD sequence number") + if self.sha1_key.auth_type == BFDAuthType.meticulous_keyed_sha1: + self.test.assert_equal(recvd_seq_num, 0, "BFD sequence number") else: - self.test.assertIn(recvd_seq_num, (self.vpp_seq_number, 0), - "BFD sequence number not one of " - "(%s, 0)" % self.vpp_seq_number) + self.test.assertIn( + recvd_seq_num, + (self.vpp_seq_number, 0), + "BFD sequence number not one of " + "(%s, 0)" % self.vpp_seq_number, + ) self.vpp_seq_number = recvd_seq_num # last 20 bytes represent the hash - so replace them with the key, # pad the result with zeros and hash the result - hash_material = bfd.original[:-20] + self.sha1_key.key + \ - b"\0" * (20 - len(self.sha1_key.key)) + hash_material = ( + bfd.original[:-20] + + self.sha1_key.key + + b"\0" * (20 - len(self.sha1_key.key)) + ) expected_hash = hashlib.sha1(hash_material).hexdigest() - self.test.assert_equal(binascii.hexlify(bfd.auth_key_hash), - expected_hash.encode(), "Auth key hash") + self.test.assert_equal( + binascii.hexlify(bfd.auth_key_hash), expected_hash.encode(), "Auth key hash" + ) def verify_bfd(self, packet): - """ Verify correctness of BFD layer. """ + """Verify correctness of BFD layer.""" bfd = packet[BFD] self.test.assert_equal(bfd.version, 1, "BFD version") - self.test.assert_equal(bfd.your_discriminator, - self.my_discriminator, - "BFD - your discriminator") + self.test.assert_equal( + bfd.your_discriminator, self.my_discriminator, "BFD - your discriminator" + ) if self.sha1_key: self.verify_sha1_auth(packet) def bfd_session_up(test): - """ Bring BFD session up """ + """Bring BFD session up""" test.logger.info("BFD: Waiting for slow hello") p = wait_for_bfd_packet(test, 2, is_tunnel=test.vpp_session.is_tunnel) old_offset = None - if hasattr(test, 'vpp_clock_offset'): + if hasattr(test, "vpp_clock_offset"): old_offset = test.vpp_clock_offset test.vpp_clock_offset = time.time() - float(p.time) - test.logger.debug("BFD: Calculated vpp clock offset: %s", - test.vpp_clock_offset) + test.logger.debug("BFD: Calculated vpp clock offset: %s", test.vpp_clock_offset) if old_offset: test.assertAlmostEqual( - old_offset, test.vpp_clock_offset, delta=0.5, - msg="vpp clock offset not stable (new: %s, old: %s)" % - (test.vpp_clock_offset, old_offset)) + old_offset, + test.vpp_clock_offset, + delta=0.5, + msg="vpp clock offset not stable (new: %s, old: %s)" + % (test.vpp_clock_offset, old_offset), + ) test.logger.info("BFD: Sending Init") - test.test_session.update(my_discriminator=randint(0, 40000000), - your_discriminator=p[BFD].my_discriminator, - state=BFDState.init) - if test.test_session.sha1_key and test.test_session.sha1_key.auth_type == \ - BFDAuthType.meticulous_keyed_sha1: + test.test_session.update( + my_discriminator=randint(0, 40000000), + your_discriminator=p[BFD].my_discriminator, + state=BFDState.init, + ) + if ( + test.test_session.sha1_key + and test.test_session.sha1_key.auth_type == BFDAuthType.meticulous_keyed_sha1 + ): test.test_session.inc_seq_num() test.test_session.send_packet() test.logger.info("BFD: Waiting for event") @@ -588,19 +653,23 @@ def bfd_session_up(test): verify_event(test, e, expected_state=BFDState.up) test.logger.info("BFD: Session is Up") test.test_session.update(state=BFDState.up) - if test.test_session.sha1_key and test.test_session.sha1_key.auth_type == \ - BFDAuthType.meticulous_keyed_sha1: + if ( + test.test_session.sha1_key + and test.test_session.sha1_key.auth_type == BFDAuthType.meticulous_keyed_sha1 + ): test.test_session.inc_seq_num() test.test_session.send_packet() test.assert_equal(test.vpp_session.state, BFDState.up, BFDState) def bfd_session_down(test): - """ Bring BFD session down """ + """Bring BFD session down""" test.assert_equal(test.vpp_session.state, BFDState.up, BFDState) test.test_session.update(state=BFDState.down) - if test.test_session.sha1_key and test.test_session.sha1_key.auth_type == \ - BFDAuthType.meticulous_keyed_sha1: + if ( + test.test_session.sha1_key + and test.test_session.sha1_key.auth_type == BFDAuthType.meticulous_keyed_sha1 + ): test.test_session.inc_seq_num() test.test_session.send_packet() test.logger.info("BFD: Waiting for event") @@ -617,25 +686,25 @@ def verify_bfd_session_config(test, session, state=None): # are valid (in get_bfd_udp_session_dump_entry) if state: test.assert_equal(dump.state, state, "session state") - test.assert_equal(dump.required_min_rx, session.required_min_rx, - "required min rx interval") - test.assert_equal(dump.desired_min_tx, session.desired_min_tx, - "desired min tx interval") - test.assert_equal(dump.detect_mult, session.detect_mult, - "detect multiplier") + test.assert_equal( + dump.required_min_rx, session.required_min_rx, "required min rx interval" + ) + test.assert_equal( + dump.desired_min_tx, session.desired_min_tx, "desired min tx interval" + ) + test.assert_equal(dump.detect_mult, session.detect_mult, "detect multiplier") if session.sha1_key is None: test.assert_equal(dump.is_authenticated, 0, "is_authenticated flag") else: test.assert_equal(dump.is_authenticated, 1, "is_authenticated flag") - test.assert_equal(dump.bfd_key_id, session.bfd_key_id, - "bfd key id") - test.assert_equal(dump.conf_key_id, - session.sha1_key.conf_key_id, - "config key id") + test.assert_equal(dump.bfd_key_id, session.bfd_key_id, "bfd key id") + test.assert_equal( + dump.conf_key_id, session.sha1_key.conf_key_id, "config key id" + ) def verify_ip(test, packet): - """ Verify correctness of IP layer. """ + """Verify correctness of IP layer.""" if test.vpp_session.af == AF_INET6: ip = packet[IPv6] local_ip = test.vpp_session.interface.local_ip6 @@ -651,30 +720,31 @@ def verify_ip(test, packet): def verify_udp(test, packet): - """ Verify correctness of UDP layer. """ + """Verify correctness of UDP layer.""" udp = packet[UDP] test.assert_equal(udp.dport, BFD.udp_dport, "UDP destination port") - test.assert_in_range(udp.sport, BFD.udp_sport_min, BFD.udp_sport_max, - "UDP source port") + test.assert_in_range( + udp.sport, BFD.udp_sport_min, BFD.udp_sport_max, "UDP source port" + ) def verify_event(test, event, expected_state): - """ Verify correctness of event values. """ + """Verify correctness of event values.""" e = event test.logger.debug("BFD: Event: %s" % reprlib.repr(e)) - test.assert_equal(e.sw_if_index, - test.vpp_session.interface.sw_if_index, - "BFD interface index") - - test.assert_equal(str(e.local_addr), test.vpp_session.local_addr, - "Local IPv6 address") - test.assert_equal(str(e.peer_addr), test.vpp_session.peer_addr, - "Peer IPv6 address") + test.assert_equal( + e.sw_if_index, test.vpp_session.interface.sw_if_index, "BFD interface index" + ) + + test.assert_equal( + str(e.local_addr), test.vpp_session.local_addr, "Local IPv6 address" + ) + test.assert_equal(str(e.peer_addr), test.vpp_session.peer_addr, "Peer IPv6 address") test.assert_equal(e.state, expected_state, BFDState) def wait_for_bfd_packet(test, timeout=1, pcap_time_min=None, is_tunnel=False): - """ wait for BFD packet and verify its correctness + """wait for BFD packet and verify its correctness :param timeout: how long to wait :param pcap_time_min: ignore packets with pcap timestamp lower than this @@ -695,9 +765,13 @@ def wait_for_bfd_packet(test, timeout=1, pcap_time_min=None, is_tunnel=False): test.test_session.rx_packets += 1 test.logger.debug(ppp("BFD: Got packet:", p)) if pcap_time_min is not None and p.time < pcap_time_min: - test.logger.debug(ppp("BFD: ignoring packet (pcap time %s < " - "pcap time min %s):" % - (p.time, pcap_time_min), p)) + test.logger.debug( + ppp( + "BFD: ignoring packet (pcap time %s < " + "pcap time min %s):" % (p.time, pcap_time_min), + p, + ) + ) else: break if is_tunnel: @@ -722,15 +796,15 @@ def bfd_grab_stats_snapshot(test, bs_idx=0, thread_index=None): s = test.statistics ti = thread_index if ti is None: - rx = s['/bfd/rx-session-counters'][:, bs_idx].sum_packets() - rx_echo = s['/bfd/rx-session-echo-counters'][:, bs_idx].sum_packets() - tx = s['/bfd/tx-session-counters'][:, bs_idx].sum_packets() - tx_echo = s['/bfd/tx-session-echo-counters'][:, bs_idx].sum_packets() + rx = s["/bfd/rx-session-counters"][:, bs_idx].sum_packets() + rx_echo = s["/bfd/rx-session-echo-counters"][:, bs_idx].sum_packets() + tx = s["/bfd/tx-session-counters"][:, bs_idx].sum_packets() + tx_echo = s["/bfd/tx-session-echo-counters"][:, bs_idx].sum_packets() else: - rx = s['/bfd/rx-session-counters'][ti, bs_idx].sum_packets() - rx_echo = s['/bfd/rx-session-echo-counters'][ti, bs_idx].sum_packets() - tx = s['/bfd/tx-session-counters'][ti, bs_idx].sum_packets() - tx_echo = s['/bfd/tx-session-echo-counters'][ti, bs_idx].sum_packets() + rx = s["/bfd/rx-session-counters"][ti, bs_idx].sum_packets() + rx_echo = s["/bfd/rx-session-echo-counters"][ti, bs_idx].sum_packets() + tx = s["/bfd/tx-session-counters"][ti, bs_idx].sum_packets() + tx_echo = s["/bfd/tx-session-echo-counters"][ti, bs_idx].sum_packets() return BFDStats(rx, rx_echo, tx, tx_echo) @@ -780,10 +854,9 @@ class BFD4TestCase(VppTestCase): self.vapi.want_bfd_events() self.pg0.enable_capture() try: - self.bfd_udp4_sessions = self.statistics['/bfd/udp4/sessions'] - self.bfd_udp6_sessions = self.statistics['/bfd/udp6/sessions'] - self.vpp_session = VppBFDUDPSession(self, self.pg0, - self.pg0.remote_ip4) + self.bfd_udp4_sessions = self.statistics["/bfd/udp4/sessions"] + self.bfd_udp6_sessions = self.statistics["/bfd/udp6/sessions"] + self.vpp_session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4) self.vpp_session.add_vpp_config() self.vpp_session.admin_up() self.test_session = BFDTestSession(self, self.pg0, AF_INET) @@ -798,26 +871,29 @@ class BFD4TestCase(VppTestCase): super(BFD4TestCase, self).tearDown() def test_session_up(self): - """ bring BFD session up """ + """bring BFD session up""" bfd_session_up(self) - bfd_udp4_sessions = self.statistics['/bfd/udp4/sessions'] - bfd_udp6_sessions = self.statistics['/bfd/udp6/sessions'] + bfd_udp4_sessions = self.statistics["/bfd/udp4/sessions"] + bfd_udp6_sessions = self.statistics["/bfd/udp6/sessions"] self.assert_equal(bfd_udp4_sessions - self.bfd_udp4_sessions, 1) self.assert_equal(bfd_udp6_sessions, self.bfd_udp6_sessions) def test_session_up_by_ip(self): - """ bring BFD session up - first frame looked up by address pair """ + """bring BFD session up - first frame looked up by address pair""" self.logger.info("BFD: Sending Slow control frame") self.test_session.update(my_discriminator=randint(0, 40000000)) self.test_session.send_packet() self.pg0.enable_capture() p = self.pg0.wait_for_packet(1) - self.assert_equal(p[BFD].your_discriminator, - self.test_session.my_discriminator, - "BFD - your discriminator") + self.assert_equal( + p[BFD].your_discriminator, + self.test_session.my_discriminator, + "BFD - your discriminator", + ) self.assert_equal(p[BFD].state, BFDState.init, BFDState) - self.test_session.update(your_discriminator=p[BFD].my_discriminator, - state=BFDState.up) + self.test_session.update( + your_discriminator=p[BFD].my_discriminator, state=BFDState.up + ) self.logger.info("BFD: Waiting for event") e = self.vapi.wait_for_event(1, "bfd_udp_session_event") verify_event(self, e, expected_state=BFDState.init) @@ -832,21 +908,20 @@ class BFD4TestCase(VppTestCase): self.assert_equal(self.vpp_session.state, BFDState.up, BFDState) def test_session_down(self): - """ bring BFD session down """ + """bring BFD session down""" bfd_session_up(self) bfd_session_down(self) def test_hold_up(self): - """ hold BFD session up """ + """hold BFD session up""" bfd_session_up(self) for dummy in range(self.test_session.detect_mult * 2): wait_for_bfd_packet(self) self.test_session.send_packet() - self.assert_equal(len(self.vapi.collect_events()), 0, - "number of bfd events") + self.assert_equal(len(self.vapi.collect_events()), 0, "number of bfd events") def test_slow_timer(self): - """ verify slow periodic control frames while session down """ + """verify slow periodic control frames while session down""" packet_count = 3 self.logger.info("BFD: Waiting for %d BFD packets", packet_count) prev_packet = wait_for_bfd_packet(self, 2) @@ -855,55 +930,60 @@ class BFD4TestCase(VppTestCase): time_diff = next_packet.time - prev_packet.time # spec says the range should be <0.75, 1>, allow extra 0.05 margin # to work around timing issues - self.assert_in_range( - time_diff, 0.70, 1.05, "time between slow packets") + self.assert_in_range(time_diff, 0.70, 1.05, "time between slow packets") prev_packet = next_packet def test_zero_remote_min_rx(self): - """ no packets when zero remote required min rx interval """ + """no packets when zero remote required min rx interval""" bfd_session_up(self) self.test_session.update(required_min_rx=0) self.test_session.send_packet() for dummy in range(self.test_session.detect_mult): - self.sleep(self.vpp_session.required_min_rx / USEC_IN_SEC, - "sleep before transmitting bfd packet") + self.sleep( + self.vpp_session.required_min_rx / USEC_IN_SEC, + "sleep before transmitting bfd packet", + ) self.test_session.send_packet() try: p = wait_for_bfd_packet(self, timeout=0) self.logger.error(ppp("Received unexpected packet:", p)) except CaptureTimeoutError: pass - self.assert_equal( - len(self.vapi.collect_events()), 0, "number of bfd events") + self.assert_equal(len(self.vapi.collect_events()), 0, "number of bfd events") self.test_session.update(required_min_rx=300000) for dummy in range(3): self.test_session.send_packet() wait_for_bfd_packet( - self, timeout=self.test_session.required_min_rx / USEC_IN_SEC) - self.assert_equal( - len(self.vapi.collect_events()), 0, "number of bfd events") + self, timeout=self.test_session.required_min_rx / USEC_IN_SEC + ) + self.assert_equal(len(self.vapi.collect_events()), 0, "number of bfd events") def test_conn_down(self): - """ verify session goes down after inactivity """ + """verify session goes down after inactivity""" bfd_session_up(self) - detection_time = self.test_session.detect_mult *\ - self.vpp_session.required_min_rx / USEC_IN_SEC + detection_time = ( + self.test_session.detect_mult + * self.vpp_session.required_min_rx + / USEC_IN_SEC + ) self.sleep(detection_time, "waiting for BFD session time-out") e = self.vapi.wait_for_event(1, "bfd_udp_session_event") verify_event(self, e, expected_state=BFDState.down) def test_peer_discr_reset_sess_down(self): - """ peer discriminator reset after session goes down """ + """peer discriminator reset after session goes down""" bfd_session_up(self) - detection_time = self.test_session.detect_mult *\ - self.vpp_session.required_min_rx / USEC_IN_SEC + detection_time = ( + self.test_session.detect_mult + * self.vpp_session.required_min_rx + / USEC_IN_SEC + ) self.sleep(detection_time, "waiting for BFD session time-out") self.test_session.my_discriminator = 0 - wait_for_bfd_packet(self, - pcap_time_min=time.time() - self.vpp_clock_offset) + wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset) def test_large_required_min_rx(self): - """ large remote required min rx interval """ + """large remote required min rx interval""" bfd_session_up(self) p = wait_for_bfd_packet(self) interval = 3000000 @@ -932,14 +1012,14 @@ class BFD4TestCase(VppTestCase): self.assert_equal(count, 0, "number of packets received") def test_immediate_remote_min_rx_reduction(self): - """ immediately honor remote required min rx reduction """ + """immediately honor remote required min rx reduction""" self.vpp_session.remove_vpp_config() self.vpp_session = VppBFDUDPSession( - self, self.pg0, self.pg0.remote_ip4, desired_min_tx=10000) + self, self.pg0, self.pg0.remote_ip4, desired_min_tx=10000 + ) self.pg0.enable_capture() self.vpp_session.add_vpp_config() - self.test_session.update(desired_min_tx=1000000, - required_min_rx=1000000) + self.test_session.update(desired_min_tx=1000000, required_min_rx=1000000) bfd_session_up(self) reference_packet = wait_for_bfd_packet(self) time_mark = time.time() @@ -950,131 +1030,143 @@ class BFD4TestCase(VppTestCase): p = wait_for_bfd_packet(self) # first packet is allowed to be late by time we spent doing the update # calculated in extra_time - self.assert_in_range(p.time - reference_packet.time, - .95 * 0.75 * interval / USEC_IN_SEC, - 1.05 * interval / USEC_IN_SEC + extra_time, - "time between BFD packets") + self.assert_in_range( + p.time - reference_packet.time, + 0.95 * 0.75 * interval / USEC_IN_SEC, + 1.05 * interval / USEC_IN_SEC + extra_time, + "time between BFD packets", + ) reference_packet = p for dummy in range(3): p = wait_for_bfd_packet(self) diff = p.time - reference_packet.time - self.assert_in_range(diff, .95 * .75 * interval / USEC_IN_SEC, - 1.05 * interval / USEC_IN_SEC, - "time between BFD packets") + self.assert_in_range( + diff, + 0.95 * 0.75 * interval / USEC_IN_SEC, + 1.05 * interval / USEC_IN_SEC, + "time between BFD packets", + ) reference_packet = p def test_modify_req_min_rx_double(self): - """ modify session - double required min rx """ + """modify session - double required min rx""" bfd_session_up(self) p = wait_for_bfd_packet(self) - self.test_session.update(desired_min_tx=10000, - required_min_rx=10000) + self.test_session.update(desired_min_tx=10000, required_min_rx=10000) self.test_session.send_packet() # double required min rx self.vpp_session.modify_parameters( - required_min_rx=2 * self.vpp_session.required_min_rx) - p = wait_for_bfd_packet( - self, pcap_time_min=time.time() - self.vpp_clock_offset) + required_min_rx=2 * self.vpp_session.required_min_rx + ) + p = wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset) # poll bit needs to be set - self.assertIn("P", p.sprintf("%BFD.flags%"), - "Poll bit not set in BFD packet") + self.assertIn("P", p.sprintf("%BFD.flags%"), "Poll bit not set in BFD packet") # finish poll sequence with final packet final = self.test_session.create_packet() final[BFD].flags = "F" - timeout = self.test_session.detect_mult * \ - max(self.test_session.desired_min_tx, - self.vpp_session.required_min_rx) / USEC_IN_SEC + timeout = ( + self.test_session.detect_mult + * max(self.test_session.desired_min_tx, self.vpp_session.required_min_rx) + / USEC_IN_SEC + ) self.test_session.send_packet(final) time_mark = time.time() e = self.vapi.wait_for_event(2 * timeout, "bfd_udp_session_event") verify_event(self, e, expected_state=BFDState.down) time_to_event = time.time() - time_mark - self.assert_in_range(time_to_event, .9 * timeout, - 1.1 * timeout, "session timeout") + self.assert_in_range( + time_to_event, 0.9 * timeout, 1.1 * timeout, "session timeout" + ) def test_modify_req_min_rx_halve(self): - """ modify session - halve required min rx """ + """modify session - halve required min rx""" self.vpp_session.modify_parameters( - required_min_rx=2 * self.vpp_session.required_min_rx) + required_min_rx=2 * self.vpp_session.required_min_rx + ) bfd_session_up(self) p = wait_for_bfd_packet(self) - self.test_session.update(desired_min_tx=10000, - required_min_rx=10000) + self.test_session.update(desired_min_tx=10000, required_min_rx=10000) self.test_session.send_packet() - p = wait_for_bfd_packet( - self, pcap_time_min=time.time() - self.vpp_clock_offset) + p = wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset) # halve required min rx old_required_min_rx = self.vpp_session.required_min_rx self.vpp_session.modify_parameters( - required_min_rx=self.vpp_session.required_min_rx // 2) + required_min_rx=self.vpp_session.required_min_rx // 2 + ) # now we wait 0.8*3*old-req-min-rx and the session should still be up - self.sleep(0.8 * self.vpp_session.detect_mult * - old_required_min_rx / USEC_IN_SEC, - "wait before finishing poll sequence") - self.assert_equal(len(self.vapi.collect_events()), 0, - "number of bfd events") + self.sleep( + 0.8 * self.vpp_session.detect_mult * old_required_min_rx / USEC_IN_SEC, + "wait before finishing poll sequence", + ) + self.assert_equal(len(self.vapi.collect_events()), 0, "number of bfd events") p = wait_for_bfd_packet(self) # poll bit needs to be set - self.assertIn("P", p.sprintf("%BFD.flags%"), - "Poll bit not set in BFD packet") + self.assertIn("P", p.sprintf("%BFD.flags%"), "Poll bit not set in BFD packet") # finish poll sequence with final packet final = self.test_session.create_packet() final[BFD].flags = "F" self.test_session.send_packet(final) # now the session should time out under new conditions - detection_time = self.test_session.detect_mult *\ - self.vpp_session.required_min_rx / USEC_IN_SEC + detection_time = ( + self.test_session.detect_mult + * self.vpp_session.required_min_rx + / USEC_IN_SEC + ) before = time.time() - e = self.vapi.wait_for_event( - 2 * detection_time, "bfd_udp_session_event") + e = self.vapi.wait_for_event(2 * detection_time, "bfd_udp_session_event") after = time.time() - self.assert_in_range(after - before, - 0.9 * detection_time, - 1.1 * detection_time, - "time before bfd session goes down") + self.assert_in_range( + after - before, + 0.9 * detection_time, + 1.1 * detection_time, + "time before bfd session goes down", + ) verify_event(self, e, expected_state=BFDState.down) def test_modify_detect_mult(self): - """ modify detect multiplier """ + """modify detect multiplier""" bfd_session_up(self) p = wait_for_bfd_packet(self) self.vpp_session.modify_parameters(detect_mult=1) - p = wait_for_bfd_packet( - self, pcap_time_min=time.time() - self.vpp_clock_offset) - self.assert_equal(self.vpp_session.detect_mult, - p[BFD].detect_mult, - "detect mult") + p = wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset) + self.assert_equal( + self.vpp_session.detect_mult, p[BFD].detect_mult, "detect mult" + ) # poll bit must not be set - self.assertNotIn("P", p.sprintf("%BFD.flags%"), - "Poll bit not set in BFD packet") + self.assertNotIn( + "P", p.sprintf("%BFD.flags%"), "Poll bit not set in BFD packet" + ) self.vpp_session.modify_parameters(detect_mult=10) - p = wait_for_bfd_packet( - self, pcap_time_min=time.time() - self.vpp_clock_offset) - self.assert_equal(self.vpp_session.detect_mult, - p[BFD].detect_mult, - "detect mult") + p = wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset) + self.assert_equal( + self.vpp_session.detect_mult, p[BFD].detect_mult, "detect mult" + ) # poll bit must not be set - self.assertNotIn("P", p.sprintf("%BFD.flags%"), - "Poll bit not set in BFD packet") + self.assertNotIn( + "P", p.sprintf("%BFD.flags%"), "Poll bit not set in BFD packet" + ) def test_queued_poll(self): - """ test poll sequence queueing """ + """test poll sequence queueing""" bfd_session_up(self) p = wait_for_bfd_packet(self) self.vpp_session.modify_parameters( - required_min_rx=2 * self.vpp_session.required_min_rx) + required_min_rx=2 * self.vpp_session.required_min_rx + ) p = wait_for_bfd_packet(self) poll_sequence_start = time.time() poll_sequence_length_min = 0.5 send_final_after = time.time() + poll_sequence_length_min # poll bit needs to be set - self.assertIn("P", p.sprintf("%BFD.flags%"), - "Poll bit not set in BFD packet") - self.assert_equal(p[BFD].required_min_rx_interval, - self.vpp_session.required_min_rx, - "BFD required min rx interval") + self.assertIn("P", p.sprintf("%BFD.flags%"), "Poll bit not set in BFD packet") + self.assert_equal( + p[BFD].required_min_rx_interval, + self.vpp_session.required_min_rx, + "BFD required min rx interval", + ) self.vpp_session.modify_parameters( - required_min_rx=2 * self.vpp_session.required_min_rx) + required_min_rx=2 * self.vpp_session.required_min_rx + ) # 2nd poll sequence should be queued now # don't send the reply back yet, wait for some time to emulate # longer round-trip time @@ -1082,15 +1174,19 @@ class BFD4TestCase(VppTestCase): while time.time() < send_final_after: self.test_session.send_packet() p = wait_for_bfd_packet(self) - self.assert_equal(len(self.vapi.collect_events()), 0, - "number of bfd events") - self.assert_equal(p[BFD].required_min_rx_interval, - self.vpp_session.required_min_rx, - "BFD required min rx interval") + self.assert_equal( + len(self.vapi.collect_events()), 0, "number of bfd events" + ) + self.assert_equal( + p[BFD].required_min_rx_interval, + self.vpp_session.required_min_rx, + "BFD required min rx interval", + ) packet_count += 1 # poll bit must be set - self.assertIn("P", p.sprintf("%BFD.flags%"), - "Poll bit not set in BFD packet") + self.assertIn( + "P", p.sprintf("%BFD.flags%"), "Poll bit not set in BFD packet" + ) final = self.test_session.create_packet() final[BFD].flags = "F" self.test_session.send_packet(final) @@ -1100,8 +1196,9 @@ class BFD4TestCase(VppTestCase): poll_no_2_started = False for dummy in range(2 * packet_count): p = wait_for_bfd_packet(self) - self.assert_equal(len(self.vapi.collect_events()), 0, - "number of bfd events") + self.assert_equal( + len(self.vapi.collect_events()), 0, "number of bfd events" + ) if "P" in p.sprintf("%BFD.flags%"): poll_no_2_started = True if time.time() < poll_sequence_start + poll_sequence_length: @@ -1119,31 +1216,32 @@ class BFD4TestCase(VppTestCase): self.test_session.send_packet(final) p = wait_for_bfd_packet(self) # poll bit must not be set - self.assertNotIn("P", p.sprintf("%BFD.flags%"), - "Poll bit set in BFD packet") + self.assertNotIn("P", p.sprintf("%BFD.flags%"), "Poll bit set in BFD packet") # returning inconsistent results requiring retries in per-patch tests @unittest.skipUnless(config.extended, "part of extended tests") def test_poll_response(self): - """ test correct response to control frame with poll bit set """ + """test correct response to control frame with poll bit set""" bfd_session_up(self) poll = self.test_session.create_packet() poll[BFD].flags = "P" self.test_session.send_packet(poll) final = wait_for_bfd_packet( - self, pcap_time_min=time.time() - self.vpp_clock_offset) + self, pcap_time_min=time.time() - self.vpp_clock_offset + ) self.assertIn("F", final.sprintf("%BFD.flags%")) def test_no_periodic_if_remote_demand(self): - """ no periodic frames outside poll sequence if remote demand set """ + """no periodic frames outside poll sequence if remote demand set""" bfd_session_up(self) demand = self.test_session.create_packet() demand[BFD].flags = "D" self.test_session.send_packet(demand) - transmit_time = 0.9 \ - * max(self.vpp_session.required_min_rx, - self.test_session.desired_min_tx) \ + transmit_time = ( + 0.9 + * max(self.vpp_session.required_min_rx, self.test_session.desired_min_tx) / USEC_IN_SEC + ) count = 0 for dummy in range(self.test_session.detect_mult * 2): self.sleep(transmit_time) @@ -1161,7 +1259,7 @@ class BFD4TestCase(VppTestCase): self.assert_equal(len(events), 0, "number of events received") def test_echo_looped_back(self): - """ echo packets looped back """ + """echo packets looped back""" bfd_session_up(self) stats_before = bfd_grab_stats_snapshot(self) self.pg0.enable_capture() @@ -1169,14 +1267,14 @@ class BFD4TestCase(VppTestCase): # random source port low enough to increment a few times.. udp_sport_tx = randint(1, 50000) udp_sport_rx = udp_sport_tx - echo_packet = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, - dst=self.pg0.remote_ip4) / - UDP(dport=BFD.udp_dport_echo) / - Raw("this should be looped back")) + echo_packet = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.remote_ip4) + / UDP(dport=BFD.udp_dport_echo) + / Raw("this should be looped back") + ) for dummy in range(echo_packet_count): - self.sleep(.01, "delay between echo packets") + self.sleep(0.01, "delay between echo packets") echo_packet[UDP].sport = udp_sport_tx udp_sport_tx += 1 self.logger.debug(ppp("Sending packet:", echo_packet)) @@ -1189,8 +1287,7 @@ class BFD4TestCase(VppTestCase): p = self.pg0.wait_for_packet(1) self.logger.debug(ppp("Got packet:", p)) ether = p[Ether] - self.assert_equal(self.pg0.remote_mac, - ether.dst, "Destination MAC") + self.assert_equal(self.pg0.remote_mac, ether.dst, "Destination MAC") self.assert_equal(self.pg0.local_mac, ether.src, "Source MAC") ip = p[IP] self.assert_equal(self.pg0.remote_ip4, ip.dst, "Destination IP") @@ -1199,50 +1296,57 @@ class BFD4TestCase(VppTestCase): bfd_control_packets_rx += 1 continue self.assert_equal(self.pg0.remote_ip4, ip.src, "Source IP") - self.assert_equal(udp.dport, BFD.udp_dport_echo, - "UDP destination port") + self.assert_equal(udp.dport, BFD.udp_dport_echo, "UDP destination port") self.assert_equal(udp.sport, udp_sport_rx, "UDP source port") udp_sport_rx += 1 # need to compare the hex payload here, otherwise BFD_vpp_echo # gets in way - self.assertEqual(scapy.compat.raw(p[UDP].payload), - scapy.compat.raw(echo_packet[UDP].payload), - "Received packet is not the echo packet sent") + self.assertEqual( + scapy.compat.raw(p[UDP].payload), + scapy.compat.raw(echo_packet[UDP].payload), + "Received packet is not the echo packet sent", + ) counter += 1 - self.assert_equal(udp_sport_tx, udp_sport_rx, "UDP source port (== " - "ECHO packet identifier for test purposes)") + self.assert_equal( + udp_sport_tx, + udp_sport_rx, + "UDP source port (== ECHO packet identifier for test purposes)", + ) stats_after = bfd_grab_stats_snapshot(self) diff = bfd_stats_diff(stats_before, stats_after) + self.assertEqual(0, diff.rx, "RX counter bumped but no BFD packets sent") + self.assertEqual(bfd_control_packets_rx, diff.tx, "TX counter incorrect") self.assertEqual( - 0, diff.rx, "RX counter bumped but no BFD packets sent") + 0, diff.rx_echo, "RX echo counter bumped but no BFD session exists" + ) self.assertEqual( - bfd_control_packets_rx, diff.tx, "TX counter incorrect") - self.assertEqual(0, diff.rx_echo, - "RX echo counter bumped but no BFD session exists") - self.assertEqual(0, diff.tx_echo, - "TX echo counter bumped but no BFD session exists") + 0, diff.tx_echo, "TX echo counter bumped but no BFD session exists" + ) def test_echo(self): - """ echo function """ + """echo function""" stats_before = bfd_grab_stats_snapshot(self) bfd_session_up(self) self.test_session.update(required_min_echo_rx=150000) self.test_session.send_packet() - detection_time = self.test_session.detect_mult *\ - self.vpp_session.required_min_rx / USEC_IN_SEC + detection_time = ( + self.test_session.detect_mult + * self.vpp_session.required_min_rx + / USEC_IN_SEC + ) # echo shouldn't work without echo source set for dummy in range(10): sleep = self.vpp_session.required_min_rx / USEC_IN_SEC self.sleep(sleep, "delay before sending bfd packet") self.test_session.send_packet() - p = wait_for_bfd_packet( - self, pcap_time_min=time.time() - self.vpp_clock_offset) - self.assert_equal(p[BFD].required_min_rx_interval, - self.vpp_session.required_min_rx, - "BFD required min rx interval") + p = wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset) + self.assert_equal( + p[BFD].required_min_rx_interval, + self.vpp_session.required_min_rx, + "BFD required min rx interval", + ) self.test_session.send_packet() - self.vapi.bfd_udp_set_echo_source( - sw_if_index=self.loopback0.sw_if_index) + self.vapi.bfd_udp_set_echo_source(sw_if_index=self.loopback0.sw_if_index) echo_seen = False # should be turned on - loopback echo packets for dummy in range(3): @@ -1251,13 +1355,18 @@ class BFD4TestCase(VppTestCase): p = self.pg0.wait_for_packet(1) self.logger.debug(ppp("Got packet:", p)) if p[UDP].dport == BFD.udp_dport_echo: - self.assert_equal( - p[IP].dst, self.pg0.local_ip4, "BFD ECHO dst IP") - self.assertNotEqual(p[IP].src, self.loopback0.local_ip4, - "BFD ECHO src IP equal to loopback IP") + self.assert_equal(p[IP].dst, self.pg0.local_ip4, "BFD ECHO dst IP") + self.assertNotEqual( + p[IP].src, + self.loopback0.local_ip4, + "BFD ECHO src IP equal to loopback IP", + ) self.logger.debug(ppp("Looping back packet:", p)) - self.assert_equal(p[Ether].dst, self.pg0.remote_mac, - "ECHO packet destination MAC address") + self.assert_equal( + p[Ether].dst, + self.pg0.remote_mac, + "ECHO packet destination MAC address", + ) p[Ether].dst = self.pg0.local_mac self.pg0.add_stream(p) self.test_session.rx_packets_echo += 1 @@ -1268,8 +1377,8 @@ class BFD4TestCase(VppTestCase): self.test_session.rx_packets += 1 if echo_seen: self.assertGreaterEqual( - p[BFD].required_min_rx_interval, - 1000000) + p[BFD].required_min_rx_interval, 1000000 + ) if "P" in p.sprintf("%BFD.flags%"): final = self.test_session.create_packet() final[BFD].flags = "F" @@ -1277,34 +1386,45 @@ class BFD4TestCase(VppTestCase): else: raise Exception(ppp("Received unknown packet:", p)) - self.assert_equal(len(self.vapi.collect_events()), 0, - "number of bfd events") + self.assert_equal( + len(self.vapi.collect_events()), 0, "number of bfd events" + ) self.test_session.send_packet() self.assertTrue(echo_seen, "No echo packets received") stats_after = bfd_grab_stats_snapshot(self) diff = bfd_stats_diff(stats_before, stats_after) # our rx is vpp tx and vice versa, also tolerate one packet off - self.assert_in_range(self.test_session.tx_packets, - diff.rx - 1, diff.rx + 1, "RX counter") - self.assert_in_range(self.test_session.rx_packets, - diff.tx - 1, diff.tx + 1, "TX counter") - self.assert_in_range(self.test_session.tx_packets_echo, - diff.rx_echo - 1, diff.rx_echo + 1, - "RX echo counter") - self.assert_in_range(self.test_session.rx_packets_echo, - diff.tx_echo - 1, diff.tx_echo + 1, - "TX echo counter") + self.assert_in_range( + self.test_session.tx_packets, diff.rx - 1, diff.rx + 1, "RX counter" + ) + self.assert_in_range( + self.test_session.rx_packets, diff.tx - 1, diff.tx + 1, "TX counter" + ) + self.assert_in_range( + self.test_session.tx_packets_echo, + diff.rx_echo - 1, + diff.rx_echo + 1, + "RX echo counter", + ) + self.assert_in_range( + self.test_session.rx_packets_echo, + diff.tx_echo - 1, + diff.tx_echo + 1, + "TX echo counter", + ) def test_echo_fail(self): - """ session goes down if echo function fails """ + """session goes down if echo function fails""" bfd_session_up(self) self.test_session.update(required_min_echo_rx=150000) self.test_session.send_packet() - detection_time = self.test_session.detect_mult *\ - self.vpp_session.required_min_rx / USEC_IN_SEC - self.vapi.bfd_udp_set_echo_source( - sw_if_index=self.loopback0.sw_if_index) + detection_time = ( + self.test_session.detect_mult + * self.vpp_session.required_min_rx + / USEC_IN_SEC + ) + self.vapi.bfd_udp_set_echo_source(sw_if_index=self.loopback0.sw_if_index) # echo function should be used now, but we will drop the echo packets verified_diag = False for dummy in range(3): @@ -1318,15 +1438,15 @@ class BFD4TestCase(VppTestCase): elif p.haslayer(BFD): if "P" in p.sprintf("%BFD.flags%"): self.assertGreaterEqual( - p[BFD].required_min_rx_interval, - 1000000) + p[BFD].required_min_rx_interval, 1000000 + ) final = self.test_session.create_packet() final[BFD].flags = "F" self.test_session.send_packet(final) if p[BFD].state == BFDState.down: - self.assert_equal(p[BFD].diag, - BFDDiagCode.echo_function_failed, - BFDDiagCode) + self.assert_equal( + p[BFD].diag, BFDDiagCode.echo_function_failed, BFDDiagCode + ) verified_diag = True else: raise Exception(ppp("Received unknown packet:", p)) @@ -1337,12 +1457,11 @@ class BFD4TestCase(VppTestCase): self.assertTrue(verified_diag, "Incorrect diagnostics code received") def test_echo_stop(self): - """ echo function stops if peer sets required min echo rx zero """ + """echo function stops if peer sets required min echo rx zero""" bfd_session_up(self) self.test_session.update(required_min_echo_rx=150000) self.test_session.send_packet() - self.vapi.bfd_udp_set_echo_source( - sw_if_index=self.loopback0.sw_if_index) + self.vapi.bfd_udp_set_echo_source(sw_if_index=self.loopback0.sw_if_index) # wait for first echo packet while True: p = self.pg0.wait_for_packet(1) @@ -1362,19 +1481,17 @@ class BFD4TestCase(VppTestCase): self.test_session.send_packet() # echo packets shouldn't arrive anymore for dummy in range(5): - wait_for_bfd_packet( - self, pcap_time_min=time.time() - self.vpp_clock_offset) + wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset) self.test_session.send_packet() events = self.vapi.collect_events() self.assert_equal(len(events), 0, "number of bfd events") def test_echo_source_removed(self): - """ echo function stops if echo source is removed """ + """echo function stops if echo source is removed""" bfd_session_up(self) self.test_session.update(required_min_echo_rx=150000) self.test_session.send_packet() - self.vapi.bfd_udp_set_echo_source( - sw_if_index=self.loopback0.sw_if_index) + self.vapi.bfd_udp_set_echo_source(sw_if_index=self.loopback0.sw_if_index) # wait for first echo packet while True: p = self.pg0.wait_for_packet(1) @@ -1394,18 +1511,16 @@ class BFD4TestCase(VppTestCase): self.test_session.send_packet() # echo packets shouldn't arrive anymore for dummy in range(5): - wait_for_bfd_packet( - self, pcap_time_min=time.time() - self.vpp_clock_offset) + wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset) self.test_session.send_packet() events = self.vapi.collect_events() self.assert_equal(len(events), 0, "number of bfd events") def test_stale_echo(self): - """ stale echo packets don't keep a session up """ + """stale echo packets don't keep a session up""" bfd_session_up(self) self.test_session.update(required_min_echo_rx=150000) - self.vapi.bfd_udp_set_echo_source( - sw_if_index=self.loopback0.sw_if_index) + self.vapi.bfd_udp_set_echo_source(sw_if_index=self.loopback0.sw_if_index) self.test_session.send_packet() # should be turned on - loopback echo packets echo_packet = None @@ -1417,8 +1532,12 @@ class BFD4TestCase(VppTestCase): if echo_packet is None: self.logger.debug(ppp("Got first echo packet:", p)) echo_packet = p - timeout_at = time.time() + self.vpp_session.detect_mult * \ - self.test_session.required_min_echo_rx / USEC_IN_SEC + timeout_at = ( + time.time() + + self.vpp_session.detect_mult + * self.test_session.required_min_echo_rx + / USEC_IN_SEC + ) else: self.logger.debug(ppp("Got followup echo packet:", p)) self.logger.debug(ppp("Looping back first echo packet:", p)) @@ -1434,15 +1553,18 @@ class BFD4TestCase(VppTestCase): if p[BFD].state == BFDState.down: self.assertIsNotNone( timeout_at, - "Session went down before first echo packet received") + "Session went down before first echo packet received", + ) now = time.time() self.assertGreaterEqual( - now, timeout_at, - "Session timeout at %s, but is expected at %s" % - (now, timeout_at)) - self.assert_equal(p[BFD].diag, - BFDDiagCode.echo_function_failed, - BFDDiagCode) + now, + timeout_at, + "Session timeout at %s, but is expected at %s" + % (now, timeout_at), + ) + self.assert_equal( + p[BFD].diag, BFDDiagCode.echo_function_failed, BFDDiagCode + ) events = self.vapi.collect_events() self.assert_equal(len(events), 1, "number of bfd events") self.assert_equal(events[0].state, BFDState.down, BFDState) @@ -1454,11 +1576,10 @@ class BFD4TestCase(VppTestCase): self.assertTrue(timeout_ok, "Expected timeout event didn't occur") def test_invalid_echo_checksum(self): - """ echo packets with invalid checksum don't keep a session up """ + """echo packets with invalid checksum don't keep a session up""" bfd_session_up(self) self.test_session.update(required_min_echo_rx=150000) - self.vapi.bfd_udp_set_echo_source( - sw_if_index=self.loopback0.sw_if_index) + self.vapi.bfd_udp_set_echo_source(sw_if_index=self.loopback0.sw_if_index) self.test_session.send_packet() # should be turned on - loopback echo packets timeout_at = None @@ -1468,8 +1589,12 @@ class BFD4TestCase(VppTestCase): if p[UDP].dport == BFD.udp_dport_echo: self.logger.debug(ppp("Got echo packet:", p)) if timeout_at is None: - timeout_at = time.time() + self.vpp_session.detect_mult * \ - self.test_session.required_min_echo_rx / USEC_IN_SEC + timeout_at = ( + time.time() + + self.vpp_session.detect_mult + * self.test_session.required_min_echo_rx + / USEC_IN_SEC + ) p[BFD_vpp_echo].checksum = getrandbits(64) p[Ether].dst = self.pg0.local_mac self.logger.debug(ppp("Looping back modified echo packet:", p)) @@ -1484,15 +1609,18 @@ class BFD4TestCase(VppTestCase): if p[BFD].state == BFDState.down: self.assertIsNotNone( timeout_at, - "Session went down before first echo packet received") + "Session went down before first echo packet received", + ) now = time.time() self.assertGreaterEqual( - now, timeout_at, - "Session timeout at %s, but is expected at %s" % - (now, timeout_at)) - self.assert_equal(p[BFD].diag, - BFDDiagCode.echo_function_failed, - BFDDiagCode) + now, + timeout_at, + "Session timeout at %s, but is expected at %s" + % (now, timeout_at), + ) + self.assert_equal( + p[BFD].diag, BFDDiagCode.echo_function_failed, BFDDiagCode + ) events = self.vapi.collect_events() self.assert_equal(len(events), 1, "number of bfd events") self.assert_equal(events[0].state, BFDState.down, BFDState) @@ -1504,7 +1632,7 @@ class BFD4TestCase(VppTestCase): self.assertTrue(timeout_ok, "Expected timeout event didn't occur") def test_admin_up_down(self): - """ put session admin-up and admin-down """ + """put session admin-up and admin-down""" bfd_session_up(self) self.vpp_session.admin_down() self.pg0.enable_capture() @@ -1523,33 +1651,30 @@ class BFD4TestCase(VppTestCase): self.test_session.update(state=BFDState.down) e = self.vapi.wait_for_event(1, "bfd_udp_session_event") verify_event(self, e, expected_state=BFDState.down) - p = wait_for_bfd_packet( - self, pcap_time_min=time.time() - self.vpp_clock_offset) + p = wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset) self.assert_equal(p[BFD].state, BFDState.down, BFDState) self.test_session.send_packet() - p = wait_for_bfd_packet( - self, pcap_time_min=time.time() - self.vpp_clock_offset) + p = wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset) self.assert_equal(p[BFD].state, BFDState.init, BFDState) e = self.vapi.wait_for_event(1, "bfd_udp_session_event") verify_event(self, e, expected_state=BFDState.init) self.test_session.update(state=BFDState.up) self.test_session.send_packet() - p = wait_for_bfd_packet( - self, pcap_time_min=time.time() - self.vpp_clock_offset) + p = wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset) self.assert_equal(p[BFD].state, BFDState.up, BFDState) e = self.vapi.wait_for_event(1, "bfd_udp_session_event") verify_event(self, e, expected_state=BFDState.up) def test_config_change_remote_demand(self): - """ configuration change while peer in demand mode """ + """configuration change while peer in demand mode""" bfd_session_up(self) demand = self.test_session.create_packet() demand[BFD].flags = "D" self.test_session.send_packet(demand) self.vpp_session.modify_parameters( - required_min_rx=2 * self.vpp_session.required_min_rx) - p = wait_for_bfd_packet( - self, pcap_time_min=time.time() - self.vpp_clock_offset) + required_min_rx=2 * self.vpp_session.required_min_rx + ) + p = wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset) # poll bit must be set self.assertIn("P", p.sprintf("%BFD.flags%"), "Poll bit not set") # terminate poll sequence @@ -1557,10 +1682,11 @@ class BFD4TestCase(VppTestCase): final[BFD].flags = "D+F" self.test_session.send_packet(final) # vpp should be quiet now again - transmit_time = 0.9 \ - * max(self.vpp_session.required_min_rx, - self.test_session.desired_min_tx) \ + transmit_time = ( + 0.9 + * max(self.vpp_session.required_min_rx, self.test_session.desired_min_tx) / USEC_IN_SEC + ) count = 0 for dummy in range(self.test_session.detect_mult * 2): self.sleep(transmit_time) @@ -1578,7 +1704,7 @@ class BFD4TestCase(VppTestCase): self.assert_equal(len(events), 0, "number of events received") def test_intf_deleted(self): - """ interface with bfd session deleted """ + """interface with bfd session deleted""" intf = VppLoInterface(self) intf.config_ip4() intf.admin_up() @@ -1595,7 +1721,7 @@ class BFD4TestCase(VppTestCase): @tag_run_solo @tag_fixme_vpp_workers class BFD6TestCase(VppTestCase): - """Bidirectional Forwarding Detection (BFD) (IPv6) """ + """Bidirectional Forwarding Detection (BFD) (IPv6)""" pg0 = None vpp_clock_offset = None @@ -1631,11 +1757,11 @@ class BFD6TestCase(VppTestCase): self.vapi.want_bfd_events() self.pg0.enable_capture() try: - self.bfd_udp4_sessions = self.statistics['/bfd/udp4/sessions'] - self.bfd_udp6_sessions = self.statistics['/bfd/udp6/sessions'] - self.vpp_session = VppBFDUDPSession(self, self.pg0, - self.pg0.remote_ip6, - af=AF_INET6) + self.bfd_udp4_sessions = self.statistics["/bfd/udp4/sessions"] + self.bfd_udp6_sessions = self.statistics["/bfd/udp6/sessions"] + self.vpp_session = VppBFDUDPSession( + self, self.pg0, self.pg0.remote_ip6, af=AF_INET6 + ) self.vpp_session.add_vpp_config() self.vpp_session.admin_up() self.test_session = BFDTestSession(self, self.pg0, AF_INET6) @@ -1651,26 +1777,29 @@ class BFD6TestCase(VppTestCase): super(BFD6TestCase, self).tearDown() def test_session_up(self): - """ bring BFD session up """ + """bring BFD session up""" bfd_session_up(self) - bfd_udp4_sessions = self.statistics['/bfd/udp4/sessions'] - bfd_udp6_sessions = self.statistics['/bfd/udp6/sessions'] + bfd_udp4_sessions = self.statistics["/bfd/udp4/sessions"] + bfd_udp6_sessions = self.statistics["/bfd/udp6/sessions"] self.assert_equal(bfd_udp4_sessions, self.bfd_udp4_sessions) self.assert_equal(bfd_udp6_sessions - self.bfd_udp6_sessions, 1) def test_session_up_by_ip(self): - """ bring BFD session up - first frame looked up by address pair """ + """bring BFD session up - first frame looked up by address pair""" self.logger.info("BFD: Sending Slow control frame") self.test_session.update(my_discriminator=randint(0, 40000000)) self.test_session.send_packet() self.pg0.enable_capture() p = self.pg0.wait_for_packet(1) - self.assert_equal(p[BFD].your_discriminator, - self.test_session.my_discriminator, - "BFD - your discriminator") + self.assert_equal( + p[BFD].your_discriminator, + self.test_session.my_discriminator, + "BFD - your discriminator", + ) self.assert_equal(p[BFD].state, BFDState.init, BFDState) - self.test_session.update(your_discriminator=p[BFD].my_discriminator, - state=BFDState.up) + self.test_session.update( + your_discriminator=p[BFD].my_discriminator, state=BFDState.up + ) self.logger.info("BFD: Waiting for event") e = self.vapi.wait_for_event(1, "bfd_udp_session_event") verify_event(self, e, expected_state=BFDState.init) @@ -1685,17 +1814,16 @@ class BFD6TestCase(VppTestCase): self.assert_equal(self.vpp_session.state, BFDState.up, BFDState) def test_hold_up(self): - """ hold BFD session up """ + """hold BFD session up""" bfd_session_up(self) for dummy in range(self.test_session.detect_mult * 2): wait_for_bfd_packet(self) self.test_session.send_packet() - self.assert_equal(len(self.vapi.collect_events()), 0, - "number of bfd events") + self.assert_equal(len(self.vapi.collect_events()), 0, "number of bfd events") self.assert_equal(self.vpp_session.state, BFDState.up, BFDState) def test_echo_looped_back(self): - """ echo packets looped back """ + """echo packets looped back""" bfd_session_up(self) stats_before = bfd_grab_stats_snapshot(self) self.pg0.enable_capture() @@ -1703,14 +1831,14 @@ class BFD6TestCase(VppTestCase): # random source port low enough to increment a few times.. udp_sport_tx = randint(1, 50000) udp_sport_rx = udp_sport_tx - echo_packet = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(src=self.pg0.remote_ip6, - dst=self.pg0.remote_ip6) / - UDP(dport=BFD.udp_dport_echo) / - Raw("this should be looped back")) + echo_packet = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.remote_ip6) + / UDP(dport=BFD.udp_dport_echo) + / Raw("this should be looped back") + ) for dummy in range(echo_packet_count): - self.sleep(.01, "delay between echo packets") + self.sleep(0.01, "delay between echo packets") echo_packet[UDP].sport = udp_sport_tx udp_sport_tx += 1 self.logger.debug(ppp("Sending packet:", echo_packet)) @@ -1722,8 +1850,7 @@ class BFD6TestCase(VppTestCase): p = self.pg0.wait_for_packet(1) self.logger.debug(ppp("Got packet:", p)) ether = p[Ether] - self.assert_equal(self.pg0.remote_mac, - ether.dst, "Destination MAC") + self.assert_equal(self.pg0.remote_mac, ether.dst, "Destination MAC") self.assert_equal(self.pg0.local_mac, ether.src, "Source MAC") ip = p[IPv6] self.assert_equal(self.pg0.remote_ip6, ip.dst, "Destination IP") @@ -1732,50 +1859,57 @@ class BFD6TestCase(VppTestCase): bfd_control_packets_rx += 1 continue self.assert_equal(self.pg0.remote_ip6, ip.src, "Source IP") - self.assert_equal(udp.dport, BFD.udp_dport_echo, - "UDP destination port") + self.assert_equal(udp.dport, BFD.udp_dport_echo, "UDP destination port") self.assert_equal(udp.sport, udp_sport_rx, "UDP source port") udp_sport_rx += 1 # need to compare the hex payload here, otherwise BFD_vpp_echo # gets in way - self.assertEqual(scapy.compat.raw(p[UDP].payload), - scapy.compat.raw(echo_packet[UDP].payload), - "Received packet is not the echo packet sent") + self.assertEqual( + scapy.compat.raw(p[UDP].payload), + scapy.compat.raw(echo_packet[UDP].payload), + "Received packet is not the echo packet sent", + ) counter += 1 - self.assert_equal(udp_sport_tx, udp_sport_rx, "UDP source port (== " - "ECHO packet identifier for test purposes)") + self.assert_equal( + udp_sport_tx, + udp_sport_rx, + "UDP source port (== ECHO packet identifier for test purposes)", + ) stats_after = bfd_grab_stats_snapshot(self) diff = bfd_stats_diff(stats_before, stats_after) + self.assertEqual(0, diff.rx, "RX counter bumped but no BFD packets sent") + self.assertEqual(bfd_control_packets_rx, diff.tx, "TX counter incorrect") self.assertEqual( - 0, diff.rx, "RX counter bumped but no BFD packets sent") - self.assertEqual(bfd_control_packets_rx, - diff.tx, "TX counter incorrect") - self.assertEqual(0, diff.rx_echo, - "RX echo counter bumped but no BFD session exists") - self.assertEqual(0, diff.tx_echo, - "TX echo counter bumped but no BFD session exists") + 0, diff.rx_echo, "RX echo counter bumped but no BFD session exists" + ) + self.assertEqual( + 0, diff.tx_echo, "TX echo counter bumped but no BFD session exists" + ) def test_echo(self): - """ echo function """ + """echo function""" stats_before = bfd_grab_stats_snapshot(self) bfd_session_up(self) self.test_session.update(required_min_echo_rx=150000) self.test_session.send_packet() - detection_time = self.test_session.detect_mult *\ - self.vpp_session.required_min_rx / USEC_IN_SEC + detection_time = ( + self.test_session.detect_mult + * self.vpp_session.required_min_rx + / USEC_IN_SEC + ) # echo shouldn't work without echo source set for dummy in range(10): sleep = self.vpp_session.required_min_rx / USEC_IN_SEC self.sleep(sleep, "delay before sending bfd packet") self.test_session.send_packet() - p = wait_for_bfd_packet( - self, pcap_time_min=time.time() - self.vpp_clock_offset) - self.assert_equal(p[BFD].required_min_rx_interval, - self.vpp_session.required_min_rx, - "BFD required min rx interval") + p = wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset) + self.assert_equal( + p[BFD].required_min_rx_interval, + self.vpp_session.required_min_rx, + "BFD required min rx interval", + ) self.test_session.send_packet() - self.vapi.bfd_udp_set_echo_source( - sw_if_index=self.loopback0.sw_if_index) + self.vapi.bfd_udp_set_echo_source(sw_if_index=self.loopback0.sw_if_index) echo_seen = False # should be turned on - loopback echo packets for dummy in range(3): @@ -1785,12 +1919,19 @@ class BFD6TestCase(VppTestCase): self.logger.debug(ppp("Got packet:", p)) if p[UDP].dport == BFD.udp_dport_echo: self.assert_equal( - p[IPv6].dst, self.pg0.local_ip6, "BFD ECHO dst IP") - self.assertNotEqual(p[IPv6].src, self.loopback0.local_ip6, - "BFD ECHO src IP equal to loopback IP") + p[IPv6].dst, self.pg0.local_ip6, "BFD ECHO dst IP" + ) + self.assertNotEqual( + p[IPv6].src, + self.loopback0.local_ip6, + "BFD ECHO src IP equal to loopback IP", + ) self.logger.debug(ppp("Looping back packet:", p)) - self.assert_equal(p[Ether].dst, self.pg0.remote_mac, - "ECHO packet destination MAC address") + self.assert_equal( + p[Ether].dst, + self.pg0.remote_mac, + "ECHO packet destination MAC address", + ) self.test_session.rx_packets_echo += 1 self.test_session.tx_packets_echo += 1 p[Ether].dst = self.pg0.local_mac @@ -1801,8 +1942,8 @@ class BFD6TestCase(VppTestCase): self.test_session.rx_packets += 1 if echo_seen: self.assertGreaterEqual( - p[BFD].required_min_rx_interval, - 1000000) + p[BFD].required_min_rx_interval, 1000000 + ) if "P" in p.sprintf("%BFD.flags%"): final = self.test_session.create_packet() final[BFD].flags = "F" @@ -1810,33 +1951,41 @@ class BFD6TestCase(VppTestCase): else: raise Exception(ppp("Received unknown packet:", p)) - self.assert_equal(len(self.vapi.collect_events()), 0, - "number of bfd events") + self.assert_equal( + len(self.vapi.collect_events()), 0, "number of bfd events" + ) self.test_session.send_packet() self.assertTrue(echo_seen, "No echo packets received") stats_after = bfd_grab_stats_snapshot(self) diff = bfd_stats_diff(stats_before, stats_after) # our rx is vpp tx and vice versa, also tolerate one packet off - self.assert_in_range(self.test_session.tx_packets, - diff.rx - 1, diff.rx + 1, "RX counter") - self.assert_in_range(self.test_session.rx_packets, - diff.tx - 1, diff.tx + 1, "TX counter") - self.assert_in_range(self.test_session.tx_packets_echo, - diff.rx_echo - 1, diff.rx_echo + 1, - "RX echo counter") - self.assert_in_range(self.test_session.rx_packets_echo, - diff.tx_echo - 1, diff.tx_echo + 1, - "TX echo counter") + self.assert_in_range( + self.test_session.tx_packets, diff.rx - 1, diff.rx + 1, "RX counter" + ) + self.assert_in_range( + self.test_session.rx_packets, diff.tx - 1, diff.tx + 1, "TX counter" + ) + self.assert_in_range( + self.test_session.tx_packets_echo, + diff.rx_echo - 1, + diff.rx_echo + 1, + "RX echo counter", + ) + self.assert_in_range( + self.test_session.rx_packets_echo, + diff.tx_echo - 1, + diff.tx_echo + 1, + "TX echo counter", + ) def test_intf_deleted(self): - """ interface with bfd session deleted """ + """interface with bfd session deleted""" intf = VppLoInterface(self) intf.config_ip6() intf.admin_up() sw_if_index = intf.sw_if_index - vpp_session = VppBFDUDPSession( - self, intf, intf.remote_ip6, af=AF_INET6) + vpp_session = VppBFDUDPSession(self, intf, intf.remote_ip6, af=AF_INET6) vpp_session.add_vpp_config() vpp_session.admin_up() intf.remove_vpp_config() @@ -1847,7 +1996,7 @@ class BFD6TestCase(VppTestCase): @tag_run_solo class BFDFIBTestCase(VppTestCase): - """ BFD-FIB interactions (IPv6) """ + """BFD-FIB interactions (IPv6)""" vpp_session = None test_session = None @@ -1880,40 +2029,48 @@ class BFDFIBTestCase(VppTestCase): @staticmethod def pkt_is_not_data_traffic(p): - """ not data traffic implies BFD or the usual IPv6 ND/RA""" + """not data traffic implies BFD or the usual IPv6 ND/RA""" if p.haslayer(BFD) or is_ipv6_misc(p): return True return False def test_session_with_fib(self): - """ BFD-FIB interactions """ + """BFD-FIB interactions""" # packets to match against both of the routes - p = [(Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src="3001::1", dst="2001::1") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)), - (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src="3001::1", dst="2002::1") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100))] + p = [ + ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src="3001::1", dst="2001::1") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ), + ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src="3001::1", dst="2002::1") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ), + ] # A recursive and a non-recursive route via a next-hop that # will have a BFD session - ip_2001_s_64 = VppIpRoute(self, "2001::", 64, - [VppRoutePath(self.pg0.remote_ip6, - self.pg0.sw_if_index)]) - ip_2002_s_64 = VppIpRoute(self, "2002::", 64, - [VppRoutePath(self.pg0.remote_ip6, - 0xffffffff)]) + ip_2001_s_64 = VppIpRoute( + self, + "2001::", + 64, + [VppRoutePath(self.pg0.remote_ip6, self.pg0.sw_if_index)], + ) + ip_2002_s_64 = VppIpRoute( + self, "2002::", 64, [VppRoutePath(self.pg0.remote_ip6, 0xFFFFFFFF)] + ) ip_2001_s_64.add_vpp_config() ip_2002_s_64.add_vpp_config() # bring the session up now the routes are present - self.vpp_session = VppBFDUDPSession(self, - self.pg0, - self.pg0.remote_ip6, - af=AF_INET6) + self.vpp_session = VppBFDUDPSession( + self, self.pg0, self.pg0.remote_ip6, af=AF_INET6 + ) self.vpp_session.add_vpp_config() self.vpp_session.admin_up() self.test_session = BFDTestSession(self, self.pg0, AF_INET6) @@ -1925,10 +2082,9 @@ class BFDFIBTestCase(VppTestCase): self.pg_start() for packet in p: captured = self.pg0.wait_for_packet( - 1, - filter_out_fn=self.pkt_is_not_data_traffic) - self.assertEqual(captured[IPv6].dst, - packet[IPv6].dst) + 1, filter_out_fn=self.pkt_is_not_data_traffic + ) + self.assertEqual(captured[IPv6].dst, packet[IPv6].dst) # session is up - traffic is dropped bfd_session_down(self) @@ -1945,15 +2101,14 @@ class BFDFIBTestCase(VppTestCase): self.pg_start() for packet in p: captured = self.pg0.wait_for_packet( - 1, - filter_out_fn=self.pkt_is_not_data_traffic) - self.assertEqual(captured[IPv6].dst, - packet[IPv6].dst) + 1, filter_out_fn=self.pkt_is_not_data_traffic + ) + self.assertEqual(captured[IPv6].dst, packet[IPv6].dst) @unittest.skipUnless(config.extended, "part of extended tests") class BFDTunTestCase(VppTestCase): - """ BFD over GRE tunnel """ + """BFD over GRE tunnel""" vpp_session = None test_session = None @@ -1986,42 +2141,44 @@ class BFDTunTestCase(VppTestCase): @staticmethod def pkt_is_not_data_traffic(p): - """ not data traffic implies BFD or the usual IPv6 ND/RA""" + """not data traffic implies BFD or the usual IPv6 ND/RA""" if p.haslayer(BFD) or is_ipv6_misc(p): return True return False def test_bfd_o_gre(self): - """ BFD-o-GRE """ + """BFD-o-GRE""" # A GRE interface over which to run a BFD session - gre_if = VppGreInterface(self, - self.pg0.local_ip4, - self.pg0.remote_ip4) + gre_if = VppGreInterface(self, self.pg0.local_ip4, self.pg0.remote_ip4) gre_if.add_vpp_config() gre_if.admin_up() gre_if.config_ip4() # bring the session up now the routes are present - self.vpp_session = VppBFDUDPSession(self, - gre_if, - gre_if.remote_ip4, - is_tunnel=True) + self.vpp_session = VppBFDUDPSession( + self, gre_if, gre_if.remote_ip4, is_tunnel=True + ) self.vpp_session.add_vpp_config() self.vpp_session.admin_up() self.test_session = BFDTestSession( - self, gre_if, AF_INET, - tunnel_header=(IP(src=self.pg0.remote_ip4, - dst=self.pg0.local_ip4) / - GRE()), - phy_interface=self.pg0) + self, + gre_if, + AF_INET, + tunnel_header=(IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / GRE()), + phy_interface=self.pg0, + ) # packets to match against both of the routes - p = [(Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=gre_if.remote_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100))] + p = [ + ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=gre_if.remote_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + ] # session is up - traffic passes bfd_session_up(self) @@ -2034,7 +2191,7 @@ class BFDTunTestCase(VppTestCase): @tag_run_solo class BFDSHA1TestCase(VppTestCase): - """Bidirectional Forwarding Detection (BFD) (SHA1 auth) """ + """Bidirectional Forwarding Detection (BFD) (SHA1 auth)""" pg0 = None vpp_clock_offset = None @@ -2072,31 +2229,39 @@ class BFDSHA1TestCase(VppTestCase): super(BFDSHA1TestCase, self).tearDown() def test_session_up(self): - """ bring BFD session up """ + """bring BFD session up""" key = self.factory.create_random_key(self) key.add_vpp_config() - self.vpp_session = VppBFDUDPSession(self, self.pg0, - self.pg0.remote_ip4, - sha1_key=key) + self.vpp_session = VppBFDUDPSession( + self, self.pg0, self.pg0.remote_ip4, sha1_key=key + ) self.vpp_session.add_vpp_config() self.vpp_session.admin_up() self.test_session = BFDTestSession( - self, self.pg0, AF_INET, sha1_key=key, - bfd_key_id=self.vpp_session.bfd_key_id) + self, + self.pg0, + AF_INET, + sha1_key=key, + bfd_key_id=self.vpp_session.bfd_key_id, + ) bfd_session_up(self) def test_hold_up(self): - """ hold BFD session up """ + """hold BFD session up""" key = self.factory.create_random_key(self) key.add_vpp_config() - self.vpp_session = VppBFDUDPSession(self, self.pg0, - self.pg0.remote_ip4, - sha1_key=key) + self.vpp_session = VppBFDUDPSession( + self, self.pg0, self.pg0.remote_ip4, sha1_key=key + ) self.vpp_session.add_vpp_config() self.vpp_session.admin_up() self.test_session = BFDTestSession( - self, self.pg0, AF_INET, sha1_key=key, - bfd_key_id=self.vpp_session.bfd_key_id) + self, + self.pg0, + AF_INET, + sha1_key=key, + bfd_key_id=self.vpp_session.bfd_key_id, + ) bfd_session_up(self) for dummy in range(self.test_session.detect_mult * 2): wait_for_bfd_packet(self) @@ -2104,19 +2269,23 @@ class BFDSHA1TestCase(VppTestCase): self.assert_equal(self.vpp_session.state, BFDState.up, BFDState) def test_hold_up_meticulous(self): - """ hold BFD session up - meticulous auth """ - key = self.factory.create_random_key( - self, BFDAuthType.meticulous_keyed_sha1) + """hold BFD session up - meticulous auth""" + key = self.factory.create_random_key(self, BFDAuthType.meticulous_keyed_sha1) key.add_vpp_config() - self.vpp_session = VppBFDUDPSession(self, self.pg0, - self.pg0.remote_ip4, sha1_key=key) + self.vpp_session = VppBFDUDPSession( + self, self.pg0, self.pg0.remote_ip4, sha1_key=key + ) self.vpp_session.add_vpp_config() self.vpp_session.admin_up() # specify sequence number so that it wraps self.test_session = BFDTestSession( - self, self.pg0, AF_INET, sha1_key=key, + self, + self.pg0, + AF_INET, + sha1_key=key, bfd_key_id=self.vpp_session.bfd_key_id, - our_seq_number=0xFFFFFFFF - 4) + our_seq_number=0xFFFFFFFF - 4, + ) bfd_session_up(self) for dummy in range(30): wait_for_bfd_packet(self) @@ -2125,35 +2294,47 @@ class BFDSHA1TestCase(VppTestCase): self.assert_equal(self.vpp_session.state, BFDState.up, BFDState) def test_send_bad_seq_number(self): - """ session is not kept alive by msgs with bad sequence numbers""" - key = self.factory.create_random_key( - self, BFDAuthType.meticulous_keyed_sha1) + """session is not kept alive by msgs with bad sequence numbers""" + key = self.factory.create_random_key(self, BFDAuthType.meticulous_keyed_sha1) key.add_vpp_config() - self.vpp_session = VppBFDUDPSession(self, self.pg0, - self.pg0.remote_ip4, sha1_key=key) + self.vpp_session = VppBFDUDPSession( + self, self.pg0, self.pg0.remote_ip4, sha1_key=key + ) self.vpp_session.add_vpp_config() self.test_session = BFDTestSession( - self, self.pg0, AF_INET, sha1_key=key, - bfd_key_id=self.vpp_session.bfd_key_id) + self, + self.pg0, + AF_INET, + sha1_key=key, + bfd_key_id=self.vpp_session.bfd_key_id, + ) bfd_session_up(self) - detection_time = self.test_session.detect_mult *\ - self.vpp_session.required_min_rx / USEC_IN_SEC + detection_time = ( + self.test_session.detect_mult + * self.vpp_session.required_min_rx + / USEC_IN_SEC + ) send_until = time.time() + 2 * detection_time while time.time() < send_until: self.test_session.send_packet() - self.sleep(0.7 * self.vpp_session.required_min_rx / USEC_IN_SEC, - "time between bfd packets") + self.sleep( + 0.7 * self.vpp_session.required_min_rx / USEC_IN_SEC, + "time between bfd packets", + ) e = self.vapi.collect_events() # session should be down now, because the sequence numbers weren't # updated self.assert_equal(len(e), 1, "number of bfd events") verify_event(self, e[0], expected_state=BFDState.down) - def execute_rogue_session_scenario(self, vpp_bfd_udp_session, - legitimate_test_session, - rogue_test_session, - rogue_bfd_values=None): - """ execute a rogue session interaction scenario + def execute_rogue_session_scenario( + self, + vpp_bfd_udp_session, + legitimate_test_session, + rogue_test_session, + rogue_bfd_values=None, + ): + """execute a rogue session interaction scenario 1. create vpp session, add config 2. bring the legitimate session up @@ -2178,7 +2359,8 @@ class BFDSHA1TestCase(VppTestCase): detect_mult=self.test_session.detect_mult, diag=self.test_session.diag, state=self.test_session.state, - auth_type=self.test_session.auth_type) + auth_type=self.test_session.auth_type, + ) if rogue_bfd_values: rogue_test_session.update(**rogue_bfd_values) rogue_test_session.update(state=BFDState.down) @@ -2187,69 +2369,84 @@ class BFDSHA1TestCase(VppTestCase): self.assert_equal(self.vpp_session.state, BFDState.up, BFDState) def test_mismatch_auth(self): - """ session is not brought down by unauthenticated msg """ + """session is not brought down by unauthenticated msg""" key = self.factory.create_random_key(self) key.add_vpp_config() vpp_session = VppBFDUDPSession( - self, self.pg0, self.pg0.remote_ip4, sha1_key=key) + self, self.pg0, self.pg0.remote_ip4, sha1_key=key + ) legitimate_test_session = BFDTestSession( - self, self.pg0, AF_INET, sha1_key=key, - bfd_key_id=vpp_session.bfd_key_id) + self, self.pg0, AF_INET, sha1_key=key, bfd_key_id=vpp_session.bfd_key_id + ) rogue_test_session = BFDTestSession(self, self.pg0, AF_INET) - self.execute_rogue_session_scenario(vpp_session, - legitimate_test_session, - rogue_test_session) + self.execute_rogue_session_scenario( + vpp_session, legitimate_test_session, rogue_test_session + ) def test_mismatch_bfd_key_id(self): - """ session is not brought down by msg with non-existent key-id """ + """session is not brought down by msg with non-existent key-id""" key = self.factory.create_random_key(self) key.add_vpp_config() vpp_session = VppBFDUDPSession( - self, self.pg0, self.pg0.remote_ip4, sha1_key=key) + self, self.pg0, self.pg0.remote_ip4, sha1_key=key + ) # pick a different random bfd key id x = randint(0, 255) while x == vpp_session.bfd_key_id: x = randint(0, 255) legitimate_test_session = BFDTestSession( - self, self.pg0, AF_INET, sha1_key=key, - bfd_key_id=vpp_session.bfd_key_id) + self, self.pg0, AF_INET, sha1_key=key, bfd_key_id=vpp_session.bfd_key_id + ) rogue_test_session = BFDTestSession( - self, self.pg0, AF_INET, sha1_key=key, bfd_key_id=x) - self.execute_rogue_session_scenario(vpp_session, - legitimate_test_session, - rogue_test_session) + self, self.pg0, AF_INET, sha1_key=key, bfd_key_id=x + ) + self.execute_rogue_session_scenario( + vpp_session, legitimate_test_session, rogue_test_session + ) def test_mismatched_auth_type(self): - """ session is not brought down by msg with wrong auth type """ + """session is not brought down by msg with wrong auth type""" key = self.factory.create_random_key(self) key.add_vpp_config() vpp_session = VppBFDUDPSession( - self, self.pg0, self.pg0.remote_ip4, sha1_key=key) + self, self.pg0, self.pg0.remote_ip4, sha1_key=key + ) legitimate_test_session = BFDTestSession( - self, self.pg0, AF_INET, sha1_key=key, - bfd_key_id=vpp_session.bfd_key_id) + self, self.pg0, AF_INET, sha1_key=key, bfd_key_id=vpp_session.bfd_key_id + ) rogue_test_session = BFDTestSession( - self, self.pg0, AF_INET, sha1_key=key, - bfd_key_id=vpp_session.bfd_key_id) + self, self.pg0, AF_INET, sha1_key=key, bfd_key_id=vpp_session.bfd_key_id + ) self.execute_rogue_session_scenario( - vpp_session, legitimate_test_session, rogue_test_session, - {'auth_type': BFDAuthType.keyed_md5}) + vpp_session, + legitimate_test_session, + rogue_test_session, + {"auth_type": BFDAuthType.keyed_md5}, + ) def test_restart(self): - """ simulate remote peer restart and resynchronization """ - key = self.factory.create_random_key( - self, BFDAuthType.meticulous_keyed_sha1) + """simulate remote peer restart and resynchronization""" + key = self.factory.create_random_key(self, BFDAuthType.meticulous_keyed_sha1) key.add_vpp_config() - self.vpp_session = VppBFDUDPSession(self, self.pg0, - self.pg0.remote_ip4, sha1_key=key) + self.vpp_session = VppBFDUDPSession( + self, self.pg0, self.pg0.remote_ip4, sha1_key=key + ) self.vpp_session.add_vpp_config() self.test_session = BFDTestSession( - self, self.pg0, AF_INET, sha1_key=key, - bfd_key_id=self.vpp_session.bfd_key_id, our_seq_number=0) + self, + self.pg0, + AF_INET, + sha1_key=key, + bfd_key_id=self.vpp_session.bfd_key_id, + our_seq_number=0, + ) bfd_session_up(self) # don't send any packets for 2*detection_time - detection_time = self.test_session.detect_mult *\ - self.vpp_session.required_min_rx / USEC_IN_SEC + detection_time = ( + self.test_session.detect_mult + * self.vpp_session.required_min_rx + / USEC_IN_SEC + ) self.sleep(2 * detection_time, "simulating peer restart") events = self.vapi.collect_events() self.assert_equal(len(events), 1, "number of bfd events") @@ -2266,7 +2463,7 @@ class BFDSHA1TestCase(VppTestCase): @tag_run_solo class BFDAuthOnOffTestCase(VppTestCase): - """Bidirectional Forwarding Detection (BFD) (changing auth) """ + """Bidirectional Forwarding Detection (BFD) (changing auth)""" pg0 = None vpp_session = None @@ -2303,11 +2500,10 @@ class BFDAuthOnOffTestCase(VppTestCase): super(BFDAuthOnOffTestCase, self).tearDown() def test_auth_on_immediate(self): - """ turn auth on without disturbing session state (immediate) """ + """turn auth on without disturbing session state (immediate)""" key = self.factory.create_random_key(self) key.add_vpp_config() - self.vpp_session = VppBFDUDPSession(self, self.pg0, - self.pg0.remote_ip4) + self.vpp_session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4) self.vpp_session.add_vpp_config() self.test_session = BFDTestSession(self, self.pg0, AF_INET) bfd_session_up(self) @@ -2323,19 +2519,23 @@ class BFDAuthOnOffTestCase(VppTestCase): self.assert_equal(p[BFD].state, BFDState.up, BFDState) self.test_session.send_packet() self.assert_equal(self.vpp_session.state, BFDState.up, BFDState) - self.assert_equal(len(self.vapi.collect_events()), 0, - "number of bfd events") + self.assert_equal(len(self.vapi.collect_events()), 0, "number of bfd events") def test_auth_off_immediate(self): - """ turn auth off without disturbing session state (immediate) """ + """turn auth off without disturbing session state (immediate)""" key = self.factory.create_random_key(self) key.add_vpp_config() - self.vpp_session = VppBFDUDPSession(self, self.pg0, - self.pg0.remote_ip4, sha1_key=key) + self.vpp_session = VppBFDUDPSession( + self, self.pg0, self.pg0.remote_ip4, sha1_key=key + ) self.vpp_session.add_vpp_config() self.test_session = BFDTestSession( - self, self.pg0, AF_INET, sha1_key=key, - bfd_key_id=self.vpp_session.bfd_key_id) + self, + self.pg0, + AF_INET, + sha1_key=key, + bfd_key_id=self.vpp_session.bfd_key_id, + ) bfd_session_up(self) # self.vapi.want_bfd_events(enable_disable=0) for dummy in range(self.test_session.detect_mult * 2): @@ -2352,21 +2552,25 @@ class BFDAuthOnOffTestCase(VppTestCase): self.test_session.inc_seq_num() self.test_session.send_packet() self.assert_equal(self.vpp_session.state, BFDState.up, BFDState) - self.assert_equal(len(self.vapi.collect_events()), 0, - "number of bfd events") + self.assert_equal(len(self.vapi.collect_events()), 0, "number of bfd events") def test_auth_change_key_immediate(self): - """ change auth key without disturbing session state (immediate) """ + """change auth key without disturbing session state (immediate)""" key1 = self.factory.create_random_key(self) key1.add_vpp_config() key2 = self.factory.create_random_key(self) key2.add_vpp_config() - self.vpp_session = VppBFDUDPSession(self, self.pg0, - self.pg0.remote_ip4, sha1_key=key1) + self.vpp_session = VppBFDUDPSession( + self, self.pg0, self.pg0.remote_ip4, sha1_key=key1 + ) self.vpp_session.add_vpp_config() self.test_session = BFDTestSession( - self, self.pg0, AF_INET, sha1_key=key1, - bfd_key_id=self.vpp_session.bfd_key_id) + self, + self.pg0, + AF_INET, + sha1_key=key1, + bfd_key_id=self.vpp_session.bfd_key_id, + ) bfd_session_up(self) for dummy in range(self.test_session.detect_mult * 2): p = wait_for_bfd_packet(self) @@ -2380,15 +2584,13 @@ class BFDAuthOnOffTestCase(VppTestCase): self.assert_equal(p[BFD].state, BFDState.up, BFDState) self.test_session.send_packet() self.assert_equal(self.vpp_session.state, BFDState.up, BFDState) - self.assert_equal(len(self.vapi.collect_events()), 0, - "number of bfd events") + self.assert_equal(len(self.vapi.collect_events()), 0, "number of bfd events") def test_auth_on_delayed(self): - """ turn auth on without disturbing session state (delayed) """ + """turn auth on without disturbing session state (delayed)""" key = self.factory.create_random_key(self) key.add_vpp_config() - self.vpp_session = VppBFDUDPSession(self, self.pg0, - self.pg0.remote_ip4) + self.vpp_session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4) self.vpp_session.add_vpp_config() self.test_session = BFDTestSession(self, self.pg0, AF_INET) bfd_session_up(self) @@ -2408,19 +2610,23 @@ class BFDAuthOnOffTestCase(VppTestCase): self.assert_equal(p[BFD].state, BFDState.up, BFDState) self.test_session.send_packet() self.assert_equal(self.vpp_session.state, BFDState.up, BFDState) - self.assert_equal(len(self.vapi.collect_events()), 0, - "number of bfd events") + self.assert_equal(len(self.vapi.collect_events()), 0, "number of bfd events") def test_auth_off_delayed(self): - """ turn auth off without disturbing session state (delayed) """ + """turn auth off without disturbing session state (delayed)""" key = self.factory.create_random_key(self) key.add_vpp_config() - self.vpp_session = VppBFDUDPSession(self, self.pg0, - self.pg0.remote_ip4, sha1_key=key) + self.vpp_session = VppBFDUDPSession( + self, self.pg0, self.pg0.remote_ip4, sha1_key=key + ) self.vpp_session.add_vpp_config() self.test_session = BFDTestSession( - self, self.pg0, AF_INET, sha1_key=key, - bfd_key_id=self.vpp_session.bfd_key_id) + self, + self.pg0, + AF_INET, + sha1_key=key, + bfd_key_id=self.vpp_session.bfd_key_id, + ) bfd_session_up(self) for dummy in range(self.test_session.detect_mult * 2): p = wait_for_bfd_packet(self) @@ -2439,22 +2645,26 @@ class BFDAuthOnOffTestCase(VppTestCase): self.assert_equal(p[BFD].state, BFDState.up, BFDState) self.test_session.send_packet() self.assert_equal(self.vpp_session.state, BFDState.up, BFDState) - self.assert_equal(len(self.vapi.collect_events()), 0, - "number of bfd events") + self.assert_equal(len(self.vapi.collect_events()), 0, "number of bfd events") def test_auth_change_key_delayed(self): - """ change auth key without disturbing session state (delayed) """ + """change auth key without disturbing session state (delayed)""" key1 = self.factory.create_random_key(self) key1.add_vpp_config() key2 = self.factory.create_random_key(self) key2.add_vpp_config() - self.vpp_session = VppBFDUDPSession(self, self.pg0, - self.pg0.remote_ip4, sha1_key=key1) + self.vpp_session = VppBFDUDPSession( + self, self.pg0, self.pg0.remote_ip4, sha1_key=key1 + ) self.vpp_session.add_vpp_config() self.vpp_session.admin_up() self.test_session = BFDTestSession( - self, self.pg0, AF_INET, sha1_key=key1, - bfd_key_id=self.vpp_session.bfd_key_id) + self, + self.pg0, + AF_INET, + sha1_key=key1, + bfd_key_id=self.vpp_session.bfd_key_id, + ) bfd_session_up(self) for dummy in range(self.test_session.detect_mult * 2): p = wait_for_bfd_packet(self) @@ -2473,13 +2683,13 @@ class BFDAuthOnOffTestCase(VppTestCase): self.assert_equal(p[BFD].state, BFDState.up, BFDState) self.test_session.send_packet() self.assert_equal(self.vpp_session.state, BFDState.up, BFDState) - self.assert_equal(len(self.vapi.collect_events()), 0, - "number of bfd events") + self.assert_equal(len(self.vapi.collect_events()), 0, "number of bfd events") @tag_run_solo class BFDCLITestCase(VppTestCase): - """Bidirectional Forwarding Detection (BFD) (CLI) """ + """Bidirectional Forwarding Detection (BFD) (CLI)""" + pg0 = None @classmethod @@ -2516,52 +2726,54 @@ class BFDCLITestCase(VppTestCase): super(BFDCLITestCase, self).tearDown() def cli_verify_no_response(self, cli): - """ execute a CLI, asserting that the response is empty """ - self.assert_equal(self.vapi.cli(cli), - "", - "CLI command response") + """execute a CLI, asserting that the response is empty""" + self.assert_equal(self.vapi.cli(cli), "", "CLI command response") def cli_verify_response(self, cli, expected): - """ execute a CLI, asserting that the response matches expectation """ + """execute a CLI, asserting that the response matches expectation""" try: reply = self.vapi.cli(cli) except CliFailedCommandError as cli_error: reply = str(cli_error) - self.assert_equal(reply.strip(), - expected, - "CLI command response") + self.assert_equal(reply.strip(), expected, "CLI command response") def test_show(self): - """ show commands """ + """show commands""" k1 = self.factory.create_random_key(self) k1.add_vpp_config() k2 = self.factory.create_random_key( - self, auth_type=BFDAuthType.meticulous_keyed_sha1) + self, auth_type=BFDAuthType.meticulous_keyed_sha1 + ) k2.add_vpp_config() s1 = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4) s1.add_vpp_config() - s2 = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip6, af=AF_INET6, - sha1_key=k2) + s2 = VppBFDUDPSession( + self, self.pg0, self.pg0.remote_ip6, af=AF_INET6, sha1_key=k2 + ) s2.add_vpp_config() self.logger.info(self.vapi.ppcli("show bfd keys")) self.logger.info(self.vapi.ppcli("show bfd sessions")) self.logger.info(self.vapi.ppcli("show bfd")) def test_set_del_sha1_key(self): - """ set/delete SHA1 auth key """ + """set/delete SHA1 auth key""" k = self.factory.create_random_key(self) self.registry.register(k, self.logger) self.cli_verify_no_response( - "bfd key set conf-key-id %s type keyed-sha1 secret %s" % - (k.conf_key_id, - "".join("{:02x}".format(scapy.compat.orb(c)) for c in k.key))) + "bfd key set conf-key-id %s type keyed-sha1 secret %s" + % ( + k.conf_key_id, + "".join("{:02x}".format(scapy.compat.orb(c)) for c in k.key), + ) + ) self.assertTrue(k.query_vpp_config()) self.vpp_session = VppBFDUDPSession( - self, self.pg0, self.pg0.remote_ip4, sha1_key=k) + self, self.pg0, self.pg0.remote_ip4, sha1_key=k + ) self.vpp_session.add_vpp_config() - self.test_session = \ - BFDTestSession(self, self.pg0, AF_INET, sha1_key=k, - bfd_key_id=self.vpp_session.bfd_key_id) + self.test_session = BFDTestSession( + self, self.pg0, AF_INET, sha1_key=k, bfd_key_id=self.vpp_session.bfd_key_id + ) self.vapi.want_bfd_events() bfd_session_up(self) bfd_session_down(self) @@ -2569,37 +2781,43 @@ class BFDCLITestCase(VppTestCase): # is in-use k2 = self.factory.create_random_key(self) self.cli_verify_response( - "bfd key set conf-key-id %s type keyed-sha1 secret %s" % - (k.conf_key_id, - "".join("{:02x}".format(scapy.compat.orb(c)) for c in k2.key)), + "bfd key set conf-key-id %s type keyed-sha1 secret %s" + % ( + k.conf_key_id, + "".join("{:02x}".format(scapy.compat.orb(c)) for c in k2.key), + ), "bfd key set: `bfd_auth_set_key' API call failed, " - "rv=-103:BFD object in use") + "rv=-103:BFD object in use", + ) # manipulating the session using old secret should still work bfd_session_up(self) bfd_session_down(self) self.vpp_session.remove_vpp_config() - self.cli_verify_no_response( - "bfd key del conf-key-id %s" % k.conf_key_id) + self.cli_verify_no_response("bfd key del conf-key-id %s" % k.conf_key_id) self.assertFalse(k.query_vpp_config()) def test_set_del_meticulous_sha1_key(self): - """ set/delete meticulous SHA1 auth key """ + """set/delete meticulous SHA1 auth key""" k = self.factory.create_random_key( - self, auth_type=BFDAuthType.meticulous_keyed_sha1) + self, auth_type=BFDAuthType.meticulous_keyed_sha1 + ) self.registry.register(k, self.logger) self.cli_verify_no_response( - "bfd key set conf-key-id %s type meticulous-keyed-sha1 secret %s" % - (k.conf_key_id, - "".join("{:02x}".format(scapy.compat.orb(c)) for c in k.key))) + "bfd key set conf-key-id %s type meticulous-keyed-sha1 secret %s" + % ( + k.conf_key_id, + "".join("{:02x}".format(scapy.compat.orb(c)) for c in k.key), + ) + ) self.assertTrue(k.query_vpp_config()) - self.vpp_session = VppBFDUDPSession(self, self.pg0, - self.pg0.remote_ip6, af=AF_INET6, - sha1_key=k) + self.vpp_session = VppBFDUDPSession( + self, self.pg0, self.pg0.remote_ip6, af=AF_INET6, sha1_key=k + ) self.vpp_session.add_vpp_config() self.vpp_session.admin_up() - self.test_session = \ - BFDTestSession(self, self.pg0, AF_INET6, sha1_key=k, - bfd_key_id=self.vpp_session.bfd_key_id) + self.test_session = BFDTestSession( + self, self.pg0, AF_INET6, sha1_key=k, bfd_key_id=self.vpp_session.bfd_key_id + ) self.vapi.want_bfd_events() bfd_session_up(self) bfd_session_down(self) @@ -2607,299 +2825,409 @@ class BFDCLITestCase(VppTestCase): # is in-use k2 = self.factory.create_random_key(self) self.cli_verify_response( - "bfd key set conf-key-id %s type keyed-sha1 secret %s" % - (k.conf_key_id, - "".join("{:02x}".format(scapy.compat.orb(c)) for c in k2.key)), + "bfd key set conf-key-id %s type keyed-sha1 secret %s" + % ( + k.conf_key_id, + "".join("{:02x}".format(scapy.compat.orb(c)) for c in k2.key), + ), "bfd key set: `bfd_auth_set_key' API call failed, " - "rv=-103:BFD object in use") + "rv=-103:BFD object in use", + ) # manipulating the session using old secret should still work bfd_session_up(self) bfd_session_down(self) self.vpp_session.remove_vpp_config() - self.cli_verify_no_response( - "bfd key del conf-key-id %s" % k.conf_key_id) + self.cli_verify_no_response("bfd key del conf-key-id %s" % k.conf_key_id) self.assertFalse(k.query_vpp_config()) def test_add_mod_del_bfd_udp(self): - """ create/modify/delete IPv4 BFD UDP session """ - vpp_session = VppBFDUDPSession( - self, self.pg0, self.pg0.remote_ip4) + """create/modify/delete IPv4 BFD UDP session""" + vpp_session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4) self.registry.register(vpp_session, self.logger) - cli_add_cmd = "bfd udp session add interface %s local-addr %s " \ - "peer-addr %s desired-min-tx %s required-min-rx %s "\ - "detect-mult %s" % (self.pg0.name, self.pg0.local_ip4, - self.pg0.remote_ip4, - vpp_session.desired_min_tx, - vpp_session.required_min_rx, - vpp_session.detect_mult) + cli_add_cmd = ( + "bfd udp session add interface %s local-addr %s " + "peer-addr %s desired-min-tx %s required-min-rx %s " + "detect-mult %s" + % ( + self.pg0.name, + self.pg0.local_ip4, + self.pg0.remote_ip4, + vpp_session.desired_min_tx, + vpp_session.required_min_rx, + vpp_session.detect_mult, + ) + ) self.cli_verify_no_response(cli_add_cmd) # 2nd add should fail self.cli_verify_response( cli_add_cmd, "bfd udp session add: `bfd_add_add_session' API call" - " failed, rv=-101:Duplicate BFD object") + " failed, rv=-101:Duplicate BFD object", + ) verify_bfd_session_config(self, vpp_session) mod_session = VppBFDUDPSession( - self, self.pg0, self.pg0.remote_ip4, + self, + self.pg0, + self.pg0.remote_ip4, required_min_rx=2 * vpp_session.required_min_rx, desired_min_tx=3 * vpp_session.desired_min_tx, - detect_mult=4 * vpp_session.detect_mult) + detect_mult=4 * vpp_session.detect_mult, + ) self.cli_verify_no_response( "bfd udp session mod interface %s local-addr %s peer-addr %s " - "desired-min-tx %s required-min-rx %s detect-mult %s" % - (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4, - mod_session.desired_min_tx, mod_session.required_min_rx, - mod_session.detect_mult)) + "desired-min-tx %s required-min-rx %s detect-mult %s" + % ( + self.pg0.name, + self.pg0.local_ip4, + self.pg0.remote_ip4, + mod_session.desired_min_tx, + mod_session.required_min_rx, + mod_session.detect_mult, + ) + ) verify_bfd_session_config(self, mod_session) - cli_del_cmd = "bfd udp session del interface %s local-addr %s "\ - "peer-addr %s" % (self.pg0.name, - self.pg0.local_ip4, self.pg0.remote_ip4) + cli_del_cmd = ( + "bfd udp session del interface %s local-addr %s " + "peer-addr %s" % (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4) + ) self.cli_verify_no_response(cli_del_cmd) # 2nd del is expected to fail self.cli_verify_response( - cli_del_cmd, "bfd udp session del: `bfd_udp_del_session' API call" - " failed, rv=-102:No such BFD object") + cli_del_cmd, + "bfd udp session del: `bfd_udp_del_session' API call" + " failed, rv=-102:No such BFD object", + ) self.assertFalse(vpp_session.query_vpp_config()) def test_add_mod_del_bfd_udp6(self): - """ create/modify/delete IPv6 BFD UDP session """ - vpp_session = VppBFDUDPSession( - self, self.pg0, self.pg0.remote_ip6, af=AF_INET6) + """create/modify/delete IPv6 BFD UDP session""" + vpp_session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip6, af=AF_INET6) self.registry.register(vpp_session, self.logger) - cli_add_cmd = "bfd udp session add interface %s local-addr %s " \ - "peer-addr %s desired-min-tx %s required-min-rx %s "\ - "detect-mult %s" % (self.pg0.name, self.pg0.local_ip6, - self.pg0.remote_ip6, - vpp_session.desired_min_tx, - vpp_session.required_min_rx, - vpp_session.detect_mult) + cli_add_cmd = ( + "bfd udp session add interface %s local-addr %s " + "peer-addr %s desired-min-tx %s required-min-rx %s " + "detect-mult %s" + % ( + self.pg0.name, + self.pg0.local_ip6, + self.pg0.remote_ip6, + vpp_session.desired_min_tx, + vpp_session.required_min_rx, + vpp_session.detect_mult, + ) + ) self.cli_verify_no_response(cli_add_cmd) # 2nd add should fail self.cli_verify_response( cli_add_cmd, "bfd udp session add: `bfd_add_add_session' API call" - " failed, rv=-101:Duplicate BFD object") + " failed, rv=-101:Duplicate BFD object", + ) verify_bfd_session_config(self, vpp_session) mod_session = VppBFDUDPSession( - self, self.pg0, self.pg0.remote_ip6, af=AF_INET6, + self, + self.pg0, + self.pg0.remote_ip6, + af=AF_INET6, required_min_rx=2 * vpp_session.required_min_rx, desired_min_tx=3 * vpp_session.desired_min_tx, - detect_mult=4 * vpp_session.detect_mult) + detect_mult=4 * vpp_session.detect_mult, + ) self.cli_verify_no_response( "bfd udp session mod interface %s local-addr %s peer-addr %s " - "desired-min-tx %s required-min-rx %s detect-mult %s" % - (self.pg0.name, self.pg0.local_ip6, self.pg0.remote_ip6, - mod_session.desired_min_tx, - mod_session.required_min_rx, mod_session.detect_mult)) + "desired-min-tx %s required-min-rx %s detect-mult %s" + % ( + self.pg0.name, + self.pg0.local_ip6, + self.pg0.remote_ip6, + mod_session.desired_min_tx, + mod_session.required_min_rx, + mod_session.detect_mult, + ) + ) verify_bfd_session_config(self, mod_session) - cli_del_cmd = "bfd udp session del interface %s local-addr %s "\ - "peer-addr %s" % (self.pg0.name, - self.pg0.local_ip6, self.pg0.remote_ip6) + cli_del_cmd = ( + "bfd udp session del interface %s local-addr %s " + "peer-addr %s" % (self.pg0.name, self.pg0.local_ip6, self.pg0.remote_ip6) + ) self.cli_verify_no_response(cli_del_cmd) # 2nd del is expected to fail self.cli_verify_response( cli_del_cmd, "bfd udp session del: `bfd_udp_del_session' API call" - " failed, rv=-102:No such BFD object") + " failed, rv=-102:No such BFD object", + ) self.assertFalse(vpp_session.query_vpp_config()) def test_add_mod_del_bfd_udp_auth(self): - """ create/modify/delete IPv4 BFD UDP session (authenticated) """ + """create/modify/delete IPv4 BFD UDP session (authenticated)""" key = self.factory.create_random_key(self) key.add_vpp_config() vpp_session = VppBFDUDPSession( - self, self.pg0, self.pg0.remote_ip4, sha1_key=key) + self, self.pg0, self.pg0.remote_ip4, sha1_key=key + ) self.registry.register(vpp_session, self.logger) - cli_add_cmd = "bfd udp session add interface %s local-addr %s " \ - "peer-addr %s desired-min-tx %s required-min-rx %s "\ - "detect-mult %s conf-key-id %s bfd-key-id %s"\ - % (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4, - vpp_session.desired_min_tx, vpp_session.required_min_rx, - vpp_session.detect_mult, key.conf_key_id, - vpp_session.bfd_key_id) + cli_add_cmd = ( + "bfd udp session add interface %s local-addr %s " + "peer-addr %s desired-min-tx %s required-min-rx %s " + "detect-mult %s conf-key-id %s bfd-key-id %s" + % ( + self.pg0.name, + self.pg0.local_ip4, + self.pg0.remote_ip4, + vpp_session.desired_min_tx, + vpp_session.required_min_rx, + vpp_session.detect_mult, + key.conf_key_id, + vpp_session.bfd_key_id, + ) + ) self.cli_verify_no_response(cli_add_cmd) # 2nd add should fail self.cli_verify_response( cli_add_cmd, "bfd udp session add: `bfd_add_add_session' API call" - " failed, rv=-101:Duplicate BFD object") + " failed, rv=-101:Duplicate BFD object", + ) verify_bfd_session_config(self, vpp_session) mod_session = VppBFDUDPSession( - self, self.pg0, self.pg0.remote_ip4, sha1_key=key, + self, + self.pg0, + self.pg0.remote_ip4, + sha1_key=key, bfd_key_id=vpp_session.bfd_key_id, required_min_rx=2 * vpp_session.required_min_rx, desired_min_tx=3 * vpp_session.desired_min_tx, - detect_mult=4 * vpp_session.detect_mult) + detect_mult=4 * vpp_session.detect_mult, + ) self.cli_verify_no_response( "bfd udp session mod interface %s local-addr %s peer-addr %s " - "desired-min-tx %s required-min-rx %s detect-mult %s" % - (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4, - mod_session.desired_min_tx, - mod_session.required_min_rx, mod_session.detect_mult)) + "desired-min-tx %s required-min-rx %s detect-mult %s" + % ( + self.pg0.name, + self.pg0.local_ip4, + self.pg0.remote_ip4, + mod_session.desired_min_tx, + mod_session.required_min_rx, + mod_session.detect_mult, + ) + ) verify_bfd_session_config(self, mod_session) - cli_del_cmd = "bfd udp session del interface %s local-addr %s "\ - "peer-addr %s" % (self.pg0.name, - self.pg0.local_ip4, self.pg0.remote_ip4) + cli_del_cmd = ( + "bfd udp session del interface %s local-addr %s " + "peer-addr %s" % (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4) + ) self.cli_verify_no_response(cli_del_cmd) # 2nd del is expected to fail self.cli_verify_response( cli_del_cmd, "bfd udp session del: `bfd_udp_del_session' API call" - " failed, rv=-102:No such BFD object") + " failed, rv=-102:No such BFD object", + ) self.assertFalse(vpp_session.query_vpp_config()) def test_add_mod_del_bfd_udp6_auth(self): - """ create/modify/delete IPv6 BFD UDP session (authenticated) """ + """create/modify/delete IPv6 BFD UDP session (authenticated)""" key = self.factory.create_random_key( - self, auth_type=BFDAuthType.meticulous_keyed_sha1) + self, auth_type=BFDAuthType.meticulous_keyed_sha1 + ) key.add_vpp_config() vpp_session = VppBFDUDPSession( - self, self.pg0, self.pg0.remote_ip6, af=AF_INET6, sha1_key=key) + self, self.pg0, self.pg0.remote_ip6, af=AF_INET6, sha1_key=key + ) self.registry.register(vpp_session, self.logger) - cli_add_cmd = "bfd udp session add interface %s local-addr %s " \ - "peer-addr %s desired-min-tx %s required-min-rx %s "\ - "detect-mult %s conf-key-id %s bfd-key-id %s" \ - % (self.pg0.name, self.pg0.local_ip6, self.pg0.remote_ip6, - vpp_session.desired_min_tx, vpp_session.required_min_rx, - vpp_session.detect_mult, key.conf_key_id, - vpp_session.bfd_key_id) + cli_add_cmd = ( + "bfd udp session add interface %s local-addr %s " + "peer-addr %s desired-min-tx %s required-min-rx %s " + "detect-mult %s conf-key-id %s bfd-key-id %s" + % ( + self.pg0.name, + self.pg0.local_ip6, + self.pg0.remote_ip6, + vpp_session.desired_min_tx, + vpp_session.required_min_rx, + vpp_session.detect_mult, + key.conf_key_id, + vpp_session.bfd_key_id, + ) + ) self.cli_verify_no_response(cli_add_cmd) # 2nd add should fail self.cli_verify_response( cli_add_cmd, "bfd udp session add: `bfd_add_add_session' API call" - " failed, rv=-101:Duplicate BFD object") + " failed, rv=-101:Duplicate BFD object", + ) verify_bfd_session_config(self, vpp_session) mod_session = VppBFDUDPSession( - self, self.pg0, self.pg0.remote_ip6, af=AF_INET6, sha1_key=key, + self, + self.pg0, + self.pg0.remote_ip6, + af=AF_INET6, + sha1_key=key, bfd_key_id=vpp_session.bfd_key_id, required_min_rx=2 * vpp_session.required_min_rx, desired_min_tx=3 * vpp_session.desired_min_tx, - detect_mult=4 * vpp_session.detect_mult) + detect_mult=4 * vpp_session.detect_mult, + ) self.cli_verify_no_response( "bfd udp session mod interface %s local-addr %s peer-addr %s " - "desired-min-tx %s required-min-rx %s detect-mult %s" % - (self.pg0.name, self.pg0.local_ip6, self.pg0.remote_ip6, - mod_session.desired_min_tx, - mod_session.required_min_rx, mod_session.detect_mult)) + "desired-min-tx %s required-min-rx %s detect-mult %s" + % ( + self.pg0.name, + self.pg0.local_ip6, + self.pg0.remote_ip6, + mod_session.desired_min_tx, + mod_session.required_min_rx, + mod_session.detect_mult, + ) + ) verify_bfd_session_config(self, mod_session) - cli_del_cmd = "bfd udp session del interface %s local-addr %s "\ - "peer-addr %s" % (self.pg0.name, - self.pg0.local_ip6, self.pg0.remote_ip6) + cli_del_cmd = ( + "bfd udp session del interface %s local-addr %s " + "peer-addr %s" % (self.pg0.name, self.pg0.local_ip6, self.pg0.remote_ip6) + ) self.cli_verify_no_response(cli_del_cmd) # 2nd del is expected to fail self.cli_verify_response( cli_del_cmd, "bfd udp session del: `bfd_udp_del_session' API call" - " failed, rv=-102:No such BFD object") + " failed, rv=-102:No such BFD object", + ) self.assertFalse(vpp_session.query_vpp_config()) def test_auth_on_off(self): - """ turn authentication on and off """ + """turn authentication on and off""" key = self.factory.create_random_key( - self, auth_type=BFDAuthType.meticulous_keyed_sha1) + self, auth_type=BFDAuthType.meticulous_keyed_sha1 + ) key.add_vpp_config() session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4) - auth_session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4, - sha1_key=key) + auth_session = VppBFDUDPSession( + self, self.pg0, self.pg0.remote_ip4, sha1_key=key + ) session.add_vpp_config() - cli_activate = \ - "bfd udp session auth activate interface %s local-addr %s "\ - "peer-addr %s conf-key-id %s bfd-key-id %s"\ - % (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4, - key.conf_key_id, auth_session.bfd_key_id) + cli_activate = ( + "bfd udp session auth activate interface %s local-addr %s " + "peer-addr %s conf-key-id %s bfd-key-id %s" + % ( + self.pg0.name, + self.pg0.local_ip4, + self.pg0.remote_ip4, + key.conf_key_id, + auth_session.bfd_key_id, + ) + ) self.cli_verify_no_response(cli_activate) verify_bfd_session_config(self, auth_session) self.cli_verify_no_response(cli_activate) verify_bfd_session_config(self, auth_session) - cli_deactivate = \ - "bfd udp session auth deactivate interface %s local-addr %s "\ - "peer-addr %s "\ - % (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4) + cli_deactivate = ( + "bfd udp session auth deactivate interface %s local-addr %s " + "peer-addr %s " % (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4) + ) self.cli_verify_no_response(cli_deactivate) verify_bfd_session_config(self, session) self.cli_verify_no_response(cli_deactivate) verify_bfd_session_config(self, session) def test_auth_on_off_delayed(self): - """ turn authentication on and off (delayed) """ + """turn authentication on and off (delayed)""" key = self.factory.create_random_key( - self, auth_type=BFDAuthType.meticulous_keyed_sha1) + self, auth_type=BFDAuthType.meticulous_keyed_sha1 + ) key.add_vpp_config() session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4) - auth_session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4, - sha1_key=key) + auth_session = VppBFDUDPSession( + self, self.pg0, self.pg0.remote_ip4, sha1_key=key + ) session.add_vpp_config() - cli_activate = \ - "bfd udp session auth activate interface %s local-addr %s "\ - "peer-addr %s conf-key-id %s bfd-key-id %s delayed yes"\ - % (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4, - key.conf_key_id, auth_session.bfd_key_id) + cli_activate = ( + "bfd udp session auth activate interface %s local-addr %s " + "peer-addr %s conf-key-id %s bfd-key-id %s delayed yes" + % ( + self.pg0.name, + self.pg0.local_ip4, + self.pg0.remote_ip4, + key.conf_key_id, + auth_session.bfd_key_id, + ) + ) self.cli_verify_no_response(cli_activate) verify_bfd_session_config(self, auth_session) self.cli_verify_no_response(cli_activate) verify_bfd_session_config(self, auth_session) - cli_deactivate = \ - "bfd udp session auth deactivate interface %s local-addr %s "\ - "peer-addr %s delayed yes"\ + cli_deactivate = ( + "bfd udp session auth deactivate interface %s local-addr %s " + "peer-addr %s delayed yes" % (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4) + ) self.cli_verify_no_response(cli_deactivate) verify_bfd_session_config(self, session) self.cli_verify_no_response(cli_deactivate) verify_bfd_session_config(self, session) def test_admin_up_down(self): - """ put session admin-up and admin-down """ + """put session admin-up and admin-down""" session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4) session.add_vpp_config() - cli_down = \ - "bfd udp session set-flags admin down interface %s local-addr %s "\ - "peer-addr %s "\ - % (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4) - cli_up = \ - "bfd udp session set-flags admin up interface %s local-addr %s "\ - "peer-addr %s "\ - % (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4) + cli_down = ( + "bfd udp session set-flags admin down interface %s local-addr %s " + "peer-addr %s " % (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4) + ) + cli_up = ( + "bfd udp session set-flags admin up interface %s local-addr %s " + "peer-addr %s " % (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4) + ) self.cli_verify_no_response(cli_down) verify_bfd_session_config(self, session, state=BFDState.admin_down) self.cli_verify_no_response(cli_up) verify_bfd_session_config(self, session, state=BFDState.down) def test_set_del_udp_echo_source(self): - """ set/del udp echo source """ + """set/del udp echo source""" self.create_loopback_interfaces(1) self.loopback0 = self.lo_interfaces[0] self.loopback0.admin_up() - self.cli_verify_response("show bfd echo-source", - "UDP echo source is not set.") + self.cli_verify_response("show bfd echo-source", "UDP echo source is not set.") cli_set = "bfd udp echo-source set interface %s" % self.loopback0.name self.cli_verify_no_response(cli_set) - self.cli_verify_response("show bfd echo-source", - "UDP echo source is: %s\n" - "IPv4 address usable as echo source: none\n" - "IPv6 address usable as echo source: none" % - self.loopback0.name) + self.cli_verify_response( + "show bfd echo-source", + "UDP echo source is: %s\n" + "IPv4 address usable as echo source: none\n" + "IPv6 address usable as echo source: none" % self.loopback0.name, + ) self.loopback0.config_ip4() - echo_ip4 = str(ipaddress.IPv4Address(int(ipaddress.IPv4Address( - self.loopback0.local_ip4)) ^ 1)) - self.cli_verify_response("show bfd echo-source", - "UDP echo source is: %s\n" - "IPv4 address usable as echo source: %s\n" - "IPv6 address usable as echo source: none" % - (self.loopback0.name, echo_ip4)) - echo_ip6 = str(ipaddress.IPv6Address(int(ipaddress.IPv6Address( - self.loopback0.local_ip6)) ^ 1)) + echo_ip4 = str( + ipaddress.IPv4Address( + int(ipaddress.IPv4Address(self.loopback0.local_ip4)) ^ 1 + ) + ) + self.cli_verify_response( + "show bfd echo-source", + "UDP echo source is: %s\n" + "IPv4 address usable as echo source: %s\n" + "IPv6 address usable as echo source: none" + % (self.loopback0.name, echo_ip4), + ) + echo_ip6 = str( + ipaddress.IPv6Address( + int(ipaddress.IPv6Address(self.loopback0.local_ip6)) ^ 1 + ) + ) self.loopback0.config_ip6() - self.cli_verify_response("show bfd echo-source", - "UDP echo source is: %s\n" - "IPv4 address usable as echo source: %s\n" - "IPv6 address usable as echo source: %s" % - (self.loopback0.name, echo_ip4, echo_ip6)) + self.cli_verify_response( + "show bfd echo-source", + "UDP echo source is: %s\n" + "IPv4 address usable as echo source: %s\n" + "IPv6 address usable as echo source: %s" + % (self.loopback0.name, echo_ip4, echo_ip6), + ) cli_del = "bfd udp echo-source del" self.cli_verify_no_response(cli_del) - self.cli_verify_response("show bfd echo-source", - "UDP echo source is not set.") + self.cli_verify_response("show bfd echo-source", "UDP echo source is not set.") -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_bier.py b/test/test_bier.py index 7dd6a30f34b..f58449ef4c3 100644 --- a/test/test_bier.py +++ b/test/test_bier.py @@ -5,12 +5,27 @@ import unittest from config import config from framework import VppTestCase, VppTestRunner from vpp_ip import DpoProto -from vpp_ip_route import VppIpRoute, VppRoutePath, \ - VppMplsTable, VppIpMRoute, VppMRoutePath, VppIpTable, \ - MPLS_LABEL_INVALID, \ - VppMplsLabel, FibPathProto, FibPathType -from vpp_bier import BIER_HDR_PAYLOAD, VppBierImp, VppBierDispEntry, \ - VppBierDispTable, VppBierTable, VppBierTableID, VppBierRoute +from vpp_ip_route import ( + VppIpRoute, + VppRoutePath, + VppMplsTable, + VppIpMRoute, + VppMRoutePath, + VppIpTable, + MPLS_LABEL_INVALID, + VppMplsLabel, + FibPathProto, + FibPathType, +) +from vpp_bier import ( + BIER_HDR_PAYLOAD, + VppBierImp, + VppBierDispEntry, + VppBierDispTable, + VppBierTable, + VppBierTableID, + VppBierRoute, +) from vpp_udp_encap import VppUdpEncap from vpp_papi import VppEnum @@ -26,10 +41,10 @@ NUM_PKTS = 67 class TestBFIB(VppTestCase): - """ BIER FIB Test Case """ + """BIER FIB Test Case""" def test_bfib(self): - """ BFIB Unit Tests """ + """BFIB Unit Tests""" error = self.vapi.cli("test bier") if error: @@ -38,7 +53,7 @@ class TestBFIB(VppTestCase): class TestBier(VppTestCase): - """ BIER Test Case """ + """BIER Test Case""" def setUp(self): super(TestBier, self).setUp() @@ -86,16 +101,17 @@ class TestBier(VppTestCase): # # A packet with no bits set gets dropped # - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - MPLS(label=77, ttl=255) / - BIER(length=hdr_len_id) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg0.remote_ip6) / - UDP(sport=1234, dport=1234) / - Raw()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / MPLS(label=77, ttl=255) + / BIER(length=hdr_len_id) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.remote_ip6) + / UDP(sport=1234, dport=1234) + / Raw() + ) pkts = [p] - self.send_and_assert_no_replies(self.pg0, pkts, - "Empty Bit-String") + self.send_and_assert_no_replies(self.pg0, pkts, "Empty Bit-String") # # Add a BIER route for each bit-position in the table via a different @@ -104,19 +120,32 @@ class TestBier(VppTestCase): # nh_routes = [] bier_routes = [] - for i in range(1, max_bp+1): + for i in range(1, max_bp + 1): nh = "10.0.%d.%d" % (i / 255, i % 255) nh_routes.append( - VppIpRoute(self, nh, 32, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index, - labels=[VppMplsLabel(2000+i)])])) + VppIpRoute( + self, + nh, + 32, + [ + VppRoutePath( + self.pg1.remote_ip4, + self.pg1.sw_if_index, + labels=[VppMplsLabel(2000 + i)], + ) + ], + ) + ) nh_routes[-1].add_vpp_config() bier_routes.append( - VppBierRoute(self, bti, i, - [VppRoutePath(nh, 0xffffffff, - labels=[VppMplsLabel(100+i)])])) + VppBierRoute( + self, + bti, + i, + [VppRoutePath(nh, 0xFFFFFFFF, labels=[VppMplsLabel(100 + i)])], + ) + ) bier_routes[-1].add_vpp_config() # @@ -125,13 +154,14 @@ class TestBier(VppTestCase): pkt_sizes = [64, 1400] for pkt_size in pkt_sizes: - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - MPLS(label=77, ttl=255) / - BIER(length=hdr_len_id, - BitString=scapy.compat.chb(255)*n_bytes) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg0.remote_ip6) / - UDP(sport=1234, dport=1234) / - Raw(scapy.compat.chb(5) * pkt_size)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / MPLS(label=77, ttl=255) + / BIER(length=hdr_len_id, BitString=scapy.compat.chb(255) * n_bytes) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.remote_ip6) + / UDP(sport=1234, dport=1234) + / Raw(scapy.compat.chb(5) * pkt_size) + ) pkts = p self.pg0.add_stream(pkts) @@ -150,7 +180,7 @@ class TestBier(VppTestCase): bp = olabel.label - 2000 blabel = olabel[MPLS].payload - self.assertEqual(blabel.label, 100+bp) + self.assertEqual(blabel.label, 100 + bp) self.assertEqual(blabel.ttl, 254) bier_hdr = blabel[MPLS].payload @@ -165,11 +195,11 @@ class TestBier(VppTestCase): self.assertEqual(bier_hdr.Proto, 5) # The bit-string should consist only of the BP given by i. - byte_array = [b'\0'] * (n_bytes) + byte_array = [b"\0"] * (n_bytes) byte_val = scapy.compat.chb(1 << (bp - 1) % 8) byte_pos = n_bytes - (((bp - 1) // 8) + 1) byte_array[byte_pos] = byte_val - bitstring = b''.join(byte_array) + bitstring = b"".join(byte_array) self.assertEqual(len(bitstring), len(bier_hdr.BitString)) self.assertEqual(bitstring, bier_hdr.BitString) @@ -223,39 +253,55 @@ class TestBier(VppTestCase): # pkts = [] for ii in range(257): - pkts.append((Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - MPLS(label=77, ttl=255) / - BIER(length=BIERLength.BIER_LEN_64, - entropy=ii, - BitString=scapy.compat.chb(255)*16) / - IPv6(src=self.pg0.remote_ip6, - dst=self.pg0.remote_ip6) / - UDP(sport=1234, dport=1234) / - Raw())) + pkts.append( + ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / MPLS(label=77, ttl=255) + / BIER( + length=BIERLength.BIER_LEN_64, + entropy=ii, + BitString=scapy.compat.chb(255) * 16, + ) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.remote_ip6) + / UDP(sport=1234, dport=1234) + / Raw() + ) + ) # # 4 next hops # - nhs = [{'ip': "10.0.0.1", 'label': 201}, - {'ip': "10.0.0.2", 'label': 202}, - {'ip': "10.0.0.3", 'label': 203}, - {'ip': "10.0.0.4", 'label': 204}] + nhs = [ + {"ip": "10.0.0.1", "label": 201}, + {"ip": "10.0.0.2", "label": 202}, + {"ip": "10.0.0.3", "label": 203}, + {"ip": "10.0.0.4", "label": 204}, + ] for nh in nhs: ipr = VppIpRoute( - self, nh['ip'], 32, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index, - labels=[VppMplsLabel(nh['label'])])]) + self, + nh["ip"], + 32, + [ + VppRoutePath( + self.pg1.remote_ip4, + self.pg1.sw_if_index, + labels=[VppMplsLabel(nh["label"])], + ) + ], + ) ipr.add_vpp_config() bier_route = VppBierRoute( - self, bti, 1, - [VppRoutePath(nhs[0]['ip'], 0xffffffff, - labels=[VppMplsLabel(101)]), - VppRoutePath(nhs[1]['ip'], 0xffffffff, - labels=[VppMplsLabel(101)])]) + self, + bti, + 1, + [ + VppRoutePath(nhs[0]["ip"], 0xFFFFFFFF, labels=[VppMplsLabel(101)]), + VppRoutePath(nhs[1]["ip"], 0xFFFFFFFF, labels=[VppMplsLabel(101)]), + ], + ) bier_route.add_vpp_config() rx = self.send_and_expect(self.pg0, pkts, self.pg1) @@ -264,37 +310,38 @@ class TestBier(VppTestCase): # we should have recieved a packet from each neighbor # for nh in nhs[:2]: - self.assertTrue(sum(p[MPLS].label == nh['label'] for p in rx)) + self.assertTrue(sum(p[MPLS].label == nh["label"] for p in rx)) # # add the other paths # bier_route.update_paths( - [VppRoutePath(nhs[0]['ip'], 0xffffffff, - labels=[VppMplsLabel(101)]), - VppRoutePath(nhs[1]['ip'], 0xffffffff, - labels=[VppMplsLabel(101)]), - VppRoutePath(nhs[2]['ip'], 0xffffffff, - labels=[VppMplsLabel(101)]), - VppRoutePath(nhs[3]['ip'], 0xffffffff, - labels=[VppMplsLabel(101)])]) + [ + VppRoutePath(nhs[0]["ip"], 0xFFFFFFFF, labels=[VppMplsLabel(101)]), + VppRoutePath(nhs[1]["ip"], 0xFFFFFFFF, labels=[VppMplsLabel(101)]), + VppRoutePath(nhs[2]["ip"], 0xFFFFFFFF, labels=[VppMplsLabel(101)]), + VppRoutePath(nhs[3]["ip"], 0xFFFFFFFF, labels=[VppMplsLabel(101)]), + ] + ) rx = self.send_and_expect(self.pg0, pkts, self.pg1) for nh in nhs: - self.assertTrue(sum(p[MPLS].label == nh['label'] for p in rx)) + self.assertTrue(sum(p[MPLS].label == nh["label"] for p in rx)) # # remove first two paths # - bier_route.remove_path(VppRoutePath(nhs[0]['ip'], 0xffffffff, - labels=[VppMplsLabel(101)])) - bier_route.remove_path(VppRoutePath(nhs[1]['ip'], 0xffffffff, - labels=[VppMplsLabel(101)])) + bier_route.remove_path( + VppRoutePath(nhs[0]["ip"], 0xFFFFFFFF, labels=[VppMplsLabel(101)]) + ) + bier_route.remove_path( + VppRoutePath(nhs[1]["ip"], 0xFFFFFFFF, labels=[VppMplsLabel(101)]) + ) rx = self.send_and_expect(self.pg0, pkts, self.pg1) for nh in nhs[2:]: - self.assertTrue(sum(p[MPLS].label == nh['label'] for p in rx)) + self.assertTrue(sum(p[MPLS].label == nh["label"] for p in rx)) # # remove the last of the paths, deleteing the entry @@ -321,23 +368,39 @@ class TestBier(VppTestCase): # nh1 = "10.0.0.1" nh2 = "10.0.0.2" - ip_route_1 = VppIpRoute(self, nh1, 32, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index, - labels=[VppMplsLabel(2001)])]) - ip_route_2 = VppIpRoute(self, nh2, 32, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index, - labels=[VppMplsLabel(2002)])]) + ip_route_1 = VppIpRoute( + self, + nh1, + 32, + [ + VppRoutePath( + self.pg1.remote_ip4, + self.pg1.sw_if_index, + labels=[VppMplsLabel(2001)], + ) + ], + ) + ip_route_2 = VppIpRoute( + self, + nh2, + 32, + [ + VppRoutePath( + self.pg1.remote_ip4, + self.pg1.sw_if_index, + labels=[VppMplsLabel(2002)], + ) + ], + ) ip_route_1.add_vpp_config() ip_route_2.add_vpp_config() - bier_route_1 = VppBierRoute(self, bti, 1, - [VppRoutePath(nh1, 0xffffffff, - labels=[VppMplsLabel(101)])]) - bier_route_2 = VppBierRoute(self, bti, 2, - [VppRoutePath(nh2, 0xffffffff, - labels=[VppMplsLabel(102)])]) + bier_route_1 = VppBierRoute( + self, bti, 1, [VppRoutePath(nh1, 0xFFFFFFFF, labels=[VppMplsLabel(101)])] + ) + bier_route_2 = VppBierRoute( + self, bti, 2, [VppRoutePath(nh2, 0xFFFFFFFF, labels=[VppMplsLabel(102)])] + ) bier_route_1.add_vpp_config() bier_route_2.add_vpp_config() @@ -353,25 +416,33 @@ class TestBier(VppTestCase): route_ing_232_1_1_1 = VppIpMRoute( self, "0.0.0.0", - "232.1.1.1", 32, + "232.1.1.1", + 32, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - paths=[VppMRoutePath(self.pg0.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT), - VppMRoutePath(0xffffffff, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, - proto=FibPathProto.FIB_PATH_NH_PROTO_BIER, - type=FibPathType.FIB_PATH_TYPE_BIER_IMP, - bier_imp=bi.bi_index)]) + paths=[ + VppMRoutePath( + self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT + ), + VppMRoutePath( + 0xFFFFFFFF, + MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + proto=FibPathProto.FIB_PATH_NH_PROTO_BIER, + type=FibPathType.FIB_PATH_TYPE_BIER_IMP, + bier_imp=bi.bi_index, + ), + ], + ) route_ing_232_1_1_1.add_vpp_config() # # inject an IP packet. We expect it to be BIER encapped and # replicated. # - p = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IP(src="1.1.1.1", dst="232.1.1.1") / - UDP(sport=1234, dport=1234)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src="1.1.1.1", dst="232.1.1.1") + / UDP(sport=1234, dport=1234) + ) self.pg0.add_stream([p]) self.pg_enable_capture(self.pg_interfaces) @@ -425,20 +496,33 @@ class TestBier(VppTestCase): # BIER route in table that's for-us # bier_route_1 = VppBierRoute( - self, bti, 1, - [VppRoutePath("0.0.0.0", - 0xffffffff, - proto=FibPathProto.FIB_PATH_NH_PROTO_BIER, - nh_table_id=8)]) + self, + bti, + 1, + [ + VppRoutePath( + "0.0.0.0", + 0xFFFFFFFF, + proto=FibPathProto.FIB_PATH_NH_PROTO_BIER, + nh_table_id=8, + ) + ], + ) bier_route_1.add_vpp_config() # # An entry in the disposition table # - bier_de_1 = VppBierDispEntry(self, bdt.id, 99, - BIER_HDR_PAYLOAD.BIER_HDR_PROTO_IPV4, - FibPathProto.FIB_PATH_NH_PROTO_BIER, - "0.0.0.0", 0, rpf_id=8192) + bier_de_1 = VppBierDispEntry( + self, + bdt.id, + 99, + BIER_HDR_PAYLOAD.BIER_HDR_PROTO_IPV4, + FibPathProto.FIB_PATH_NH_PROTO_BIER, + "0.0.0.0", + 0, + rpf_id=8192, + ) bier_de_1.add_vpp_config() # @@ -447,48 +531,68 @@ class TestBier(VppTestCase): route_eg_232_1_1_1 = VppIpMRoute( self, "0.0.0.0", - "232.1.1.1", 32, + "232.1.1.1", + 32, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - paths=[VppMRoutePath(self.pg1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)]) + paths=[ + VppMRoutePath( + self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ) + ], + ) route_eg_232_1_1_1.add_vpp_config() route_eg_232_1_1_1.update_rpf_id(8192) # # A packet with all bits set gets spat out to BP:1 # - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - MPLS(label=77, ttl=255) / - BIER(length=BIERLength.BIER_LEN_256, - BitString=scapy.compat.chb(255)*32, - BFRID=99) / - IP(src="1.1.1.1", dst="232.1.1.1") / - UDP(sport=1234, dport=1234) / - Raw()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / MPLS(label=77, ttl=255) + / BIER( + length=BIERLength.BIER_LEN_256, + BitString=scapy.compat.chb(255) * 32, + BFRID=99, + ) + / IP(src="1.1.1.1", dst="232.1.1.1") + / UDP(sport=1234, dport=1234) + / Raw() + ) self.send_and_expect(self.pg0, [p], self.pg1) # # A packet that does not match the Disposition entry gets dropped # - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - MPLS(label=77, ttl=255) / - BIER(length=BIERLength.BIER_LEN_256, - BitString=scapy.compat.chb(255)*32, - BFRID=77) / - IP(src="1.1.1.1", dst="232.1.1.1") / - UDP(sport=1234, dport=1234) / - Raw()) - self.send_and_assert_no_replies(self.pg0, p*2, - "no matching disposition entry") + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / MPLS(label=77, ttl=255) + / BIER( + length=BIERLength.BIER_LEN_256, + BitString=scapy.compat.chb(255) * 32, + BFRID=77, + ) + / IP(src="1.1.1.1", dst="232.1.1.1") + / UDP(sport=1234, dport=1234) + / Raw() + ) + self.send_and_assert_no_replies( + self.pg0, p * 2, "no matching disposition entry" + ) # # Add the default route to the disposition table # - bier_de_2 = VppBierDispEntry(self, bdt.id, 0, - BIER_HDR_PAYLOAD.BIER_HDR_PROTO_IPV4, - FibPathProto.FIB_PATH_NH_PROTO_BIER, - "0.0.0.0", 0, rpf_id=8192) + bier_de_2 = VppBierDispEntry( + self, + bdt.id, + 0, + BIER_HDR_PAYLOAD.BIER_HDR_PROTO_IPV4, + FibPathProto.FIB_PATH_NH_PROTO_BIER, + "0.0.0.0", + 0, + rpf_id=8192, + ) bier_de_2.add_vpp_config() # @@ -506,30 +610,41 @@ class TestBier(VppTestCase): route_eg_232_1_1_2 = VppIpMRoute( self, "0.0.0.0", - "232.1.1.2", 32, + "232.1.1.2", + 32, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - paths=[VppMRoutePath(0xffffffff, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, - proto=DpoProto.DPO_PROTO_BIER, - type=FibPathType.FIB_PATH_TYPE_BIER_IMP, - bier_imp=bi.bi_index), - VppMRoutePath(self.pg1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)]) + paths=[ + VppMRoutePath( + 0xFFFFFFFF, + MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + proto=DpoProto.DPO_PROTO_BIER, + type=FibPathType.FIB_PATH_TYPE_BIER_IMP, + bier_imp=bi.bi_index, + ), + VppMRoutePath( + self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ), + ], + ) route_eg_232_1_1_2.add_vpp_config() route_eg_232_1_1_2.update_rpf_id(8192) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - MPLS(label=77, ttl=255) / - BIER(length=BIERLength.BIER_LEN_256, - BitString=scapy.compat.chb(255)*32, - BFRID=77) / - IP(src="1.1.1.1", dst="232.1.1.2") / - UDP(sport=1234, dport=1234) / - Raw()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / MPLS(label=77, ttl=255) + / BIER( + length=BIERLength.BIER_LEN_256, + BitString=scapy.compat.chb(255) * 32, + BFRID=77, + ) + / IP(src="1.1.1.1", dst="232.1.1.2") + / UDP(sport=1234, dport=1234) + / Raw() + ) self.send_and_expect(self.pg0, [p], self.pg1) def bier_e2e(self, hdr_len_id, n_bytes, max_bp): - """ BIER end-to-end""" + """BIER end-to-end""" MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t @@ -541,9 +656,9 @@ class TestBier(VppTestCase): bt = VppBierTable(self, bti, 77) bt.add_vpp_config() - lowest = [b'\0'] * (n_bytes) + lowest = [b"\0"] * (n_bytes) lowest[-1] = scapy.compat.chb(1) - highest = [b'\0'] * (n_bytes) + highest = [b"\0"] * (n_bytes) highest[0] = scapy.compat.chb(128) # @@ -560,28 +675,42 @@ class TestBier(VppTestCase): route_ing_232_1_1_1 = VppIpMRoute( self, "0.0.0.0", - "232.1.1.1", 32, + "232.1.1.1", + 32, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - paths=[VppMRoutePath(self.pg0.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT), - VppMRoutePath(0xffffffff, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, - proto=FibPathProto.FIB_PATH_NH_PROTO_BIER, - type=FibPathType.FIB_PATH_TYPE_BIER_IMP, - bier_imp=bi_low.bi_index)]) + paths=[ + VppMRoutePath( + self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT + ), + VppMRoutePath( + 0xFFFFFFFF, + MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + proto=FibPathProto.FIB_PATH_NH_PROTO_BIER, + type=FibPathType.FIB_PATH_TYPE_BIER_IMP, + bier_imp=bi_low.bi_index, + ), + ], + ) route_ing_232_1_1_1.add_vpp_config() route_ing_232_1_1_2 = VppIpMRoute( self, "0.0.0.0", - "232.1.1.2", 32, + "232.1.1.2", + 32, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - paths=[VppMRoutePath(self.pg0.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT), - VppMRoutePath(0xffffffff, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, - proto=FibPathProto.FIB_PATH_NH_PROTO_BIER, - type=FibPathType.FIB_PATH_TYPE_BIER_IMP, - bier_imp=bi_high.bi_index)]) + paths=[ + VppMRoutePath( + self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT + ), + VppMRoutePath( + 0xFFFFFFFF, + MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + proto=FibPathProto.FIB_PATH_NH_PROTO_BIER, + type=FibPathType.FIB_PATH_TYPE_BIER_IMP, + bier_imp=bi_high.bi_index, + ), + ], + ) route_ing_232_1_1_2.add_vpp_config() # @@ -595,33 +724,59 @@ class TestBier(VppTestCase): # disp table 8. # bier_route_1 = VppBierRoute( - self, bti, 1, - [VppRoutePath("0.0.0.0", - 0xffffffff, - proto=FibPathProto.FIB_PATH_NH_PROTO_BIER, - nh_table_id=8)]) + self, + bti, + 1, + [ + VppRoutePath( + "0.0.0.0", + 0xFFFFFFFF, + proto=FibPathProto.FIB_PATH_NH_PROTO_BIER, + nh_table_id=8, + ) + ], + ) bier_route_1.add_vpp_config() bier_route_max = VppBierRoute( - self, bti, max_bp, - [VppRoutePath("0.0.0.0", - 0xffffffff, - proto=FibPathProto.FIB_PATH_NH_PROTO_BIER, - nh_table_id=8)]) + self, + bti, + max_bp, + [ + VppRoutePath( + "0.0.0.0", + 0xFFFFFFFF, + proto=FibPathProto.FIB_PATH_NH_PROTO_BIER, + nh_table_id=8, + ) + ], + ) bier_route_max.add_vpp_config() # # An entry in the disposition table for sender 333 # lookup in VRF 10 # - bier_de_1 = VppBierDispEntry(self, bdt.id, 333, - BIER_HDR_PAYLOAD.BIER_HDR_PROTO_IPV4, - FibPathProto.FIB_PATH_NH_PROTO_BIER, - "0.0.0.0", 10, rpf_id=8192) + bier_de_1 = VppBierDispEntry( + self, + bdt.id, + 333, + BIER_HDR_PAYLOAD.BIER_HDR_PROTO_IPV4, + FibPathProto.FIB_PATH_NH_PROTO_BIER, + "0.0.0.0", + 10, + rpf_id=8192, + ) bier_de_1.add_vpp_config() - bier_de_1 = VppBierDispEntry(self, bdt.id, 334, - BIER_HDR_PAYLOAD.BIER_HDR_PROTO_IPV4, - FibPathProto.FIB_PATH_NH_PROTO_BIER, - "0.0.0.0", 10, rpf_id=8193) + bier_de_1 = VppBierDispEntry( + self, + bdt.id, + 334, + BIER_HDR_PAYLOAD.BIER_HDR_PROTO_IPV4, + FibPathProto.FIB_PATH_NH_PROTO_BIER, + "0.0.0.0", + 10, + rpf_id=8193, + ) bier_de_1.add_vpp_config() # @@ -631,21 +786,31 @@ class TestBier(VppTestCase): route_eg_232_1_1_1 = VppIpMRoute( self, "0.0.0.0", - "232.1.1.1", 32, + "232.1.1.1", + 32, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, table_id=10, - paths=[VppMRoutePath(self.pg1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)]) + paths=[ + VppMRoutePath( + self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ) + ], + ) route_eg_232_1_1_1.add_vpp_config() route_eg_232_1_1_1.update_rpf_id(8192) route_eg_232_1_1_2 = VppIpMRoute( self, "0.0.0.0", - "232.1.1.2", 32, + "232.1.1.2", + 32, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, table_id=10, - paths=[VppMRoutePath(self.pg1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)]) + paths=[ + VppMRoutePath( + self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ) + ], + ) route_eg_232_1_1_2.add_vpp_config() route_eg_232_1_1_2.update_rpf_id(8193) @@ -654,49 +819,51 @@ class TestBier(VppTestCase): # replicated, then hit the disposition and be forwarded # out of VRF 10, i.e. on pg1 # - p = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IP(src="1.1.1.1", dst="232.1.1.1") / - UDP(sport=1234, dport=1234) / - Raw(scapy.compat.chb(5) * 32)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src="1.1.1.1", dst="232.1.1.1") + / UDP(sport=1234, dport=1234) + / Raw(scapy.compat.chb(5) * 32) + ) - rx = self.send_and_expect(self.pg0, p*NUM_PKTS, self.pg1) + rx = self.send_and_expect(self.pg0, p * NUM_PKTS, self.pg1) self.assertEqual(rx[0][IP].src, "1.1.1.1") self.assertEqual(rx[0][IP].dst, "232.1.1.1") - p = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IP(src="1.1.1.1", dst="232.1.1.2") / - UDP(sport=1234, dport=1234) / - Raw(scapy.compat.chb(5) * 512)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src="1.1.1.1", dst="232.1.1.2") + / UDP(sport=1234, dport=1234) + / Raw(scapy.compat.chb(5) * 512) + ) - rx = self.send_and_expect(self.pg0, p*NUM_PKTS, self.pg1) + rx = self.send_and_expect(self.pg0, p * NUM_PKTS, self.pg1) self.assertEqual(rx[0][IP].src, "1.1.1.1") self.assertEqual(rx[0][IP].dst, "232.1.1.2") @unittest.skipUnless(config.extended, "part of extended tests") def test_bier_e2e_1024(self): - """ BIER end-to-end BSL:1024""" + """BIER end-to-end BSL:1024""" self.bier_e2e(BIERLength.BIER_LEN_1024, 128, 1024) @unittest.skipUnless(config.extended, "part of extended tests") def test_bier_e2e_512(self): - """ BIER end-to-end BSL:512""" + """BIER end-to-end BSL:512""" self.bier_e2e(BIERLength.BIER_LEN_512, 64, 512) @unittest.skipUnless(config.extended, "part of extended tests") def test_bier_e2e_256(self): - """ BIER end-to-end BSL:256""" + """BIER end-to-end BSL:256""" self.bier_e2e(BIERLength.BIER_LEN_256, 32, 256) @unittest.skipUnless(config.extended, "part of extended tests") def test_bier_e2e_128(self): - """ BIER end-to-end BSL:128""" + """BIER end-to-end BSL:128""" self.bier_e2e(BIERLength.BIER_LEN_128, 16, 128) def test_bier_e2e_64(self): - """ BIER end-to-end BSL:64""" + """BIER end-to-end BSL:64""" self.bier_e2e(BIERLength.BIER_LEN_64, 8, 64) def test_bier_head_o_udp(self): @@ -716,24 +883,36 @@ class TestBier(VppTestCase): # 1 bit positions via 1 next hops # nh1 = "10.0.0.1" - ip_route = VppIpRoute(self, nh1, 32, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index, - labels=[VppMplsLabel(2001)])]) + ip_route = VppIpRoute( + self, + nh1, + 32, + [ + VppRoutePath( + self.pg1.remote_ip4, + self.pg1.sw_if_index, + labels=[VppMplsLabel(2001)], + ) + ], + ) ip_route.add_vpp_config() - udp_encap = VppUdpEncap(self, - self.pg0.local_ip4, - nh1, - 330, 8138) + udp_encap = VppUdpEncap(self, self.pg0.local_ip4, nh1, 330, 8138) udp_encap.add_vpp_config() bier_route = VppBierRoute( - self, bti, 1, - [VppRoutePath("0.0.0.0", - 0xFFFFFFFF, - type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP, - next_hop_id=udp_encap.id)]) + self, + bti, + 1, + [ + VppRoutePath( + "0.0.0.0", + 0xFFFFFFFF, + type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP, + next_hop_id=udp_encap.id, + ) + ], + ) bier_route.add_vpp_config() # @@ -741,9 +920,9 @@ class TestBier(VppTestCase): # only use the second, but creating 2 tests with a non-zero # value index in the route add # - bi = VppBierImp(self, bti, 333, scapy.compat.chb(0xff) * 32) + bi = VppBierImp(self, bti, 333, scapy.compat.chb(0xFF) * 32) bi.add_vpp_config() - bi2 = VppBierImp(self, bti, 334, scapy.compat.chb(0xff) * 32) + bi2 = VppBierImp(self, bti, 334, scapy.compat.chb(0xFF) * 32) bi2.add_vpp_config() # @@ -752,24 +931,32 @@ class TestBier(VppTestCase): route_ing_232_1_1_1 = VppIpMRoute( self, "0.0.0.0", - "232.1.1.1", 32, + "232.1.1.1", + 32, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - paths=[VppMRoutePath(self.pg0.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT), - VppMRoutePath(0xffffffff, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, - proto=FibPathProto.FIB_PATH_NH_PROTO_BIER, - type=FibPathType.FIB_PATH_TYPE_BIER_IMP, - bier_imp=bi2.bi_index)]) + paths=[ + VppMRoutePath( + self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT + ), + VppMRoutePath( + 0xFFFFFFFF, + MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + proto=FibPathProto.FIB_PATH_NH_PROTO_BIER, + type=FibPathType.FIB_PATH_TYPE_BIER_IMP, + bier_imp=bi2.bi_index, + ), + ], + ) route_ing_232_1_1_1.add_vpp_config() # # inject a packet an IP. We expect it to be BIER and UDP encapped, # - p = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IP(src="1.1.1.1", dst="232.1.1.1") / - UDP(sport=1234, dport=1234)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src="1.1.1.1", dst="232.1.1.1") + / UDP(sport=1234, dport=1234) + ) self.pg0.add_stream([p]) self.pg_enable_capture(self.pg_interfaces) @@ -813,20 +1000,33 @@ class TestBier(VppTestCase): # BIER route in table that's for-us # bier_route_1 = VppBierRoute( - self, bti, 1, - [VppRoutePath("0.0.0.0", - 0xffffffff, - proto=FibPathProto.FIB_PATH_NH_PROTO_BIER, - nh_table_id=8)]) + self, + bti, + 1, + [ + VppRoutePath( + "0.0.0.0", + 0xFFFFFFFF, + proto=FibPathProto.FIB_PATH_NH_PROTO_BIER, + nh_table_id=8, + ) + ], + ) bier_route_1.add_vpp_config() # # An entry in the disposition table # - bier_de_1 = VppBierDispEntry(self, bdt.id, 99, - BIER_HDR_PAYLOAD.BIER_HDR_PROTO_IPV4, - FibPathProto.FIB_PATH_NH_PROTO_BIER, - "0.0.0.0", 0, rpf_id=8192) + bier_de_1 = VppBierDispEntry( + self, + bdt.id, + 99, + BIER_HDR_PAYLOAD.BIER_HDR_PROTO_IPV4, + FibPathProto.FIB_PATH_NH_PROTO_BIER, + "0.0.0.0", + 0, + rpf_id=8192, + ) bier_de_1.add_vpp_config() # @@ -835,29 +1035,38 @@ class TestBier(VppTestCase): route_eg_232_1_1_1 = VppIpMRoute( self, "0.0.0.0", - "232.1.1.1", 32, + "232.1.1.1", + 32, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - paths=[VppMRoutePath(self.pg1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)]) + paths=[ + VppMRoutePath( + self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ) + ], + ) route_eg_232_1_1_1.add_vpp_config() route_eg_232_1_1_1.update_rpf_id(8192) # # A packet with all bits set gets spat out to BP:1 # - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / - UDP(sport=333, dport=8138) / - BIFT(sd=1, set=0, bsl=2, ttl=255) / - BIER(length=BIERLength.BIER_LEN_256, - BitString=scapy.compat.chb(255)*32, - BFRID=99) / - IP(src="1.1.1.1", dst="232.1.1.1") / - UDP(sport=1234, dport=1234) / - Raw()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / UDP(sport=333, dport=8138) + / BIFT(sd=1, set=0, bsl=2, ttl=255) + / BIER( + length=BIERLength.BIER_LEN_256, + BitString=scapy.compat.chb(255) * 32, + BFRID=99, + ) + / IP(src="1.1.1.1", dst="232.1.1.1") + / UDP(sport=1234, dport=1234) + / Raw() + ) rx = self.send_and_expect(self.pg0, [p], self.pg1) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_bihash.py b/test/test_bihash.py index 32eb4ff3a21..b57485a3e9a 100644 --- a/test/test_bihash.py +++ b/test/test_bihash.py @@ -8,7 +8,7 @@ from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath class TestBihash(VppTestCase): - """ Bihash Test Cases """ + """Bihash Test Cases""" @classmethod def setUpClass(cls): @@ -28,48 +28,54 @@ class TestBihash(VppTestCase): super(TestBihash, self).tearDown() def test_bihash_unittest(self): - """ Bihash Add/Del Test """ + """Bihash Add/Del Test""" error = self.vapi.cli("test bihash careful 0 verbose 0") if error: self.logger.critical(error) - self.assertNotIn('failed', error) + self.assertNotIn("failed", error) def test_bihash_thread(self): - """ Bihash Thread Test """ + """Bihash Thread Test""" - error = self.vapi.cli("test bihash threads 2 nbuckets" + - " 64000 careful 0 verbose 0") + error = self.vapi.cli( + "test bihash threads 2 nbuckets" + " 64000 careful 0 verbose 0" + ) if error: self.logger.critical(error) - self.assertNotIn('failed', error) + self.assertNotIn("failed", error) def test_bihash_vec64(self): - """ Bihash vec64 Test """ + """Bihash vec64 Test""" error = self.vapi.cli("test bihash vec64") if error: self.logger.critical(error) - self.assertNotIn('failed', error) + self.assertNotIn("failed", error) @unittest.skipUnless(config.gcov, "part of code coverage tests") def test_bihash_coverage(self): - """ Improve Code Coverage """ + """Improve Code Coverage""" - error = self.vapi.cli("test bihash nitems 10 ncycles 3" + - "search 2 careful 1 verbose 2 non-random-keys") + error = self.vapi.cli( + "test bihash nitems 10 ncycles 3" + + "search 2 careful 1 verbose 2 non-random-keys" + ) if error: self.logger.critical(error) - self.assertNotIn('failed', error) + self.assertNotIn("failed", error) - error = self.vapi.cli("test bihash nitems 10 nbuckets 1 ncycles 3" + - "search 2 careful 1 verbose 2 non-random-keys") + error = self.vapi.cli( + "test bihash nitems 10 nbuckets 1 ncycles 3" + + "search 2 careful 1 verbose 2 non-random-keys" + ) if error: self.logger.critical(error) - self.assertNotIn('failed', error) + self.assertNotIn("failed", error) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_bond.py b/test/test_bond.py index 5df86ae5b0f..159bae5fea0 100644 --- a/test/test_bond.py +++ b/test/test_bond.py @@ -13,15 +13,13 @@ from vpp_papi import MACAddress, VppEnum class TestBondInterface(VppTestCase): - """Bond Test Case - - """ + """Bond Test Case""" @classmethod def setUpClass(cls): super(TestBondInterface, cls).setUpClass() # Test variables - cls.pkts_per_burst = 257 # Number of packets per burst + cls.pkts_per_burst = 257 # Number of packets per burst # create 3 pg interfaces cls.create_pg_interfaces(range(4)) @@ -46,7 +44,7 @@ class TestBondInterface(VppTestCase): self.logger.info(self.vapi.ppcli("show interface")) def test_bond_traffic(self): - """ Bond traffic test """ + """Bond traffic test""" # topology # @@ -69,12 +67,13 @@ class TestBondInterface(VppTestCase): lb=VppEnum.vl_api_bond_lb_algo_t.BOND_API_LB_ALGO_L34, numa_only=0, use_custom_mac=1, - mac_address=mac) + mac_address=mac, + ) bond0.add_vpp_config() bond0.admin_up() self.vapi.sw_interface_add_del_address( - sw_if_index=bond0.sw_if_index, - prefix="10.10.10.1/24") + sw_if_index=bond0.sw_if_index, prefix="10.10.10.1/24" + ) self.pg2.config_ip4() self.pg2.resolve_arp() @@ -98,29 +97,39 @@ class TestBondInterface(VppTestCase): # generate a packet from pg2 -> BondEthernet0 -> pg1 # BondEthernet0 TX hashes this packet to pg1 - p2 = (Ether(src=bond0_mac, dst=self.pg2.local_mac) / - IP(src=self.pg2.local_ip4, dst="10.10.10.12") / - UDP(sport=1235, dport=1235) / - Raw(b'\xa5' * 100)) + p2 = ( + Ether(src=bond0_mac, dst=self.pg2.local_mac) + / IP(src=self.pg2.local_ip4, dst="10.10.10.12") + / UDP(sport=1235, dport=1235) + / Raw(b"\xa5" * 100) + ) self.pg2.add_stream(p2) # generate a packet from pg3 -> BondEthernet0 -> pg0 # BondEthernet0 TX hashes this packet to pg0 # notice the ip address and ports are different than p2 packet - p3 = (Ether(src=bond0_mac, dst=self.pg3.local_mac) / - IP(src=self.pg3.local_ip4, dst="10.10.10.11") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p3 = ( + Ether(src=bond0_mac, dst=self.pg3.local_mac) + / IP(src=self.pg3.local_ip4, dst="10.10.10.11") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) self.pg3.add_stream(p3) self.pg_enable_capture(self.pg_interfaces) # set up the static arp entries pointing to the BondEthernet0 interface # so that it does not try to resolve the ip address - self.logger.info(self.vapi.cli( - "set ip neighbor static BondEthernet0 10.10.10.12 abcd.abcd.0002")) - self.logger.info(self.vapi.cli( - "set ip neighbor static BondEthernet0 10.10.10.11 abcd.abcd.0004")) + self.logger.info( + self.vapi.cli( + "set ip neighbor static BondEthernet0 10.10.10.12 abcd.abcd.0002" + ) + ) + self.logger.info( + self.vapi.cli( + "set ip neighbor static BondEthernet0 10.10.10.11 abcd.abcd.0004" + ) + ) # clear the interface counters self.logger.info(self.vapi.cli("clear interfaces")) @@ -166,14 +175,13 @@ class TestBondInterface(VppTestCase): bond0.remove_vpp_config() def test_bond_add_member(self): - """ Bond add_member/detach member test """ + """Bond add_member/detach member test""" # create interface (BondEthernet0) and set bond mode to LACP self.logger.info("create bond") bond0 = VppBondInterface( - self, - mode=VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP, - enable_gso=0) + self, mode=VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP, enable_gso=0 + ) bond0.add_vpp_config() bond0.admin_up() @@ -187,15 +195,13 @@ class TestBondInterface(VppTestCase): # add_member pg0 and pg1 to BondEthernet0 self.logger.info("bond add_member interface pg0 to BondEthernet0") bond0.add_member_vpp_bond_interface( - sw_if_index=self.pg0.sw_if_index, - is_passive=0, - is_long_timeout=0) + sw_if_index=self.pg0.sw_if_index, is_passive=0, is_long_timeout=0 + ) self.logger.info("bond add_member interface pg1 to BondEthernet0") bond0.add_member_vpp_bond_interface( - sw_if_index=self.pg1.sw_if_index, - is_passive=0, - is_long_timeout=0) + sw_if_index=self.pg1.sw_if_index, is_passive=0, is_long_timeout=0 + ) # verify both members in BondEthernet0 if_dump = self.vapi.sw_member_interface_dump(bond0.sw_if_index) self.assertTrue(self.pg0.is_interface_config_in_dump(if_dump)) @@ -222,25 +228,27 @@ class TestBondInterface(VppTestCase): bond0.remove_vpp_config() def test_bond(self): - """ Bond add/delete interface test """ + """Bond add/delete interface test""" self.logger.info("Bond add interfaces") # create interface 1 (BondEthernet0) bond0 = VppBondInterface( - self, mode=VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP) + self, mode=VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP + ) bond0.add_vpp_config() bond0.admin_up() # create interface 2 (BondEthernet1) bond1 = VppBondInterface( - self, mode=VppEnum.vl_api_bond_mode_t.BOND_API_MODE_XOR) + self, mode=VppEnum.vl_api_bond_mode_t.BOND_API_MODE_XOR + ) bond1.add_vpp_config() bond1.admin_up() # verify both interfaces in the show ifs = self.vapi.cli("show interface") - self.assertIn('BondEthernet0', ifs) - self.assertIn('BondEthernet1', ifs) + self.assertIn("BondEthernet0", ifs) + self.assertIn("BondEthernet1", ifs) # verify they are in the dump also if_dump = self.vapi.sw_bond_interface_dump(sw_if_index=0xFFFFFFFF) @@ -255,10 +263,10 @@ class TestBondInterface(VppTestCase): ifs = self.vapi.cli("show interface") # verify BondEthernet0 still in the show - self.assertIn('BondEthernet0', ifs) + self.assertIn("BondEthernet0", ifs) # verify BondEthernet1 not in the show - self.assertNotIn('BondEthernet1', ifs) + self.assertNotIn("BondEthernet1", ifs) # verify BondEthernet1 is not in the dump if_dump = self.vapi.sw_bond_interface_dump(sw_if_index=0xFFFFFFFF) @@ -275,15 +283,14 @@ class TestBondInterface(VppTestCase): # verify BondEthernet0 not in the show ifs = self.vapi.cli("show interface") - self.assertNotIn('BondEthernet0', ifs) + self.assertNotIn("BondEthernet0", ifs) # verify BondEthernet0 is not in the dump - if_dump = self.vapi.sw_bond_interface_dump( - sw_if_index=bond0.sw_if_index) + if_dump = self.vapi.sw_bond_interface_dump(sw_if_index=bond0.sw_if_index) self.assertFalse(bond0.is_interface_config_in_dump(if_dump)) def test_bond_link(self): - """ Bond hw interface link state test """ + """Bond hw interface link state test""" # for convenience bond_modes = VppEnum.vl_api_bond_mode_t @@ -292,16 +299,17 @@ class TestBondInterface(VppTestCase): # create interface 1 (BondEthernet0) self.logger.info("Create bond interface") # use round-robin mode to avoid negotiation required by LACP - bond0 = VppBondInterface(self, - mode=bond_modes.BOND_API_MODE_ROUND_ROBIN) + bond0 = VppBondInterface(self, mode=bond_modes.BOND_API_MODE_ROUND_ROBIN) bond0.add_vpp_config() # set bond admin up. self.logger.info("set interface BondEthernet0 admin up") bond0.admin_up() # confirm link up - bond0.assert_interface_state(intf_flags.IF_STATUS_API_FLAG_ADMIN_UP, - intf_flags.IF_STATUS_API_FLAG_LINK_UP) + bond0.assert_interface_state( + intf_flags.IF_STATUS_API_FLAG_ADMIN_UP, + intf_flags.IF_STATUS_API_FLAG_LINK_UP, + ) # toggle bond admin state self.logger.info("toggle interface BondEthernet0") @@ -309,13 +317,15 @@ class TestBondInterface(VppTestCase): bond0.admin_up() # confirm link is still up - bond0.assert_interface_state(intf_flags.IF_STATUS_API_FLAG_ADMIN_UP, - intf_flags.IF_STATUS_API_FLAG_LINK_UP) + bond0.assert_interface_state( + intf_flags.IF_STATUS_API_FLAG_ADMIN_UP, + intf_flags.IF_STATUS_API_FLAG_LINK_UP, + ) # delete BondEthernet0 self.logger.info("Deleting BondEthernet0") bond0.remove_vpp_config() -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_buffers.py b/test/test_buffers.py index f50f05c609a..01875526812 100644 --- a/test/test_buffers.py +++ b/test/test_buffers.py @@ -4,7 +4,7 @@ from framework import VppTestCase class TestBuffers(VppTestCase): - """ Buffer C Unit Tests """ + """Buffer C Unit Tests""" @classmethod def setUpClass(cls): @@ -21,9 +21,9 @@ class TestBuffers(VppTestCase): super(TestBuffers, self).tearDown() def test_linearize(self): - """ Chained Buffer Linearization """ + """Chained Buffer Linearization""" error = self.vapi.cli("test chained-buffer-linearization") if error: self.logger.critical(error) - self.assertNotIn('failed', error) + self.assertNotIn("failed", error) diff --git a/test/test_cdp.py b/test/test_cdp.py index 46751e81d86..da378dbebe3 100644 --- a/test/test_cdp.py +++ b/test/test_cdp.py @@ -4,8 +4,13 @@ from scapy.packet import Packet from scapy.all import ShortField, StrField from scapy.layers.l2 import Dot3, LLC, SNAP -from scapy.contrib.cdp import CDPMsgDeviceID, CDPMsgSoftwareVersion, \ - CDPMsgPlatform, CDPMsgPortID, CDPv2_HDR +from scapy.contrib.cdp import ( + CDPMsgDeviceID, + CDPMsgSoftwareVersion, + CDPMsgPlatform, + CDPMsgPortID, + CDPv2_HDR, +) from framework import VppTestCase from scapy.all import raw @@ -25,18 +30,17 @@ CDP test. class CustomTLV(Packet): - """ Custom TLV protocol layer for scapy """ + """Custom TLV protocol layer for scapy""" fields_desc = [ ShortField("type", 0), ShortField("length", 4), - StrField("value", "") - + StrField("value", ""), ] class TestCDP(VppTestCase): - """ CDP Test Case """ + """CDP Test Case""" nen_ptr = compile(r"not enabled") cdp_ptr = compile(r"^([-\.\w]+)\s+([-\.\w]+)\s+([-\.\w]+)\s+([-\.\w]+)$") @@ -95,8 +99,9 @@ class TestCDP(VppTestCase): length = min(len(system), len(self.device_id)) self.assert_equal(port, self.port_id, "CDP received invalid port id") - self.assert_equal(system[:length], self.device_id[:length], - "CDP received invalid device id") + self.assert_equal( + system[:length], self.device_id[:length], "CDP received invalid device id" + ) def test_cdp_underflow_tlv(self): self.send_bad_packet(3, ".") @@ -109,7 +114,8 @@ class TestCDP(VppTestCase): self.send_packet(self.create_bad_packet(l, v)) err = self.statistics.get_err_counter( - '/err/cdp-input/cdp packets with bad TLVs') + "/err/cdp-input/cdp packets with bad TLVs" + ) self.assertTrue(err >= 1, "CDP didn't drop bad packet") def send_packet(self, packet): @@ -118,29 +124,30 @@ class TestCDP(VppTestCase): self.pg_start() def create_base_packet(self): - packet = (Dot3(src=self.interface.remote_mac, - dst="01:00:0c:cc:cc:cc") / - LLC(dsap=0xaa, ssap=0xaa, ctrl=0x03) / - SNAP()/CDPv2_HDR()) + packet = ( + Dot3(src=self.interface.remote_mac, dst="01:00:0c:cc:cc:cc") + / LLC(dsap=0xAA, ssap=0xAA, ctrl=0x03) + / SNAP() + / CDPv2_HDR() + ) return packet def create_packet(self): - packet = (self.create_base_packet() / - CDPMsgDeviceID(val=self.device_id) / - CDPMsgSoftwareVersion(val=self.version) / - CDPMsgPortID(iface=self.port_id) / - CDPMsgPlatform(val=self.platform)) + packet = ( + self.create_base_packet() + / CDPMsgDeviceID(val=self.device_id) + / CDPMsgSoftwareVersion(val=self.version) + / CDPMsgPortID(iface=self.port_id) + / CDPMsgPlatform(val=self.platform) + ) return packet def create_bad_packet(self, tl=4, tv=""): - packet = (self.create_base_packet() / - CustomTLV(type=1, - length=tl, - value=tv)) + packet = self.create_base_packet() / CustomTLV(type=1, length=tl, value=tv) return packet def process_cli(self, exp, ptr): - for line in self.vapi.cli(exp).split('\n')[1:]: + for line in self.vapi.cli(exp).split("\n")[1:]: m = ptr.match(line.strip()) if m: yield m.groups() diff --git a/test/test_classifier.py b/test/test_classifier.py index 9f0fdbf587a..068561230ea 100644 --- a/test/test_classifier.py +++ b/test/test_classifier.py @@ -19,7 +19,7 @@ from vpp_papi import VppEnum # Tests split to different test case classes because of issue reported in # ticket VPP-1336 class TestClassifierIP(TestClassifier): - """ Classifier IP Test Case """ + """Classifier IP Test Case""" @classmethod def setUpClass(cls): @@ -30,7 +30,7 @@ class TestClassifierIP(TestClassifier): super(TestClassifierIP, cls).tearDownClass() def test_iacl_src_ip(self): - """ Source IP iACL test + """Source IP iACL test Test scenario for basic IP ACL with source IP - Create IPv4 stream for pg0 -> pg1 interface. @@ -42,11 +42,11 @@ class TestClassifierIP(TestClassifier): pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes) self.pg0.add_stream(pkts) - key = 'ip_src' - self.create_classify_table(key, self.build_ip_mask(src_ip='ffffffff')) + key = "ip_src" + self.create_classify_table(key, self.build_ip_mask(src_ip="ffffffff")) self.create_classify_session( - self.acl_tbl_idx.get(key), - self.build_ip_match(src_ip=self.pg0.remote_ip4)) + self.acl_tbl_idx.get(key), self.build_ip_match(src_ip=self.pg0.remote_ip4) + ) self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key @@ -60,7 +60,7 @@ class TestClassifierIP(TestClassifier): self.pg3.assert_nothing_captured(remark="packets forwarded") def test_iacl_dst_ip(self): - """ Destination IP iACL test + """Destination IP iACL test Test scenario for basic IP ACL with destination IP - Create IPv4 stream for pg0 -> pg1 interface. @@ -72,11 +72,11 @@ class TestClassifierIP(TestClassifier): pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes) self.pg0.add_stream(pkts) - key = 'ip_dst' - self.create_classify_table(key, self.build_ip_mask(dst_ip='ffffffff')) + key = "ip_dst" + self.create_classify_table(key, self.build_ip_mask(dst_ip="ffffffff")) self.create_classify_session( - self.acl_tbl_idx.get(key), - self.build_ip_match(dst_ip=self.pg1.remote_ip4)) + self.acl_tbl_idx.get(key), self.build_ip_match(dst_ip=self.pg1.remote_ip4) + ) self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key @@ -90,7 +90,7 @@ class TestClassifierIP(TestClassifier): self.pg3.assert_nothing_captured(remark="packets forwarded") def test_iacl_src_dst_ip(self): - """ Source and destination IP iACL test + """Source and destination IP iACL test Test scenario for basic IP ACL with source and destination IP - Create IPv4 stream for pg0 -> pg1 interface. @@ -102,13 +102,14 @@ class TestClassifierIP(TestClassifier): pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes) self.pg0.add_stream(pkts) - key = 'ip' + key = "ip" self.create_classify_table( - key, self.build_ip_mask(src_ip='ffffffff', dst_ip='ffffffff')) + key, self.build_ip_mask(src_ip="ffffffff", dst_ip="ffffffff") + ) self.create_classify_session( self.acl_tbl_idx.get(key), - self.build_ip_match(src_ip=self.pg0.remote_ip4, - dst_ip=self.pg1.remote_ip4)) + self.build_ip_match(src_ip=self.pg0.remote_ip4, dst_ip=self.pg1.remote_ip4), + ) self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key @@ -123,7 +124,7 @@ class TestClassifierIP(TestClassifier): class TestClassifierUDP(TestClassifier): - """ Classifier UDP proto Test Case """ + """Classifier UDP proto Test Case""" @classmethod def setUpClass(cls): @@ -134,7 +135,7 @@ class TestClassifierUDP(TestClassifier): super(TestClassifierUDP, cls).tearDownClass() def test_iacl_proto_udp(self): - """ UDP protocol iACL test + """UDP protocol iACL test Test scenario for basic protocol ACL with UDP protocol - Create IPv4 stream for pg0 -> pg1 interface. @@ -146,13 +147,12 @@ class TestClassifierUDP(TestClassifier): pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes) self.pg0.add_stream(pkts) - key = 'proto_udp' - self.create_classify_table(key, self.build_ip_mask(proto='ff')) + key = "proto_udp" + self.create_classify_table(key, self.build_ip_mask(proto="ff")) self.create_classify_session( - self.acl_tbl_idx.get(key), - self.build_ip_match(proto=socket.IPPROTO_UDP)) - self.input_acl_set_interface( - self.pg0, self.acl_tbl_idx.get(key)) + self.acl_tbl_idx.get(key), self.build_ip_match(proto=socket.IPPROTO_UDP) + ) + self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key self.pg_enable_capture(self.pg_interfaces) @@ -165,7 +165,7 @@ class TestClassifierUDP(TestClassifier): self.pg3.assert_nothing_captured(remark="packets forwarded") def test_iacl_proto_udp_sport(self): - """ UDP source port iACL test + """UDP source port iACL test Test scenario for basic protocol ACL with UDP and sport - Create IPv4 stream for pg0 -> pg1 interface. @@ -175,18 +175,18 @@ class TestClassifierUDP(TestClassifier): # Basic iACL testing with UDP and sport sport = 38 - pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes, - UDP(sport=sport, dport=5678)) + pkts = self.create_stream( + self.pg0, self.pg1, self.pg_if_packet_sizes, UDP(sport=sport, dport=5678) + ) self.pg0.add_stream(pkts) - key = 'proto_udp_sport' - self.create_classify_table( - key, self.build_ip_mask(proto='ff', src_port='ffff')) + key = "proto_udp_sport" + self.create_classify_table(key, self.build_ip_mask(proto="ff", src_port="ffff")) self.create_classify_session( self.acl_tbl_idx.get(key), - self.build_ip_match(proto=socket.IPPROTO_UDP, src_port=sport)) - self.input_acl_set_interface( - self.pg0, self.acl_tbl_idx.get(key)) + self.build_ip_match(proto=socket.IPPROTO_UDP, src_port=sport), + ) + self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key self.pg_enable_capture(self.pg_interfaces) @@ -199,7 +199,7 @@ class TestClassifierUDP(TestClassifier): self.pg3.assert_nothing_captured(remark="packets forwarded") def test_iacl_proto_udp_dport(self): - """ UDP destination port iACL test + """UDP destination port iACL test Test scenario for basic protocol ACL with UDP and dport - Create IPv4 stream for pg0 -> pg1 interface. @@ -209,18 +209,18 @@ class TestClassifierUDP(TestClassifier): # Basic iACL testing with UDP and dport dport = 427 - pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes, - UDP(sport=1234, dport=dport)) + pkts = self.create_stream( + self.pg0, self.pg1, self.pg_if_packet_sizes, UDP(sport=1234, dport=dport) + ) self.pg0.add_stream(pkts) - key = 'proto_udp_dport' - self.create_classify_table( - key, self.build_ip_mask(proto='ff', dst_port='ffff')) + key = "proto_udp_dport" + self.create_classify_table(key, self.build_ip_mask(proto="ff", dst_port="ffff")) self.create_classify_session( self.acl_tbl_idx.get(key), - self.build_ip_match(proto=socket.IPPROTO_UDP, dst_port=dport)) - self.input_acl_set_interface( - self.pg0, self.acl_tbl_idx.get(key)) + self.build_ip_match(proto=socket.IPPROTO_UDP, dst_port=dport), + ) + self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key self.pg_enable_capture(self.pg_interfaces) @@ -233,7 +233,7 @@ class TestClassifierUDP(TestClassifier): self.pg3.assert_nothing_captured(remark="packets forwarded") def test_iacl_proto_udp_sport_dport(self): - """ UDP source and destination ports iACL test + """UDP source and destination ports iACL test Test scenario for basic protocol ACL with UDP and sport and dport - Create IPv4 stream for pg0 -> pg1 interface. @@ -244,20 +244,22 @@ class TestClassifierUDP(TestClassifier): # Basic iACL testing with UDP and sport and dport sport = 13720 dport = 9080 - pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes, - UDP(sport=sport, dport=dport)) + pkts = self.create_stream( + self.pg0, self.pg1, self.pg_if_packet_sizes, UDP(sport=sport, dport=dport) + ) self.pg0.add_stream(pkts) - key = 'proto_udp_ports' + key = "proto_udp_ports" self.create_classify_table( - key, - self.build_ip_mask(proto='ff', src_port='ffff', dst_port='ffff')) + key, self.build_ip_mask(proto="ff", src_port="ffff", dst_port="ffff") + ) self.create_classify_session( self.acl_tbl_idx.get(key), - self.build_ip_match(proto=socket.IPPROTO_UDP, src_port=sport, - dst_port=dport)) - self.input_acl_set_interface( - self.pg0, self.acl_tbl_idx.get(key)) + self.build_ip_match( + proto=socket.IPPROTO_UDP, src_port=sport, dst_port=dport + ), + ) + self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key self.pg_enable_capture(self.pg_interfaces) @@ -271,7 +273,7 @@ class TestClassifierUDP(TestClassifier): class TestClassifierTCP(TestClassifier): - """ Classifier TCP proto Test Case """ + """Classifier TCP proto Test Case""" @classmethod def setUpClass(cls): @@ -282,7 +284,7 @@ class TestClassifierTCP(TestClassifier): super(TestClassifierTCP, cls).tearDownClass() def test_iacl_proto_tcp(self): - """ TCP protocol iACL test + """TCP protocol iACL test Test scenario for basic protocol ACL with TCP protocol - Create IPv4 stream for pg0 -> pg1 interface. @@ -291,17 +293,17 @@ class TestClassifierTCP(TestClassifier): """ # Basic iACL testing with TCP protocol - pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes, - TCP(sport=1234, dport=5678)) + pkts = self.create_stream( + self.pg0, self.pg1, self.pg_if_packet_sizes, TCP(sport=1234, dport=5678) + ) self.pg0.add_stream(pkts) - key = 'proto_tcp' - self.create_classify_table(key, self.build_ip_mask(proto='ff')) + key = "proto_tcp" + self.create_classify_table(key, self.build_ip_mask(proto="ff")) self.create_classify_session( - self.acl_tbl_idx.get(key), - self.build_ip_match(proto=socket.IPPROTO_TCP)) - self.input_acl_set_interface( - self.pg0, self.acl_tbl_idx.get(key)) + self.acl_tbl_idx.get(key), self.build_ip_match(proto=socket.IPPROTO_TCP) + ) + self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key self.pg_enable_capture(self.pg_interfaces) @@ -314,7 +316,7 @@ class TestClassifierTCP(TestClassifier): self.pg3.assert_nothing_captured(remark="packets forwarded") def test_iacl_proto_tcp_sport(self): - """ TCP source port iACL test + """TCP source port iACL test Test scenario for basic protocol ACL with TCP and sport - Create IPv4 stream for pg0 -> pg1 interface. @@ -324,18 +326,18 @@ class TestClassifierTCP(TestClassifier): # Basic iACL testing with TCP and sport sport = 38 - pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes, - TCP(sport=sport, dport=5678)) + pkts = self.create_stream( + self.pg0, self.pg1, self.pg_if_packet_sizes, TCP(sport=sport, dport=5678) + ) self.pg0.add_stream(pkts) - key = 'proto_tcp_sport' - self.create_classify_table( - key, self.build_ip_mask(proto='ff', src_port='ffff')) + key = "proto_tcp_sport" + self.create_classify_table(key, self.build_ip_mask(proto="ff", src_port="ffff")) self.create_classify_session( self.acl_tbl_idx.get(key), - self.build_ip_match(proto=socket.IPPROTO_TCP, src_port=sport)) - self.input_acl_set_interface( - self.pg0, self.acl_tbl_idx.get(key)) + self.build_ip_match(proto=socket.IPPROTO_TCP, src_port=sport), + ) + self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key self.pg_enable_capture(self.pg_interfaces) @@ -348,7 +350,7 @@ class TestClassifierTCP(TestClassifier): self.pg3.assert_nothing_captured(remark="packets forwarded") def test_iacl_proto_tcp_dport(self): - """ TCP destination port iACL test + """TCP destination port iACL test Test scenario for basic protocol ACL with TCP and dport - Create IPv4 stream for pg0 -> pg1 interface. @@ -358,18 +360,18 @@ class TestClassifierTCP(TestClassifier): # Basic iACL testing with TCP and dport dport = 427 - pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes, - TCP(sport=1234, dport=dport)) + pkts = self.create_stream( + self.pg0, self.pg1, self.pg_if_packet_sizes, TCP(sport=1234, dport=dport) + ) self.pg0.add_stream(pkts) - key = 'proto_tcp_sport' - self.create_classify_table( - key, self.build_ip_mask(proto='ff', dst_port='ffff')) + key = "proto_tcp_sport" + self.create_classify_table(key, self.build_ip_mask(proto="ff", dst_port="ffff")) self.create_classify_session( self.acl_tbl_idx.get(key), - self.build_ip_match(proto=socket.IPPROTO_TCP, dst_port=dport)) - self.input_acl_set_interface( - self.pg0, self.acl_tbl_idx.get(key)) + self.build_ip_match(proto=socket.IPPROTO_TCP, dst_port=dport), + ) + self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key self.pg_enable_capture(self.pg_interfaces) @@ -382,7 +384,7 @@ class TestClassifierTCP(TestClassifier): self.pg3.assert_nothing_captured(remark="packets forwarded") def test_iacl_proto_tcp_sport_dport(self): - """ TCP source and destination ports iACL test + """TCP source and destination ports iACL test Test scenario for basic protocol ACL with TCP and sport and dport - Create IPv4 stream for pg0 -> pg1 interface. @@ -393,20 +395,22 @@ class TestClassifierTCP(TestClassifier): # Basic iACL testing with TCP and sport and dport sport = 13720 dport = 9080 - pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes, - TCP(sport=sport, dport=dport)) + pkts = self.create_stream( + self.pg0, self.pg1, self.pg_if_packet_sizes, TCP(sport=sport, dport=dport) + ) self.pg0.add_stream(pkts) - key = 'proto_tcp_ports' + key = "proto_tcp_ports" self.create_classify_table( - key, - self.build_ip_mask(proto='ff', src_port='ffff', dst_port='ffff')) + key, self.build_ip_mask(proto="ff", src_port="ffff", dst_port="ffff") + ) self.create_classify_session( self.acl_tbl_idx.get(key), - self.build_ip_match(proto=socket.IPPROTO_TCP, src_port=sport, - dst_port=dport)) - self.input_acl_set_interface( - self.pg0, self.acl_tbl_idx.get(key)) + self.build_ip_match( + proto=socket.IPPROTO_TCP, src_port=sport, dst_port=dport + ), + ) + self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key self.pg_enable_capture(self.pg_interfaces) @@ -420,7 +424,7 @@ class TestClassifierTCP(TestClassifier): class TestClassifierIPOut(TestClassifier): - """ Classifier output IP Test Case """ + """Classifier output IP Test Case""" @classmethod def setUpClass(cls): @@ -431,7 +435,7 @@ class TestClassifierIPOut(TestClassifier): super(TestClassifierIPOut, cls).tearDownClass() def test_acl_ip_out(self): - """ Output IP ACL test + """Output IP ACL test Test scenario for basic IP ACL with source IP - Create IPv4 stream for pg1 -> pg0 interface. @@ -443,12 +447,13 @@ class TestClassifierIPOut(TestClassifier): pkts = self.create_stream(self.pg1, self.pg0, self.pg_if_packet_sizes) self.pg1.add_stream(pkts) - key = 'ip_out' + key = "ip_out" self.create_classify_table( - key, self.build_ip_mask(src_ip='ffffffff'), data_offset=0) + key, self.build_ip_mask(src_ip="ffffffff"), data_offset=0 + ) self.create_classify_session( - self.acl_tbl_idx.get(key), - self.build_ip_match(src_ip=self.pg1.remote_ip4)) + self.acl_tbl_idx.get(key), self.build_ip_match(src_ip=self.pg1.remote_ip4) + ) self.output_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key @@ -463,7 +468,7 @@ class TestClassifierIPOut(TestClassifier): class TestClassifierMAC(TestClassifier): - """ Classifier MAC Test Case """ + """Classifier MAC Test Case""" @classmethod def setUpClass(cls): @@ -474,7 +479,7 @@ class TestClassifierMAC(TestClassifier): super(TestClassifierMAC, cls).tearDownClass() def test_acl_mac(self): - """ MAC ACL test + """MAC ACL test Test scenario for basic MAC ACL with source MAC - Create IPv4 stream for pg0 -> pg2 interface. @@ -486,12 +491,13 @@ class TestClassifierMAC(TestClassifier): pkts = self.create_stream(self.pg0, self.pg2, self.pg_if_packet_sizes) self.pg0.add_stream(pkts) - key = 'mac' + key = "mac" self.create_classify_table( - key, self.build_mac_mask(src_mac='ffffffffffff'), data_offset=-14) + key, self.build_mac_mask(src_mac="ffffffffffff"), data_offset=-14 + ) self.create_classify_session( - self.acl_tbl_idx.get(key), - self.build_mac_match(src_mac=self.pg0.remote_mac)) + self.acl_tbl_idx.get(key), self.build_mac_match(src_mac=self.pg0.remote_mac) + ) self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key @@ -506,7 +512,7 @@ class TestClassifierMAC(TestClassifier): class TestClassifierComplex(TestClassifier): - """ Large & Nested Classifiers Test Cases """ + """Large & Nested Classifiers Test Cases""" @classmethod def setUpClass(cls): @@ -517,7 +523,7 @@ class TestClassifierComplex(TestClassifier): super(TestClassifierComplex, cls).tearDownClass() def test_iacl_large(self): - """ Large input ACL test + """Large input ACL test Test scenario for Large ACL matching on ethernet+ip+udp headers - Create IPv4 stream for pg0 -> pg1 interface. @@ -527,7 +533,7 @@ class TestClassifierComplex(TestClassifier): # 40b offset = 80bytes - (sizeof(UDP/IP/ETH) + 4b) # + 4b as build_ip_ma*() func, do not match against UDP Len & Chksum - msk = VarMask(offset=40, spec='ffff') + msk = VarMask(offset=40, spec="ffff") mth = VarMatch(offset=40, value=0x1234, length=2) payload_msk = self.build_payload_mask([msk]) @@ -537,38 +543,49 @@ class TestClassifierComplex(TestClassifier): dport = 9080 # 36b offset = 80bytes - (sizeof(UDP/IP/ETH)) - packet_ex = bytes.fromhex(('0' * 36) + '1234') - pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes, - UDP(sport=sport, dport=dport), - packet_ex) + packet_ex = bytes.fromhex(("0" * 36) + "1234") + pkts = self.create_stream( + self.pg0, + self.pg1, + self.pg_if_packet_sizes, + UDP(sport=sport, dport=dport), + packet_ex, + ) self.pg0.add_stream(pkts) - key = 'large_in' + key = "large_in" self.create_classify_table( key, - self.build_mac_mask(src_mac='ffffffffffff', - dst_mac='ffffffffffff', - ether_type='ffff') + - self.build_ip_mask(proto='ff', - src_ip='ffffffff', - dst_ip='ffffffff', - src_port='ffff', - dst_port='ffff') + - payload_msk, - data_offset=-14) + self.build_mac_mask( + src_mac="ffffffffffff", dst_mac="ffffffffffff", ether_type="ffff" + ) + + self.build_ip_mask( + proto="ff", + src_ip="ffffffff", + dst_ip="ffffffff", + src_port="ffff", + dst_port="ffff", + ) + + payload_msk, + data_offset=-14, + ) self.create_classify_session( self.acl_tbl_idx.get(key), - self.build_mac_match(src_mac=self.pg0.remote_mac, - dst_mac=self.pg0.local_mac, - # ipv4 next header - ether_type='0800') + - self.build_ip_match(proto=socket.IPPROTO_UDP, - src_ip=self.pg0.remote_ip4, - dst_ip=self.pg1.remote_ip4, - src_port=sport, - dst_port=dport) + - payload_match + self.build_mac_match( + src_mac=self.pg0.remote_mac, + dst_mac=self.pg0.local_mac, + # ipv4 next header + ether_type="0800", + ) + + self.build_ip_match( + proto=socket.IPPROTO_UDP, + src_ip=self.pg0.remote_ip4, + dst_ip=self.pg1.remote_ip4, + src_port=sport, + dst_port=dport, + ) + + payload_match, ) self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) @@ -584,7 +601,7 @@ class TestClassifierComplex(TestClassifier): self.pg3.assert_nothing_captured(remark="packets forwarded") def test_oacl_large(self): - """ Large output ACL test + """Large output ACL test Test scenario for Large ACL matching on ethernet+ip+udp headers - Create IPv4 stream for pg1 -> pg0 interface. - Create large acl matching on ethernet+ip+udp header fields @@ -593,7 +610,7 @@ class TestClassifierComplex(TestClassifier): # 40b offset = 80bytes - (sizeof(UDP/IP/ETH) + 4b) # + 4b as build_ip_ma*() func, do not match against UDP Len & Chksum - msk = VarMask(offset=40, spec='ffff') + msk = VarMask(offset=40, spec="ffff") mth = VarMatch(offset=40, value=0x1234, length=2) payload_msk = self.build_payload_mask([msk]) @@ -603,38 +620,50 @@ class TestClassifierComplex(TestClassifier): dport = 9080 # 36b offset = 80bytes - (sizeof(UDP/IP/ETH)) - packet_ex = bytes.fromhex(('0' * 36) + '1234') - pkts = self.create_stream(self.pg1, self.pg0, self.pg_if_packet_sizes, - UDP(sport=sport, dport=dport), - packet_ex) + packet_ex = bytes.fromhex(("0" * 36) + "1234") + pkts = self.create_stream( + self.pg1, + self.pg0, + self.pg_if_packet_sizes, + UDP(sport=sport, dport=dport), + packet_ex, + ) self.pg1.add_stream(pkts) - key = 'large_out' + key = "large_out" self.create_classify_table( key, - self.build_mac_mask(src_mac='ffffffffffff', - dst_mac='ffffffffffff', - ether_type='ffff') + - self.build_ip_mask(proto='ff', - src_ip='ffffffff', - dst_ip='ffffffff', - src_port='ffff', - dst_port='ffff') + - payload_msk, - data_offset=-14) + self.build_mac_mask( + src_mac="ffffffffffff", dst_mac="ffffffffffff", ether_type="ffff" + ) + + self.build_ip_mask( + proto="ff", + src_ip="ffffffff", + dst_ip="ffffffff", + src_port="ffff", + dst_port="ffff", + ) + + payload_msk, + data_offset=-14, + ) self.create_classify_session( self.acl_tbl_idx.get(key), - self.build_mac_match(src_mac=self.pg0.local_mac, - dst_mac=self.pg0.remote_mac, - # ipv4 next header - ether_type='0800') + - self.build_ip_match(proto=socket.IPPROTO_UDP, - src_ip=self.pg1.remote_ip4, - dst_ip=self.pg0.remote_ip4, - src_port=sport, - dst_port=dport) + - payload_match) + self.build_mac_match( + src_mac=self.pg0.local_mac, + dst_mac=self.pg0.remote_mac, + # ipv4 next header + ether_type="0800", + ) + + self.build_ip_match( + proto=socket.IPPROTO_UDP, + src_ip=self.pg1.remote_ip4, + dst_ip=self.pg0.remote_ip4, + src_port=sport, + dst_port=dport, + ) + + payload_match, + ) self.output_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key @@ -649,7 +678,7 @@ class TestClassifierComplex(TestClassifier): self.pg3.assert_nothing_captured(remark="packets forwarded") def test_iacl_nested(self): - """ Nested input ACL test + """Nested input ACL test Test scenario for Large ACL matching on ethernet+ip+udp headers - Create IPv4 stream for pg0 -> pg1 interface. @@ -660,48 +689,60 @@ class TestClassifierComplex(TestClassifier): sport = 13720 dport = 9080 - pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes, - UDP(sport=sport, dport=dport)) + pkts = self.create_stream( + self.pg0, self.pg1, self.pg_if_packet_sizes, UDP(sport=sport, dport=dport) + ) self.pg0.add_stream(pkts) - subtable_key = 'subtable_in' + subtable_key = "subtable_in" self.create_classify_table( subtable_key, - self.build_mac_mask(src_mac='ffffffffffff', - dst_mac='ffffffffffff', - ether_type='ffff') + - self.build_ip_mask(proto='ff', - src_ip='ffffffff', - dst_ip='ffffffff', - src_port='ffff', - dst_port='ffff'), - data_offset=-14) - - key = 'nested_in' + self.build_mac_mask( + src_mac="ffffffffffff", dst_mac="ffffffffffff", ether_type="ffff" + ) + + self.build_ip_mask( + proto="ff", + src_ip="ffffffff", + dst_ip="ffffffff", + src_port="ffff", + dst_port="ffff", + ), + data_offset=-14, + ) + + key = "nested_in" self.create_classify_table( key, - self.build_mac_mask(src_mac='ffffffffffff', - dst_mac='ffffffffffff', - ether_type='ffff') + - self.build_ip_mask(proto='ff', - src_ip='ffffffff', - dst_ip='ffffffff', - src_port='ffff', - dst_port='ffff'), - next_table_index=self.acl_tbl_idx.get(subtable_key)) + self.build_mac_mask( + src_mac="ffffffffffff", dst_mac="ffffffffffff", ether_type="ffff" + ) + + self.build_ip_mask( + proto="ff", + src_ip="ffffffff", + dst_ip="ffffffff", + src_port="ffff", + dst_port="ffff", + ), + next_table_index=self.acl_tbl_idx.get(subtable_key), + ) self.create_classify_session( self.acl_tbl_idx.get(subtable_key), - self.build_mac_match(src_mac=self.pg0.remote_mac, - dst_mac=self.pg0.local_mac, - # ipv4 next header - ether_type='0800') + - self.build_ip_match(proto=socket.IPPROTO_UDP, - src_ip=self.pg0.remote_ip4, - dst_ip=self.pg1.remote_ip4, - src_port=sport, - dst_port=dport)) + self.build_mac_match( + src_mac=self.pg0.remote_mac, + dst_mac=self.pg0.local_mac, + # ipv4 next header + ether_type="0800", + ) + + self.build_ip_match( + proto=socket.IPPROTO_UDP, + src_ip=self.pg0.remote_ip4, + dst_ip=self.pg1.remote_ip4, + src_port=sport, + dst_port=dport, + ), + ) self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key @@ -716,7 +757,7 @@ class TestClassifierComplex(TestClassifier): self.pg3.assert_nothing_captured(remark="packets forwarded") def test_oacl_nested(self): - """ Nested output ACL test + """Nested output ACL test Test scenario for Large ACL matching on ethernet+ip+udp headers - Create IPv4 stream for pg1 -> pg0 interface. @@ -727,48 +768,60 @@ class TestClassifierComplex(TestClassifier): sport = 13720 dport = 9080 - pkts = self.create_stream(self.pg1, self.pg0, self.pg_if_packet_sizes, - UDP(sport=sport, dport=dport)) + pkts = self.create_stream( + self.pg1, self.pg0, self.pg_if_packet_sizes, UDP(sport=sport, dport=dport) + ) self.pg1.add_stream(pkts) - subtable_key = 'subtable_out' + subtable_key = "subtable_out" self.create_classify_table( subtable_key, - self.build_mac_mask(src_mac='ffffffffffff', - dst_mac='ffffffffffff', - ether_type='ffff') + - self.build_ip_mask(proto='ff', - src_ip='ffffffff', - dst_ip='ffffffff', - src_port='ffff', - dst_port='ffff'), - data_offset=-14) - - key = 'nested_out' + self.build_mac_mask( + src_mac="ffffffffffff", dst_mac="ffffffffffff", ether_type="ffff" + ) + + self.build_ip_mask( + proto="ff", + src_ip="ffffffff", + dst_ip="ffffffff", + src_port="ffff", + dst_port="ffff", + ), + data_offset=-14, + ) + + key = "nested_out" self.create_classify_table( key, - self.build_mac_mask(src_mac='ffffffffffff', - dst_mac='ffffffffffff', - ether_type='ffff') + - self.build_ip_mask(proto='ff', - src_ip='ffffffff', - dst_ip='ffffffff', - src_port='ffff', - dst_port='ffff'), + self.build_mac_mask( + src_mac="ffffffffffff", dst_mac="ffffffffffff", ether_type="ffff" + ) + + self.build_ip_mask( + proto="ff", + src_ip="ffffffff", + dst_ip="ffffffff", + src_port="ffff", + dst_port="ffff", + ), next_table_index=self.acl_tbl_idx.get(subtable_key), - data_offset=-14) + data_offset=-14, + ) self.create_classify_session( self.acl_tbl_idx.get(subtable_key), - self.build_mac_match(src_mac=self.pg0.local_mac, - dst_mac=self.pg0.remote_mac, - # ipv4 next header - ether_type='0800') + - self.build_ip_match(proto=socket.IPPROTO_UDP, - src_ip=self.pg1.remote_ip4, - dst_ip=self.pg0.remote_ip4, - src_port=sport, - dst_port=dport)) + self.build_mac_match( + src_mac=self.pg0.local_mac, + dst_mac=self.pg0.remote_mac, + # ipv4 next header + ether_type="0800", + ) + + self.build_ip_match( + proto=socket.IPPROTO_UDP, + src_ip=self.pg1.remote_ip4, + dst_ip=self.pg0.remote_ip4, + src_port=sport, + dst_port=dport, + ), + ) self.output_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key @@ -784,7 +837,7 @@ class TestClassifierComplex(TestClassifier): class TestClassifierPBR(TestClassifier): - """ Classifier PBR Test Case """ + """Classifier PBR Test Case""" @classmethod def setUpClass(cls): @@ -795,7 +848,7 @@ class TestClassifierPBR(TestClassifier): super(TestClassifierPBR, cls).tearDownClass() def test_acl_pbr(self): - """ IP PBR test + """IP PBR test Test scenario for PBR with source IP - Create IPv4 stream for pg0 -> pg3 interface. @@ -807,19 +860,24 @@ class TestClassifierPBR(TestClassifier): pkts = self.create_stream(self.pg0, self.pg3, self.pg_if_packet_sizes) self.pg0.add_stream(pkts) - key = 'pbr' - self.create_classify_table(key, self.build_ip_mask(src_ip='ffffffff')) + key = "pbr" + self.create_classify_table(key, self.build_ip_mask(src_ip="ffffffff")) pbr_option = 1 # this will create the VRF/table in which we will insert the route self.create_classify_session( self.acl_tbl_idx.get(key), self.build_ip_match(src_ip=self.pg0.remote_ip4), - pbr_option, self.pbr_vrfid) + pbr_option, + self.pbr_vrfid, + ) self.assertTrue(self.verify_vrf(self.pbr_vrfid)) - r = VppIpRoute(self, self.pg3.local_ip4, 24, - [VppRoutePath(self.pg3.remote_ip4, - INVALID_INDEX)], - table_id=self.pbr_vrfid) + r = VppIpRoute( + self, + self.pg3.local_ip4, + 24, + [VppRoutePath(self.pg3.remote_ip4, INVALID_INDEX)], + table_id=self.pbr_vrfid, + ) r.add_vpp_config() self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) @@ -839,14 +897,17 @@ class TestClassifierPBR(TestClassifier): self.create_classify_session( self.acl_tbl_idx.get(key), self.build_ip_match(src_ip=self.pg0.remote_ip4), - pbr_option, self.pbr_vrfid, is_add=0) + pbr_option, + self.pbr_vrfid, + is_add=0, + ) # and the table should be gone. self.assertFalse(self.verify_vrf(self.pbr_vrfid)) class TestClassifierPunt(TestClassifier): - """ Classifier punt Test Case """ + """Classifier punt Test Case""" @classmethod def setUpClass(cls): @@ -857,7 +918,7 @@ class TestClassifierPunt(TestClassifier): super(TestClassifierPunt, cls).tearDownClass() def test_punt_udp(self): - """ IPv4/UDP protocol punt ACL test + """IPv4/UDP protocol punt ACL test Test scenario for basic punt ACL with UDP protocol - Create IPv4 stream for pg0 -> pg1 interface. @@ -868,13 +929,10 @@ class TestClassifierPunt(TestClassifier): sport = 6754 dport = 17923 - key = 'ip4_udp_punt' + key = "ip4_udp_punt" self.create_classify_table( - key, - self.build_ip_mask( - src_ip='ffffffff', - proto='ff', - src_port='ffff')) + key, self.build_ip_mask(src_ip="ffffffff", proto="ff", src_port="ffff") + ) table_index = self.acl_tbl_idx.get(key) self.vapi.punt_acl_add_del(ip4_table_index=table_index) self.acl_active_table = key @@ -883,52 +941,67 @@ class TestClassifierPunt(TestClassifier): self.vapi.set_punt( is_add=1, punt={ - 'type': VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_L4, - 'punt': { - 'l4': { - 'af': VppEnum.vl_api_address_family_t.ADDRESS_IP4, - 'protocol': VppEnum.vl_api_ip_proto_t.IP_API_PROTO_UDP, - 'port': dport, - }}}) - self.vapi.ip_punt_redirect(punt={ - 'rx_sw_if_index': self.pg0.sw_if_index, - 'tx_sw_if_index': self.pg1.sw_if_index, - 'nh': self.pg1.remote_ip4, - }) - - pkts = [(Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / - UDP(sport=sport, dport=dport) / - Raw('\x17' * 100))] * 2 + "type": VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_L4, + "punt": { + "l4": { + "af": VppEnum.vl_api_address_family_t.ADDRESS_IP4, + "protocol": VppEnum.vl_api_ip_proto_t.IP_API_PROTO_UDP, + "port": dport, + } + }, + }, + ) + self.vapi.ip_punt_redirect( + punt={ + "rx_sw_if_index": self.pg0.sw_if_index, + "tx_sw_if_index": self.pg1.sw_if_index, + "nh": self.pg1.remote_ip4, + } + ) + + pkts = [ + ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / UDP(sport=sport, dport=dport) + / Raw("\x17" * 100) + ) + ] * 2 # allow a session but not matching the stream: expect to drop self.create_classify_session( table_index, - self.build_ip_match(src_ip=self.pg0.remote_ip4, - proto=socket.IPPROTO_UDP, src_port=sport + 10)) + self.build_ip_match( + src_ip=self.pg0.remote_ip4, + proto=socket.IPPROTO_UDP, + src_port=sport + 10, + ), + ) self.send_and_assert_no_replies(self.pg0, pkts) # allow a session matching the stream: expect to pass self.create_classify_session( table_index, - self.build_ip_match(src_ip=self.pg0.remote_ip4, - proto=socket.IPPROTO_UDP, src_port=sport)) + self.build_ip_match( + src_ip=self.pg0.remote_ip4, proto=socket.IPPROTO_UDP, src_port=sport + ), + ) self.send_and_expect_only(self.pg0, pkts, self.pg1) # test dump api: ip4 is set, ip6 is not r = self.vapi.punt_acl_get() self.assertEqual(r.ip4_table_index, table_index) - self.assertEqual(r.ip6_table_index, 0xffffffff) + self.assertEqual(r.ip6_table_index, 0xFFFFFFFF) # cleanup - self.acl_active_table = '' + self.acl_active_table = "" self.vapi.punt_acl_add_del(ip4_table_index=table_index, is_add=0) # test dump api: nothing set r = self.vapi.punt_acl_get() - self.assertEqual(r.ip4_table_index, 0xffffffff) - self.assertEqual(r.ip6_table_index, 0xffffffff) + self.assertEqual(r.ip4_table_index, 0xFFFFFFFF) + self.assertEqual(r.ip6_table_index, 0xFFFFFFFF) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_classifier_ip6.py b/test/test_classifier_ip6.py index 211374b5ec6..7b5d41c3eef 100644 --- a/test/test_classifier_ip6.py +++ b/test/test_classifier_ip6.py @@ -14,7 +14,7 @@ from template_classifier import TestClassifier class TestClassifierIP6(TestClassifier): - """ Classifier IP6 Test Case """ + """Classifier IP6 Test Case""" @classmethod def setUpClass(cls): @@ -26,7 +26,7 @@ class TestClassifierIP6(TestClassifier): super(TestClassifierIP6, cls).tearDownClass() def test_iacl_src_ip(self): - """ Source IP6 iACL test + """Source IP6 iACL test Test scenario for basic IP ACL with source IP - Create IPv6 stream for pg0 -> pg1 interface. @@ -38,13 +38,13 @@ class TestClassifierIP6(TestClassifier): pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes) self.pg0.add_stream(pkts) - key = 'ip6_src' + key = "ip6_src" self.create_classify_table( - key, - self.build_ip6_mask(src_ip='ffffffffffffffffffffffffffffffff')) + key, self.build_ip6_mask(src_ip="ffffffffffffffffffffffffffffffff") + ) self.create_classify_session( - self.acl_tbl_idx.get(key), - self.build_ip6_match(src_ip=self.pg0.remote_ip6)) + self.acl_tbl_idx.get(key), self.build_ip6_match(src_ip=self.pg0.remote_ip6) + ) self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key @@ -57,7 +57,7 @@ class TestClassifierIP6(TestClassifier): self.pg2.assert_nothing_captured(remark="packets forwarded") def test_iacl_dst_ip(self): - """ Destination IP6 iACL test + """Destination IP6 iACL test Test scenario for basic IP ACL with destination IP - Create IPv6 stream for pg0 -> pg1 interface. @@ -69,13 +69,13 @@ class TestClassifierIP6(TestClassifier): pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes) self.pg0.add_stream(pkts) - key = 'ip6_dst' + key = "ip6_dst" self.create_classify_table( - key, - self.build_ip6_mask(dst_ip='ffffffffffffffffffffffffffffffff')) + key, self.build_ip6_mask(dst_ip="ffffffffffffffffffffffffffffffff") + ) self.create_classify_session( - self.acl_tbl_idx.get(key), - self.build_ip6_match(dst_ip=self.pg1.remote_ip6)) + self.acl_tbl_idx.get(key), self.build_ip6_match(dst_ip=self.pg1.remote_ip6) + ) self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key @@ -88,7 +88,7 @@ class TestClassifierIP6(TestClassifier): self.pg2.assert_nothing_captured(remark="packets forwarded") def test_iacl_src_dst_ip(self): - """ Source and destination IP6 iACL test + """Source and destination IP6 iACL test Test scenario for basic IP ACL with source and destination IP - Create IPv4 stream for pg0 -> pg1 interface. @@ -100,15 +100,20 @@ class TestClassifierIP6(TestClassifier): pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes) self.pg0.add_stream(pkts) - key = 'ip6' + key = "ip6" self.create_classify_table( key, - self.build_ip6_mask(src_ip='ffffffffffffffffffffffffffffffff', - dst_ip='ffffffffffffffffffffffffffffffff')) + self.build_ip6_mask( + src_ip="ffffffffffffffffffffffffffffffff", + dst_ip="ffffffffffffffffffffffffffffffff", + ), + ) self.create_classify_session( self.acl_tbl_idx.get(key), - self.build_ip6_match(src_ip=self.pg0.remote_ip6, - dst_ip=self.pg1.remote_ip6)) + self.build_ip6_match( + src_ip=self.pg0.remote_ip6, dst_ip=self.pg1.remote_ip6 + ), + ) self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key @@ -124,7 +129,7 @@ class TestClassifierIP6(TestClassifier): # Tests split to different test case classes because of issue reported in # ticket VPP-1336 class TestClassifierIP6UDP(TestClassifier): - """ Classifier IP6 UDP proto Test Case """ + """Classifier IP6 UDP proto Test Case""" @classmethod def setUpClass(cls): @@ -132,7 +137,7 @@ class TestClassifierIP6UDP(TestClassifier): cls.af = socket.AF_INET6 def test_iacl_proto_udp(self): - """ IP6 UDP protocol iACL test + """IP6 UDP protocol iACL test Test scenario for basic protocol ACL with UDP protocol - Create IPv6 stream for pg0 -> pg1 interface. @@ -144,11 +149,11 @@ class TestClassifierIP6UDP(TestClassifier): pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes) self.pg0.add_stream(pkts) - key = 'nh_udp' - self.create_classify_table(key, self.build_ip6_mask(nh='ff')) + key = "nh_udp" + self.create_classify_table(key, self.build_ip6_mask(nh="ff")) self.create_classify_session( - self.acl_tbl_idx.get(key), - self.build_ip6_match(nh=socket.IPPROTO_UDP)) + self.acl_tbl_idx.get(key), self.build_ip6_match(nh=socket.IPPROTO_UDP) + ) self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key @@ -161,7 +166,7 @@ class TestClassifierIP6UDP(TestClassifier): self.pg2.assert_nothing_captured(remark="packets forwarded") def test_iacl_proto_udp_sport(self): - """ IP6 UDP source port iACL test + """IP6 UDP source port iACL test Test scenario for basic protocol ACL with UDP and sport - Create IPv6 stream for pg0 -> pg1 interface. @@ -171,18 +176,18 @@ class TestClassifierIP6UDP(TestClassifier): # Basic iACL testing with UDP and sport sport = 38 - pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes, - UDP(sport=sport, dport=5678)) + pkts = self.create_stream( + self.pg0, self.pg1, self.pg_if_packet_sizes, UDP(sport=sport, dport=5678) + ) self.pg0.add_stream(pkts) - key = 'nh_udp_sport' - self.create_classify_table( - key, self.build_ip6_mask(nh='ff', src_port='ffff')) + key = "nh_udp_sport" + self.create_classify_table(key, self.build_ip6_mask(nh="ff", src_port="ffff")) self.create_classify_session( self.acl_tbl_idx.get(key), - self.build_ip6_match(nh=socket.IPPROTO_UDP, src_port=sport)) - self.input_acl_set_interface( - self.pg0, self.acl_tbl_idx.get(key)) + self.build_ip6_match(nh=socket.IPPROTO_UDP, src_port=sport), + ) + self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key self.pg_enable_capture(self.pg_interfaces) @@ -194,7 +199,7 @@ class TestClassifierIP6UDP(TestClassifier): self.pg2.assert_nothing_captured(remark="packets forwarded") def test_iacl_proto_udp_dport(self): - """ IP6 UDP destination port iACL test + """IP6 UDP destination port iACL test Test scenario for basic protocol ACL with UDP and dport - Create IPv6 stream for pg0 -> pg1 interface. @@ -204,18 +209,18 @@ class TestClassifierIP6UDP(TestClassifier): # Basic iACL testing with UDP and dport dport = 427 - pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes, - UDP(sport=1234, dport=dport)) + pkts = self.create_stream( + self.pg0, self.pg1, self.pg_if_packet_sizes, UDP(sport=1234, dport=dport) + ) self.pg0.add_stream(pkts) - key = 'nh_udp_dport' - self.create_classify_table( - key, self.build_ip6_mask(nh='ff', dst_port='ffff')) + key = "nh_udp_dport" + self.create_classify_table(key, self.build_ip6_mask(nh="ff", dst_port="ffff")) self.create_classify_session( self.acl_tbl_idx.get(key), - self.build_ip6_match(nh=socket.IPPROTO_UDP, dst_port=dport)) - self.input_acl_set_interface( - self.pg0, self.acl_tbl_idx.get(key)) + self.build_ip6_match(nh=socket.IPPROTO_UDP, dst_port=dport), + ) + self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key self.pg_enable_capture(self.pg_interfaces) @@ -227,7 +232,7 @@ class TestClassifierIP6UDP(TestClassifier): self.pg2.assert_nothing_captured(remark="packets forwarded") def test_iacl_proto_udp_sport_dport(self): - """ IP6 UDP source and destination ports iACL test + """IP6 UDP source and destination ports iACL test Test scenario for basic protocol ACL with UDP and sport and dport - Create IPv6 stream for pg0 -> pg1 interface. @@ -238,20 +243,20 @@ class TestClassifierIP6UDP(TestClassifier): # Basic iACL testing with UDP and sport and dport sport = 13720 dport = 9080 - pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes, - UDP(sport=sport, dport=dport)) + pkts = self.create_stream( + self.pg0, self.pg1, self.pg_if_packet_sizes, UDP(sport=sport, dport=dport) + ) self.pg0.add_stream(pkts) - key = 'nh_udp_ports' + key = "nh_udp_ports" self.create_classify_table( - key, - self.build_ip6_mask(nh='ff', src_port='ffff', dst_port='ffff')) + key, self.build_ip6_mask(nh="ff", src_port="ffff", dst_port="ffff") + ) self.create_classify_session( self.acl_tbl_idx.get(key), - self.build_ip6_match(nh=socket.IPPROTO_UDP, src_port=sport, - dst_port=dport)) - self.input_acl_set_interface( - self.pg0, self.acl_tbl_idx.get(key)) + self.build_ip6_match(nh=socket.IPPROTO_UDP, src_port=sport, dst_port=dport), + ) + self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key self.pg_enable_capture(self.pg_interfaces) @@ -264,7 +269,7 @@ class TestClassifierIP6UDP(TestClassifier): class TestClassifierIP6TCP(TestClassifier): - """ Classifier IP6 TCP proto Test Case """ + """Classifier IP6 TCP proto Test Case""" @classmethod def setUpClass(cls): @@ -272,7 +277,7 @@ class TestClassifierIP6TCP(TestClassifier): cls.af = socket.AF_INET6 def test_iacl_proto_tcp(self): - """ IP6 TCP protocol iACL test + """IP6 TCP protocol iACL test Test scenario for basic protocol ACL with TCP protocol - Create IPv6 stream for pg0 -> pg1 interface. @@ -281,17 +286,17 @@ class TestClassifierIP6TCP(TestClassifier): """ # Basic iACL testing with TCP protocol - pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes, - TCP(sport=1234, dport=5678)) + pkts = self.create_stream( + self.pg0, self.pg1, self.pg_if_packet_sizes, TCP(sport=1234, dport=5678) + ) self.pg0.add_stream(pkts) - key = 'nh_tcp' - self.create_classify_table(key, self.build_ip6_mask(nh='ff')) + key = "nh_tcp" + self.create_classify_table(key, self.build_ip6_mask(nh="ff")) self.create_classify_session( - self.acl_tbl_idx.get(key), - self.build_ip6_match(nh=socket.IPPROTO_TCP)) - self.input_acl_set_interface( - self.pg0, self.acl_tbl_idx.get(key)) + self.acl_tbl_idx.get(key), self.build_ip6_match(nh=socket.IPPROTO_TCP) + ) + self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key self.pg_enable_capture(self.pg_interfaces) @@ -303,7 +308,7 @@ class TestClassifierIP6TCP(TestClassifier): self.pg2.assert_nothing_captured(remark="packets forwarded") def test_iacl_proto_tcp_sport(self): - """ IP6 TCP source port iACL test + """IP6 TCP source port iACL test Test scenario for basic protocol ACL with TCP and sport - Create IPv6 stream for pg0 -> pg1 interface. @@ -313,18 +318,18 @@ class TestClassifierIP6TCP(TestClassifier): # Basic iACL testing with TCP and sport sport = 38 - pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes, - TCP(sport=sport, dport=5678)) + pkts = self.create_stream( + self.pg0, self.pg1, self.pg_if_packet_sizes, TCP(sport=sport, dport=5678) + ) self.pg0.add_stream(pkts) - key = 'nh_tcp_sport' - self.create_classify_table( - key, self.build_ip6_mask(nh='ff', src_port='ffff')) + key = "nh_tcp_sport" + self.create_classify_table(key, self.build_ip6_mask(nh="ff", src_port="ffff")) self.create_classify_session( self.acl_tbl_idx.get(key), - self.build_ip6_match(nh=socket.IPPROTO_TCP, src_port=sport)) - self.input_acl_set_interface( - self.pg0, self.acl_tbl_idx.get(key)) + self.build_ip6_match(nh=socket.IPPROTO_TCP, src_port=sport), + ) + self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key self.pg_enable_capture(self.pg_interfaces) @@ -336,7 +341,7 @@ class TestClassifierIP6TCP(TestClassifier): self.pg2.assert_nothing_captured(remark="packets forwarded") def test_iacl_proto_tcp_dport(self): - """ IP6 TCP destination port iACL test + """IP6 TCP destination port iACL test Test scenario for basic protocol ACL with TCP and dport - Create IPv6 stream for pg0 -> pg1 interface. @@ -346,18 +351,18 @@ class TestClassifierIP6TCP(TestClassifier): # Basic iACL testing with TCP and dport dport = 427 - pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes, - TCP(sport=1234, dport=dport)) + pkts = self.create_stream( + self.pg0, self.pg1, self.pg_if_packet_sizes, TCP(sport=1234, dport=dport) + ) self.pg0.add_stream(pkts) - key = 'nh_tcp_dport' - self.create_classify_table( - key, self.build_ip6_mask(nh='ff', dst_port='ffff')) + key = "nh_tcp_dport" + self.create_classify_table(key, self.build_ip6_mask(nh="ff", dst_port="ffff")) self.create_classify_session( self.acl_tbl_idx.get(key), - self.build_ip6_match(nh=socket.IPPROTO_TCP, dst_port=dport)) - self.input_acl_set_interface( - self.pg0, self.acl_tbl_idx.get(key)) + self.build_ip6_match(nh=socket.IPPROTO_TCP, dst_port=dport), + ) + self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key self.pg_enable_capture(self.pg_interfaces) @@ -369,7 +374,7 @@ class TestClassifierIP6TCP(TestClassifier): self.pg2.assert_nothing_captured(remark="packets forwarded") def test_iacl_proto_tcp_sport_dport(self): - """ IP6 TCP source and destination ports iACL test + """IP6 TCP source and destination ports iACL test Test scenario for basic protocol ACL with TCP and sport and dport - Create IPv6 stream for pg0 -> pg1 interface. @@ -380,20 +385,20 @@ class TestClassifierIP6TCP(TestClassifier): # Basic iACL testing with TCP and sport and dport sport = 13720 dport = 9080 - pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes, - TCP(sport=sport, dport=dport)) + pkts = self.create_stream( + self.pg0, self.pg1, self.pg_if_packet_sizes, TCP(sport=sport, dport=dport) + ) self.pg0.add_stream(pkts) - key = 'nh_tcp_ports' + key = "nh_tcp_ports" self.create_classify_table( - key, - self.build_ip6_mask(nh='ff', src_port='ffff', dst_port='ffff')) + key, self.build_ip6_mask(nh="ff", src_port="ffff", dst_port="ffff") + ) self.create_classify_session( self.acl_tbl_idx.get(key), - self.build_ip6_match(nh=socket.IPPROTO_TCP, src_port=sport, - dst_port=dport)) - self.input_acl_set_interface( - self.pg0, self.acl_tbl_idx.get(key)) + self.build_ip6_match(nh=socket.IPPROTO_TCP, src_port=sport, dst_port=dport), + ) + self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key self.pg_enable_capture(self.pg_interfaces) @@ -406,7 +411,7 @@ class TestClassifierIP6TCP(TestClassifier): class TestClassifierIP6Out(TestClassifier): - """ Classifier output IP6 Test Case """ + """Classifier output IP6 Test Case""" @classmethod def setUpClass(cls): @@ -414,7 +419,7 @@ class TestClassifierIP6Out(TestClassifier): cls.af = socket.AF_INET6 def test_acl_ip_out(self): - """ Output IP6 ACL test + """Output IP6 ACL test Test scenario for basic IP ACL with source IP - Create IPv6 stream for pg1 -> pg0 interface. @@ -426,16 +431,16 @@ class TestClassifierIP6Out(TestClassifier): pkts = self.create_stream(self.pg1, self.pg0, self.pg_if_packet_sizes) self.pg1.add_stream(pkts) - key = 'ip6_out' + key = "ip6_out" self.create_classify_table( key, - self.build_ip6_mask(src_ip='ffffffffffffffffffffffffffffffff'), - data_offset=0) + self.build_ip6_mask(src_ip="ffffffffffffffffffffffffffffffff"), + data_offset=0, + ) self.create_classify_session( - self.acl_tbl_idx.get(key), - self.build_ip6_match(src_ip=self.pg1.remote_ip6)) - self.output_acl_set_interface( - self.pg0, self.acl_tbl_idx.get(key)) + self.acl_tbl_idx.get(key), self.build_ip6_match(src_ip=self.pg1.remote_ip6) + ) + self.output_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key self.pg_enable_capture(self.pg_interfaces) @@ -448,7 +453,7 @@ class TestClassifierIP6Out(TestClassifier): class TestClassifierIP6MAC(TestClassifier): - """ Classifier IP6 MAC Test Case """ + """Classifier IP6 MAC Test Case""" @classmethod def setUpClass(cls): @@ -456,7 +461,7 @@ class TestClassifierIP6MAC(TestClassifier): cls.af = socket.AF_INET6 def test_acl_mac(self): - """ IP6 MAC iACL test + """IP6 MAC iACL test Test scenario for basic MAC ACL with source MAC - Create IPv6 stream for pg0 -> pg2 interface. @@ -468,12 +473,13 @@ class TestClassifierIP6MAC(TestClassifier): pkts = self.create_stream(self.pg0, self.pg2, self.pg_if_packet_sizes) self.pg0.add_stream(pkts) - key = 'mac' + key = "mac" self.create_classify_table( - key, self.build_mac_mask(src_mac='ffffffffffff'), data_offset=-14) + key, self.build_mac_mask(src_mac="ffffffffffff"), data_offset=-14 + ) self.create_classify_session( - self.acl_tbl_idx.get(key), - self.build_mac_match(src_mac=self.pg0.remote_mac)) + self.acl_tbl_idx.get(key), self.build_mac_match(src_mac=self.pg0.remote_mac) + ) self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key @@ -486,5 +492,5 @@ class TestClassifierIP6MAC(TestClassifier): self.pg1.assert_nothing_captured(remark="packets forwarded") -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_classify_l2_acl.py b/test/test_classify_l2_acl.py index b1309881e58..d94af3f718e 100644 --- a/test/test_classify_l2_acl.py +++ b/test/test_classify_l2_acl.py @@ -20,7 +20,7 @@ from template_classifier import TestClassifier class TestClassifyAcl(TestClassifier): - """ Classifier-based L2 input and output ACL Test Case """ + """Classifier-based L2 input and output ACL Test Case""" # traffic types IP = 0 @@ -37,7 +37,7 @@ class TestClassifyAcl(TestClassifier): # supported protocols proto = [[6, 17], [1, 58]] - proto_map = {1: 'ICMP', 58: 'ICMPv6EchoRequest', 6: 'TCP', 17: 'UDP'} + proto_map = {1: "ICMP", 58: "ICMPv6EchoRequest", 6: "TCP", 17: "UDP"} ICMPv4 = 0 ICMPv6 = 1 TCP = 0 @@ -104,11 +104,11 @@ class TestClassifyAcl(TestClassifier): # Create BD with MAC learning and unknown unicast flooding disabled # and put interfaces to this BD - cls.vapi.bridge_domain_add_del(bd_id=cls.bd_id, uu_flood=1, - learn=1) + cls.vapi.bridge_domain_add_del(bd_id=cls.bd_id, uu_flood=1, learn=1) for pg_if in cls.pg_interfaces: cls.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=pg_if.sw_if_index, bd_id=cls.bd_id) + rx_sw_if_index=pg_if.sw_if_index, bd_id=cls.bd_id + ) # Set up all interfaces for i in cls.pg_interfaces: @@ -128,7 +128,7 @@ class TestClassifyAcl(TestClassifier): # self.warmup_test() # Holder of the active classify table key - cls.acl_active_table = '' + cls.acl_active_table = "" except Exception: super(TestClassifyAcl, cls).tearDownClass() @@ -147,25 +147,30 @@ class TestClassifyAcl(TestClassifier): Show various debug prints after each test. """ if not self.vpp_dead: - if self.acl_active_table == 'mac_inout': + if self.acl_active_table == "mac_inout": self.output_acl_set_interface( - self.pg1, self.acl_tbl_idx.get(self.acl_active_table), 0) + self.pg1, self.acl_tbl_idx.get(self.acl_active_table), 0 + ) self.input_acl_set_interface( - self.pg0, self.acl_tbl_idx.get(self.acl_active_table), 0) - self.acl_active_table = '' - elif self.acl_active_table == 'mac_out': + self.pg0, self.acl_tbl_idx.get(self.acl_active_table), 0 + ) + self.acl_active_table = "" + elif self.acl_active_table == "mac_out": self.output_acl_set_interface( - self.pg1, self.acl_tbl_idx.get(self.acl_active_table), 0) - self.acl_active_table = '' - elif self.acl_active_table == 'mac_in': + self.pg1, self.acl_tbl_idx.get(self.acl_active_table), 0 + ) + self.acl_active_table = "" + elif self.acl_active_table == "mac_in": self.input_acl_set_interface( - self.pg0, self.acl_tbl_idx.get(self.acl_active_table), 0) - self.acl_active_table = '' + self.pg0, self.acl_tbl_idx.get(self.acl_active_table), 0 + ) + self.acl_active_table = "" super(TestClassifyAcl, self).tearDown() - def create_classify_session(self, intf, table_index, match, - hit_next_index=0xffffffff, is_add=1): + def create_classify_session( + self, intf, table_index, match, hit_next_index=0xFFFFFFFF, is_add=1 + ): """Create Classify Session :param VppInterface intf: Interface to apply classify session. @@ -180,8 +185,9 @@ class TestClassifyAcl(TestClassifier): table_index=table_index, match=mask_match, match_len=mask_match_len, - hit_next_index=hit_next_index) - self.assertIsNotNone(r, 'No response msg for add_del_session') + hit_next_index=hit_next_index, + ) + self.assertIsNotNone(r, "No response msg for add_del_session") def create_hosts(self, count, start=0): """ @@ -197,39 +203,50 @@ class TestClassifyAcl(TestClassifier): for pg_if in self.pg_interfaces: i += 1 start_nr = macs_per_if * i + start - end_nr = count + start if i == (n_int - 1) \ - else macs_per_if * (i + 1) + start + end_nr = ( + count + start if i == (n_int - 1) else macs_per_if * (i + 1) + start + ) hosts = self.hosts_by_pg_idx[pg_if.sw_if_index] for j in range(start_nr, end_nr): host = Host( "00:00:00:ff:%02x:%02x" % (pg_if.sw_if_index, j), "172.17.1%02x.%u" % (pg_if.sw_if_index, j), - "2017:dead:%02x::%u" % (pg_if.sw_if_index, j)) + "2017:dead:%02x::%u" % (pg_if.sw_if_index, j), + ) hosts.append(host) def create_upper_layer(self, packet_index, proto, ports=0): p = self.proto_map[proto] - if p == 'UDP': + if p == "UDP": if ports == 0: - return UDP(sport=random.randint(self.udp_sport_from, - self.udp_sport_to), - dport=random.randint(self.udp_dport_from, - self.udp_dport_to)) + return UDP( + sport=random.randint(self.udp_sport_from, self.udp_sport_to), + dport=random.randint(self.udp_dport_from, self.udp_dport_to), + ) else: return UDP(sport=ports, dport=ports) - elif p == 'TCP': + elif p == "TCP": if ports == 0: - return TCP(sport=random.randint(self.tcp_sport_from, - self.tcp_sport_to), - dport=random.randint(self.tcp_dport_from, - self.tcp_dport_to)) + return TCP( + sport=random.randint(self.tcp_sport_from, self.tcp_sport_to), + dport=random.randint(self.tcp_dport_from, self.tcp_dport_to), + ) else: return TCP(sport=ports, dport=ports) - return '' - - def create_stream(self, src_if, packet_sizes, traffic_type=0, ipv6=0, - proto=-1, ports=0, fragments=False, - pkt_raw=True, etype=-1): + return "" + + def create_stream( + self, + src_if, + packet_sizes, + traffic_type=0, + ipv6=0, + proto=-1, + ports=0, + fragments=False, + pkt_raw=True, + etype=-1, + ): """ Create input packet stream for defined interface using hosts or deleted_hosts list. @@ -262,26 +279,25 @@ class TestClassifyAcl(TestClassifier): payload = self.info_to_payload(pkt_info) p = Ether(dst=dst_host.mac, src=src_host.mac) if etype > 0: - p = Ether(dst=dst_host.mac, - src=src_host.mac, - type=etype) + p = Ether(dst=dst_host.mac, src=src_host.mac, type=etype) if pkt_info.ip: p /= IPv6(dst=dst_host.ip6, src=src_host.ip6) if fragments: p /= IPv6ExtHdrFragment(offset=64, m=1) else: if fragments: - p /= IP(src=src_host.ip4, dst=dst_host.ip4, - flags=1, frag=64) + p /= IP( + src=src_host.ip4, dst=dst_host.ip4, flags=1, frag=64 + ) else: p /= IP(src=src_host.ip4, dst=dst_host.ip4) if traffic_type == self.ICMP: if pkt_info.ip: - p /= ICMPv6EchoRequest(type=self.icmp6_type, - code=self.icmp6_code) + p /= ICMPv6EchoRequest( + type=self.icmp6_type, code=self.icmp6_code + ) else: - p /= ICMP(type=self.icmp4_type, - code=self.icmp4_code) + p /= ICMP(type=self.icmp4_type, code=self.icmp4_code) else: p /= self.create_upper_layer(i, pkt_info.proto, ports) if pkt_raw: @@ -293,8 +309,7 @@ class TestClassifyAcl(TestClassifier): pkts.append(p) return pkts - def verify_capture(self, pg_if, capture, - traffic_type=0, ip_type=0, etype=-1): + def verify_capture(self, pg_if, capture, traffic_type=0, ip_type=0, etype=-1): """ Verify captured input packet stream for defined interface. @@ -309,22 +324,21 @@ class TestClassifyAcl(TestClassifier): for packet in capture: if etype > 0: if packet[Ether].type != etype: - self.logger.error(ppp("Unexpected ethertype in packet:", - packet)) + self.logger.error(ppp("Unexpected ethertype in packet:", packet)) else: continue try: # Raw data for ICMPv6 are stored in ICMPv6EchoRequest.data if traffic_type == self.ICMP and ip_type == self.IPV6: - payload_info = self.payload_to_info( - packet[ICMPv6EchoRequest].data) + payload_info = self.payload_to_info(packet[ICMPv6EchoRequest].data) payload = packet[ICMPv6EchoRequest] else: payload_info = self.payload_to_info(packet[Raw]) payload = packet[self.proto_map[payload_info.proto]] except: - self.logger.error(ppp("Unexpected or invalid packet " - "(outside network):", packet)) + self.logger.error( + ppp("Unexpected or invalid packet (outside network):", packet) + ) raise if ip_type != 0: @@ -338,8 +352,9 @@ class TestClassifyAcl(TestClassifier): self.assertEqual(payload.type, self.icmp6_type) self.assertEqual(payload.code, self.icmp6_code) except: - self.logger.error(ppp("Unexpected or invalid packet " - "(outside network):", packet)) + self.logger.error( + ppp("Unexpected or invalid packet (outside network):", packet) + ) raise else: try: @@ -349,12 +364,13 @@ class TestClassifyAcl(TestClassifier): packet_index = payload_info.index self.assertEqual(payload_info.dst, dst_sw_if_index) - self.logger.debug("Got packet on port %s: src=%u (id=%u)" % - (pg_if.name, payload_info.src, - packet_index)) + self.logger.debug( + "Got packet on port %s: src=%u (id=%u)" + % (pg_if.name, payload_info.src, packet_index) + ) next_info = self.get_next_packet_info_for_interface2( - payload_info.src, dst_sw_if_index, - last_info[payload_info.src]) + payload_info.src, dst_sw_if_index, last_info[payload_info.src] + ) last_info[payload_info.src] = next_info self.assertTrue(next_info is not None) self.assertEqual(packet_index, next_info.index) @@ -363,29 +379,26 @@ class TestClassifyAcl(TestClassifier): self.assertEqual(ip.src, saved_packet[ip_version].src) self.assertEqual(ip.dst, saved_packet[ip_version].dst) p = self.proto_map[payload_info.proto] - if p == 'TCP': + if p == "TCP": tcp = packet[TCP] - self.assertEqual(tcp.sport, saved_packet[ - TCP].sport) - self.assertEqual(tcp.dport, saved_packet[ - TCP].dport) - elif p == 'UDP': + self.assertEqual(tcp.sport, saved_packet[TCP].sport) + self.assertEqual(tcp.dport, saved_packet[TCP].dport) + elif p == "UDP": udp = packet[UDP] - self.assertEqual(udp.sport, saved_packet[ - UDP].sport) - self.assertEqual(udp.dport, saved_packet[ - UDP].dport) + self.assertEqual(udp.sport, saved_packet[UDP].sport) + self.assertEqual(udp.dport, saved_packet[UDP].dport) except: - self.logger.error(ppp("Unexpected or invalid packet:", - packet)) + self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise for i in self.pg_interfaces: remaining_packet = self.get_next_packet_info_for_interface2( - i, dst_sw_if_index, last_info[i.sw_if_index]) + i, dst_sw_if_index, last_info[i.sw_if_index] + ) self.assertTrue( remaining_packet is None, - "Port %u: Packet expected from source %u didn't arrive" % - (dst_sw_if_index, i.sw_if_index)) + "Port %u: Packet expected from source %u didn't arrive" + % (dst_sw_if_index, i.sw_if_index), + ) def run_traffic_no_check(self): # Test @@ -400,16 +413,32 @@ class TestClassifyAcl(TestClassifier): self.pg_enable_capture(self.pg_interfaces) self.pg_start() - def run_verify_test(self, traffic_type=0, ip_type=0, proto=-1, ports=0, - frags=False, pkt_raw=True, etype=-1): + def run_verify_test( + self, + traffic_type=0, + ip_type=0, + proto=-1, + ports=0, + frags=False, + pkt_raw=True, + etype=-1, + ): # Test # Create incoming packet streams for packet-generator interfaces pkts_cnt = 0 for i in self.pg_interfaces: if self.flows.__contains__(i): - pkts = self.create_stream(i, self.pg_if_packet_sizes, - traffic_type, ip_type, proto, ports, - frags, pkt_raw, etype) + pkts = self.create_stream( + i, + self.pg_if_packet_sizes, + traffic_type, + ip_type, + proto, + ports, + frags, + pkt_raw, + etype, + ) if len(pkts) > 0: i.add_stream(pkts) pkts_cnt += len(pkts) @@ -424,20 +453,27 @@ class TestClassifyAcl(TestClassifier): if self.flows.__contains__(src_if): for dst_if in self.flows[src_if]: capture = dst_if.get_capture(pkts_cnt) - self.logger.info("Verifying capture on interface %s" % - dst_if.name) - self.verify_capture(dst_if, capture, - traffic_type, ip_type, etype) + self.logger.info("Verifying capture on interface %s" % dst_if.name) + self.verify_capture(dst_if, capture, traffic_type, ip_type, etype) - def run_verify_negat_test(self, traffic_type=0, ip_type=0, proto=-1, - ports=0, frags=False, etype=-1): + def run_verify_negat_test( + self, traffic_type=0, ip_type=0, proto=-1, ports=0, frags=False, etype=-1 + ): # Test self.reset_packet_infos() for i in self.pg_interfaces: if self.flows.__contains__(i): - pkts = self.create_stream(i, self.pg_if_packet_sizes, - traffic_type, ip_type, proto, ports, - frags, True, etype) + pkts = self.create_stream( + i, + self.pg_if_packet_sizes, + traffic_type, + ip_type, + proto, + ports, + frags, + True, + etype, + ) if len(pkts) > 0: i.add_stream(pkts) @@ -450,101 +486,110 @@ class TestClassifyAcl(TestClassifier): for src_if in self.pg_interfaces: if self.flows.__contains__(src_if): for dst_if in self.flows[src_if]: - self.logger.info("Verifying capture on interface %s" % - dst_if.name) + self.logger.info("Verifying capture on interface %s" % dst_if.name) capture = dst_if.get_capture(0) self.assertEqual(len(capture), 0) - def build_classify_table(self, src_mac='', dst_mac='', ether_type='', - etype='', key='mac', hit_next_index=0xffffffff): + def build_classify_table( + self, + src_mac="", + dst_mac="", + ether_type="", + etype="", + key="mac", + hit_next_index=0xFFFFFFFF, + ): # Basic ACL testing - a_mask = self.build_mac_mask(src_mac=src_mac, dst_mac=dst_mac, - ether_type=ether_type) + a_mask = self.build_mac_mask( + src_mac=src_mac, dst_mac=dst_mac, ether_type=ether_type + ) self.create_classify_table(key, a_mask) for host in self.hosts_by_pg_idx[self.pg0.sw_if_index]: - s_mac = host.mac if src_mac else '' + s_mac = host.mac if src_mac else "" if dst_mac: for dst_if in self.flows[self.pg0]: for dst_host in self.hosts_by_pg_idx[dst_if.sw_if_index]: self.create_classify_session( - self.pg0, self.acl_tbl_idx.get(key), - self.build_mac_match(src_mac=s_mac, - dst_mac=dst_host.mac, - ether_type=etype), - hit_next_index=hit_next_index) + self.pg0, + self.acl_tbl_idx.get(key), + self.build_mac_match( + src_mac=s_mac, dst_mac=dst_host.mac, ether_type=etype + ), + hit_next_index=hit_next_index, + ) else: self.create_classify_session( - self.pg0, self.acl_tbl_idx.get(key), - self.build_mac_match(src_mac=s_mac, dst_mac='', - ether_type=etype), - hit_next_index=hit_next_index) + self.pg0, + self.acl_tbl_idx.get(key), + self.build_mac_match(src_mac=s_mac, dst_mac="", ether_type=etype), + hit_next_index=hit_next_index, + ) def test_0000_warmup_test(self): - """ Learn the MAC addresses - """ + """Learn the MAC addresses""" self.create_hosts(2) self.run_traffic_no_check() def test_0010_inacl_permit_src_mac(self): - """ Input L2 ACL test - permit source MAC + """Input L2 ACL test - permit source MAC Test scenario for basic IP ACL with source IP - Create IPv4 stream for pg0 -> pg1 interface. - Create ACL with source MAC address. - Send and verify received packets on pg1 interface. """ - key = 'mac_in' - self.build_classify_table(src_mac='ffffffffffff', key=key) + key = "mac_in" + self.build_classify_table(src_mac="ffffffffffff", key=key) self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key self.run_verify_test(self.IP, self.IPV4, -1) def test_0011_inacl_permit_dst_mac(self): - """ Input L2 ACL test - permit destination MAC + """Input L2 ACL test - permit destination MAC Test scenario for basic IP ACL with source IP - Create IPv4 stream for pg0 -> pg1 interface. - Create ACL with destination MAC address. - Send and verify received packets on pg1 interface. """ - key = 'mac_in' - self.build_classify_table(dst_mac='ffffffffffff', key=key) + key = "mac_in" + self.build_classify_table(dst_mac="ffffffffffff", key=key) self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key self.run_verify_test(self.IP, self.IPV4, -1) def test_0012_inacl_permit_src_dst_mac(self): - """ Input L2 ACL test - permit source and destination MAC + """Input L2 ACL test - permit source and destination MAC Test scenario for basic IP ACL with source IP - Create IPv4 stream for pg0 -> pg1 interface. - Create ACL with source and destination MAC addresses. - Send and verify received packets on pg1 interface. """ - key = 'mac_in' + key = "mac_in" self.build_classify_table( - src_mac='ffffffffffff', dst_mac='ffffffffffff', key=key) + src_mac="ffffffffffff", dst_mac="ffffffffffff", key=key + ) self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key self.run_verify_test(self.IP, self.IPV4, -1) def test_0013_inacl_permit_ether_type(self): - """ Input L2 ACL test - permit ether_type + """Input L2 ACL test - permit ether_type Test scenario for basic IP ACL with source IP - Create IPv4 stream for pg0 -> pg1 interface. - Create ACL with destination MAC address. - Send and verify received packets on pg1 interface. """ - key = 'mac_in' - self.build_classify_table( - ether_type='ffff', etype=hex(ETH_P_IP)[2:], key=key) + key = "mac_in" + self.build_classify_table(ether_type="ffff", etype=hex(ETH_P_IP)[2:], key=key) self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key self.run_verify_test(self.IP, self.IPV4, -1) def test_0015_inacl_deny(self): - """ Input L2 ACL test - deny + """Input L2 ACL test - deny Test scenario for basic IP ACL with source IP - Create IPv4 stream for pg0 -> pg1 interface. @@ -552,57 +597,55 @@ class TestClassifyAcl(TestClassifier): - Create ACL with source MAC address. - Send and verify no received packets on pg1 interface. """ - key = 'mac_in' - self.build_classify_table( - src_mac='ffffffffffff', hit_next_index=0, key=key) + key = "mac_in" + self.build_classify_table(src_mac="ffffffffffff", hit_next_index=0, key=key) self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key self.run_verify_negat_test(self.IP, self.IPV4, -1) def test_0020_outacl_permit(self): - """ Output L2 ACL test - permit + """Output L2 ACL test - permit Test scenario for basic IP ACL with source IP - Create IPv4 stream for pg0 -> pg1 interface. - Create ACL with source MAC address. - Send and verify received packets on pg1 interface. """ - key = 'mac_out' - self.build_classify_table(src_mac='ffffffffffff', key=key) + key = "mac_out" + self.build_classify_table(src_mac="ffffffffffff", key=key) self.output_acl_set_interface(self.pg1, self.acl_tbl_idx.get(key)) self.acl_active_table = key self.run_verify_test(self.IP, self.IPV4, -1) def test_0025_outacl_deny(self): - """ Output L2 ACL test - deny + """Output L2 ACL test - deny Test scenario for basic IP ACL with source IP - Create IPv4 stream for pg0 -> pg1 interface. - Create ACL with source MAC address. - Send and verify no received packets on pg1 interface. """ - key = 'mac_out' - self.build_classify_table( - src_mac='ffffffffffff', hit_next_index=0, key=key) + key = "mac_out" + self.build_classify_table(src_mac="ffffffffffff", hit_next_index=0, key=key) self.output_acl_set_interface(self.pg1, self.acl_tbl_idx.get(key)) self.acl_active_table = key self.run_verify_negat_test(self.IP, self.IPV4, -1) def test_0030_inoutacl_permit(self): - """ Input+Output L2 ACL test - permit + """Input+Output L2 ACL test - permit Test scenario for basic IP ACL with source IP - Create IPv4 stream for pg0 -> pg1 interface. - Create ACLs with source MAC address. - Send and verify received packets on pg1 interface. """ - key = 'mac_inout' - self.build_classify_table(src_mac='ffffffffffff', key=key) + key = "mac_inout" + self.build_classify_table(src_mac="ffffffffffff", key=key) self.output_acl_set_interface(self.pg1, self.acl_tbl_idx.get(key)) self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key)) self.acl_active_table = key self.run_verify_test(self.IP, self.IPV4, -1) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_cli.py b/test/test_cli.py index 5005bf4c43a..77dfdc0b9ad 100644 --- a/test/test_cli.py +++ b/test/test_cli.py @@ -11,7 +11,8 @@ from framework import VppTestCase, VppTestRunner class TestCLI(VppTestCase): - """ CLI Test Case """ + """CLI Test Case""" + maxDiff = None @classmethod @@ -31,21 +32,21 @@ class TestCLI(VppTestCase): super(TestCLI, self).tearDown() def test_cli_retval(self): - """ CLI inband retval """ - rv = self.vapi.papi.cli_inband(cmd='this command does not exist') + """CLI inband retval""" + rv = self.vapi.papi.cli_inband(cmd="this command does not exist") self.assertNotEqual(rv.retval, 0) - rv = self.vapi.papi.cli_inband(cmd='show version') + rv = self.vapi.papi.cli_inband(cmd="show version") self.assertEqual(rv.retval, 0) def test_long_cli_delay(self): - """ Test that VppApiClient raises VppIOError if timeout.""" # noqa + """Test that VppApiClient raises VppIOError if timeout.""" # noqa with self.assertRaises(VPPIOError) as ctx: - rv = self.vapi.papi.cli_inband(cmd='wait 10') + rv = self.vapi.papi.cli_inband(cmd="wait 10") def test_long_cli_delay_override(self): - """ Test per-command _timeout option.""" # noqa - rv = self.vapi.papi.cli_inband(cmd='wait 10', _timeout=15) + """Test per-command _timeout option.""" # noqa + rv = self.vapi.papi.cli_inband(cmd="wait 10", _timeout=15) self.assertEqual(rv.retval, 0) @@ -55,8 +56,10 @@ class TestCLIExtendedVapiTimeout(VppTestCase): @classmethod def setUpClass(cls): cls.vapi_response_timeout = 15 - cls.__doc__ = " CLI Test Case w/ Extended (%ssec) Vapi Timeout " \ - % cls.vapi_response_timeout + cls.__doc__ = ( + " CLI Test Case w/ Extended (%ssec) Vapi Timeout " + % cls.vapi_response_timeout + ) super(TestCLIExtendedVapiTimeout, cls).setUpClass() @classmethod @@ -70,19 +73,21 @@ class TestCLIExtendedVapiTimeout(VppTestCase): super(TestCLIExtendedVapiTimeout, self).tearDown() def test_long_cli_delay(self): - """ Test that delayed result returns with extended timeout.""" + """Test that delayed result returns with extended timeout.""" wait_secs = self.vapi_response_timeout - 1 # get vpp time as float start = self.vapi.papi.show_vpe_system_time( - _no_type_conversion=True).vpe_system_time - rv = self.vapi.papi.cli_inband(cmd='wait %s' % wait_secs) + _no_type_conversion=True + ).vpe_system_time + rv = self.vapi.papi.cli_inband(cmd="wait %s" % wait_secs) now = self.vapi.papi.show_vpe_system_time( - _no_type_conversion=True).vpe_system_time + _no_type_conversion=True + ).vpe_system_time # assume that the overhead of the measurement is not more that .5 sec. self.assertEqual(round(now - start), wait_secs) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_cnat.py b/test/test_cnat.py index 25c2a6454cb..e2e7c6bab8c 100644 --- a/test/test_cnat.py +++ b/test/test_cnat.py @@ -15,8 +15,14 @@ from scapy.layers.inet6 import ICMPv6EchoRequest, ICMPv6EchoReply import struct -from ipaddress import ip_address, ip_network, \ - IPv4Address, IPv6Address, IPv4Network, IPv6Network +from ipaddress import ( + ip_address, + ip_network, + IPv4Address, + IPv6Address, + IPv4Network, + IPv6Network, +) from vpp_object import VppObject from vpp_papi import VppEnum @@ -29,18 +35,27 @@ DST = 1 class CnatCommonTestCase(VppTestCase): - """ CNat common test class """ + """CNat common test class""" # # turn the scanner off whilst testing otherwise sessions # will time out # - extra_vpp_punt_config = ["cnat", "{", - "session-db-buckets", "64", - "session-cleanup-timeout", "0.1", - "session-max-age", "1", - "tcp-max-age", "1", - "scanner", "off", "}"] + extra_vpp_punt_config = [ + "cnat", + "{", + "session-db-buckets", + "64", + "session-cleanup-timeout", + "0.1", + "session-max-age", + "1", + "tcp-max-age", + "1", + "scanner", + "off", + "}", + ] @classmethod def setUpClass(cls): @@ -52,7 +67,7 @@ class CnatCommonTestCase(VppTestCase): class Endpoint(object): - """ CNat endpoint """ + """CNat endpoint""" def __init__(self, pg=None, pgi=None, port=0, is_v6=False, ip=None): self.port = port @@ -83,17 +98,18 @@ class Endpoint(object): return VppEnum.vl_api_address_family_t.ADDRESS_IP4 def encode(self): - return {'addr': self.ip, - 'port': self.port, - 'sw_if_index': self.sw_if_index, - 'if_af': self._vpp_if_af()} + return { + "addr": self.ip, + "port": self.port, + "sw_if_index": self.sw_if_index, + "if_af": self._vpp_if_af(), + } def __str__(self): - return ("%s:%d" % (self.ip, self.port)) + return "%s:%d" % (self.ip, self.port) class Translation(VppObject): - def __init__(self, test, iproto, vip, paths): self._test = test self.vip = vip @@ -102,7 +118,7 @@ class Translation(VppObject): self.id = None def __str__(self): - return ("%s %s %s" % (self.vip, self.iproto, self.paths)) + return "%s %s %s" % (self.vip, self.iproto, self.paths) def _vl4_proto(self): ip_proto = VppEnum.vl_api_ip_proto_t @@ -112,21 +128,26 @@ class Translation(VppObject): }[self.iproto] def _encoded_paths(self): - return [{'src_ep': src.encode(), - 'dst_ep': dst.encode()} for (src, dst) in self.paths] + return [ + {"src_ep": src.encode(), "dst_ep": dst.encode()} + for (src, dst) in self.paths + ] def add_vpp_config(self): r = self._test.vapi.cnat_translation_update( - {'vip': self.vip.encode(), - 'ip_proto': self._vl4_proto(), - 'n_paths': len(self.paths), - 'paths': self._encoded_paths()}) + { + "vip": self.vip.encode(), + "ip_proto": self._vl4_proto(), + "n_paths": len(self.paths), + "paths": self._encoded_paths(), + } + ) self._test.registry.register(self, self._test.logger) self.id = r.id return self def remove_vpp_config(self): - assert(self.id is not None) + assert self.id is not None self._test.vapi.cnat_translation_del(id=self.id) return self @@ -172,8 +193,9 @@ class CnatTestContext(object): def IP46(self): return IPv6 if self.is_v6 else IP - def cnat_send(self, src_pg, src_id, src_port, dst_pg, dst_id, dst_port, - no_replies=False): + def cnat_send( + self, src_pg, src_id, src_port, dst_pg, dst_id, dst_port, no_replies=False + ): if isinstance(src_id, int): self.src_addr = self.get_ip46(src_pg.remote_hosts[src_id]) else: @@ -191,11 +213,12 @@ class CnatTestContext(object): l4 = self.L4PROTO(id=self.src_port, type=self.dst_port) elif self.L4PROTO in [ICMP] and self.is_v6: l4 = ICMPv6EchoRequest(id=self.src_port) - p1 = (Ether(src=src_pg.remote_mac, - dst=src_pg.local_mac) / - self.IP46(src=self.src_addr, dst=self.dst_addr) / - l4 / - Raw()) + p1 = ( + Ether(src=src_pg.remote_mac, dst=src_pg.local_mac) + / self.IP46(src=self.src_addr, dst=self.dst_addr) + / l4 + / Raw() + ) if no_replies: self._test.send_and_assert_no_replies(src_pg, p1 * N_PKTS, dst_pg) @@ -230,38 +253,35 @@ class CnatTestContext(object): self._test.assertEqual(rx[self.IP46].dst, self.expect_dst_addr) self._test.assertEqual(rx[self.IP46].src, self.expect_src_addr) if self.L4PROTO in [TCP, UDP]: - self._test.assertEqual( - rx[self.L4PROTO].dport, self.expect_dst_port) - self._test.assertEqual( - rx[self.L4PROTO].sport, self.expect_src_port) + self._test.assertEqual(rx[self.L4PROTO].dport, self.expect_dst_port) + self._test.assertEqual(rx[self.L4PROTO].sport, self.expect_src_port) elif self.L4PROTO in [ICMP] and not self.is_v6: - self._test.assertEqual( - rx[self.L4PROTO].type, self.expect_dst_port) - self._test.assertEqual( - rx[self.L4PROTO].id, self.expect_src_port) + self._test.assertEqual(rx[self.L4PROTO].type, self.expect_dst_port) + self._test.assertEqual(rx[self.L4PROTO].id, self.expect_src_port) elif self.L4PROTO in [ICMP] and self.is_v6: - self._test.assertEqual( - rx[ICMPv6EchoRequest].id, self.expect_src_port) + self._test.assertEqual(rx[ICMPv6EchoRequest].id, self.expect_src_port) return self def cnat_send_return(self): """This sends the return traffic""" if self.L4PROTO in [TCP, UDP]: - l4 = self.L4PROTO(sport=self.expect_dst_port, - dport=self.expect_src_port) + l4 = self.L4PROTO(sport=self.expect_dst_port, dport=self.expect_src_port) elif self.L4PROTO in [ICMP] and not self.is_v6: # icmp type 0 if echo reply l4 = self.L4PROTO(id=self.expect_src_port, type=0) elif self.L4PROTO in [ICMP] and self.is_v6: l4 = ICMPv6EchoReply(id=self.expect_src_port) src_mac = self.expected_dst_pg.remote_mac - p1 = (Ether(src=src_mac, dst=self.expected_dst_pg.local_mac) / - self.IP46(src=self.expect_dst_addr, dst=self.expect_src_addr) / - l4 / - Raw()) + p1 = ( + Ether(src=src_mac, dst=self.expected_dst_pg.local_mac) + / self.IP46(src=self.expect_dst_addr, dst=self.expect_src_addr) + / l4 + / Raw() + ) self.return_rxs = self._test.send_and_expect( - self.expected_dst_pg, p1 * N_PKTS, self.expected_src_pg) + self.expected_dst_pg, p1 * N_PKTS, self.expected_src_pg + ) return self def cnat_expect_return(self): @@ -288,12 +308,16 @@ class CnatTestContext(object): ICMPelem = ICMPv6DestUnreach(code=1) if self.is_v6 else ICMP(type=11) InnerIP = self.rxs[0][self.IP46] p1 = ( - Ether(src=self.expected_dst_pg.remote_mac, - dst=self.expected_dst_pg.local_mac) / - self.IP46(src=self.expect_dst_addr, dst=self.expect_src_addr) / - ICMPelem / InnerIP) + Ether( + src=self.expected_dst_pg.remote_mac, dst=self.expected_dst_pg.local_mac + ) + / self.IP46(src=self.expect_dst_addr, dst=self.expect_src_addr) + / ICMPelem + / InnerIP + ) self.return_rxs = self._test.send_and_expect( - self.expected_dst_pg, p1 * N_PKTS, self.expected_src_pg) + self.expected_dst_pg, p1 * N_PKTS, self.expected_src_pg + ) return self def cnat_expect_icmp_error_return(self): @@ -306,12 +330,11 @@ class CnatTestContext(object): self._test.assertEqual(rx[self.IP46].src, self.dst_addr) self._test.assertEqual(rx[ICMP46][IP46err].src, self.src_addr) self._test.assertEqual(rx[ICMP46][IP46err].dst, self.dst_addr) - self._test.assertEqual( - rx[ICMP46][IP46err][L4err].sport, self.src_port) - self._test.assertEqual( - rx[ICMP46][IP46err][L4err].dport, self.dst_port) + self._test.assertEqual(rx[ICMP46][IP46err][L4err].sport, self.src_port) + self._test.assertEqual(rx[ICMP46][IP46err][L4err].dport, self.dst_port) return self + # ------------------------------------------------------------------- # ------------------------------------------------------------------- # ------------------------------------------------------------------- @@ -319,7 +342,7 @@ class CnatTestContext(object): class TestCNatTranslation(CnatCommonTestCase): - """ CNat Translation """ + """CNat Translation""" @classmethod def setUpClass(cls): @@ -359,7 +382,7 @@ class TestCNatTranslation(CnatCommonTestCase): super(TestCNatTranslation, self).tearDown() def cnat_translation(self): - """ CNat Translation """ + """CNat Translation""" self.logger.info(self.vapi.cli("sh cnat client")) self.logger.info(self.vapi.cli("sh cnat translation")) @@ -372,11 +395,9 @@ class TestCNatTranslation(CnatCommonTestCase): ctx = CnatTestContext(self, translation.iproto, vip.is_v6) for src_pgi, sport in product(range(N_REMOTE_HOSTS), [1234, 1233]): # from client to vip - ctx.cnat_send(self.pg0, src_pgi, sport, - self.pg1, vip.ip, vip.port) + ctx.cnat_send(self.pg0, src_pgi, sport, self.pg1, vip.ip, vip.port) dst_port = translation.paths[0][DST].port - ctx.cnat_expect(self.pg0, src_pgi, sport, - self.pg1, nbr, dst_port) + ctx.cnat_expect(self.pg0, src_pgi, sport, self.pg1, nbr, dst_port) # from vip to client ctx.cnat_send_return().cnat_expect_return() @@ -384,8 +405,9 @@ class TestCNatTranslation(CnatCommonTestCase): # packets to the VIP that do not match a # translation are dropped # - ctx.cnat_send(self.pg0, src_pgi, sport, self.pg1, - vip.ip, 6666, no_replies=True) + ctx.cnat_send( + self.pg0, src_pgi, sport, self.pg1, vip.ip, 6666, no_replies=True + ) # # packets from the VIP that do not match a @@ -399,7 +421,8 @@ class TestCNatTranslation(CnatCommonTestCase): # old_dst_port = translation.paths[0][DST].port translation.paths[0][DST].udpate( - pg=self.pg2, pgi=0, port=5000, is_v6=vip.is_v6) + pg=self.pg2, pgi=0, port=5000, is_v6=vip.is_v6 + ) translation.add_vpp_config() # @@ -408,10 +431,10 @@ class TestCNatTranslation(CnatCommonTestCase): for src_pgi in range(N_REMOTE_HOSTS): for sport in [1234, 1233]: # from client to vip - ctx.cnat_send(self.pg0, src_pgi, sport, - self.pg1, vip.ip, vip.port) - ctx.cnat_expect(self.pg0, src_pgi, sport, - self.pg1, nbr, old_dst_port) + ctx.cnat_send(self.pg0, src_pgi, sport, self.pg1, vip.ip, vip.port) + ctx.cnat_expect( + self.pg0, src_pgi, sport, self.pg1, nbr, old_dst_port + ) # from vip to client ctx.cnat_send_return().cnat_expect_return() @@ -419,8 +442,7 @@ class TestCNatTranslation(CnatCommonTestCase): # new flows go to the new backend # for src_pgi in range(N_REMOTE_HOSTS): - ctx.cnat_send(self.pg0, src_pgi, 9999, - self.pg2, vip.ip, vip.port) + ctx.cnat_send(self.pg0, src_pgi, 9999, self.pg2, vip.ip, vip.port) ctx.cnat_expect(self.pg0, src_pgi, 9999, self.pg2, 0, 5000) self.logger.info(self.vapi.cli("sh cnat session verbose")) @@ -444,10 +466,8 @@ class TestCNatTranslation(CnatCommonTestCase): for src_pgi in range(N_REMOTE_HOSTS): for sport in [1234, 1233]: # from client to vip - ctx.cnat_send(self.pg0, src_pgi, sport, - self.pg2, vip.ip, vip.port) - ctx.cnat_expect(self.pg0, src_pgi, - sport, self.pg2, 0, 5000) + ctx.cnat_send(self.pg0, src_pgi, sport, self.pg2, vip.ip, vip.port) + ctx.cnat_expect(self.pg0, src_pgi, sport, self.pg2, 0, 5000) def _test_icmp(self): @@ -477,51 +497,87 @@ class TestCNatTranslation(CnatCommonTestCase): def _make_translations_v4(self): self.translations = [] - self.translations.append(Translation( - self, TCP, Endpoint(ip="30.0.0.1", port=5555, is_v6=False), - [( - Endpoint(is_v6=False), - Endpoint(pg=self.pg1, pgi=0, port=4001, is_v6=False), - )] - ).add_vpp_config()) - self.translations.append(Translation( - self, TCP, Endpoint(ip="30.0.0.2", port=5554, is_v6=False), - [( - Endpoint(is_v6=False), - Endpoint(pg=self.pg1, pgi=1, port=4002, is_v6=False), - )] - ).add_vpp_config()) - self.translations.append(Translation( - self, UDP, Endpoint(ip="30.0.0.2", port=5553, is_v6=False), - [( - Endpoint(is_v6=False), - Endpoint(pg=self.pg1, pgi=2, port=4003, is_v6=False), - )] - ).add_vpp_config()) + self.translations.append( + Translation( + self, + TCP, + Endpoint(ip="30.0.0.1", port=5555, is_v6=False), + [ + ( + Endpoint(is_v6=False), + Endpoint(pg=self.pg1, pgi=0, port=4001, is_v6=False), + ) + ], + ).add_vpp_config() + ) + self.translations.append( + Translation( + self, + TCP, + Endpoint(ip="30.0.0.2", port=5554, is_v6=False), + [ + ( + Endpoint(is_v6=False), + Endpoint(pg=self.pg1, pgi=1, port=4002, is_v6=False), + ) + ], + ).add_vpp_config() + ) + self.translations.append( + Translation( + self, + UDP, + Endpoint(ip="30.0.0.2", port=5553, is_v6=False), + [ + ( + Endpoint(is_v6=False), + Endpoint(pg=self.pg1, pgi=2, port=4003, is_v6=False), + ) + ], + ).add_vpp_config() + ) def _make_translations_v6(self): self.translations = [] - self.translations.append(Translation( - self, TCP, Endpoint(ip="30::1", port=5555, is_v6=True), - [( - Endpoint(is_v6=True), - Endpoint(pg=self.pg1, pgi=0, port=4001, is_v6=True), - )] - ).add_vpp_config()) - self.translations.append(Translation( - self, TCP, Endpoint(ip="30::2", port=5554, is_v6=True), - [( - Endpoint(is_v6=True), - Endpoint(pg=self.pg1, pgi=1, port=4002, is_v6=True), - )] - ).add_vpp_config()) - self.translations.append(Translation( - self, UDP, Endpoint(ip="30::2", port=5553, is_v6=True), - [( - Endpoint(is_v6=True), - Endpoint(pg=self.pg1, pgi=2, port=4003, is_v6=True), - )] - ).add_vpp_config()) + self.translations.append( + Translation( + self, + TCP, + Endpoint(ip="30::1", port=5555, is_v6=True), + [ + ( + Endpoint(is_v6=True), + Endpoint(pg=self.pg1, pgi=0, port=4001, is_v6=True), + ) + ], + ).add_vpp_config() + ) + self.translations.append( + Translation( + self, + TCP, + Endpoint(ip="30::2", port=5554, is_v6=True), + [ + ( + Endpoint(is_v6=True), + Endpoint(pg=self.pg1, pgi=1, port=4002, is_v6=True), + ) + ], + ).add_vpp_config() + ) + self.translations.append( + Translation( + self, + UDP, + Endpoint(ip="30::2", port=5553, is_v6=True), + [ + ( + Endpoint(is_v6=True), + Endpoint(pg=self.pg1, pgi=2, port=4003, is_v6=True), + ) + ], + ).add_vpp_config() + ) def test_icmp4(self): # """ CNat Translation icmp v4 """ @@ -545,7 +601,7 @@ class TestCNatTranslation(CnatCommonTestCase): class TestCNatSourceNAT(CnatCommonTestCase): - """ CNat Source NAT """ + """CNat Source NAT""" @classmethod def setUpClass(cls): @@ -559,28 +615,36 @@ class TestCNatSourceNAT(CnatCommonTestCase): self.vapi.cnat_set_snat_addresses( snat_ip4=self.pg2.remote_hosts[0].ip4, snat_ip6=self.pg2.remote_hosts[0].ip6, - sw_if_index=INVALID_INDEX) + sw_if_index=INVALID_INDEX, + ) self.vapi.feature_enable_disable( enable=1 if is_enable else 0, arc_name="ip6-unicast", feature_name="cnat-snat-ip6", - sw_if_index=self.pg0.sw_if_index) + sw_if_index=self.pg0.sw_if_index, + ) self.vapi.feature_enable_disable( enable=1 if is_enable else 0, arc_name="ip4-unicast", feature_name="cnat-snat-ip4", - sw_if_index=self.pg0.sw_if_index) + sw_if_index=self.pg0.sw_if_index, + ) policie_tbls = VppEnum.vl_api_cnat_snat_policy_table_t self.vapi.cnat_set_snat_policy( - policy=VppEnum.vl_api_cnat_snat_policies_t.CNAT_POLICY_IF_PFX) + policy=VppEnum.vl_api_cnat_snat_policies_t.CNAT_POLICY_IF_PFX + ) for i in self.pg_interfaces: self.vapi.cnat_snat_policy_add_del_if( - sw_if_index=i.sw_if_index, is_add=1 if is_enable else 0, - table=policie_tbls.CNAT_POLICY_INCLUDE_V6) + sw_if_index=i.sw_if_index, + is_add=1 if is_enable else 0, + table=policie_tbls.CNAT_POLICY_INCLUDE_V6, + ) self.vapi.cnat_snat_policy_add_del_if( - sw_if_index=i.sw_if_index, is_add=1 if is_enable else 0, - table=policie_tbls.CNAT_POLICY_INCLUDE_V4) + sw_if_index=i.sw_if_index, + is_add=1 if is_enable else 0, + table=policie_tbls.CNAT_POLICY_INCLUDE_V4, + ) def setUp(self): super(TestCNatSourceNAT, self).setUp() @@ -624,7 +688,7 @@ class TestCNatSourceNAT(CnatCommonTestCase): def sourcenat_test_icmp_echo_conf(self, is_v6=False): ctx = CnatTestContext(self, ICMP, is_v6=is_v6) # 8 is ICMP type echo (v4 only) - ctx.cnat_send(self.pg0, 0, 0xfeed, self.pg1, 0, 8) + ctx.cnat_send(self.pg0, 0, 0xFEED, self.pg1, 0, 8) ctx.cnat_expect(self.pg2, 0, None, self.pg1, 0, 8) ctx.cnat_send_return().cnat_expect_return() @@ -638,14 +702,15 @@ class TestCNatSourceNAT(CnatCommonTestCase): # exclude dst address of pg1.1 from snat if is_v6: exclude_prefix = ip_network( - "%s/100" % self.pg1.remote_hosts[1].ip6, strict=False) + "%s/100" % self.pg1.remote_hosts[1].ip6, strict=False + ) else: exclude_prefix = ip_network( - "%s/16" % self.pg1.remote_hosts[1].ip4, strict=False) + "%s/16" % self.pg1.remote_hosts[1].ip4, strict=False + ) # add remote host to exclude list - self.vapi.cnat_snat_policy_add_del_exclude_pfx( - prefix=exclude_prefix, is_add=1) + self.vapi.cnat_snat_policy_add_del_exclude_pfx(prefix=exclude_prefix, is_add=1) # We should not source NAT the id=1 ctx.cnat_send(self.pg0, 0, 1234, self.pg1, 1, 6661) @@ -658,8 +723,7 @@ class TestCNatSourceNAT(CnatCommonTestCase): ctx.cnat_send_return().cnat_expect_return() # remove remote host from exclude list - self.vapi.cnat_snat_policy_add_del_exclude_pfx( - prefix=exclude_prefix, is_add=0) + self.vapi.cnat_snat_policy_add_del_exclude_pfx(prefix=exclude_prefix, is_add=0) self.vapi.cnat_session_purge() # We should source NAT again @@ -676,7 +740,7 @@ class TestCNatSourceNAT(CnatCommonTestCase): class TestCNatDHCP(CnatCommonTestCase): - """ CNat Translation """ + """CNat Translation""" @classmethod def setUpClass(cls): @@ -703,33 +767,35 @@ class TestCNatDHCP(CnatCommonTestCase): def check_resolved(self, tr, addr_id, is_v6=False): qt = tr.query_vpp_config() - self.assertEqual(str(qt.vip.addr), self.make_addr( - tr.vip.sw_if_index, addr_id, is_v6)) + self.assertEqual( + str(qt.vip.addr), self.make_addr(tr.vip.sw_if_index, addr_id, is_v6) + ) self.assertEqual(len(qt.paths), len(tr.paths)) for path_tr, path_qt in zip(tr.paths, qt.paths): src_qt = path_qt.src_ep dst_qt = path_qt.dst_ep src_tr, dst_tr = path_tr - self.assertEqual(str(src_qt.addr), self.make_addr( - src_tr.sw_if_index, addr_id, is_v6)) - self.assertEqual(str(dst_qt.addr), self.make_addr( - dst_tr.sw_if_index, addr_id, is_v6)) + self.assertEqual( + str(src_qt.addr), self.make_addr(src_tr.sw_if_index, addr_id, is_v6) + ) + self.assertEqual( + str(dst_qt.addr), self.make_addr(dst_tr.sw_if_index, addr_id, is_v6) + ) def add_del_address(self, pg, addr_id, is_add=True, is_v6=False): self.vapi.sw_interface_add_del_address( sw_if_index=pg.sw_if_index, prefix=self.make_prefix(pg.sw_if_index, addr_id, is_v6), - is_add=1 if is_add else 0) + is_add=1 if is_add else 0, + ) def _test_dhcp_v46(self, is_v6): self.create_pg_interfaces(range(4)) for i in self.pg_interfaces: i.admin_up() paths = [ - (Endpoint(pg=self.pg1, is_v6=is_v6), - Endpoint(pg=self.pg2, is_v6=is_v6)), - (Endpoint(pg=self.pg1, is_v6=is_v6), - Endpoint(pg=self.pg3, is_v6=is_v6)) + (Endpoint(pg=self.pg1, is_v6=is_v6), Endpoint(pg=self.pg2, is_v6=is_v6)), + (Endpoint(pg=self.pg1, is_v6=is_v6), Endpoint(pg=self.pg3, is_v6=is_v6)), ] ep = Endpoint(pg=self.pg0, is_v6=is_v6) t = Translation(self, TCP, ep, paths).add_vpp_config() @@ -766,10 +832,13 @@ class TestCNatDHCP(CnatCommonTestCase): self.add_del_address(pg, addr_id=0, is_add=True, is_v6=False) self.add_del_address(pg, addr_id=0, is_add=True, is_v6=True) r = self.vapi.cnat_get_snat_addresses() - self.assertEqual(str(r.snat_ip4), self.make_addr( - self.pg0.sw_if_index, addr_id=0, is_v6=False)) - self.assertEqual(str(r.snat_ip6), self.make_addr( - self.pg0.sw_if_index, addr_id=0, is_v6=True)) + self.assertEqual( + str(r.snat_ip4), + self.make_addr(self.pg0.sw_if_index, addr_id=0, is_v6=False), + ) + self.assertEqual( + str(r.snat_ip6), self.make_addr(self.pg0.sw_if_index, addr_id=0, is_v6=True) + ) # Add a new address on every interface, remove the old one # and check it is reflected in the cnat config for pg in self.pg_interfaces: @@ -778,10 +847,13 @@ class TestCNatDHCP(CnatCommonTestCase): self.add_del_address(pg, addr_id=0, is_add=False, is_v6=False) self.add_del_address(pg, addr_id=0, is_add=False, is_v6=True) r = self.vapi.cnat_get_snat_addresses() - self.assertEqual(str(r.snat_ip4), self.make_addr( - self.pg0.sw_if_index, addr_id=1, is_v6=False)) - self.assertEqual(str(r.snat_ip6), self.make_addr( - self.pg0.sw_if_index, addr_id=1, is_v6=True)) + self.assertEqual( + str(r.snat_ip4), + self.make_addr(self.pg0.sw_if_index, addr_id=1, is_v6=False), + ) + self.assertEqual( + str(r.snat_ip6), self.make_addr(self.pg0.sw_if_index, addr_id=1, is_v6=True) + ) # remove the configuration for pg in self.pg_interfaces: self.add_del_address(pg, addr_id=1, is_add=False, is_v6=False) @@ -789,5 +861,5 @@ class TestCNatDHCP(CnatCommonTestCase): self.vapi.cnat_set_snat_addresses(sw_if_index=INVALID_INDEX) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_container.py b/test/test_container.py index 739aaaf915a..d79e5c3c67d 100644 --- a/test/test_container.py +++ b/test/test_container.py @@ -24,7 +24,7 @@ class Conn(L4_Conn): @unittest.skipUnless(config.extended, "part of extended tests") class ContainerIntegrationTestCase(VppTestCase): - """ Container integration extended testcases """ + """Container integration extended testcases""" @classmethod def setUpClass(cls): @@ -43,22 +43,21 @@ class ContainerIntegrationTestCase(VppTestCase): super(ContainerIntegrationTestCase, cls).tearDownClass() def tearDown(self): - """Run standard test teardown and log various show commands - """ + """Run standard test teardown and log various show commands""" super(ContainerIntegrationTestCase, self).tearDown() def show_commands_at_teardown(self): self.logger.info(self.vapi.cli("show ip neighbors")) def run_basic_conn_test(self, af, acl_side): - """ Basic connectivity test """ + """Basic connectivity test""" conn1 = Conn(self, self.pg0, self.pg1, af, UDP, 42001, 4242) conn1.send_through(0) # the return packets should pass conn1.send_through(1) def run_negative_conn_test(self, af, acl_side): - """ Packets with local spoofed address """ + """Packets with local spoofed address""" conn1 = Conn(self, self.pg0, self.pg1, af, UDP, 42001, 4242) try: p2 = conn1.send_through(0).command() @@ -69,15 +68,15 @@ class ContainerIntegrationTestCase(VppTestCase): self.assert_equal(p2, None, ": packet should have been dropped") def test_0010_basic_conn_test(self): - """ IPv4 basic connectivity test """ + """IPv4 basic connectivity test""" self.run_basic_conn_test(AF_INET, 0) def test_0011_basic_conn_test(self): - """ IPv6 basic connectivity test """ + """IPv6 basic connectivity test""" self.run_basic_conn_test(AF_INET6, 0) def test_0050_loopback_prepare_test(self): - """ Create loopbacks overlapping with remote addresses """ + """Create loopbacks overlapping with remote addresses""" self.create_loopback_interfaces(2) for i in range(2): intf = self.lo_interfaces[i] @@ -90,47 +89,60 @@ class ContainerIntegrationTestCase(VppTestCase): intf.config_ip6() def test_0110_basic_conn_test(self): - """ IPv4 local-spoof connectivity test """ + """IPv4 local-spoof connectivity test""" self.run_negative_conn_test(AF_INET, 0) def test_0111_basic_conn_test(self): - """ IPv6 local-spoof connectivity test """ + """IPv6 local-spoof connectivity test""" self.run_negative_conn_test(AF_INET, 1) def test_0200_basic_conn_test(self): - """ Configure container commands """ + """Configure container commands""" for i in range(2): - for addr in [self.pg_interfaces[i].remote_ip4, - self.pg_interfaces[i].remote_ip6]: - self.vapi.ppcli("ip container " + addr + " " + - self.pg_interfaces[i].name) - self.vapi.ppcli("stn rule address " + addr + - " interface " + self.pg_interfaces[i].name) + for addr in [ + self.pg_interfaces[i].remote_ip4, + self.pg_interfaces[i].remote_ip6, + ]: + self.vapi.ppcli( + "ip container " + addr + " " + self.pg_interfaces[i].name + ) + self.vapi.ppcli( + "stn rule address " + + addr + + " interface " + + self.pg_interfaces[i].name + ) def test_0210_basic_conn_test(self): - """ IPv4 test after configuring container """ + """IPv4 test after configuring container""" self.run_basic_conn_test(AF_INET, 0) def test_0211_basic_conn_test(self): - """ IPv6 test after configuring container """ + """IPv6 test after configuring container""" self.run_basic_conn_test(AF_INET, 1) def test_0300_unconfigure_commands(self): - """ Unconfigure container commands """ + """Unconfigure container commands""" for i in range(2): - for addr in [self.pg_interfaces[i].remote_ip4, - self.pg_interfaces[i].remote_ip6]: - self.vapi.ppcli("ip container " + addr + " " + - self.pg_interfaces[i].name + - " del") - self.vapi.ppcli("stn rule address " + addr + - " interface " + self.pg_interfaces[i].name + - " del") + for addr in [ + self.pg_interfaces[i].remote_ip4, + self.pg_interfaces[i].remote_ip6, + ]: + self.vapi.ppcli( + "ip container " + addr + " " + self.pg_interfaces[i].name + " del" + ) + self.vapi.ppcli( + "stn rule address " + + addr + + " interface " + + self.pg_interfaces[i].name + + " del" + ) def test_0410_spoof_test(self): - """ IPv4 local-spoof after unconfig test """ + """IPv4 local-spoof after unconfig test""" self.run_negative_conn_test(AF_INET, 0) def test_0411_spoof_test(self): - """ IPv6 local-spoof after unconfig test """ + """IPv6 local-spoof after unconfig test""" self.run_negative_conn_test(AF_INET, 1) diff --git a/test/test_counters.py b/test/test_counters.py index e4cb85621d0..158b07eb063 100644 --- a/test/test_counters.py +++ b/test/test_counters.py @@ -6,7 +6,7 @@ from framework import tag_fixme_vpp_workers @tag_fixme_vpp_workers class TestCounters(VppTestCase): - """ Counters C Unit Tests """ + """Counters C Unit Tests""" @classmethod def setUpClass(cls): @@ -23,17 +23,17 @@ class TestCounters(VppTestCase): super(TestCounters, self).tearDown() def test_counter_simple_expand(self): - """ Simple Counter Expand """ + """Simple Counter Expand""" error = self.vapi.cli("test counter simple expand") if error: self.logger.critical(error) - self.assertNotIn('failed', error) + self.assertNotIn("failed", error) def test_counter_combined_expand(self): - """ Combined Counter Expand """ + """Combined Counter Expand""" error = self.vapi.cli("test counter combined expand") if error: self.logger.critical(error) - self.assertNotIn('failed', error) + self.assertNotIn("failed", error) diff --git a/test/test_crypto.py b/test/test_crypto.py index aa62dba1bab..07ddd2c0f08 100644 --- a/test/test_crypto.py +++ b/test/test_crypto.py @@ -6,7 +6,7 @@ from framework import VppTestCase, VppTestRunner class TestCrypto(VppTestCase): - """ Crypto Test Case """ + """Crypto Test Case""" @classmethod def setUpClass(cls): @@ -17,12 +17,13 @@ class TestCrypto(VppTestCase): super(TestCrypto, cls).tearDownClass() def test_crypto(self): - """ Crypto Unit Tests """ + """Crypto Unit Tests""" error = self.vapi.cli("test crypto") if error: self.logger.critical(error) self.assertNotIn("FAIL", error) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_det44.py b/test/test_det44.py index f137e760c38..ecd57a65b05 100644 --- a/test/test_det44.py +++ b/test/test_det44.py @@ -15,7 +15,7 @@ from util import ppp class TestDET44(VppTestCase): - """ Deterministic NAT Test Cases """ + """Deterministic NAT Test Cases""" @classmethod def setUpClass(cls): @@ -27,7 +27,7 @@ class TestDET44(VppTestCase): cls.udp_port_in = 6304 cls.udp_external_port = 6304 cls.icmp_id_in = 6305 - cls.nat_addr = '10.0.0.3' + cls.nat_addr = "10.0.0.3" cls.create_pg_interfaces(range(3)) cls.interfaces = list(cls.pg_interfaces) @@ -79,8 +79,9 @@ class TestDET44(VppTestCase): self.assertEqual(packet[ICMP].id, self.icmp_id_in) except: fired = True - self.logger.error(ppp("Unexpected or invalid packet " - "(inside network):", packet)) + self.logger.error( + ppp("Unexpected or invalid packet (inside network):", packet) + ) if fired: raise @@ -112,10 +113,11 @@ class TestDET44(VppTestCase): """ # SYN packet in->out - p = (Ether(src=in_if.remote_mac, dst=in_if.local_mac) / - IP(src=in_if.remote_ip4, dst=out_if.remote_ip4) / - TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, - flags="S")) + p = ( + Ether(src=in_if.remote_mac, dst=in_if.local_mac) + / IP(src=in_if.remote_ip4, dst=out_if.remote_ip4) + / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="S") + ) in_if.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -124,20 +126,22 @@ class TestDET44(VppTestCase): self.tcp_port_out = p[TCP].sport # SYN + ACK packet out->in - p = (Ether(src=out_if.remote_mac, dst=out_if.local_mac) / - IP(src=out_if.remote_ip4, dst=self.nat_addr) / - TCP(sport=self.tcp_external_port, dport=self.tcp_port_out, - flags="SA")) + p = ( + Ether(src=out_if.remote_mac, dst=out_if.local_mac) + / IP(src=out_if.remote_ip4, dst=self.nat_addr) + / TCP(sport=self.tcp_external_port, dport=self.tcp_port_out, flags="SA") + ) out_if.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() in_if.get_capture(1) # ACK packet in->out - p = (Ether(src=in_if.remote_mac, dst=in_if.local_mac) / - IP(src=in_if.remote_ip4, dst=out_if.remote_ip4) / - TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, - flags="A")) + p = ( + Ether(src=in_if.remote_mac, dst=in_if.local_mac) + / IP(src=in_if.remote_ip4, dst=out_if.remote_ip4) + / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="A") + ) in_if.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -153,21 +157,27 @@ class TestDET44(VppTestCase): """ pkts = [] # TCP - p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) / - IP(src=in_if.remote_ip4, dst=out_if.remote_ip4, ttl=ttl) / - TCP(sport=self.tcp_port_in, dport=self.tcp_external_port)) + p = ( + Ether(dst=in_if.local_mac, src=in_if.remote_mac) + / IP(src=in_if.remote_ip4, dst=out_if.remote_ip4, ttl=ttl) + / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port) + ) pkts.append(p) # UDP - p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) / - IP(src=in_if.remote_ip4, dst=out_if.remote_ip4, ttl=ttl) / - UDP(sport=self.udp_port_in, dport=self.udp_external_port)) + p = ( + Ether(dst=in_if.local_mac, src=in_if.remote_mac) + / IP(src=in_if.remote_ip4, dst=out_if.remote_ip4, ttl=ttl) + / UDP(sport=self.udp_port_in, dport=self.udp_external_port) + ) pkts.append(p) # ICMP - p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) / - IP(src=in_if.remote_ip4, dst=out_if.remote_ip4, ttl=ttl) / - ICMP(id=self.icmp_id_in, type='echo-request')) + p = ( + Ether(dst=in_if.local_mac, src=in_if.remote_mac) + / IP(src=in_if.remote_ip4, dst=out_if.remote_ip4, ttl=ttl) + / ICMP(id=self.icmp_id_in, type="echo-request") + ) pkts.append(p) return pkts @@ -184,21 +194,27 @@ class TestDET44(VppTestCase): dst_ip = self.nat_addr pkts = [] # TCP - p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) / - IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) / - TCP(dport=self.tcp_port_out, sport=self.tcp_external_port)) + p = ( + Ether(dst=out_if.local_mac, src=out_if.remote_mac) + / IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) + / TCP(dport=self.tcp_port_out, sport=self.tcp_external_port) + ) pkts.append(p) # UDP - p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) / - IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) / - UDP(dport=self.udp_port_out, sport=self.udp_external_port)) + p = ( + Ether(dst=out_if.local_mac, src=out_if.remote_mac) + / IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) + / UDP(dport=self.udp_port_out, sport=self.udp_external_port) + ) pkts.append(p) # ICMP - p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) / - IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) / - ICMP(id=self.icmp_external_id, type='echo-reply')) + p = ( + Ether(dst=out_if.local_mac, src=out_if.remote_mac) + / IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) + / ICMP(id=self.icmp_external_id, type="echo-reply") + ) pkts.append(p) return pkts @@ -223,21 +239,26 @@ class TestDET44(VppTestCase): else: self.icmp_external_id = packet[ICMP].id except: - self.logger.error(ppp("Unexpected or invalid packet " - "(outside network):", packet)) + self.logger.error( + ppp("Unexpected or invalid packet (outside network):", packet) + ) raise def test_deterministic_mode(self): - """ NAT plugin run deterministic mode """ - in_addr = '172.16.255.0' - out_addr = '172.17.255.50' - in_addr_t = '172.16.255.20' + """NAT plugin run deterministic mode""" + in_addr = "172.16.255.0" + out_addr = "172.17.255.50" + in_addr_t = "172.16.255.20" in_plen = 24 out_plen = 32 - self.vapi.det44_add_del_map(is_add=1, in_addr=in_addr, - in_plen=in_plen, out_addr=out_addr, - out_plen=out_plen) + self.vapi.det44_add_del_map( + is_add=1, + in_addr=in_addr, + in_plen=in_plen, + out_addr=out_addr, + out_plen=out_plen, + ) rep1 = self.vapi.det44_forward(in_addr_t) self.assertEqual(str(rep1.out_addr), out_addr) @@ -254,40 +275,46 @@ class TestDET44(VppTestCase): self.assertEqual(out_plen, dsm.out_plen) def test_set_timeouts(self): - """ Set deterministic NAT timeouts """ + """Set deterministic NAT timeouts""" timeouts_before = self.vapi.det44_get_timeouts() self.vapi.det44_set_timeouts( udp=timeouts_before.udp + 10, tcp_established=timeouts_before.tcp_established + 10, tcp_transitory=timeouts_before.tcp_transitory + 10, - icmp=timeouts_before.icmp + 10) + icmp=timeouts_before.icmp + 10, + ) timeouts_after = self.vapi.det44_get_timeouts() self.assertNotEqual(timeouts_before.udp, timeouts_after.udp) self.assertNotEqual(timeouts_before.icmp, timeouts_after.icmp) - self.assertNotEqual(timeouts_before.tcp_established, - timeouts_after.tcp_established) - self.assertNotEqual(timeouts_before.tcp_transitory, - timeouts_after.tcp_transitory) + self.assertNotEqual( + timeouts_before.tcp_established, timeouts_after.tcp_established + ) + self.assertNotEqual( + timeouts_before.tcp_transitory, timeouts_after.tcp_transitory + ) def test_in(self): - """ DET44 translation test (TCP, UDP, ICMP) """ + """DET44 translation test (TCP, UDP, ICMP)""" nat_ip = "10.0.0.10" - self.vapi.det44_add_del_map(is_add=1, in_addr=self.pg0.remote_ip4, - in_plen=32, - out_addr=socket.inet_aton(nat_ip), - out_plen=32) + self.vapi.det44_add_del_map( + is_add=1, + in_addr=self.pg0.remote_ip4, + in_plen=32, + out_addr=socket.inet_aton(nat_ip), + out_plen=32, + ) self.vapi.det44_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - is_add=1, is_inside=1) + sw_if_index=self.pg0.sw_if_index, is_add=1, is_inside=1 + ) self.vapi.det44_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1, is_inside=0) + sw_if_index=self.pg1.sw_if_index, is_add=1, is_inside=0 + ) # in2out pkts = self.create_stream_in(self.pg0, self.pg1) @@ -330,7 +357,7 @@ class TestDET44(VppTestCase): self.assertEqual(s.out_port, self.icmp_external_id) def test_multiple_users(self): - """ Deterministic NAT multiple users """ + """Deterministic NAT multiple users""" nat_ip = "10.0.0.10" port_in = 80 @@ -339,20 +366,26 @@ class TestDET44(VppTestCase): host0 = self.pg0.remote_hosts[0] host1 = self.pg0.remote_hosts[1] - self.vapi.det44_add_del_map(is_add=1, in_addr=host0.ip4, in_plen=24, - out_addr=socket.inet_aton(nat_ip), - out_plen=32) + self.vapi.det44_add_del_map( + is_add=1, + in_addr=host0.ip4, + in_plen=24, + out_addr=socket.inet_aton(nat_ip), + out_plen=32, + ) self.vapi.det44_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - is_add=1, is_inside=1) + sw_if_index=self.pg0.sw_if_index, is_add=1, is_inside=1 + ) self.vapi.det44_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1, is_inside=0) + sw_if_index=self.pg1.sw_if_index, is_add=1, is_inside=0 + ) # host0 to out - p = (Ether(src=host0.mac, dst=self.pg0.local_mac) / - IP(src=host0.ip4, dst=self.pg1.remote_ip4) / - TCP(sport=port_in, dport=external_port)) + p = ( + Ether(src=host0.mac, dst=self.pg0.local_mac) + / IP(src=host0.ip4, dst=self.pg1.remote_ip4) + / TCP(sport=port_in, dport=external_port) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -370,9 +403,11 @@ class TestDET44(VppTestCase): raise # host1 to out - p = (Ether(src=host1.mac, dst=self.pg0.local_mac) / - IP(src=host1.ip4, dst=self.pg1.remote_ip4) / - TCP(sport=port_in, dport=external_port)) + p = ( + Ether(src=host1.mac, dst=self.pg0.local_mac) + / IP(src=host1.ip4, dst=self.pg1.remote_ip4) + / TCP(sport=port_in, dport=external_port) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -394,9 +429,11 @@ class TestDET44(VppTestCase): self.assertEqual(2, dms[0].ses_num) # out to host0 - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=nat_ip) / - TCP(sport=external_port, dport=port_out0)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=nat_ip) + / TCP(sport=external_port, dport=port_out0) + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -414,9 +451,11 @@ class TestDET44(VppTestCase): raise # out to host1 - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=nat_ip) / - TCP(sport=external_port, dport=port_out1)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=nat_ip) + / TCP(sport=external_port, dport=port_out1) + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -434,42 +473,44 @@ class TestDET44(VppTestCase): raise # session close api test - self.vapi.det44_close_session_out(socket.inet_aton(nat_ip), - port_out1, - self.pg1.remote_ip4, - external_port) + self.vapi.det44_close_session_out( + socket.inet_aton(nat_ip), port_out1, self.pg1.remote_ip4, external_port + ) dms = self.vapi.det44_map_dump() self.assertEqual(dms[0].ses_num, 1) - self.vapi.det44_close_session_in(host0.ip4, - port_in, - self.pg1.remote_ip4, - external_port) + self.vapi.det44_close_session_in( + host0.ip4, port_in, self.pg1.remote_ip4, external_port + ) dms = self.vapi.det44_map_dump() self.assertEqual(dms[0].ses_num, 0) def test_tcp_session_close_detection_in(self): - """ DET44 TCP session close from inside network """ - self.vapi.det44_add_del_map(is_add=1, in_addr=self.pg0.remote_ip4, - in_plen=32, - out_addr=socket.inet_aton(self.nat_addr), - out_plen=32) + """DET44 TCP session close from inside network""" + self.vapi.det44_add_del_map( + is_add=1, + in_addr=self.pg0.remote_ip4, + in_plen=32, + out_addr=socket.inet_aton(self.nat_addr), + out_plen=32, + ) self.vapi.det44_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - is_add=1, is_inside=1) + sw_if_index=self.pg0.sw_if_index, is_add=1, is_inside=1 + ) self.vapi.det44_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1, is_inside=0) + sw_if_index=self.pg1.sw_if_index, is_add=1, is_inside=0 + ) self.initiate_tcp_session(self.pg0, self.pg1) # close the session from inside try: # FIN packet in -> out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, - flags="F")) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="F") + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -478,17 +519,19 @@ class TestDET44(VppTestCase): pkts = [] # ACK packet out -> in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=self.tcp_external_port, dport=self.tcp_port_out, - flags="A")) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=self.tcp_external_port, dport=self.tcp_port_out, flags="A") + ) pkts.append(p) # FIN packet out -> in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=self.tcp_external_port, dport=self.tcp_port_out, - flags="F")) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=self.tcp_external_port, dport=self.tcp_port_out, flags="F") + ) pkts.append(p) self.pg1.add_stream(pkts) @@ -497,10 +540,11 @@ class TestDET44(VppTestCase): self.pg0.get_capture(2) # ACK packet in -> out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, - flags="A")) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="A") + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -514,27 +558,31 @@ class TestDET44(VppTestCase): raise def test_tcp_session_close_detection_out(self): - """ Deterministic NAT TCP session close from outside network """ - self.vapi.det44_add_del_map(is_add=1, in_addr=self.pg0.remote_ip4, - in_plen=32, - out_addr=socket.inet_aton(self.nat_addr), - out_plen=32) + """Deterministic NAT TCP session close from outside network""" + self.vapi.det44_add_del_map( + is_add=1, + in_addr=self.pg0.remote_ip4, + in_plen=32, + out_addr=socket.inet_aton(self.nat_addr), + out_plen=32, + ) self.vapi.det44_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - is_add=1, is_inside=1) + sw_if_index=self.pg0.sw_if_index, is_add=1, is_inside=1 + ) self.vapi.det44_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1, is_inside=0) + sw_if_index=self.pg1.sw_if_index, is_add=1, is_inside=0 + ) self.initiate_tcp_session(self.pg0, self.pg1) # close the session from outside try: # FIN packet out -> in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=self.tcp_external_port, dport=self.tcp_port_out, - flags="F")) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=self.tcp_external_port, dport=self.tcp_port_out, flags="F") + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -543,17 +591,19 @@ class TestDET44(VppTestCase): pkts = [] # ACK packet in -> out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, - flags="A")) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="A") + ) pkts.append(p) # ACK packet in -> out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, - flags="F")) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="F") + ) pkts.append(p) self.pg0.add_stream(pkts) @@ -562,10 +612,11 @@ class TestDET44(VppTestCase): self.pg1.get_capture(2) # ACK packet out -> in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=self.tcp_external_port, dport=self.tcp_port_out, - flags="A")) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=self.tcp_external_port, dport=self.tcp_port_out, flags="A") + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -579,21 +630,23 @@ class TestDET44(VppTestCase): raise def test_session_timeout(self): - """ Deterministic NAT session timeouts """ - self.vapi.det44_add_del_map(is_add=1, in_addr=self.pg0.remote_ip4, - in_plen=32, - out_addr=socket.inet_aton(self.nat_addr), - out_plen=32) + """Deterministic NAT session timeouts""" + self.vapi.det44_add_del_map( + is_add=1, + in_addr=self.pg0.remote_ip4, + in_plen=32, + out_addr=socket.inet_aton(self.nat_addr), + out_plen=32, + ) self.vapi.det44_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - is_add=1, is_inside=1) + sw_if_index=self.pg0.sw_if_index, is_add=1, is_inside=1 + ) self.vapi.det44_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1, is_inside=0) + sw_if_index=self.pg1.sw_if_index, is_add=1, is_inside=0 + ) self.initiate_tcp_session(self.pg0, self.pg1) - self.vapi.det44_set_timeouts(udp=5, tcp_established=5, - tcp_transitory=5, icmp=5) + self.vapi.det44_set_timeouts(udp=5, tcp_established=5, tcp_transitory=5, icmp=5) pkts = self.create_stream_in(self.pg0, self.pg1) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) @@ -607,29 +660,35 @@ class TestDET44(VppTestCase): # TODO: ipfix needs to be separated from NAT base plugin @unittest.skipUnless(config.extended, "part of extended tests") def test_session_limit_per_user(self): - """ Deterministic NAT maximum sessions per user limit """ - self.vapi.det44_add_del_map(is_add=1, in_addr=self.pg0.remote_ip4, - in_plen=32, - out_addr=socket.inet_aton(self.nat_addr), - out_plen=32) + """Deterministic NAT maximum sessions per user limit""" + self.vapi.det44_add_del_map( + is_add=1, + in_addr=self.pg0.remote_ip4, + in_plen=32, + out_addr=socket.inet_aton(self.nat_addr), + out_plen=32, + ) self.vapi.det44_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - is_add=1, is_inside=1) + sw_if_index=self.pg0.sw_if_index, is_add=1, is_inside=1 + ) self.vapi.det44_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1, is_inside=0) - self.vapi.set_ipfix_exporter(collector_address=self.pg2.remote_ip4, - src_address=self.pg2.local_ip4, - path_mtu=512, - template_interval=10) - self.vapi.nat_ipfix_enable_disable(domain_id=1, src_port=4739, - enable=1) + sw_if_index=self.pg1.sw_if_index, is_add=1, is_inside=0 + ) + self.vapi.set_ipfix_exporter( + collector_address=self.pg2.remote_ip4, + src_address=self.pg2.local_ip4, + path_mtu=512, + template_interval=10, + ) + self.vapi.nat_ipfix_enable_disable(domain_id=1, src_port=4739, enable=1) pkts = [] for port in range(1025, 2025): - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - UDP(sport=port, dport=port)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / UDP(sport=port, dport=port) + ) pkts.append(p) self.pg0.add_stream(pkts) @@ -637,9 +696,11 @@ class TestDET44(VppTestCase): self.pg_start() self.pg1.get_capture(len(pkts)) - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - UDP(sport=3001, dport=3002)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / UDP(sport=3001, dport=3002) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -674,8 +735,5 @@ class TestDET44(VppTestCase): for p in capture: if p.haslayer(Data): data = ipfix.decode_data_set(p.getlayer(Set)) - self.verify_ipfix_max_entries_per_user(data, - 1000, - self.pg0.remote_ip4) - self.vapi.nat_ipfix_enable_disable(domain_id=1, src_port=4739, - enable=0) + self.verify_ipfix_max_entries_per_user(data, 1000, self.pg0.remote_ip4) + self.vapi.nat_ipfix_enable_disable(domain_id=1, src_port=4739, enable=0) diff --git a/test/test_dhcp.py b/test/test_dhcp.py index a3b410c0595..a349356119a 100644 --- a/test/test_dhcp.py +++ b/test/test_dhcp.py @@ -16,9 +16,19 @@ from scapy.layers.inet import IP, UDP, ICMP from scapy.layers.inet6 import IPv6, in6_getnsmac from scapy.utils6 import in6_mactoifaceid from scapy.layers.dhcp import DHCP, BOOTP, DHCPTypes -from scapy.layers.dhcp6 import DHCP6, DHCP6_Solicit, DHCP6_RelayForward, \ - DHCP6_RelayReply, DHCP6_Advertise, DHCP6OptRelayMsg, DHCP6OptIfaceId, \ - DHCP6OptStatusCode, DHCP6OptVSS, DHCP6OptClientLinkLayerAddr, DHCP6_Request +from scapy.layers.dhcp6 import ( + DHCP6, + DHCP6_Solicit, + DHCP6_RelayForward, + DHCP6_RelayReply, + DHCP6_Advertise, + DHCP6OptRelayMsg, + DHCP6OptIfaceId, + DHCP6OptStatusCode, + DHCP6OptVSS, + DHCP6OptClientLinkLayerAddr, + DHCP6_Request, +) from socket import AF_INET, AF_INET6, inet_pton, inet_ntop from scapy.utils6 import in6_ptop from vpp_papi import mac_pton, VppEnum @@ -35,7 +45,7 @@ DHCP6_SERVER_PORT = 546 @tag_run_solo class TestDHCP(VppTestCase): - """ DHCP Test Case """ + """DHCP Test Case""" @classmethod def setUpClass(cls): @@ -136,8 +146,7 @@ class TestDHCP(VppTestCase): self.assertEqual(six.byte2int(data[2:3]), 0) self.assertEqual(six.byte2int(data[3:4]), 0) self.assertEqual(six.byte2int(data[4:5]), 0) - self.assertEqual(six.byte2int(data[5:6]), - intf._sw_if_index) + self.assertEqual(six.byte2int(data[5:6]), intf._sw_if_index) # # next sub-option is the IP address of the client side @@ -179,16 +188,15 @@ class TestDHCP(VppTestCase): self.assertEqual(six.byte2int(data[12:13]), 151) self.assertEqual(six.byte2int(data[13:14]), id_len + 1) self.assertEqual(six.byte2int(data[14:15]), 0) - self.assertEqual(data[15:15 + id_len].decode('ascii'), - vpn_id) + self.assertEqual(data[15 : 15 + id_len].decode("ascii"), vpn_id) # VSS control sub-option - self.assertEqual(six.byte2int(data[15 + len(vpn_id): - 16 + len(vpn_id)]), - 152) - self.assertEqual(six.byte2int(data[16 + len(vpn_id): - 17 + len(vpn_id)]), - 0) + self.assertEqual( + six.byte2int(data[15 + len(vpn_id) : 16 + len(vpn_id)]), 152 + ) + self.assertEqual( + six.byte2int(data[16 + len(vpn_id) : 17 + len(vpn_id)]), 0 + ) found = 1 self.assertTrue(found) @@ -200,8 +208,7 @@ class TestDHCP(VppTestCase): found = False for o in dhcp.options: if isinstance(o, tuple): - if o[0] == "message-type" \ - and DHCPTypes[o[1]] == name: + if o[0] == "message-type" and DHCPTypes[o[1]] == name: found = True self.assertTrue(found) @@ -219,8 +226,9 @@ class TestDHCP(VppTestCase): self.assertEqual(udp.sport, DHCP4_SERVER_PORT) self.verify_dhcp_msg_type(pkt, "offer") - data = self.validate_relay_options(pkt, intf, intf.local_ip4, - vpn_id, fib_id, oui) + data = self.validate_relay_options( + pkt, intf, intf.local_ip4, vpn_id, fib_id, oui + ) def verify_orig_dhcp_pkt(self, pkt, intf, dscp, l2_bc=True): ether = pkt[Ether] @@ -232,7 +240,7 @@ class TestDHCP(VppTestCase): ip = pkt[IP] - if (l2_bc): + if l2_bc: self.assertEqual(ip.dst, "255.255.255.255") self.assertEqual(ip.src, "0.0.0.0") else: @@ -244,17 +252,16 @@ class TestDHCP(VppTestCase): self.assertEqual(udp.dport, DHCP4_SERVER_PORT) self.assertEqual(udp.sport, DHCP4_CLIENT_PORT) - def verify_orig_dhcp_discover(self, pkt, intf, hostname, client_id=None, - broadcast=True, dscp=0): + def verify_orig_dhcp_discover( + self, pkt, intf, hostname, client_id=None, broadcast=True, dscp=0 + ): self.verify_orig_dhcp_pkt(pkt, intf, dscp) self.verify_dhcp_msg_type(pkt, "discover") - self.verify_dhcp_has_option(pkt, "hostname", - hostname.encode('ascii')) + self.verify_dhcp_has_option(pkt, "hostname", hostname.encode("ascii")) if client_id: - client_id = '\x00' + client_id - self.verify_dhcp_has_option(pkt, "client_id", - client_id.encode('ascii')) + client_id = "\x00" + client_id + self.verify_dhcp_has_option(pkt, "client_id", client_id.encode("ascii")) bootp = pkt[BOOTP] self.assertEqual(bootp.ciaddr, "0.0.0.0") self.assertEqual(bootp.giaddr, "0.0.0.0") @@ -263,15 +270,13 @@ class TestDHCP(VppTestCase): else: self.assertEqual(bootp.flags, 0x0000) - def verify_orig_dhcp_request(self, pkt, intf, hostname, ip, - broadcast=True, - l2_bc=True, - dscp=0): + def verify_orig_dhcp_request( + self, pkt, intf, hostname, ip, broadcast=True, l2_bc=True, dscp=0 + ): self.verify_orig_dhcp_pkt(pkt, intf, dscp, l2_bc=l2_bc) self.verify_dhcp_msg_type(pkt, "request") - self.verify_dhcp_has_option(pkt, "hostname", - hostname.encode('ascii')) + self.verify_dhcp_has_option(pkt, "hostname", hostname.encode("ascii")) self.verify_dhcp_has_option(pkt, "requested_addr", ip) bootp = pkt[BOOTP] @@ -286,10 +291,17 @@ class TestDHCP(VppTestCase): else: self.assertEqual(bootp.flags, 0x0000) - def verify_relayed_dhcp_discover(self, pkt, intf, src_intf=None, - fib_id=0, oui=0, - vpn_id="", - dst_mac=None, dst_ip=None): + def verify_relayed_dhcp_discover( + self, + pkt, + intf, + src_intf=None, + fib_id=0, + oui=0, + vpn_id="", + dst_mac=None, + dst_ip=None, + ): if not dst_mac: dst_mac = intf.remote_mac if not dst_ip: @@ -312,24 +324,27 @@ class TestDHCP(VppTestCase): is_discover = False for o in dhcp.options: if isinstance(o, tuple): - if o[0] == "message-type" \ - and DHCPTypes[o[1]] == "discover": + if o[0] == "message-type" and DHCPTypes[o[1]] == "discover": is_discover = True self.assertTrue(is_discover) - data = self.validate_relay_options(pkt, src_intf, - src_intf.local_ip4, - vpn_id, - fib_id, oui) + data = self.validate_relay_options( + pkt, src_intf, src_intf.local_ip4, vpn_id, fib_id, oui + ) return data - def verify_dhcp6_solicit(self, pkt, intf, - peer_ip, peer_mac, - vpn_id="", - fib_id=0, - oui=0, - dst_mac=None, - dst_ip=None): + def verify_dhcp6_solicit( + self, + pkt, + intf, + peer_ip, + peer_mac, + vpn_id="", + fib_id=0, + oui=0, + dst_mac=None, + dst_ip=None, + ): if not dst_mac: dst_mac = intf.remote_mac if not dst_ip: @@ -377,8 +392,7 @@ class TestDHCP(VppTestCase): vss = pkt[DHCP6OptVSS] self.assertEqual(vss.optlen, id_len + 1) self.assertEqual(vss.type, 0) - self.assertEqual(vss.data[0:id_len].decode('ascii'), - vpn_id) + self.assertEqual(vss.data[0:id_len].decode("ascii"), vpn_id) # the relay message should be an encoded Solicit msg = pkt[DHCP6OptRelayMsg] @@ -402,9 +416,8 @@ class TestDHCP(VppTestCase): # not sure why this is not decoding # adv = pkt[DHCP6_Advertise] - def wait_for_no_route(self, address, length, - n_tries=50, s_time=1): - while (n_tries): + def wait_for_no_route(self, address, length, n_tries=50, s_time=1): + while n_tries: if not find_route(self, address, length): return True n_tries = n_tries - 1 @@ -413,42 +426,45 @@ class TestDHCP(VppTestCase): return False def test_dhcp_proxy(self): - """ DHCPv4 Proxy """ + """DHCPv4 Proxy""" # # Verify no response to DHCP request without DHCP config # - p_disc_vrf0 = (Ether(dst="ff:ff:ff:ff:ff:ff", - src=self.pg3.remote_mac) / - IP(src="0.0.0.0", dst="255.255.255.255") / - UDP(sport=DHCP4_CLIENT_PORT, - dport=DHCP4_SERVER_PORT) / - BOOTP(op=1) / - DHCP(options=[('message-type', 'discover'), ('end')])) + p_disc_vrf0 = ( + Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg3.remote_mac) + / IP(src="0.0.0.0", dst="255.255.255.255") + / UDP(sport=DHCP4_CLIENT_PORT, dport=DHCP4_SERVER_PORT) + / BOOTP(op=1) + / DHCP(options=[("message-type", "discover"), ("end")]) + ) pkts_disc_vrf0 = [p_disc_vrf0] - p_disc_vrf1 = (Ether(dst="ff:ff:ff:ff:ff:ff", - src=self.pg4.remote_mac) / - IP(src="0.0.0.0", dst="255.255.255.255") / - UDP(sport=DHCP4_CLIENT_PORT, - dport=DHCP4_SERVER_PORT) / - BOOTP(op=1) / - DHCP(options=[('message-type', 'discover'), ('end')])) + p_disc_vrf1 = ( + Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg4.remote_mac) + / IP(src="0.0.0.0", dst="255.255.255.255") + / UDP(sport=DHCP4_CLIENT_PORT, dport=DHCP4_SERVER_PORT) + / BOOTP(op=1) + / DHCP(options=[("message-type", "discover"), ("end")]) + ) pkts_disc_vrf1 = [p_disc_vrf1] - p_disc_vrf2 = (Ether(dst="ff:ff:ff:ff:ff:ff", - src=self.pg5.remote_mac) / - IP(src="0.0.0.0", dst="255.255.255.255") / - UDP(sport=DHCP4_CLIENT_PORT, - dport=DHCP4_SERVER_PORT) / - BOOTP(op=1) / - DHCP(options=[('message-type', 'discover'), ('end')])) + p_disc_vrf2 = ( + Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg5.remote_mac) + / IP(src="0.0.0.0", dst="255.255.255.255") + / UDP(sport=DHCP4_CLIENT_PORT, dport=DHCP4_SERVER_PORT) + / BOOTP(op=1) + / DHCP(options=[("message-type", "discover"), ("end")]) + ) pkts_disc_vrf2 = [p_disc_vrf2] - self.send_and_assert_no_replies(self.pg3, pkts_disc_vrf0, - "DHCP with no configuration") - self.send_and_assert_no_replies(self.pg4, pkts_disc_vrf1, - "DHCP with no configuration") - self.send_and_assert_no_replies(self.pg5, pkts_disc_vrf2, - "DHCP with no configuration") + self.send_and_assert_no_replies( + self.pg3, pkts_disc_vrf0, "DHCP with no configuration" + ) + self.send_and_assert_no_replies( + self.pg4, pkts_disc_vrf1, "DHCP with no configuration" + ) + self.send_and_assert_no_replies( + self.pg5, pkts_disc_vrf2, "DHCP with no configuration" + ) # # Enable DHCP proxy in VRF 0 @@ -463,23 +479,25 @@ class TestDHCP(VppTestCase): # Discover packets from the client are dropped because there is no # IP address configured on the client facing interface # - self.send_and_assert_no_replies(self.pg3, pkts_disc_vrf0, - "Discover DHCP no relay address") + self.send_and_assert_no_replies( + self.pg3, pkts_disc_vrf0, "Discover DHCP no relay address" + ) # # Inject a response from the server # dropped, because there is no IP addrees on the # client interfce to fill in the option. # - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / - UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT) / - BOOTP(op=1) / - DHCP(options=[('message-type', 'offer'), ('end')])) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT) + / BOOTP(op=1) + / DHCP(options=[("message-type", "offer"), ("end")]) + ) pkts = [p] - self.send_and_assert_no_replies(self.pg3, pkts, - "Offer DHCP no relay address") + self.send_and_assert_no_replies(self.pg3, pkts, "Offer DHCP no relay address") # # configure an IP address on the client facing interface @@ -500,21 +518,26 @@ class TestDHCP(VppTestCase): rx = self.pg0.get_capture(1) rx = rx[0] - option_82 = self.verify_relayed_dhcp_discover(rx, self.pg0, - src_intf=self.pg3) + option_82 = self.verify_relayed_dhcp_discover(rx, self.pg0, src_intf=self.pg3) # # Create an DHCP offer reply from the server with a correctly formatted # option 82. i.e. send back what we just captured # The offer, sent mcast to the client, still has option 82. # - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / - UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT) / - BOOTP(op=1) / - DHCP(options=[('message-type', 'offer'), - ('relay_agent_Information', option_82), - ('end')])) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT) + / BOOTP(op=1) + / DHCP( + options=[ + ("message-type", "offer"), + ("relay_agent_Information", option_82), + ("end"), + ] + ) + ) pkts = [p] self.pg0.add_stream(pkts) @@ -533,36 +556,51 @@ class TestDHCP(VppTestCase): # to client bad_ip = option_82[0:8] + scapy.compat.chb(33) + option_82[9:] - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / - UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT) / - BOOTP(op=1) / - DHCP(options=[('message-type', 'offer'), - ('relay_agent_Information', bad_ip), - ('end')])) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT) + / BOOTP(op=1) + / DHCP( + options=[ + ("message-type", "offer"), + ("relay_agent_Information", bad_ip), + ("end"), + ] + ) + ) pkts = [p] - self.send_and_assert_no_replies(self.pg0, pkts, - "DHCP offer option 82 bad address") + self.send_and_assert_no_replies( + self.pg0, pkts, "DHCP offer option 82 bad address" + ) # 2. Not a sw_if_index VPP knows bad_if_index = option_82[0:2] + scapy.compat.chb(33) + option_82[3:] - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / - UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT) / - BOOTP(op=1) / - DHCP(options=[('message-type', 'offer'), - ('relay_agent_Information', bad_if_index), - ('end')])) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT) + / BOOTP(op=1) + / DHCP( + options=[ + ("message-type", "offer"), + ("relay_agent_Information", bad_if_index), + ("end"), + ] + ) + ) pkts = [p] - self.send_and_assert_no_replies(self.pg0, pkts, - "DHCP offer option 82 bad if index") + self.send_and_assert_no_replies( + self.pg0, pkts, "DHCP offer option 82 bad if index" + ) # # Send a DHCP request in VRF 1. should be dropped. # - self.send_and_assert_no_replies(self.pg4, pkts_disc_vrf1, - "DHCP with no configuration VRF 1") + self.send_and_assert_no_replies( + self.pg4, pkts_disc_vrf1, "DHCP with no configuration VRF 1" + ) # # Delete the DHCP config in VRF 0 @@ -570,10 +608,12 @@ class TestDHCP(VppTestCase): # Proxy.remove_vpp_config() - self.send_and_assert_no_replies(self.pg3, pkts_disc_vrf0, - "DHCP config removed VRF 0") - self.send_and_assert_no_replies(self.pg4, pkts_disc_vrf1, - "DHCP config removed VRF 1") + self.send_and_assert_no_replies( + self.pg3, pkts_disc_vrf0, "DHCP config removed VRF 0" + ) + self.send_and_assert_no_replies( + self.pg4, pkts_disc_vrf1, "DHCP config removed VRF 1" + ) # # Add DHCP config for VRF 1 & 2 @@ -581,31 +621,27 @@ class TestDHCP(VppTestCase): server_addr1 = self.pg1.remote_ip4 src_addr1 = self.pg1.local_ip4 Proxy1 = VppDHCPProxy( - self, - server_addr1, - src_addr1, - rx_vrf_id=1, - server_vrf_id=1) + self, server_addr1, src_addr1, rx_vrf_id=1, server_vrf_id=1 + ) Proxy1.add_vpp_config() server_addr2 = self.pg2.remote_ip4 src_addr2 = self.pg2.local_ip4 Proxy2 = VppDHCPProxy( - self, - server_addr2, - src_addr2, - rx_vrf_id=2, - server_vrf_id=2) + self, server_addr2, src_addr2, rx_vrf_id=2, server_vrf_id=2 + ) Proxy2.add_vpp_config() # # Confim DHCP requests ok in VRF 1 & 2. # - dropped on IP config on client interface # - self.send_and_assert_no_replies(self.pg4, pkts_disc_vrf1, - "DHCP config removed VRF 1") - self.send_and_assert_no_replies(self.pg5, pkts_disc_vrf2, - "DHCP config removed VRF 2") + self.send_and_assert_no_replies( + self.pg4, pkts_disc_vrf1, "DHCP config removed VRF 1" + ) + self.send_and_assert_no_replies( + self.pg5, pkts_disc_vrf2, "DHCP config removed VRF 2" + ) # # configure an IP address on the client facing interface @@ -630,10 +666,10 @@ class TestDHCP(VppTestCase): # Add VSS config # table=1, vss_type=1, vpn_index=1, oui=4 # table=2, vss_type=0, vpn_id = "ip4-table-2" - self.vapi.dhcp_proxy_set_vss(tbl_id=1, vss_type=1, - vpn_index=1, oui=4, is_add=1) - self.vapi.dhcp_proxy_set_vss(tbl_id=2, vss_type=0, - vpn_ascii_id="ip4-table-2", is_add=1) + self.vapi.dhcp_proxy_set_vss(tbl_id=1, vss_type=1, vpn_index=1, oui=4, is_add=1) + self.vapi.dhcp_proxy_set_vss( + tbl_id=2, vss_type=0, vpn_ascii_id="ip4-table-2", is_add=1 + ) self.pg4.add_stream(pkts_disc_vrf1) self.pg_enable_capture(self.pg_interfaces) @@ -641,9 +677,9 @@ class TestDHCP(VppTestCase): rx = self.pg1.get_capture(1) rx = rx[0] - self.verify_relayed_dhcp_discover(rx, self.pg1, - src_intf=self.pg4, - fib_id=1, oui=4) + self.verify_relayed_dhcp_discover( + rx, self.pg1, src_intf=self.pg4, fib_id=1, oui=4 + ) self.pg5.add_stream(pkts_disc_vrf2) self.pg_enable_capture(self.pg_interfaces) @@ -651,9 +687,9 @@ class TestDHCP(VppTestCase): rx = self.pg2.get_capture(1) rx = rx[0] - self.verify_relayed_dhcp_discover(rx, self.pg2, - src_intf=self.pg5, - vpn_id="ip4-table-2") + self.verify_relayed_dhcp_discover( + rx, self.pg2, src_intf=self.pg5, vpn_id="ip4-table-2" + ) # # Add a second DHCP server in VRF 1 @@ -663,20 +699,19 @@ class TestDHCP(VppTestCase): server_addr12 = self.pg1.remote_hosts[1].ip4 Proxy12 = VppDHCPProxy( - self, - server_addr12, - src_addr, - rx_vrf_id=1, - server_vrf_id=1) + self, server_addr12, src_addr, rx_vrf_id=1, server_vrf_id=1 + ) Proxy12.add_vpp_config() # # We'll need an ARP entry for the server to send it packets # - arp_entry = VppNeighbor(self, - self.pg1.sw_if_index, - self.pg1.remote_hosts[1].mac, - self.pg1.remote_hosts[1].ip4) + arp_entry = VppNeighbor( + self, + self.pg1.sw_if_index, + self.pg1.remote_hosts[1].mac, + self.pg1.remote_hosts[1].ip4, + ) arp_entry.add_vpp_config() # @@ -691,32 +726,47 @@ class TestDHCP(VppTestCase): rx = self.pg1.get_capture(2) option_82 = self.verify_relayed_dhcp_discover( - rx[0], self.pg1, + rx[0], + self.pg1, src_intf=self.pg4, dst_mac=self.pg1.remote_hosts[1].mac, dst_ip=self.pg1.remote_hosts[1].ip4, - fib_id=1, oui=4) - self.verify_relayed_dhcp_discover(rx[1], self.pg1, - src_intf=self.pg4, - fib_id=1, oui=4) + fib_id=1, + oui=4, + ) + self.verify_relayed_dhcp_discover( + rx[1], self.pg1, src_intf=self.pg4, fib_id=1, oui=4 + ) # # Send both packets back. Client gets both. # - p1 = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IP(src=self.pg1.remote_ip4, dst=self.pg1.local_ip4) / - UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT) / - BOOTP(op=1) / - DHCP(options=[('message-type', 'offer'), - ('relay_agent_Information', option_82), - ('end')])) - p2 = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IP(src=self.pg1.remote_hosts[1].ip4, dst=self.pg1.local_ip4) / - UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT) / - BOOTP(op=1) / - DHCP(options=[('message-type', 'offer'), - ('relay_agent_Information', option_82), - ('end')])) + p1 = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src=self.pg1.remote_ip4, dst=self.pg1.local_ip4) + / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT) + / BOOTP(op=1) + / DHCP( + options=[ + ("message-type", "offer"), + ("relay_agent_Information", option_82), + ("end"), + ] + ) + ) + p2 = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src=self.pg1.remote_hosts[1].ip4, dst=self.pg1.local_ip4) + / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT) + / BOOTP(op=1) + / DHCP( + options=[ + ("message-type", "offer"), + ("relay_agent_Information", option_82), + ("end"), + ] + ) + ) pkts = [p1, p2] self.pg1.add_stream(pkts) @@ -731,27 +781,31 @@ class TestDHCP(VppTestCase): # # Ensure offers from non-servers are dropeed # - p2 = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IP(src="8.8.8.8", dst=self.pg1.local_ip4) / - UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT) / - BOOTP(op=1) / - DHCP(options=[('message-type', 'offer'), - ('relay_agent_Information', option_82), - ('end')])) - self.send_and_assert_no_replies(self.pg1, p2, - "DHCP offer from non-server") + p2 = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src="8.8.8.8", dst=self.pg1.local_ip4) + / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT) + / BOOTP(op=1) + / DHCP( + options=[ + ("message-type", "offer"), + ("relay_agent_Information", option_82), + ("end"), + ] + ) + ) + self.send_and_assert_no_replies(self.pg1, p2, "DHCP offer from non-server") # # Ensure only the discover is sent to multiple servers # - p_req_vrf1 = (Ether(dst="ff:ff:ff:ff:ff:ff", - src=self.pg4.remote_mac) / - IP(src="0.0.0.0", dst="255.255.255.255") / - UDP(sport=DHCP4_CLIENT_PORT, - dport=DHCP4_SERVER_PORT) / - BOOTP(op=1) / - DHCP(options=[('message-type', 'request'), - ('end')])) + p_req_vrf1 = ( + Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg4.remote_mac) + / IP(src="0.0.0.0", dst="255.255.255.255") + / UDP(sport=DHCP4_CLIENT_PORT, dport=DHCP4_SERVER_PORT) + / BOOTP(op=1) + / DHCP(options=[("message-type", "request"), ("end")]) + ) self.pg4.add_stream(p_req_vrf1) self.pg_enable_capture(self.pg_interfaces) @@ -773,9 +827,9 @@ class TestDHCP(VppTestCase): rx = self.pg1.get_capture(1) rx = rx[0] - self.verify_relayed_dhcp_discover(rx, self.pg1, - src_intf=self.pg4, - fib_id=1, oui=4) + self.verify_relayed_dhcp_discover( + rx, self.pg1, src_intf=self.pg4, fib_id=1, oui=4 + ) # # Remove the VSS config @@ -798,19 +852,16 @@ class TestDHCP(VppTestCase): Proxy1.remove_vpp_config() Proxy2.remove_vpp_config() - self.send_and_assert_no_replies(self.pg3, pkts_disc_vrf0, - "DHCP cleanup VRF 0") - self.send_and_assert_no_replies(self.pg4, pkts_disc_vrf1, - "DHCP cleanup VRF 1") - self.send_and_assert_no_replies(self.pg5, pkts_disc_vrf2, - "DHCP cleanup VRF 2") + self.send_and_assert_no_replies(self.pg3, pkts_disc_vrf0, "DHCP cleanup VRF 0") + self.send_and_assert_no_replies(self.pg4, pkts_disc_vrf1, "DHCP cleanup VRF 1") + self.send_and_assert_no_replies(self.pg5, pkts_disc_vrf2, "DHCP cleanup VRF 2") self.pg3.unconfig_ip4() self.pg4.unconfig_ip4() self.pg5.unconfig_ip4() def test_dhcp6_proxy(self): - """ DHCPv6 Proxy""" + """DHCPv6 Proxy""" # # Verify no response to DHCP request without DHCP config # @@ -826,31 +877,34 @@ class TestDHCP(VppTestCase): src_addr_vrf2 = self.pg2.local_ip6 dmac = in6_getnsmac(inet_pton(socket.AF_INET6, dhcp_solicit_dst)) - p_solicit_vrf0 = (Ether(dst=dmac, src=self.pg3.remote_mac) / - IPv6(src=dhcp_solicit_src_vrf0, - dst=dhcp_solicit_dst) / - UDP(sport=DHCP6_SERVER_PORT, - dport=DHCP6_CLIENT_PORT) / - DHCP6_Solicit()) - p_solicit_vrf1 = (Ether(dst=dmac, src=self.pg4.remote_mac) / - IPv6(src=dhcp_solicit_src_vrf1, - dst=dhcp_solicit_dst) / - UDP(sport=DHCP6_SERVER_PORT, - dport=DHCP6_CLIENT_PORT) / - DHCP6_Solicit()) - p_solicit_vrf2 = (Ether(dst=dmac, src=self.pg5.remote_mac) / - IPv6(src=dhcp_solicit_src_vrf2, - dst=dhcp_solicit_dst) / - UDP(sport=DHCP6_SERVER_PORT, - dport=DHCP6_CLIENT_PORT) / - DHCP6_Solicit()) - - self.send_and_assert_no_replies(self.pg3, p_solicit_vrf0, - "DHCP with no configuration") - self.send_and_assert_no_replies(self.pg4, p_solicit_vrf1, - "DHCP with no configuration") - self.send_and_assert_no_replies(self.pg5, p_solicit_vrf2, - "DHCP with no configuration") + p_solicit_vrf0 = ( + Ether(dst=dmac, src=self.pg3.remote_mac) + / IPv6(src=dhcp_solicit_src_vrf0, dst=dhcp_solicit_dst) + / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_CLIENT_PORT) + / DHCP6_Solicit() + ) + p_solicit_vrf1 = ( + Ether(dst=dmac, src=self.pg4.remote_mac) + / IPv6(src=dhcp_solicit_src_vrf1, dst=dhcp_solicit_dst) + / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_CLIENT_PORT) + / DHCP6_Solicit() + ) + p_solicit_vrf2 = ( + Ether(dst=dmac, src=self.pg5.remote_mac) + / IPv6(src=dhcp_solicit_src_vrf2, dst=dhcp_solicit_dst) + / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_CLIENT_PORT) + / DHCP6_Solicit() + ) + + self.send_and_assert_no_replies( + self.pg3, p_solicit_vrf0, "DHCP with no configuration" + ) + self.send_and_assert_no_replies( + self.pg4, p_solicit_vrf1, "DHCP with no configuration" + ) + self.send_and_assert_no_replies( + self.pg5, p_solicit_vrf2, "DHCP with no configuration" + ) # # DHCPv6 config in VRF 0. @@ -858,17 +912,16 @@ class TestDHCP(VppTestCase): # IPv6 config # Proxy = VppDHCPProxy( - self, - server_addr_vrf0, - src_addr_vrf0, - rx_vrf_id=0, - server_vrf_id=0) + self, server_addr_vrf0, src_addr_vrf0, rx_vrf_id=0, server_vrf_id=0 + ) Proxy.add_vpp_config() - self.send_and_assert_no_replies(self.pg3, p_solicit_vrf0, - "DHCP with no configuration") - self.send_and_assert_no_replies(self.pg4, p_solicit_vrf1, - "DHCP with no configuration") + self.send_and_assert_no_replies( + self.pg3, p_solicit_vrf0, "DHCP with no configuration" + ) + self.send_and_assert_no_replies( + self.pg4, p_solicit_vrf1, "DHCP with no configuration" + ) # # configure an IP address on the client facing interface @@ -884,62 +937,70 @@ class TestDHCP(VppTestCase): rx = self.pg0.get_capture(1) - self.verify_dhcp6_solicit(rx[0], self.pg0, - dhcp_solicit_src_vrf0, - self.pg3.remote_mac) + self.verify_dhcp6_solicit( + rx[0], self.pg0, dhcp_solicit_src_vrf0, self.pg3.remote_mac + ) # # Exception cases for rejected relay responses # # 1 - not a relay reply - p_adv_vrf0 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) / - UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) / - DHCP6_Advertise()) - self.send_and_assert_no_replies(self.pg3, p_adv_vrf0, - "DHCP6 not a relay reply") + p_adv_vrf0 = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) + / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) + / DHCP6_Advertise() + ) + self.send_and_assert_no_replies(self.pg3, p_adv_vrf0, "DHCP6 not a relay reply") # 2 - no relay message option - p_adv_vrf0 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) / - UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) / - DHCP6_RelayReply() / - DHCP6_Advertise()) - self.send_and_assert_no_replies(self.pg3, p_adv_vrf0, - "DHCP not a relay message") + p_adv_vrf0 = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) + / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) + / DHCP6_RelayReply() + / DHCP6_Advertise() + ) + self.send_and_assert_no_replies( + self.pg3, p_adv_vrf0, "DHCP not a relay message" + ) # 3 - no circuit ID - p_adv_vrf0 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) / - UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) / - DHCP6_RelayReply() / - DHCP6OptRelayMsg(optlen=0) / - DHCP6_Advertise()) - self.send_and_assert_no_replies(self.pg3, p_adv_vrf0, - "DHCP6 no circuit ID") + p_adv_vrf0 = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) + / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) + / DHCP6_RelayReply() + / DHCP6OptRelayMsg(optlen=0) + / DHCP6_Advertise() + ) + self.send_and_assert_no_replies(self.pg3, p_adv_vrf0, "DHCP6 no circuit ID") # 4 - wrong circuit ID - p_adv_vrf0 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) / - UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) / - DHCP6_RelayReply() / - DHCP6OptIfaceId(optlen=4, ifaceid='\x00\x00\x00\x05') / - DHCP6OptRelayMsg(optlen=0) / - DHCP6_Advertise()) - self.send_and_assert_no_replies(self.pg3, p_adv_vrf0, - "DHCP6 wrong circuit ID") + p_adv_vrf0 = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) + / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) + / DHCP6_RelayReply() + / DHCP6OptIfaceId(optlen=4, ifaceid="\x00\x00\x00\x05") + / DHCP6OptRelayMsg(optlen=0) + / DHCP6_Advertise() + ) + self.send_and_assert_no_replies(self.pg3, p_adv_vrf0, "DHCP6 wrong circuit ID") # # Send the relay response (the advertisement) # - no peer address - p_adv_vrf0 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) / - UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) / - DHCP6_RelayReply() / - DHCP6OptIfaceId(optlen=4, ifaceid='\x00\x00\x00\x04') / - DHCP6OptRelayMsg(optlen=0) / - DHCP6_Advertise(trid=1) / - DHCP6OptStatusCode(statuscode=0)) + p_adv_vrf0 = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) + / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) + / DHCP6_RelayReply() + / DHCP6OptIfaceId(optlen=4, ifaceid="\x00\x00\x00\x04") + / DHCP6OptRelayMsg(optlen=0) + / DHCP6_Advertise(trid=1) + / DHCP6OptStatusCode(statuscode=0) + ) pkts_adv_vrf0 = [p_adv_vrf0] self.pg0.add_stream(pkts_adv_vrf0) @@ -953,14 +1014,16 @@ class TestDHCP(VppTestCase): # # Send the relay response (the advertisement) # - with peer address - p_adv_vrf0 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) / - UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) / - DHCP6_RelayReply(peeraddr=dhcp_solicit_src_vrf0) / - DHCP6OptIfaceId(optlen=4, ifaceid='\x00\x00\x00\x04') / - DHCP6OptRelayMsg(optlen=0) / - DHCP6_Advertise(trid=1) / - DHCP6OptStatusCode(statuscode=0)) + p_adv_vrf0 = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) + / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) + / DHCP6_RelayReply(peeraddr=dhcp_solicit_src_vrf0) + / DHCP6OptIfaceId(optlen=4, ifaceid="\x00\x00\x00\x04") + / DHCP6OptRelayMsg(optlen=0) + / DHCP6_Advertise(trid=1) + / DHCP6OptStatusCode(statuscode=0) + ) pkts_adv_vrf0 = [p_adv_vrf0] self.pg0.add_stream(pkts_adv_vrf0) @@ -975,20 +1038,14 @@ class TestDHCP(VppTestCase): # Add all the config for VRF 1 & 2 # Proxy1 = VppDHCPProxy( - self, - server_addr_vrf1, - src_addr_vrf1, - rx_vrf_id=1, - server_vrf_id=1) + self, server_addr_vrf1, src_addr_vrf1, rx_vrf_id=1, server_vrf_id=1 + ) Proxy1.add_vpp_config() self.pg4.config_ip6() Proxy2 = VppDHCPProxy( - self, - server_addr_vrf2, - src_addr_vrf2, - rx_vrf_id=2, - server_vrf_id=2) + self, server_addr_vrf2, src_addr_vrf2, rx_vrf_id=2, server_vrf_id=2 + ) Proxy2.add_vpp_config() self.pg5.config_ip6() @@ -1001,9 +1058,9 @@ class TestDHCP(VppTestCase): rx = self.pg1.get_capture(1) - self.verify_dhcp6_solicit(rx[0], self.pg1, - dhcp_solicit_src_vrf1, - self.pg4.remote_mac) + self.verify_dhcp6_solicit( + rx[0], self.pg1, dhcp_solicit_src_vrf1, self.pg4.remote_mac + ) # # VRF 2 solicit @@ -1014,21 +1071,23 @@ class TestDHCP(VppTestCase): rx = self.pg2.get_capture(1) - self.verify_dhcp6_solicit(rx[0], self.pg2, - dhcp_solicit_src_vrf2, - self.pg5.remote_mac) + self.verify_dhcp6_solicit( + rx[0], self.pg2, dhcp_solicit_src_vrf2, self.pg5.remote_mac + ) # # VRF 1 Advert # - p_adv_vrf1 = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IPv6(dst=self.pg1.local_ip6, src=self.pg1.remote_ip6) / - UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) / - DHCP6_RelayReply(peeraddr=dhcp_solicit_src_vrf1) / - DHCP6OptIfaceId(optlen=4, ifaceid='\x00\x00\x00\x05') / - DHCP6OptRelayMsg(optlen=0) / - DHCP6_Advertise(trid=1) / - DHCP6OptStatusCode(statuscode=0)) + p_adv_vrf1 = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(dst=self.pg1.local_ip6, src=self.pg1.remote_ip6) + / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) + / DHCP6_RelayReply(peeraddr=dhcp_solicit_src_vrf1) + / DHCP6OptIfaceId(optlen=4, ifaceid="\x00\x00\x00\x05") + / DHCP6OptRelayMsg(optlen=0) + / DHCP6_Advertise(trid=1) + / DHCP6OptStatusCode(statuscode=0) + ) pkts_adv_vrf1 = [p_adv_vrf1] self.pg1.add_stream(pkts_adv_vrf1) @@ -1043,13 +1102,11 @@ class TestDHCP(VppTestCase): # Add VSS config # self.vapi.dhcp_proxy_set_vss( - tbl_id=1, vss_type=1, oui=4, vpn_index=1, is_ipv6=1, is_add=1) + tbl_id=1, vss_type=1, oui=4, vpn_index=1, is_ipv6=1, is_add=1 + ) self.vapi.dhcp_proxy_set_vss( - tbl_id=2, - vss_type=0, - vpn_ascii_id="IPv6-table-2", - is_ipv6=1, - is_add=1) + tbl_id=2, vss_type=0, vpn_ascii_id="IPv6-table-2", is_ipv6=1, is_add=1 + ) self.pg4.add_stream(p_solicit_vrf1) self.pg_enable_capture(self.pg_interfaces) @@ -1057,11 +1114,9 @@ class TestDHCP(VppTestCase): rx = self.pg1.get_capture(1) - self.verify_dhcp6_solicit(rx[0], self.pg1, - dhcp_solicit_src_vrf1, - self.pg4.remote_mac, - fib_id=1, - oui=4) + self.verify_dhcp6_solicit( + rx[0], self.pg1, dhcp_solicit_src_vrf1, self.pg4.remote_mac, fib_id=1, oui=4 + ) self.pg5.add_stream(p_solicit_vrf2) self.pg_enable_capture(self.pg_interfaces) @@ -1069,10 +1124,13 @@ class TestDHCP(VppTestCase): rx = self.pg2.get_capture(1) - self.verify_dhcp6_solicit(rx[0], self.pg2, - dhcp_solicit_src_vrf2, - self.pg5.remote_mac, - vpn_id="IPv6-table-2") + self.verify_dhcp6_solicit( + rx[0], + self.pg2, + dhcp_solicit_src_vrf2, + self.pg5.remote_mac, + vpn_id="IPv6-table-2", + ) # # Remove the VSS config @@ -1086,9 +1144,9 @@ class TestDHCP(VppTestCase): rx = self.pg1.get_capture(1) - self.verify_dhcp6_solicit(rx[0], self.pg1, - dhcp_solicit_src_vrf1, - self.pg4.remote_mac) + self.verify_dhcp6_solicit( + rx[0], self.pg1, dhcp_solicit_src_vrf1, self.pg4.remote_mac + ) # # Add a second DHCP server in VRF 1 @@ -1098,20 +1156,19 @@ class TestDHCP(VppTestCase): server_addr12 = self.pg1.remote_hosts[1].ip6 Proxy12 = VppDHCPProxy( - self, - server_addr12, - src_addr_vrf1, - rx_vrf_id=1, - server_vrf_id=1) + self, server_addr12, src_addr_vrf1, rx_vrf_id=1, server_vrf_id=1 + ) Proxy12.add_vpp_config() # # We'll need an ND entry for the server to send it packets # - nd_entry = VppNeighbor(self, - self.pg1.sw_if_index, - self.pg1.remote_hosts[1].mac, - self.pg1.remote_hosts[1].ip6) + nd_entry = VppNeighbor( + self, + self.pg1.sw_if_index, + self.pg1.remote_hosts[1].mac, + self.pg1.remote_hosts[1].ip6, + ) nd_entry.add_vpp_config() # @@ -1125,34 +1182,41 @@ class TestDHCP(VppTestCase): rx = self.pg1.get_capture(2) - self.verify_dhcp6_solicit(rx[0], self.pg1, - dhcp_solicit_src_vrf1, - self.pg4.remote_mac) - self.verify_dhcp6_solicit(rx[1], self.pg1, - dhcp_solicit_src_vrf1, - self.pg4.remote_mac, - dst_mac=self.pg1.remote_hosts[1].mac, - dst_ip=self.pg1.remote_hosts[1].ip6) + self.verify_dhcp6_solicit( + rx[0], self.pg1, dhcp_solicit_src_vrf1, self.pg4.remote_mac + ) + self.verify_dhcp6_solicit( + rx[1], + self.pg1, + dhcp_solicit_src_vrf1, + self.pg4.remote_mac, + dst_mac=self.pg1.remote_hosts[1].mac, + dst_ip=self.pg1.remote_hosts[1].ip6, + ) # # Send both packets back. Client gets both. # - p1 = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IPv6(dst=self.pg1.local_ip6, src=self.pg1.remote_ip6) / - UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) / - DHCP6_RelayReply(peeraddr=dhcp_solicit_src_vrf1) / - DHCP6OptIfaceId(optlen=4, ifaceid='\x00\x00\x00\x05') / - DHCP6OptRelayMsg(optlen=0) / - DHCP6_Advertise(trid=1) / - DHCP6OptStatusCode(statuscode=0)) - p2 = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_hosts[1].mac) / - IPv6(dst=self.pg1.local_ip6, src=self.pg1._remote_hosts[1].ip6) / - UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) / - DHCP6_RelayReply(peeraddr=dhcp_solicit_src_vrf1) / - DHCP6OptIfaceId(optlen=4, ifaceid='\x00\x00\x00\x05') / - DHCP6OptRelayMsg(optlen=0) / - DHCP6_Advertise(trid=1) / - DHCP6OptStatusCode(statuscode=0)) + p1 = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(dst=self.pg1.local_ip6, src=self.pg1.remote_ip6) + / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) + / DHCP6_RelayReply(peeraddr=dhcp_solicit_src_vrf1) + / DHCP6OptIfaceId(optlen=4, ifaceid="\x00\x00\x00\x05") + / DHCP6OptRelayMsg(optlen=0) + / DHCP6_Advertise(trid=1) + / DHCP6OptStatusCode(statuscode=0) + ) + p2 = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_hosts[1].mac) + / IPv6(dst=self.pg1.local_ip6, src=self.pg1._remote_hosts[1].ip6) + / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) + / DHCP6_RelayReply(peeraddr=dhcp_solicit_src_vrf1) + / DHCP6OptIfaceId(optlen=4, ifaceid="\x00\x00\x00\x05") + / DHCP6OptRelayMsg(optlen=0) + / DHCP6_Advertise(trid=1) + / DHCP6OptStatusCode(statuscode=0) + ) pkts = [p1, p2] @@ -1168,12 +1232,12 @@ class TestDHCP(VppTestCase): # # Ensure only solicit messages are duplicated # - p_request_vrf1 = (Ether(dst=dmac, src=self.pg4.remote_mac) / - IPv6(src=dhcp_solicit_src_vrf1, - dst=dhcp_solicit_dst) / - UDP(sport=DHCP6_SERVER_PORT, - dport=DHCP6_CLIENT_PORT) / - DHCP6_Request()) + p_request_vrf1 = ( + Ether(dst=dmac, src=self.pg4.remote_mac) + / IPv6(src=dhcp_solicit_src_vrf1, dst=dhcp_solicit_dst) + / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_CLIENT_PORT) + / DHCP6_Request() + ) self.pg4.add_stream(p_request_vrf1) self.pg_enable_capture(self.pg_interfaces) @@ -1185,16 +1249,17 @@ class TestDHCP(VppTestCase): # Test we drop DHCP packets from addresses that are not configured as # DHCP servers # - p2 = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_hosts[1].mac) / - IPv6(dst=self.pg1.local_ip6, src="3001::1") / - UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) / - DHCP6_RelayReply(peeraddr=dhcp_solicit_src_vrf1) / - DHCP6OptIfaceId(optlen=4, ifaceid='\x00\x00\x00\x05') / - DHCP6OptRelayMsg(optlen=0) / - DHCP6_Advertise(trid=1) / - DHCP6OptStatusCode(statuscode=0)) - self.send_and_assert_no_replies(self.pg1, p2, - "DHCP6 not from server") + p2 = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_hosts[1].mac) + / IPv6(dst=self.pg1.local_ip6, src="3001::1") + / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) + / DHCP6_RelayReply(peeraddr=dhcp_solicit_src_vrf1) + / DHCP6OptIfaceId(optlen=4, ifaceid="\x00\x00\x00\x05") + / DHCP6OptRelayMsg(optlen=0) + / DHCP6_Advertise(trid=1) + / DHCP6OptStatusCode(statuscode=0) + ) + self.send_and_assert_no_replies(self.pg1, p2, "DHCP6 not from server") # # Remove the second DHCP server @@ -1210,9 +1275,9 @@ class TestDHCP(VppTestCase): rx = self.pg1.get_capture(1) - self.verify_dhcp6_solicit(rx[0], self.pg1, - dhcp_solicit_src_vrf1, - self.pg4.remote_mac) + self.verify_dhcp6_solicit( + rx[0], self.pg1, dhcp_solicit_src_vrf1, self.pg4.remote_mac + ) # # Cleanup @@ -1226,10 +1291,10 @@ class TestDHCP(VppTestCase): self.pg5.unconfig_ip6() def test_dhcp_client(self): - """ DHCP Client""" + """DHCP Client""" vdscp = VppEnum.vl_api_ip_dscp_t - hostname = 'universal-dp' + hostname = "universal-dp" self.pg_enable_capture(self.pg_interfaces) @@ -1247,38 +1312,50 @@ class TestDHCP(VppTestCase): # # Send back on offer, expect the request # - p_offer = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) / - IP(src=self.pg3.remote_ip4, dst="255.255.255.255") / - UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT) / - BOOTP(op=1, - yiaddr=self.pg3.local_ip4, - chaddr=mac_pton(self.pg3.local_mac)) / - DHCP(options=[('message-type', 'offer'), - ('server_id', self.pg3.remote_ip4), - 'end'])) + p_offer = ( + Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) + / IP(src=self.pg3.remote_ip4, dst="255.255.255.255") + / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT) + / BOOTP( + op=1, yiaddr=self.pg3.local_ip4, chaddr=mac_pton(self.pg3.local_mac) + ) + / DHCP( + options=[ + ("message-type", "offer"), + ("server_id", self.pg3.remote_ip4), + "end", + ] + ) + ) self.pg3.add_stream(p_offer) self.pg_enable_capture(self.pg_interfaces) self.pg_start() rx = self.pg3.get_capture(1) - self.verify_orig_dhcp_request(rx[0], self.pg3, hostname, - self.pg3.local_ip4) + self.verify_orig_dhcp_request(rx[0], self.pg3, hostname, self.pg3.local_ip4) # # Send an acknowledgment # - p_ack = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) / - IP(src=self.pg3.remote_ip4, dst="255.255.255.255") / - UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT) / - BOOTP(op=1, yiaddr=self.pg3.local_ip4, - chaddr=mac_pton(self.pg3.local_mac)) / - DHCP(options=[('message-type', 'ack'), - ('subnet_mask', "255.255.255.0"), - ('router', self.pg3.remote_ip4), - ('server_id', self.pg3.remote_ip4), - ('lease_time', 43200), - 'end'])) + p_ack = ( + Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) + / IP(src=self.pg3.remote_ip4, dst="255.255.255.255") + / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT) + / BOOTP( + op=1, yiaddr=self.pg3.local_ip4, chaddr=mac_pton(self.pg3.local_mac) + ) + / DHCP( + options=[ + ("message-type", "ack"), + ("subnet_mask", "255.255.255.0"), + ("router", self.pg3.remote_ip4), + ("server_id", self.pg3.remote_ip4), + ("lease_time", 43200), + "end", + ] + ) + ) self.pg3.add_stream(p_ack) self.pg_enable_capture(self.pg_interfaces) @@ -1317,16 +1394,19 @@ class TestDHCP(VppTestCase): self.pg3.admin_down() self.sleep(1) self.pg3.admin_up() - Client.set_client(self.pg3.sw_if_index, hostname, - id=self.pg3.local_mac, - dscp=vdscp.IP_API_DSCP_EF) + Client.set_client( + self.pg3.sw_if_index, + hostname, + id=self.pg3.local_mac, + dscp=vdscp.IP_API_DSCP_EF, + ) Client.add_vpp_config() rx = self.pg3.get_capture(1) - self.verify_orig_dhcp_discover(rx[0], self.pg3, hostname, - self.pg3.local_mac, - dscp=vdscp.IP_API_DSCP_EF) + self.verify_orig_dhcp_discover( + rx[0], self.pg3, hostname, self.pg3.local_mac, dscp=vdscp.IP_API_DSCP_EF + ) # TODO: VPP DHCP client should not accept DHCP OFFER message with # the XID (Transaction ID) not matching the XID of the most recent @@ -1338,24 +1418,31 @@ class TestDHCP(VppTestCase): self.pg_start() rx = self.pg3.get_capture(1) - self.verify_orig_dhcp_request(rx[0], self.pg3, hostname, - self.pg3.local_ip4, - dscp=vdscp.IP_API_DSCP_EF) + self.verify_orig_dhcp_request( + rx[0], self.pg3, hostname, self.pg3.local_ip4, dscp=vdscp.IP_API_DSCP_EF + ) # # unicast the ack to the offered address # - p_ack = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) / - IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) / - UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT) / - BOOTP(op=1, yiaddr=self.pg3.local_ip4, - chaddr=mac_pton(self.pg3.local_mac)) / - DHCP(options=[('message-type', 'ack'), - ('subnet_mask', "255.255.255.0"), - ('router', self.pg3.remote_ip4), - ('server_id', self.pg3.remote_ip4), - ('lease_time', 43200), - 'end'])) + p_ack = ( + Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) + / IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) + / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT) + / BOOTP( + op=1, yiaddr=self.pg3.local_ip4, chaddr=mac_pton(self.pg3.local_mac) + ) + / DHCP( + options=[ + ("message-type", "ack"), + ("subnet_mask", "255.255.255.0"), + ("router", self.pg3.remote_ip4), + ("server_id", self.pg3.remote_ip4), + ("lease_time", 43200), + "end", + ] + ) + ) self.pg3.add_stream(p_ack) self.pg_enable_capture(self.pg_interfaces) @@ -1391,55 +1478,65 @@ class TestDHCP(VppTestCase): # # Configure DHCP client on PG3 and capture the discover sent # - Client.set_client( - self.pg3.sw_if_index, - hostname, - set_broadcast_flag=False) + Client.set_client(self.pg3.sw_if_index, hostname, set_broadcast_flag=False) Client.add_vpp_config() rx = self.pg3.get_capture(1) - self.verify_orig_dhcp_discover(rx[0], self.pg3, hostname, - broadcast=False) + self.verify_orig_dhcp_discover(rx[0], self.pg3, hostname, broadcast=False) # # Send back on offer, unicasted to the offered address. # Expect the request. # - p_offer = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) / - IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) / - UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT) / - BOOTP(op=1, yiaddr=self.pg3.local_ip4, - chaddr=mac_pton(self.pg3.local_mac)) / - DHCP(options=[('message-type', 'offer'), - ('server_id', self.pg3.remote_ip4), - 'end'])) + p_offer = ( + Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) + / IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) + / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT) + / BOOTP( + op=1, yiaddr=self.pg3.local_ip4, chaddr=mac_pton(self.pg3.local_mac) + ) + / DHCP( + options=[ + ("message-type", "offer"), + ("server_id", self.pg3.remote_ip4), + "end", + ] + ) + ) self.pg3.add_stream(p_offer) self.pg_enable_capture(self.pg_interfaces) self.pg_start() rx = self.pg3.get_capture(1) - self.verify_orig_dhcp_request(rx[0], self.pg3, hostname, - self.pg3.local_ip4, - broadcast=False) + self.verify_orig_dhcp_request( + rx[0], self.pg3, hostname, self.pg3.local_ip4, broadcast=False + ) # # Send an acknowledgment, the lease renewal time is 2 seconds # so we should expect the renew straight after # - p_ack = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) / - IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) / - UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT) / - BOOTP(op=1, yiaddr=self.pg3.local_ip4, - chaddr=mac_pton(self.pg3.local_mac)) / - DHCP(options=[('message-type', 'ack'), - ('subnet_mask', "255.255.255.0"), - ('router', self.pg3.remote_ip4), - ('server_id', self.pg3.remote_ip4), - ('lease_time', 43200), - ('renewal_time', 2), - 'end'])) + p_ack = ( + Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) + / IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) + / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT) + / BOOTP( + op=1, yiaddr=self.pg3.local_ip4, chaddr=mac_pton(self.pg3.local_mac) + ) + / DHCP( + options=[ + ("message-type", "ack"), + ("subnet_mask", "255.255.255.0"), + ("router", self.pg3.remote_ip4), + ("server_id", self.pg3.remote_ip4), + ("lease_time", 43200), + ("renewal_time", 2), + "end", + ] + ) + ) self.pg3.add_stream(p_ack) self.pg_enable_capture(self.pg_interfaces) @@ -1465,19 +1562,15 @@ class TestDHCP(VppTestCase): # clients = self.vapi.dhcp_client_dump() - self.assertEqual(clients[0].client.sw_if_index, - self.pg3.sw_if_index) - self.assertEqual(clients[0].lease.sw_if_index, - self.pg3.sw_if_index) + self.assertEqual(clients[0].client.sw_if_index, self.pg3.sw_if_index) + self.assertEqual(clients[0].lease.sw_if_index, self.pg3.sw_if_index) self.assertEqual(clients[0].client.hostname, hostname) self.assertEqual(clients[0].lease.hostname, hostname) # 0 = DISCOVER, 1 = REQUEST, 2 = BOUND self.assertEqual(clients[0].lease.state, 2) self.assertEqual(clients[0].lease.mask_width, 24) - self.assertEqual(str(clients[0].lease.router_address), - self.pg3.remote_ip4) - self.assertEqual(str(clients[0].lease.host_address), - self.pg3.local_ip4) + self.assertEqual(str(clients[0].lease.router_address), self.pg3.remote_ip4) + self.assertEqual(str(clients[0].lease.host_address), self.pg3.local_ip4) # # wait for the unicasted renewal @@ -1490,37 +1583,46 @@ class TestDHCP(VppTestCase): self.assertEqual(rx[0][ARP].pdst, self.pg3.remote_ip4) # respond to the arp - p_arp = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) / - ARP(op="is-at", - hwdst=self.pg3.local_mac, - hwsrc=self.pg3.remote_mac, - pdst=self.pg3.local_ip4, - psrc=self.pg3.remote_ip4)) + p_arp = Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) / ARP( + op="is-at", + hwdst=self.pg3.local_mac, + hwsrc=self.pg3.remote_mac, + pdst=self.pg3.local_ip4, + psrc=self.pg3.remote_ip4, + ) self.pg3.add_stream(p_arp) self.pg_enable_capture(self.pg_interfaces) self.pg_start() # the next packet is the unicasted renewal rx = self.pg3.get_capture(1, timeout=10) - self.verify_orig_dhcp_request(rx[0], self.pg3, hostname, - self.pg3.local_ip4, - l2_bc=False, - broadcast=False) + self.verify_orig_dhcp_request( + rx[0], self.pg3, hostname, self.pg3.local_ip4, l2_bc=False, broadcast=False + ) # send an ACK with different data from the original offer * self.pg3.generate_remote_hosts(4) - p_ack = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) / - IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) / - UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT) / - BOOTP(op=1, yiaddr=self.pg3.remote_hosts[3].ip4, - chaddr=mac_pton(self.pg3.local_mac)) / - DHCP(options=[('message-type', 'ack'), - ('subnet_mask', "255.255.255.0"), - ('router', self.pg3.remote_hosts[1].ip4), - ('server_id', self.pg3.remote_hosts[2].ip4), - ('lease_time', 43200), - ('renewal_time', 2), - 'end'])) + p_ack = ( + Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) + / IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) + / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT) + / BOOTP( + op=1, + yiaddr=self.pg3.remote_hosts[3].ip4, + chaddr=mac_pton(self.pg3.local_mac), + ) + / DHCP( + options=[ + ("message-type", "ack"), + ("subnet_mask", "255.255.255.0"), + ("router", self.pg3.remote_hosts[1].ip4), + ("server_id", self.pg3.remote_hosts[2].ip4), + ("lease_time", 43200), + ("renewal_time", 2), + "end", + ] + ) + ) self.pg3.add_stream(p_ack) self.pg_enable_capture(self.pg_interfaces) @@ -1531,19 +1633,19 @@ class TestDHCP(VppTestCase): # clients = self.vapi.dhcp_client_dump() - self.assertEqual(clients[0].client.sw_if_index, - self.pg3.sw_if_index) - self.assertEqual(clients[0].lease.sw_if_index, - self.pg3.sw_if_index) + self.assertEqual(clients[0].client.sw_if_index, self.pg3.sw_if_index) + self.assertEqual(clients[0].lease.sw_if_index, self.pg3.sw_if_index) self.assertEqual(clients[0].client.hostname, hostname) self.assertEqual(clients[0].lease.hostname, hostname) # 0 = DISCOVER, 1 = REQUEST, 2 = BOUND self.assertEqual(clients[0].lease.state, 2) self.assertEqual(clients[0].lease.mask_width, 24) - self.assertEqual(str(clients[0].lease.router_address), - self.pg3.remote_hosts[1].ip4) - self.assertEqual(str(clients[0].lease.host_address), - self.pg3.remote_hosts[3].ip4) + self.assertEqual( + str(clients[0].lease.router_address), self.pg3.remote_hosts[1].ip4 + ) + self.assertEqual( + str(clients[0].lease.host_address), self.pg3.remote_hosts[3].ip4 + ) # # remove the DHCP config @@ -1577,39 +1679,51 @@ class TestDHCP(VppTestCase): # Send back on offer with requested lease time, expect the request # lease_time = 1 - p_offer = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) / - IP(src=self.pg3.remote_ip4, dst='255.255.255.255') / - UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT) / - BOOTP(op=1, - yiaddr=self.pg3.local_ip4, - chaddr=mac_pton(self.pg3.local_mac)) / - DHCP(options=[('message-type', 'offer'), - ('server_id', self.pg3.remote_ip4), - ('lease_time', lease_time), - 'end'])) + p_offer = ( + Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) + / IP(src=self.pg3.remote_ip4, dst="255.255.255.255") + / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT) + / BOOTP( + op=1, yiaddr=self.pg3.local_ip4, chaddr=mac_pton(self.pg3.local_mac) + ) + / DHCP( + options=[ + ("message-type", "offer"), + ("server_id", self.pg3.remote_ip4), + ("lease_time", lease_time), + "end", + ] + ) + ) self.pg3.add_stream(p_offer) self.pg_enable_capture(self.pg_interfaces) self.pg_start() rx = self.pg3.get_capture(1) - self.verify_orig_dhcp_request(rx[0], self.pg3, hostname, - self.pg3.local_ip4) + self.verify_orig_dhcp_request(rx[0], self.pg3, hostname, self.pg3.local_ip4) # # Send an acknowledgment # - p_ack = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) / - IP(src=self.pg3.remote_ip4, dst='255.255.255.255') / - UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT) / - BOOTP(op=1, yiaddr=self.pg3.local_ip4, - chaddr=mac_pton(self.pg3.local_mac)) / - DHCP(options=[('message-type', 'ack'), - ('subnet_mask', '255.255.255.0'), - ('router', self.pg3.remote_ip4), - ('server_id', self.pg3.remote_ip4), - ('lease_time', lease_time), - 'end'])) + p_ack = ( + Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) + / IP(src=self.pg3.remote_ip4, dst="255.255.255.255") + / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT) + / BOOTP( + op=1, yiaddr=self.pg3.local_ip4, chaddr=mac_pton(self.pg3.local_mac) + ) + / DHCP( + options=[ + ("message-type", "ack"), + ("subnet_mask", "255.255.255.0"), + ("router", self.pg3.remote_ip4), + ("server_id", self.pg3.remote_ip4), + ("lease_time", lease_time), + "end", + ] + ) + ) self.pg3.add_stream(p_ack) self.pg_enable_capture(self.pg_interfaces) @@ -1641,11 +1755,11 @@ class TestDHCP(VppTestCase): Client.remove_vpp_config() def test_dhcp_client_vlan(self): - """ DHCP Client w/ VLAN""" + """DHCP Client w/ VLAN""" vdscp = VppEnum.vl_api_ip_dscp_t vqos = VppEnum.vl_api_qos_source_t - hostname = 'universal-dp' + hostname = "universal-dp" self.pg_enable_capture(self.pg_interfaces) @@ -1653,24 +1767,20 @@ class TestDHCP(VppTestCase): vlan_100.admin_up() output = [scapy.compat.chb(4)] * 256 - os = b''.join(output) - rows = [{'outputs': os}, - {'outputs': os}, - {'outputs': os}, - {'outputs': os}] + os = b"".join(output) + rows = [{"outputs": os}, {"outputs": os}, {"outputs": os}, {"outputs": os}] qem1 = VppQosEgressMap(self, 1, rows).add_vpp_config() - qm1 = VppQosMark(self, vlan_100, qem1, - vqos.QOS_API_SOURCE_VLAN).add_vpp_config() + qm1 = VppQosMark( + self, vlan_100, qem1, vqos.QOS_API_SOURCE_VLAN + ).add_vpp_config() # # Configure DHCP client on PG3 and capture the discover sent # Client = VppDHCPClient( - self, - vlan_100.sw_if_index, - hostname, - dscp=vdscp.IP_API_DSCP_EF) + self, vlan_100.sw_if_index, hostname, dscp=vdscp.IP_API_DSCP_EF + ) Client.add_vpp_config() rx = self.pg3.get_capture(1) @@ -1678,9 +1788,10 @@ class TestDHCP(VppTestCase): self.assertEqual(rx[0][Dot1Q].vlan, 100) self.assertEqual(rx[0][Dot1Q].prio, 2) - self.verify_orig_dhcp_discover(rx[0], self.pg3, hostname, - dscp=vdscp.IP_API_DSCP_EF) + self.verify_orig_dhcp_discover( + rx[0], self.pg3, hostname, dscp=vdscp.IP_API_DSCP_EF + ) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_dhcp6.py b/test/test_dhcp6.py index 57eb113fb13..8a00cb81f90 100644 --- a/test/test_dhcp6.py +++ b/test/test_dhcp6.py @@ -1,10 +1,24 @@ from socket import AF_INET6, inet_ntop, inet_pton -from scapy.layers.dhcp6 import DHCP6_Advertise, DHCP6OptClientId, \ - DHCP6OptStatusCode, DHCP6OptPref, DHCP6OptIA_PD, DHCP6OptIAPrefix, \ - DHCP6OptServerId, DHCP6_Solicit, DHCP6_Reply, DHCP6_Request, DHCP6_Renew, \ - DHCP6_Rebind, DUID_LL, DHCP6_Release, DHCP6OptElapsedTime, DHCP6OptIA_NA, \ - DHCP6OptIAAddress +from scapy.layers.dhcp6 import ( + DHCP6_Advertise, + DHCP6OptClientId, + DHCP6OptStatusCode, + DHCP6OptPref, + DHCP6OptIA_PD, + DHCP6OptIAPrefix, + DHCP6OptServerId, + DHCP6_Solicit, + DHCP6_Reply, + DHCP6_Request, + DHCP6_Renew, + DHCP6_Rebind, + DUID_LL, + DHCP6_Release, + DHCP6OptElapsedTime, + DHCP6OptIA_NA, + DHCP6OptIAAddress, +) from scapy.layers.inet6 import IPv6, Ether, UDP from scapy.utils6 import in6_mactoifaceid @@ -21,7 +35,7 @@ def ip6_normalize(ip6): class TestDHCPv6DataPlane(VppTestCase): - """ DHCPv6 Data Plane Test Case """ + """DHCPv6 Data Plane Test Case""" @classmethod def setUpClass(cls): @@ -49,25 +63,23 @@ class TestDHCPv6DataPlane(VppTestCase): super(TestDHCPv6DataPlane, self).tearDown() def test_dhcp_ia_na_send_solicit_receive_advertise(self): - """ Verify DHCPv6 IA NA Solicit packet and Advertise event """ + """Verify DHCPv6 IA NA Solicit packet and Advertise event""" self.vapi.dhcp6_clients_enable_disable(enable=1) self.pg_enable_capture(self.pg_interfaces) self.pg_start() - address = {'address': '1:2:3::5', - 'preferred_time': 60, - 'valid_time': 120} + address = {"address": "1:2:3::5", "preferred_time": 60, "valid_time": 120} self.vapi.dhcp6_send_client_message( - server_index=0xffffffff, + server_index=0xFFFFFFFF, mrc=1, msg_type=VppEnum.vl_api_dhcpv6_msg_type_t.DHCPV6_MSG_API_SOLICIT, sw_if_index=self.pg0.sw_if_index, T1=20, T2=40, addresses=[address], - n_addresses=len( - [address])) + n_addresses=len([address]), + ) rx_list = self.pg0.get_capture(1) self.assertEqual(len(rx_list), 1) packet = rx_list[0] @@ -89,27 +101,27 @@ class TestDHCPv6DataPlane(VppTestCase): self.assert_equal(ia_na.T2, 40) self.assert_equal(len(ia_na.ianaopts), 1) address = ia_na.ianaopts[0] - self.assert_equal(address.addr, '1:2:3::5') + self.assert_equal(address.addr, "1:2:3::5") self.assert_equal(address.preflft, 60) self.assert_equal(address.validlft, 120) - self.vapi.want_dhcp6_reply_events(enable_disable=1, - pid=os.getpid()) + self.vapi.want_dhcp6_reply_events(enable_disable=1, pid=os.getpid()) try: - ia_na_opts = DHCP6OptIAAddress(addr='7:8::2', preflft=60, - validlft=120) - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IPv6(src=util.mk_ll_addr(self.pg0.remote_mac), - dst=self.pg0.local_ip6_ll) / - UDP(sport=547, dport=546) / - DHCP6_Advertise(trid=trid) / - DHCP6OptServerId(duid=self.server_duid) / - DHCP6OptClientId(duid=client_duid) / - DHCP6OptPref(prefval=7) / - DHCP6OptStatusCode(statuscode=1) / - DHCP6OptIA_NA(iaid=1, T1=20, T2=40, ianaopts=ia_na_opts) - ) + ia_na_opts = DHCP6OptIAAddress(addr="7:8::2", preflft=60, validlft=120) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6( + src=util.mk_ll_addr(self.pg0.remote_mac), dst=self.pg0.local_ip6_ll + ) + / UDP(sport=547, dport=546) + / DHCP6_Advertise(trid=trid) + / DHCP6OptServerId(duid=self.server_duid) + / DHCP6OptClientId(duid=client_duid) + / DHCP6OptPref(prefval=7) + / DHCP6OptStatusCode(statuscode=1) + / DHCP6OptIA_NA(iaid=1, T1=20, T2=40, ianaopts=ia_na_opts) + ) self.pg0.add_stream([p]) self.pg_start() @@ -123,36 +135,41 @@ class TestDHCPv6DataPlane(VppTestCase): reported_address = ev.addresses[0] address = ia_na_opts.getfieldval("addr") self.assert_equal(str(reported_address.address), address) - self.assert_equal(reported_address.preferred_time, - ia_na_opts.getfieldval("preflft")) - self.assert_equal(reported_address.valid_time, - ia_na_opts.getfieldval("validlft")) + self.assert_equal( + reported_address.preferred_time, ia_na_opts.getfieldval("preflft") + ) + self.assert_equal( + reported_address.valid_time, ia_na_opts.getfieldval("validlft") + ) finally: self.vapi.want_dhcp6_reply_events(enable_disable=0) self.vapi.dhcp6_clients_enable_disable(enable=0) def test_dhcp_pd_send_solicit_receive_advertise(self): - """ Verify DHCPv6 PD Solicit packet and Advertise event """ + """Verify DHCPv6 PD Solicit packet and Advertise event""" self.vapi.dhcp6_clients_enable_disable(enable=1) self.pg_enable_capture(self.pg_interfaces) self.pg_start() - prefix = {'prefix': {'address': '1:2:3::', 'len': 50}, - 'preferred_time': 60, - 'valid_time': 120} + prefix = { + "prefix": {"address": "1:2:3::", "len": 50}, + "preferred_time": 60, + "valid_time": 120, + } prefixes = [prefix] self.vapi.dhcp6_pd_send_client_message( - server_index=0xffffffff, + server_index=0xFFFFFFFF, mrc=1, msg_type=VppEnum.vl_api_dhcpv6_msg_type_t.DHCPV6_MSG_API_SOLICIT, sw_if_index=self.pg0.sw_if_index, T1=20, T2=40, prefixes=prefixes, - n_prefixes=len(prefixes)) + n_prefixes=len(prefixes), + ) rx_list = self.pg0.get_capture(1) self.assertEqual(len(rx_list), 1) packet = rx_list[0] @@ -174,28 +191,30 @@ class TestDHCPv6DataPlane(VppTestCase): self.assert_equal(ia_pd.T2, 40) self.assert_equal(len(ia_pd.iapdopt), 1) prefix = ia_pd.iapdopt[0] - self.assert_equal(prefix.prefix, '1:2:3::') + self.assert_equal(prefix.prefix, "1:2:3::") self.assert_equal(prefix.plen, 50) self.assert_equal(prefix.preflft, 60) self.assert_equal(prefix.validlft, 120) - self.vapi.want_dhcp6_pd_reply_events(enable_disable=1, - pid=os.getpid()) + self.vapi.want_dhcp6_pd_reply_events(enable_disable=1, pid=os.getpid()) try: - ia_pd_opts = DHCP6OptIAPrefix(prefix='7:8::', plen=56, preflft=60, - validlft=120) - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IPv6(src=util.mk_ll_addr(self.pg0.remote_mac), - dst=self.pg0.local_ip6_ll) / - UDP(sport=547, dport=546) / - DHCP6_Advertise(trid=trid) / - DHCP6OptServerId(duid=self.server_duid) / - DHCP6OptClientId(duid=client_duid) / - DHCP6OptPref(prefval=7) / - DHCP6OptStatusCode(statuscode=1) / - DHCP6OptIA_PD(iaid=1, T1=20, T2=40, iapdopt=ia_pd_opts) - ) + ia_pd_opts = DHCP6OptIAPrefix( + prefix="7:8::", plen=56, preflft=60, validlft=120 + ) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6( + src=util.mk_ll_addr(self.pg0.remote_mac), dst=self.pg0.local_ip6_ll + ) + / UDP(sport=547, dport=546) + / DHCP6_Advertise(trid=trid) + / DHCP6OptServerId(duid=self.server_duid) + / DHCP6OptClientId(duid=client_duid) + / DHCP6OptPref(prefval=7) + / DHCP6OptStatusCode(statuscode=1) + / DHCP6OptIA_PD(iaid=1, T1=20, T2=40, iapdopt=ia_pd_opts) + ) self.pg0.add_stream([p]) self.pg_start() @@ -208,14 +227,17 @@ class TestDHCPv6DataPlane(VppTestCase): reported_prefix = ev.prefixes[0] prefix = ia_pd_opts.getfieldval("prefix") + self.assert_equal(str(reported_prefix.prefix).split("/")[0], prefix) + self.assert_equal( + int(str(reported_prefix.prefix).split("/")[1]), + ia_pd_opts.getfieldval("plen"), + ) self.assert_equal( - str(reported_prefix.prefix).split('/')[0], prefix) - self.assert_equal(int(str(reported_prefix.prefix).split('/')[1]), - ia_pd_opts.getfieldval("plen")) - self.assert_equal(reported_prefix.preferred_time, - ia_pd_opts.getfieldval("preflft")) - self.assert_equal(reported_prefix.valid_time, - ia_pd_opts.getfieldval("validlft")) + reported_prefix.preferred_time, ia_pd_opts.getfieldval("preflft") + ) + self.assert_equal( + reported_prefix.valid_time, ia_pd_opts.getfieldval("validlft") + ) finally: self.vapi.want_dhcp6_pd_reply_events(enable_disable=0) @@ -224,7 +246,7 @@ class TestDHCPv6DataPlane(VppTestCase): @tag_run_solo class TestDHCPv6IANAControlPlane(VppTestCase): - """ DHCPv6 IA NA Control Plane Test Case """ + """DHCPv6 IA NA Control Plane Test Case""" @classmethod def setUpClass(cls): @@ -248,18 +270,19 @@ class TestDHCPv6IANAControlPlane(VppTestCase): self.T2 = 2 fib = self.vapi.ip_route_dump(0, True) - self.initial_addresses = set(self.get_interface_addresses(fib, - self.pg0)) + self.initial_addresses = set(self.get_interface_addresses(fib, self.pg0)) self.pg_enable_capture(self.pg_interfaces) self.pg_start() - self.vapi.dhcp6_client_enable_disable(sw_if_index=self.pg0.sw_if_index, - enable=1) + self.vapi.dhcp6_client_enable_disable( + sw_if_index=self.pg0.sw_if_index, enable=1 + ) def tearDown(self): - self.vapi.dhcp6_client_enable_disable(sw_if_index=self.pg0.sw_if_index, - enable=0) + self.vapi.dhcp6_client_enable_disable( + sw_if_index=self.pg0.sw_if_index, enable=0 + ) for i in self.interfaces: i.admin_down() @@ -302,12 +325,12 @@ class TestDHCPv6IANAControlPlane(VppTestCase): self.trid = packet[msg_type].trid ip = packet[IPv6] udp = packet[UDP] - self.assertEqual(ip.dst, 'ff02::1:2') + self.assertEqual(ip.dst, "ff02::1:2") self.assertEqual(udp.sport, 546) self.assertEqual(udp.dport, 547) dhcpv6 = packet[msg_type] elapsed_time = dhcpv6[DHCP6OptElapsedTime] - if (is_resend): + if is_resend: self.assertNotEqual(elapsed_time.elapsedtime, 0) else: self.assertEqual(elapsed_time.elapsedtime, 0) @@ -346,15 +369,15 @@ class TestDHCPv6IANAControlPlane(VppTestCase): opt_ia_na = DHCP6OptIA_NA(iaid=1, T1=t1, T2=t2) else: opt_ia_na = DHCP6OptIA_NA(iaid=1, T1=t1, T2=t2, ianaopts=ianaopts) - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IPv6(src=util.mk_ll_addr(self.pg0.remote_mac), - dst=self.pg0.local_ip6_ll) / - UDP(sport=547, dport=546) / - msg_type(trid=self.trid) / - DHCP6OptServerId(duid=self.server_duid) / - DHCP6OptClientId(duid=self.client_duid) / - opt_ia_na - ) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=util.mk_ll_addr(self.pg0.remote_mac), dst=self.pg0.local_ip6_ll) + / UDP(sport=547, dport=546) + / msg_type(trid=self.trid) + / DHCP6OptServerId(duid=self.server_duid) + / DHCP6OptClientId(duid=self.client_duid) + / opt_ia_na + ) self.pg0.add_stream([p]) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -366,7 +389,7 @@ class TestDHCPv6IANAControlPlane(VppTestCase): self.send_packet(DHCP6_Reply, t1, t2, ianaopts) def test_T1_and_T2_timeouts(self): - """ Test T1 and T2 timeouts """ + """Test T1 and T2 timeouts""" self.wait_for_solicit() self.send_advertise() @@ -384,10 +407,9 @@ class TestDHCPv6IANAControlPlane(VppTestCase): self.wait_for_rebind() def test_addresses(self): - """ Test handling of addresses """ + """Test handling of addresses""" - ia_na_opts = DHCP6OptIAAddress(addr='7:8::2', preflft=1, - validlft=2) + ia_na_opts = DHCP6OptIAAddress(addr="7:8::2", preflft=1, validlft=2) self.wait_for_solicit() self.send_advertise(t1=20, t2=40, ianaopts=ia_na_opts) @@ -399,7 +421,7 @@ class TestDHCPv6IANAControlPlane(VppTestCase): new_addresses = self.get_addresses() self.assertEqual(len(new_addresses), 1) addr = list(new_addresses)[0] - self.assertEqual(addr, '7:8::2') + self.assertEqual(addr, "7:8::2") self.sleep(2) @@ -410,7 +432,7 @@ class TestDHCPv6IANAControlPlane(VppTestCase): self.assertEqual(len(new_addresses), 0) def test_sending_client_messages_solicit(self): - """ VPP receives messages from DHCPv6 client """ + """VPP receives messages from DHCPv6 client""" self.wait_for_solicit() self.send_packet(DHCP6_Solicit) @@ -421,7 +443,7 @@ class TestDHCPv6IANAControlPlane(VppTestCase): self.wait_for_solicit(is_resend=True) def test_sending_inappropriate_packets(self): - """ Server sends messages with inappropriate message types """ + """Server sends messages with inappropriate message types""" self.wait_for_solicit() self.send_reply() @@ -434,7 +456,7 @@ class TestDHCPv6IANAControlPlane(VppTestCase): self.wait_for_renew() def test_no_address_available_in_advertise(self): - """ Advertise message contains NoAddrsAvail status code """ + """Advertise message contains NoAddrsAvail status code""" self.wait_for_solicit() noavail = DHCP6OptStatusCode(statuscode=2) # NoAddrsAvail @@ -442,12 +464,12 @@ class TestDHCPv6IANAControlPlane(VppTestCase): self.wait_for_solicit(is_resend=True) def test_preferred_greater_than_valid_lifetime(self): - """ Preferred lifetime is greater than valid lifetime """ + """Preferred lifetime is greater than valid lifetime""" self.wait_for_solicit() self.send_advertise() self.wait_for_request() - ia_na_opts = DHCP6OptIAAddress(addr='7:8::2', preflft=4, validlft=3) + ia_na_opts = DHCP6OptIAAddress(addr="7:8::2", preflft=4, validlft=3) self.send_reply(ianaopts=ia_na_opts) self.sleep(0.5) @@ -459,12 +481,12 @@ class TestDHCPv6IANAControlPlane(VppTestCase): self.assertEqual(len(new_addresses), 0) def test_T1_greater_than_T2(self): - """ T1 is greater than T2 """ + """T1 is greater than T2""" self.wait_for_solicit() self.send_advertise() self.wait_for_request() - ia_na_opts = DHCP6OptIAAddress(addr='7:8::2', preflft=4, validlft=8) + ia_na_opts = DHCP6OptIAAddress(addr="7:8::2", preflft=4, validlft=8) self.send_reply(t1=80, t2=40, ianaopts=ia_na_opts) self.sleep(0.5) @@ -478,7 +500,7 @@ class TestDHCPv6IANAControlPlane(VppTestCase): @tag_fixme_vpp_workers class TestDHCPv6PDControlPlane(VppTestCase): - """ DHCPv6 PD Control Plane Test Case """ + """DHCPv6 PD Control Plane Test Case""" @classmethod def setUpClass(cls): @@ -502,22 +524,19 @@ class TestDHCPv6PDControlPlane(VppTestCase): self.T2 = 2 fib = self.vapi.ip_route_dump(0, True) - self.initial_addresses = set(self.get_interface_addresses(fib, - self.pg1)) + self.initial_addresses = set(self.get_interface_addresses(fib, self.pg1)) self.pg_enable_capture(self.pg_interfaces) self.pg_start() - self.prefix_group = 'my-pd-prefix-group' + self.prefix_group = "my-pd-prefix-group" self.vapi.dhcp6_pd_client_enable_disable( - enable=1, - sw_if_index=self.pg0.sw_if_index, - prefix_group=self.prefix_group) + enable=1, sw_if_index=self.pg0.sw_if_index, prefix_group=self.prefix_group + ) def tearDown(self): - self.vapi.dhcp6_pd_client_enable_disable(self.pg0.sw_if_index, - enable=0) + self.vapi.dhcp6_pd_client_enable_disable(self.pg0.sw_if_index, enable=0) for i in self.interfaces: i.admin_down() @@ -560,12 +579,12 @@ class TestDHCPv6PDControlPlane(VppTestCase): self.trid = packet[msg_type].trid ip = packet[IPv6] udp = packet[UDP] - self.assertEqual(ip.dst, 'ff02::1:2') + self.assertEqual(ip.dst, "ff02::1:2") self.assertEqual(udp.sport, 546) self.assertEqual(udp.dport, 547) dhcpv6 = packet[msg_type] elapsed_time = dhcpv6[DHCP6OptElapsedTime] - if (is_resend): + if is_resend: self.assertNotEqual(elapsed_time.elapsedtime, 0) else: self.assertEqual(elapsed_time.elapsedtime, 0) @@ -604,15 +623,15 @@ class TestDHCPv6PDControlPlane(VppTestCase): opt_ia_pd = DHCP6OptIA_PD(iaid=1, T1=t1, T2=t2) else: opt_ia_pd = DHCP6OptIA_PD(iaid=1, T1=t1, T2=t2, iapdopt=iapdopt) - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IPv6(src=util.mk_ll_addr(self.pg0.remote_mac), - dst=self.pg0.local_ip6_ll) / - UDP(sport=547, dport=546) / - msg_type(trid=self.trid) / - DHCP6OptServerId(duid=self.server_duid) / - DHCP6OptClientId(duid=self.client_duid) / - opt_ia_pd - ) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=util.mk_ll_addr(self.pg0.remote_mac), dst=self.pg0.local_ip6_ll) + / UDP(sport=547, dport=546) + / msg_type(trid=self.trid) + / DHCP6OptServerId(duid=self.server_duid) + / DHCP6OptClientId(duid=self.client_duid) + / opt_ia_pd + ) self.pg0.add_stream([p]) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -624,7 +643,7 @@ class TestDHCPv6PDControlPlane(VppTestCase): self.send_packet(DHCP6_Reply, t1, t2, iapdopt) def test_T1_and_T2_timeouts(self): - """ Test T1 and T2 timeouts """ + """Test T1 and T2 timeouts""" self.wait_for_solicit() self.send_advertise() @@ -642,18 +661,20 @@ class TestDHCPv6PDControlPlane(VppTestCase): self.wait_for_rebind() def test_prefixes(self): - """ Test handling of prefixes """ + """Test handling of prefixes""" - address1 = '::2:0:0:0:405/60' - address2 = '::76:0:0:0:406/62' + address1 = "::2:0:0:0:405/60" + address2 = "::76:0:0:0:406/62" try: self.vapi.ip6_add_del_address_using_prefix( sw_if_index=self.pg1.sw_if_index, address_with_prefix=address1, - prefix_group=self.prefix_group) + prefix_group=self.prefix_group, + ) - ia_pd_opts = DHCP6OptIAPrefix(prefix='7:8::', plen=56, preflft=2, - validlft=3) + ia_pd_opts = DHCP6OptIAPrefix( + prefix="7:8::", plen=56, preflft=2, validlft=3 + ) self.wait_for_solicit() self.send_advertise(t1=20, t2=40, iapdopt=ia_pd_opts) @@ -665,14 +686,15 @@ class TestDHCPv6PDControlPlane(VppTestCase): new_addresses = self.get_addresses() self.assertEqual(len(new_addresses), 1) addr = list(new_addresses)[0] - self.assertEqual(addr, '7:8:0:2::405') + self.assertEqual(addr, "7:8:0:2::405") self.sleep(1) self.vapi.ip6_add_del_address_using_prefix( sw_if_index=self.pg1.sw_if_index, address_with_prefix=address2, - prefix_group=self.prefix_group) + prefix_group=self.prefix_group, + ) self.sleep(1) @@ -683,10 +705,10 @@ class TestDHCPv6PDControlPlane(VppTestCase): self.assertEqual(len(new_addresses), 2) addr1 = list(new_addresses)[0] addr2 = list(new_addresses)[1] - if addr1 == '7:8:0:76::406': + if addr1 == "7:8:0:76::406": addr1, addr2 = addr2, addr1 - self.assertEqual(addr1, '7:8:0:2::405') - self.assertEqual(addr2, '7:8:0:76::406') + self.assertEqual(addr1, "7:8:0:2::405") + self.assertEqual(addr2, "7:8:0:76::406") self.sleep(1) @@ -701,15 +723,19 @@ class TestDHCPv6PDControlPlane(VppTestCase): self.vapi.ip6_add_del_address_using_prefix( sw_if_index=self.pg1.sw_if_index, address_with_prefix=address1, - prefix_group=self.prefix_group, is_add=0) + prefix_group=self.prefix_group, + is_add=0, + ) if address2 is not None: self.vapi.ip6_add_del_address_using_prefix( sw_if_index=self.pg1.sw_if_index, address_with_prefix=address2, - prefix_group=self.prefix_group, is_add=0) + prefix_group=self.prefix_group, + is_add=0, + ) def test_sending_client_messages_solicit(self): - """ VPP receives messages from DHCPv6 client """ + """VPP receives messages from DHCPv6 client""" self.wait_for_solicit() self.send_packet(DHCP6_Solicit) @@ -720,7 +746,7 @@ class TestDHCPv6PDControlPlane(VppTestCase): self.wait_for_solicit(is_resend=True) def test_sending_inappropriate_packets(self): - """ Server sends messages with inappropriate message types """ + """Server sends messages with inappropriate message types""" self.wait_for_solicit() self.send_reply() @@ -733,7 +759,7 @@ class TestDHCPv6PDControlPlane(VppTestCase): self.wait_for_renew() def test_no_prefix_available_in_advertise(self): - """ Advertise message contains NoPrefixAvail status code """ + """Advertise message contains NoPrefixAvail status code""" self.wait_for_solicit() noavail = DHCP6OptStatusCode(statuscode=6) # NoPrefixAvail @@ -741,20 +767,22 @@ class TestDHCPv6PDControlPlane(VppTestCase): self.wait_for_solicit(is_resend=True) def test_preferred_greater_than_valid_lifetime(self): - """ Preferred lifetime is greater than valid lifetime """ + """Preferred lifetime is greater than valid lifetime""" - address1 = '::2:0:0:0:405/60' + address1 = "::2:0:0:0:405/60" try: self.vapi.ip6_add_del_address_using_prefix( sw_if_index=self.pg1.sw_if_index, address_with_prefix=address1, - prefix_group=self.prefix_group) + prefix_group=self.prefix_group, + ) self.wait_for_solicit() self.send_advertise() self.wait_for_request() - ia_pd_opts = DHCP6OptIAPrefix(prefix='7:8::', plen=56, preflft=4, - validlft=3) + ia_pd_opts = DHCP6OptIAPrefix( + prefix="7:8::", plen=56, preflft=4, validlft=3 + ) self.send_reply(iapdopt=ia_pd_opts) self.sleep(0.5) @@ -770,23 +798,26 @@ class TestDHCPv6PDControlPlane(VppTestCase): sw_if_index=self.pg1.sw_if_index, address_with_prefix=address1, prefix_group=self.prefix_group, - is_add=0) + is_add=0, + ) def test_T1_greater_than_T2(self): - """ T1 is greater than T2 """ + """T1 is greater than T2""" - address1 = '::2:0:0:0:405/60' + address1 = "::2:0:0:0:405/60" try: self.vapi.ip6_add_del_address_using_prefix( sw_if_index=self.pg1.sw_if_index, address_with_prefix=address1, - prefix_group=self.prefix_group) + prefix_group=self.prefix_group, + ) self.wait_for_solicit() self.send_advertise() self.wait_for_request() - ia_pd_opts = DHCP6OptIAPrefix(prefix='7:8::', plen=56, preflft=4, - validlft=8) + ia_pd_opts = DHCP6OptIAPrefix( + prefix="7:8::", plen=56, preflft=4, validlft=8 + ) self.send_reply(t1=80, t2=40, iapdopt=ia_pd_opts) self.sleep(0.5) @@ -802,4 +833,5 @@ class TestDHCPv6PDControlPlane(VppTestCase): sw_if_index=self.pg1.sw_if_index, prefix_group=self.prefix_group, address_with_prefix=address1, - is_add=False) + is_add=False, + ) diff --git a/test/test_dns.py b/test/test_dns.py index fb8958c511b..acc9bfe889c 100644 --- a/test/test_dns.py +++ b/test/test_dns.py @@ -15,7 +15,7 @@ from scapy.layers.dns import DNSRR, DNS, DNSQR class TestDns(VppTestCase): - """ Dns Test Cases """ + """Dns Test Cases""" @classmethod def setUpClass(cls): @@ -43,15 +43,19 @@ class TestDns(VppTestCase): :param VppInterface src_if: Interface to create packet stream for. """ - good_request = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - IP(src=src_if.remote_ip4) / - UDP(sport=1234, dport=53) / - DNS(rd=1, qd=DNSQR(qname="bozo.clown.org"))) - - bad_request = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - IP(src=src_if.remote_ip4) / - UDP(sport=1234, dport=53) / - DNS(rd=1, qd=DNSQR(qname="no.clown.org"))) + good_request = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / IP(src=src_if.remote_ip4) + / UDP(sport=1234, dport=53) + / DNS(rd=1, qd=DNSQR(qname="bozo.clown.org")) + ) + + bad_request = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / IP(src=src_if.remote_ip4) + / UDP(sport=1234, dport=53) + / DNS(rd=1, qd=DNSQR(qname="no.clown.org")) + ) pkts = [good_request, bad_request] return pkts @@ -65,14 +69,15 @@ class TestDns(VppTestCase): self.logger.info("Verifying capture on interface %s" % dst_if.name) for packet in capture: dns = packet[DNS] - self.assertEqual(dns.an[0].rdata, '1.2.3.4') + self.assertEqual(dns.an[0].rdata, "1.2.3.4") def test_dns_unittest(self): - """ DNS Name Resolver Basic Functional Test """ + """DNS Name Resolver Basic Functional Test""" # Set up an upstream name resolver. We won't actually go there self.vapi.dns_name_server_add_del( - is_ip6=0, is_add=1, server_address=IPv4Address(u'8.8.8.8').packed) + is_ip6=0, is_add=1, server_address=IPv4Address("8.8.8.8").packed + ) # Enable name resolution self.vapi.dns_enable_disable(enable=1) @@ -81,13 +86,13 @@ class TestDns(VppTestCase): self.logger.info(self.vapi.cli("dns cache add bozo.clown.org 1.2.3.4")) # Test the binary API - rv = self.vapi.dns_resolve_name(name=b'bozo.clown.org') - self.assertEqual(rv.ip4_address, IPv4Address(u'1.2.3.4').packed) + rv = self.vapi.dns_resolve_name(name=b"bozo.clown.org") + self.assertEqual(rv.ip4_address, IPv4Address("1.2.3.4").packed) # Configure 127.0.0.1/8 on the pg interface self.vapi.sw_interface_add_del_address( - sw_if_index=self.pg0.sw_if_index, - prefix="127.0.0.1/8") + sw_if_index=self.pg0.sw_if_index, prefix="127.0.0.1/8" + ) # Send a couple of DNS request packets, one for bozo.clown.org # and one for no.clown.org which won't resolve @@ -102,8 +107,9 @@ class TestDns(VppTestCase): # Make sure that the cache contents are correct str = self.vapi.cli("show dns cache verbose") - self.assertIn('1.2.3.4', str) - self.assertIn('[P] no.clown.org:', str) + self.assertIn("1.2.3.4", str) + self.assertIn("[P] no.clown.org:", str) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_dslite.py b/test/test_dslite.py index 912ae17da58..cd3482b1cb5 100644 --- a/test/test_dslite.py +++ b/test/test_dslite.py @@ -11,8 +11,15 @@ from framework import VppTestCase, VppTestRunner import scapy.compat from scapy.layers.inet import IP, TCP, UDP, ICMP from scapy.layers.inet import IPerror, TCPerror, UDPerror, ICMPerror -from scapy.layers.inet6 import IPv6, ICMPv6EchoRequest, ICMPv6EchoReply, \ - ICMPv6ND_NS, ICMPv6ND_NA, ICMPv6NDOptDstLLAddr, fragment6 +from scapy.layers.inet6 import ( + IPv6, + ICMPv6EchoRequest, + ICMPv6EchoReply, + ICMPv6ND_NS, + ICMPv6ND_NA, + ICMPv6NDOptDstLLAddr, + fragment6, +) from scapy.layers.inet6 import ICMPv6DestUnreach, IPerror6, IPv6ExtHdrFragment from scapy.layers.l2 import Ether, ARP, GRE from scapy.data import IP_PROTOS @@ -28,22 +35,32 @@ from io import BytesIO from vpp_papi import VppEnum from vpp_ip_route import VppIpRoute, VppRoutePath, FibPathType from vpp_neighbor import VppNeighbor -from scapy.all import bind_layers, Packet, ByteEnumField, ShortField, \ - IPField, IntField, LongField, XByteField, FlagsField, FieldLenField, \ - PacketListField +from scapy.all import ( + bind_layers, + Packet, + ByteEnumField, + ShortField, + IPField, + IntField, + LongField, + XByteField, + FlagsField, + FieldLenField, + PacketListField, +) from ipaddress import IPv6Network @tag_fixme_vpp_workers class TestDSlite(VppTestCase): - """ DS-Lite Test Cases """ + """DS-Lite Test Cases""" @classmethod def setUpClass(cls): super(TestDSlite, cls).setUpClass() try: - cls.nat_addr = '10.0.0.3' + cls.nat_addr = "10.0.0.3" cls.create_pg_interfaces(range(3)) cls.pg0.admin_up() @@ -65,44 +82,45 @@ class TestDSlite(VppTestCase): def tearDownClass(cls): super(TestDSlite, cls).tearDownClass() - def verify_syslog_apmadd(self, data, isaddr, isport, xsaddr, xsport, - sv6enc, proto): - message = data.decode('utf-8') + def verify_syslog_apmadd(self, data, isaddr, isport, xsaddr, xsport, sv6enc, proto): + message = data.decode("utf-8") try: message = SyslogMessage.parse(message) except ParseError as e: self.logger.error(e) else: self.assertEqual(message.severity, SyslogSeverity.info) - self.assertEqual(message.appname, 'NAT') - self.assertEqual(message.msgid, 'APMADD') - sd_params = message.sd.get('napmap') + self.assertEqual(message.appname, "NAT") + self.assertEqual(message.msgid, "APMADD") + sd_params = message.sd.get("napmap") self.assertTrue(sd_params is not None) - self.assertEqual(sd_params.get('IATYP'), 'IPv4') - self.assertEqual(sd_params.get('ISADDR'), isaddr) - self.assertEqual(sd_params.get('ISPORT'), "%d" % isport) - self.assertEqual(sd_params.get('XATYP'), 'IPv4') - self.assertEqual(sd_params.get('XSADDR'), xsaddr) - self.assertEqual(sd_params.get('XSPORT'), "%d" % xsport) - self.assertEqual(sd_params.get('PROTO'), "%d" % proto) - self.assertTrue(sd_params.get('SSUBIX') is not None) - self.assertEqual(sd_params.get('SV6ENC'), sv6enc) + self.assertEqual(sd_params.get("IATYP"), "IPv4") + self.assertEqual(sd_params.get("ISADDR"), isaddr) + self.assertEqual(sd_params.get("ISPORT"), "%d" % isport) + self.assertEqual(sd_params.get("XATYP"), "IPv4") + self.assertEqual(sd_params.get("XSADDR"), xsaddr) + self.assertEqual(sd_params.get("XSPORT"), "%d" % xsport) + self.assertEqual(sd_params.get("PROTO"), "%d" % proto) + self.assertTrue(sd_params.get("SSUBIX") is not None) + self.assertEqual(sd_params.get("SV6ENC"), sv6enc) def test_dslite(self): - """ Test DS-Lite """ - self.vapi.dslite_add_del_pool_addr_range(start_addr=self.nat_addr, - end_addr=self.nat_addr, - is_add=1) - aftr_ip4 = '192.0.0.1' - aftr_ip6 = '2001:db8:85a3::8a2e:370:1' + """Test DS-Lite""" + self.vapi.dslite_add_del_pool_addr_range( + start_addr=self.nat_addr, end_addr=self.nat_addr, is_add=1 + ) + aftr_ip4 = "192.0.0.1" + aftr_ip6 = "2001:db8:85a3::8a2e:370:1" self.vapi.dslite_set_aftr_addr(ip4_addr=aftr_ip4, ip6_addr=aftr_ip6) self.vapi.syslog_set_sender(self.pg2.local_ip4, self.pg2.remote_ip4) # UDP - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IPv6(dst=aftr_ip6, src=self.pg1.remote_hosts[0].ip6) / - IP(dst=self.pg0.remote_ip4, src='192.168.1.1') / - UDP(sport=20000, dport=10000)) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(dst=aftr_ip6, src=self.pg1.remote_hosts[0].ip6) + / IP(dst=self.pg0.remote_ip4, src="192.168.1.1") + / UDP(sport=20000, dport=10000) + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -116,13 +134,21 @@ class TestDSlite(VppTestCase): self.assert_packet_checksums_valid(capture) out_port = capture[UDP].sport capture = self.pg2.get_capture(1) - self.verify_syslog_apmadd(capture[0][Raw].load, '192.168.1.1', - 20000, self.nat_addr, out_port, - self.pg1.remote_hosts[0].ip6, IP_PROTOS.udp) - - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(dst=self.nat_addr, src=self.pg0.remote_ip4) / - UDP(sport=10000, dport=out_port)) + self.verify_syslog_apmadd( + capture[0][Raw].load, + "192.168.1.1", + 20000, + self.nat_addr, + out_port, + self.pg1.remote_hosts[0].ip6, + IP_PROTOS.udp, + ) + + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(dst=self.nat_addr, src=self.pg0.remote_ip4) + / UDP(sport=10000, dport=out_port) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -131,16 +157,18 @@ class TestDSlite(VppTestCase): self.assertEqual(capture[IPv6].src, aftr_ip6) self.assertEqual(capture[IPv6].dst, self.pg1.remote_hosts[0].ip6) self.assertEqual(capture[IP].src, self.pg0.remote_ip4) - self.assertEqual(capture[IP].dst, '192.168.1.1') + self.assertEqual(capture[IP].dst, "192.168.1.1") self.assertEqual(capture[UDP].sport, 10000) self.assertEqual(capture[UDP].dport, 20000) self.assert_packet_checksums_valid(capture) # TCP - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IPv6(dst=aftr_ip6, src=self.pg1.remote_hosts[1].ip6) / - IP(dst=self.pg0.remote_ip4, src='192.168.1.1') / - TCP(sport=20001, dport=10001)) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(dst=aftr_ip6, src=self.pg1.remote_hosts[1].ip6) + / IP(dst=self.pg0.remote_ip4, src="192.168.1.1") + / TCP(sport=20001, dport=10001) + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -154,9 +182,11 @@ class TestDSlite(VppTestCase): self.assert_packet_checksums_valid(capture) out_port = capture[TCP].sport - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(dst=self.nat_addr, src=self.pg0.remote_ip4) / - TCP(sport=10001, dport=out_port)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(dst=self.nat_addr, src=self.pg0.remote_ip4) + / TCP(sport=10001, dport=out_port) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -165,16 +195,18 @@ class TestDSlite(VppTestCase): self.assertEqual(capture[IPv6].src, aftr_ip6) self.assertEqual(capture[IPv6].dst, self.pg1.remote_hosts[1].ip6) self.assertEqual(capture[IP].src, self.pg0.remote_ip4) - self.assertEqual(capture[IP].dst, '192.168.1.1') + self.assertEqual(capture[IP].dst, "192.168.1.1") self.assertEqual(capture[TCP].sport, 10001) self.assertEqual(capture[TCP].dport, 20001) self.assert_packet_checksums_valid(capture) # ICMP - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IPv6(dst=aftr_ip6, src=self.pg1.remote_hosts[1].ip6) / - IP(dst=self.pg0.remote_ip4, src='192.168.1.1') / - ICMP(id=4000, type='echo-request')) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(dst=aftr_ip6, src=self.pg1.remote_hosts[1].ip6) + / IP(dst=self.pg0.remote_ip4, src="192.168.1.1") + / ICMP(id=4000, type="echo-request") + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -187,9 +219,11 @@ class TestDSlite(VppTestCase): self.assert_packet_checksums_valid(capture) out_id = capture[ICMP].id - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(dst=self.nat_addr, src=self.pg0.remote_ip4) / - ICMP(id=out_id, type='echo-reply')) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(dst=self.nat_addr, src=self.pg0.remote_ip4) + / ICMP(id=out_id, type="echo-reply") + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -198,14 +232,16 @@ class TestDSlite(VppTestCase): self.assertEqual(capture[IPv6].src, aftr_ip6) self.assertEqual(capture[IPv6].dst, self.pg1.remote_hosts[1].ip6) self.assertEqual(capture[IP].src, self.pg0.remote_ip4) - self.assertEqual(capture[IP].dst, '192.168.1.1') + self.assertEqual(capture[IP].dst, "192.168.1.1") self.assertEqual(capture[ICMP].id, 4000) self.assert_packet_checksums_valid(capture) # ping DS-Lite AFTR tunnel endpoint address - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IPv6(src=self.pg1.remote_hosts[1].ip6, dst=aftr_ip6) / - ICMPv6EchoRequest()) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(src=self.pg1.remote_hosts[1].ip6, dst=aftr_ip6) + / ICMPv6EchoRequest() + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -215,9 +251,9 @@ class TestDSlite(VppTestCase): self.assertEqual(capture[IPv6].dst, self.pg1.remote_hosts[1].ip6) self.assertTrue(capture.haslayer(ICMPv6EchoReply)) - b4s = self.statistics.get_counter('/dslite/total-b4s') + b4s = self.statistics.get_counter("/dslite/total-b4s") self.assertEqual(b4s[0][0], 2) - sessions = self.statistics.get_counter('/dslite/total-sessions') + sessions = self.statistics.get_counter("/dslite/total-sessions") self.assertEqual(sessions[0][0], 3) def tearDown(self): @@ -225,13 +261,12 @@ class TestDSlite(VppTestCase): def show_commands_at_teardown(self): self.logger.info(self.vapi.cli("show dslite pool")) - self.logger.info( - self.vapi.cli("show dslite aftr-tunnel-endpoint-address")) + self.logger.info(self.vapi.cli("show dslite aftr-tunnel-endpoint-address")) self.logger.info(self.vapi.cli("show dslite sessions")) class TestDSliteCE(VppTestCase): - """ DS-Lite CE Test Cases """ + """DS-Lite CE Test Cases""" @classmethod def setUpConstants(cls): @@ -261,25 +296,30 @@ class TestDSliteCE(VppTestCase): super(TestDSliteCE, cls).tearDownClass() def test_dslite_ce(self): - """ Test DS-Lite CE """ - b4_ip4 = '192.0.0.2' - b4_ip6 = '2001:db8:62aa::375e:f4c1:1' + """Test DS-Lite CE""" + b4_ip4 = "192.0.0.2" + b4_ip6 = "2001:db8:62aa::375e:f4c1:1" self.vapi.dslite_set_b4_addr(ip4_addr=b4_ip4, ip6_addr=b4_ip6) - aftr_ip4 = '192.0.0.1' - aftr_ip6 = '2001:db8:85a3::8a2e:370:1' + aftr_ip4 = "192.0.0.1" + aftr_ip6 = "2001:db8:85a3::8a2e:370:1" aftr_ip6_n = socket.inet_pton(socket.AF_INET6, aftr_ip6) self.vapi.dslite_set_aftr_addr(ip4_addr=aftr_ip4, ip6_addr=aftr_ip6) - r1 = VppIpRoute(self, aftr_ip6, 128, - [VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index)]) + r1 = VppIpRoute( + self, + aftr_ip6, + 128, + [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)], + ) r1.add_vpp_config() # UDP encapsulation - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(dst=self.pg1.remote_ip4, src=self.pg0.remote_ip4) / - UDP(sport=10000, dport=20000)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(dst=self.pg1.remote_ip4, src=self.pg0.remote_ip4) + / UDP(sport=10000, dport=20000) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -294,10 +334,12 @@ class TestDSliteCE(VppTestCase): self.assert_packet_checksums_valid(capture) # UDP decapsulation - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IPv6(dst=b4_ip6, src=aftr_ip6) / - IP(dst=self.pg0.remote_ip4, src=self.pg1.remote_ip4) / - UDP(sport=20000, dport=10000)) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(dst=b4_ip6, src=aftr_ip6) + / IP(dst=self.pg0.remote_ip4, src=self.pg1.remote_ip4) + / UDP(sport=20000, dport=10000) + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -311,9 +353,11 @@ class TestDSliteCE(VppTestCase): self.assert_packet_checksums_valid(capture) # ping DS-Lite B4 tunnel endpoint address - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IPv6(src=self.pg1.remote_hosts[0].ip6, dst=b4_ip6) / - ICMPv6EchoRequest()) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(src=self.pg1.remote_hosts[0].ip6, dst=b4_ip6) + / ICMPv6EchoRequest() + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -327,7 +371,5 @@ class TestDSliteCE(VppTestCase): super(TestDSliteCE, self).tearDown() def show_commands_at_teardown(self): - self.logger.info( - self.vapi.cli("show dslite aftr-tunnel-endpoint-address")) - self.logger.info( - self.vapi.cli("show dslite b4-tunnel-endpoint-address")) + self.logger.info(self.vapi.cli("show dslite aftr-tunnel-endpoint-address")) + self.logger.info(self.vapi.cli("show dslite b4-tunnel-endpoint-address")) diff --git a/test/test_dvr.py b/test/test_dvr.py index c0424a3047f..cd2e09a9d46 100644 --- a/test/test_dvr.py +++ b/test/test_dvr.py @@ -17,7 +17,7 @@ NUM_PKTS = 67 class TestDVR(VppTestCase): - """ Distributed Virtual Router """ + """Distributed Virtual Router""" @classmethod def setUpClass(cls): @@ -62,7 +62,7 @@ class TestDVR(VppTestCase): self.assertFalse(p.haslayer(Dot1Q)) def test_dvr(self): - """ Distributed Virtual Router """ + """Distributed Virtual Router""" # # A packet destined to an IP address that is L2 bridged via @@ -72,18 +72,18 @@ class TestDVR(VppTestCase): ip_tag_bridged = "10.10.10.11" any_src_addr = "1.1.1.1" - pkt_no_tag = (Ether(src=self.pg0.remote_mac, - dst=self.loop0.local_mac) / - IP(src=any_src_addr, - dst=ip_non_tag_bridged) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - pkt_tag = (Ether(src=self.pg0.remote_mac, - dst=self.loop0.local_mac) / - IP(src=any_src_addr, - dst=ip_tag_bridged) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + pkt_no_tag = ( + Ether(src=self.pg0.remote_mac, dst=self.loop0.local_mac) + / IP(src=any_src_addr, dst=ip_non_tag_bridged) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + pkt_tag = ( + Ether(src=self.pg0.remote_mac, dst=self.loop0.local_mac) + / IP(src=any_src_addr, dst=ip_tag_bridged) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) # # Two sub-interfaces so we can test VLAN tag push/pop @@ -97,32 +97,45 @@ class TestDVR(VppTestCase): # Put all the interfaces into a new bridge domain # self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg0.sw_if_index, bd_id=1) + rx_sw_if_index=self.pg0.sw_if_index, bd_id=1 + ) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg1.sw_if_index, bd_id=1) + rx_sw_if_index=self.pg1.sw_if_index, bd_id=1 + ) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=sub_if_on_pg2.sw_if_index, bd_id=1) + rx_sw_if_index=sub_if_on_pg2.sw_if_index, bd_id=1 + ) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=sub_if_on_pg3.sw_if_index, bd_id=1) + rx_sw_if_index=sub_if_on_pg3.sw_if_index, bd_id=1 + ) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.loop0.sw_if_index, bd_id=1, - port_type=L2_PORT_TYPE.BVI) + rx_sw_if_index=self.loop0.sw_if_index, bd_id=1, port_type=L2_PORT_TYPE.BVI + ) self.vapi.l2_interface_vlan_tag_rewrite( - sw_if_index=sub_if_on_pg2.sw_if_index, vtr_op=L2_VTR_OP.L2_POP_1, - push_dot1q=92) + sw_if_index=sub_if_on_pg2.sw_if_index, + vtr_op=L2_VTR_OP.L2_POP_1, + push_dot1q=92, + ) self.vapi.l2_interface_vlan_tag_rewrite( - sw_if_index=sub_if_on_pg3.sw_if_index, vtr_op=L2_VTR_OP.L2_POP_1, - push_dot1q=93) + sw_if_index=sub_if_on_pg3.sw_if_index, + vtr_op=L2_VTR_OP.L2_POP_1, + push_dot1q=93, + ) # # Add routes to bridge the traffic via a tagged an nontagged interface # route_no_tag = VppIpRoute( - self, ip_non_tag_bridged, 32, - [VppRoutePath("0.0.0.0", - self.pg1.sw_if_index, - type=FibPathType.FIB_PATH_TYPE_DVR)]) + self, + ip_non_tag_bridged, + 32, + [ + VppRoutePath( + "0.0.0.0", self.pg1.sw_if_index, type=FibPathType.FIB_PATH_TYPE_DVR + ) + ], + ) route_no_tag.add_vpp_config() # @@ -137,10 +150,17 @@ class TestDVR(VppTestCase): # Add routes to bridge the traffic via a tagged interface # route_with_tag = VppIpRoute( - self, ip_tag_bridged, 32, - [VppRoutePath("0.0.0.0", - sub_if_on_pg3.sw_if_index, - type=FibPathType.FIB_PATH_TYPE_DVR)]) + self, + ip_tag_bridged, + 32, + [ + VppRoutePath( + "0.0.0.0", + sub_if_on_pg3.sw_if_index, + type=FibPathType.FIB_PATH_TYPE_DVR, + ) + ], + ) route_with_tag.add_vpp_config() # @@ -154,58 +174,58 @@ class TestDVR(VppTestCase): # # Tag to tag # - pkt_tag_to_tag = (Ether(src=self.pg2.remote_mac, - dst=self.loop0.local_mac) / - Dot1Q(vlan=92) / - IP(src=any_src_addr, - dst=ip_tag_bridged) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - - rx = self.send_and_expect(self.pg2, - pkt_tag_to_tag * NUM_PKTS, - self.pg3) + pkt_tag_to_tag = ( + Ether(src=self.pg2.remote_mac, dst=self.loop0.local_mac) + / Dot1Q(vlan=92) + / IP(src=any_src_addr, dst=ip_tag_bridged) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + + rx = self.send_and_expect(self.pg2, pkt_tag_to_tag * NUM_PKTS, self.pg3) self.assert_same_mac_addr(pkt_tag_to_tag, rx) self.assert_has_vlan_tag(93, rx) # # Tag to non-Tag # - pkt_tag_to_non_tag = (Ether(src=self.pg2.remote_mac, - dst=self.loop0.local_mac) / - Dot1Q(vlan=92) / - IP(src=any_src_addr, - dst=ip_non_tag_bridged) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - - rx = self.send_and_expect(self.pg2, - pkt_tag_to_non_tag * NUM_PKTS, - self.pg1) + pkt_tag_to_non_tag = ( + Ether(src=self.pg2.remote_mac, dst=self.loop0.local_mac) + / Dot1Q(vlan=92) + / IP(src=any_src_addr, dst=ip_non_tag_bridged) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + + rx = self.send_and_expect(self.pg2, pkt_tag_to_non_tag * NUM_PKTS, self.pg1) self.assert_same_mac_addr(pkt_tag_to_tag, rx) self.assert_has_no_tag(rx) # # Add an output L3 ACL that will block the traffic # - rule_1 = AclRule(is_permit=0, proto=17, ports=1234, - src_prefix=IPv4Network((any_src_addr, 32)), - dst_prefix=IPv4Network((ip_non_tag_bridged, 32))) + rule_1 = AclRule( + is_permit=0, + proto=17, + ports=1234, + src_prefix=IPv4Network((any_src_addr, 32)), + dst_prefix=IPv4Network((ip_non_tag_bridged, 32)), + ) acl = VppAcl(self, rules=[rule_1]) acl.add_vpp_config() # # Apply the ACL on the output interface # - acl_if1 = VppAclInterface(self, sw_if_index=self.pg1.sw_if_index, - n_input=0, acls=[acl]) + acl_if1 = VppAclInterface( + self, sw_if_index=self.pg1.sw_if_index, n_input=0, acls=[acl] + ) acl_if1.add_vpp_config() # # Send packet's that should match the ACL and be dropped # - rx = self.send_and_assert_no_replies(self.pg2, - pkt_tag_to_non_tag * NUM_PKTS) + rx = self.send_and_assert_no_replies(self.pg2, pkt_tag_to_non_tag * NUM_PKTS) # # cleanup @@ -214,16 +234,23 @@ class TestDVR(VppTestCase): acl.remove_vpp_config() self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg0.sw_if_index, bd_id=1, enable=0) + rx_sw_if_index=self.pg0.sw_if_index, bd_id=1, enable=0 + ) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg1.sw_if_index, bd_id=1, enable=0) + rx_sw_if_index=self.pg1.sw_if_index, bd_id=1, enable=0 + ) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=sub_if_on_pg2.sw_if_index, bd_id=1, enable=0) + rx_sw_if_index=sub_if_on_pg2.sw_if_index, bd_id=1, enable=0 + ) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=sub_if_on_pg3.sw_if_index, bd_id=1, enable=0) + rx_sw_if_index=sub_if_on_pg3.sw_if_index, bd_id=1, enable=0 + ) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.loop0.sw_if_index, bd_id=1, - port_type=L2_PORT_TYPE.BVI, enable=0) + rx_sw_if_index=self.loop0.sw_if_index, + bd_id=1, + port_type=L2_PORT_TYPE.BVI, + enable=0, + ) # # Do a FIB dump to make sure the paths are correctly reported as DVR @@ -231,16 +258,14 @@ class TestDVR(VppTestCase): routes = self.vapi.ip_route_dump(0) for r in routes: - if (ip_tag_bridged == str(r.route.prefix.network_address)): - self.assertEqual(r.route.paths[0].sw_if_index, - sub_if_on_pg3.sw_if_index) - self.assertEqual(r.route.paths[0].type, - FibPathType.FIB_PATH_TYPE_DVR) - if (ip_non_tag_bridged == str(r.route.prefix.network_address)): - self.assertEqual(r.route.paths[0].sw_if_index, - self.pg1.sw_if_index) - self.assertEqual(r.route.paths[0].type, - FibPathType.FIB_PATH_TYPE_DVR) + if ip_tag_bridged == str(r.route.prefix.network_address): + self.assertEqual( + r.route.paths[0].sw_if_index, sub_if_on_pg3.sw_if_index + ) + self.assertEqual(r.route.paths[0].type, FibPathType.FIB_PATH_TYPE_DVR) + if ip_non_tag_bridged == str(r.route.prefix.network_address): + self.assertEqual(r.route.paths[0].sw_if_index, self.pg1.sw_if_index) + self.assertEqual(r.route.paths[0].type, FibPathType.FIB_PATH_TYPE_DVR) # # the explicit route delete is require so it happens before @@ -253,5 +278,5 @@ class TestDVR(VppTestCase): sub_if_on_pg2.remove_vpp_config() -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_endian.py b/test/test_endian.py index 462ee2b6b57..bb54a03fd13 100644 --- a/test/test_endian.py +++ b/test/test_endian.py @@ -24,15 +24,20 @@ class TestEndian(framework.VppTestCase): def test_f64_endian_value(self): try: rv = self.vapi.get_f64_endian_value(f64_one=F64_ONE) - self.assertEqual(rv.f64_one_result, F64_ONE, - "client incorrectly deserializes f64 values. " - "Expected: %r. Received: %r." % ( - F64_ONE, rv.f64_one_result)) + self.assertEqual( + rv.f64_one_result, + F64_ONE, + "client incorrectly deserializes f64 values. " + "Expected: %r. Received: %r." % (F64_ONE, rv.f64_one_result), + ) except vpp_papi_provider.UnexpectedApiReturnValueError: - self.fail('client incorrectly serializes f64 values.') + self.fail("client incorrectly serializes f64 values.") def test_get_f64_increment_by_one(self): expected = 43.0 rv = self.vapi.get_f64_increment_by_one(f64_value=42.0) - self.assertEqual(rv.f64_value, expected, 'Expected %r, received:%r.' - % (expected, rv.f64_value)) + self.assertEqual( + rv.f64_value, + expected, + "Expected %r, received:%r." % (expected, rv.f64_value), + ) diff --git a/test/test_fib.py b/test/test_fib.py index 7c08722d803..136918e1232 100644 --- a/test/test_fib.py +++ b/test/test_fib.py @@ -8,7 +8,7 @@ from framework import VppTestCase, VppTestRunner @tag_fixme_vpp_workers class TestFIB(VppTestCase): - """ FIB Test Case """ + """FIB Test Case""" @classmethod def setUpClass(cls): @@ -19,7 +19,7 @@ class TestFIB(VppTestCase): super(TestFIB, cls).tearDownClass() def test_fib(self): - """ FIB Unit Tests """ + """FIB Unit Tests""" error = self.vapi.cli("test fib") # shameless test of CLIs to bump lcov results... @@ -44,5 +44,6 @@ class TestFIB(VppTestCase): self.logger.critical(error) self.assertNotIn("Failed", error) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_flowprobe.py b/test/test_flowprobe.py index 5bafd39eceb..6b271790f76 100644 --- a/test/test_flowprobe.py +++ b/test/test_flowprobe.py @@ -29,17 +29,26 @@ from vpp_papi import VppEnum class VppCFLOW(VppObject): """CFLOW object for IPFIX exporter and Flowprobe feature""" - def __init__(self, test, intf='pg2', active=0, passive=0, timeout=100, - mtu=1024, datapath='l2', layer='l2 l3 l4'): + def __init__( + self, + test, + intf="pg2", + active=0, + passive=0, + timeout=100, + mtu=1024, + datapath="l2", + layer="l2 l3 l4", + ): self._test = test self._intf = intf self._active = active if passive == 0 or passive < active: - self._passive = active+1 + self._passive = active + 1 else: self._passive = passive - self._datapath = datapath # l2 ip4 ip6 - self._collect = layer # l2 l3 l4 + self._datapath = datapath # l2 ip4 ip6 + self._collect = layer # l2 l3 l4 self._timeout = timeout self._mtu = mtu self._configured = False @@ -49,18 +58,17 @@ class VppCFLOW(VppObject): l2_flag = 0 l3_flag = 0 l4_flag = 0 - if 'l2' in self._collect.lower(): - l2_flag = (VppEnum.vl_api_flowprobe_record_flags_t. - FLOWPROBE_RECORD_FLAG_L2) - if 'l3' in self._collect.lower(): - l3_flag = (VppEnum.vl_api_flowprobe_record_flags_t. - FLOWPROBE_RECORD_FLAG_L3) - if 'l4' in self._collect.lower(): - l4_flag = (VppEnum.vl_api_flowprobe_record_flags_t. - FLOWPROBE_RECORD_FLAG_L4) + if "l2" in self._collect.lower(): + l2_flag = VppEnum.vl_api_flowprobe_record_flags_t.FLOWPROBE_RECORD_FLAG_L2 + if "l3" in self._collect.lower(): + l3_flag = VppEnum.vl_api_flowprobe_record_flags_t.FLOWPROBE_RECORD_FLAG_L3 + if "l4" in self._collect.lower(): + l4_flag = VppEnum.vl_api_flowprobe_record_flags_t.FLOWPROBE_RECORD_FLAG_L4 self._test.vapi.flowprobe_params( record_flags=(l2_flag | l3_flag | l4_flag), - active_timer=self._active, passive_timer=self._passive) + active_timer=self._active, + passive_timer=self._passive, + ) self.enable_flowprobe_feature() self._test.vapi.cli("ipfix flush") self._configured = True @@ -76,18 +84,21 @@ class VppCFLOW(VppObject): collector_address=self._test.pg0.remote_ip4, src_address=self._test.pg0.local_ip4, path_mtu=self._mtu, - template_interval=self._timeout) + template_interval=self._timeout, + ) def enable_flowprobe_feature(self): - self._test.vapi.ppcli("flowprobe feature add-del %s %s" % - (self._intf, self._datapath)) + self._test.vapi.ppcli( + "flowprobe feature add-del %s %s" % (self._intf, self._datapath) + ) def disable_exporter(self): self._test.vapi.cli("set ipfix exporter collector 0.0.0.0") def disable_flowprobe_feature(self): - self._test.vapi.cli("flowprobe feature add-del %s %s disable" % - (self._intf, self._datapath)) + self._test.vapi.cli( + "flowprobe feature add-del %s %s disable" % (self._intf, self._datapath) + ) def object_id(self): return "ipfix-collector-%s-%s" % (self._src, self.dst) @@ -99,8 +110,7 @@ class VppCFLOW(VppObject): templates = [] self._test.assertIn(count, (1, 2, 3)) for _ in range(count): - p = self._test.wait_for_cflow_packet(self._test.collector, 2, - timeout) + p = self._test.wait_for_cflow_packet(self._test.collector, 2, timeout) self._test.assertTrue(p.haslayer(IPFIX)) if decoder is not None and p.haslayer(Template): templates.append(p[Template].templateID) @@ -109,7 +119,7 @@ class VppCFLOW(VppObject): class MethodHolder(VppTestCase): - """ Flow-per-packet plugin: test L2, IP4, IP6 reporting """ + """Flow-per-packet plugin: test L2, IP4, IP6 reporting""" # Test variables debug_print = False @@ -135,9 +145,11 @@ class MethodHolder(VppTestCase): # and put interfaces to this BD cls.vapi.bridge_domain_add_del(bd_id=1, uu_flood=1, learn=1) cls.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=cls.pg1._sw_if_index, bd_id=1) + rx_sw_if_index=cls.pg1._sw_if_index, bd_id=1 + ) cls.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=cls.pg2._sw_if_index, bd_id=1) + rx_sw_if_index=cls.pg2._sw_if_index, bd_id=1 + ) # Set up all interfaces for i in cls.pg_interfaces: @@ -173,8 +185,9 @@ class MethodHolder(VppTestCase): def tearDownClass(cls): super(MethodHolder, cls).tearDownClass() - def create_stream(self, src_if=None, dst_if=None, packets=None, - size=None, ip_ver='v4'): + def create_stream( + self, src_if=None, dst_if=None, packets=None, size=None, ip_ver="v4" + ): """Create a packet stream to tickle the plugin :param VppInterface src_if: Source interface for packet stream @@ -194,7 +207,7 @@ class MethodHolder(VppTestCase): info = self.create_packet_info(src_if, dst_if) payload = self.info_to_payload(info) p = Ether(src=src_if.remote_mac, dst=src_if.local_mac) - if ip_ver == 'v4': + if ip_ver == "v4": p /= IP(src=src_if.remote_ip4, dst=dst_if.remote_ip4) else: p /= IPv6(src=src_if.remote_ip6, dst=dst_if.remote_ip6) @@ -226,16 +239,16 @@ class MethodHolder(VppTestCase): self.pg_start() return dst_if.get_capture(len(self.pkts)) - def verify_cflow_data_detail(self, decoder, capture, cflow, - data_set={1: 'octets', 2: 'packets'}, - ip_ver='v4'): + def verify_cflow_data_detail( + self, decoder, capture, cflow, data_set={1: "octets", 2: "packets"}, ip_ver="v4" + ): if self.debug_print: print(capture[0].show()) if cflow.haslayer(Data): data = decoder.decode_data_set(cflow.getlayer(Set)) if self.debug_print: print(data) - if ip_ver == 'v4': + if ip_ver == "v4": ip_layer = capture[0][IP] else: ip_layer = capture[0][IPv6] @@ -251,35 +264,31 @@ class MethodHolder(VppTestCase): if field not in record.keys(): continue value = data_set[field] - if value == 'octets': + if value == "octets": value = ip_layer.len - if ip_ver == 'v6': - value += 40 # ??? is this correct - elif value == 'packets': + if ip_ver == "v6": + value += 40 # ??? is this correct + elif value == "packets": value = 1 - elif value == 'src_ip': - if ip_ver == 'v4': - ip = socket.inet_pton(socket.AF_INET, - ip_layer.src) + elif value == "src_ip": + if ip_ver == "v4": + ip = socket.inet_pton(socket.AF_INET, ip_layer.src) else: - ip = socket.inet_pton(socket.AF_INET6, - ip_layer.src) + ip = socket.inet_pton(socket.AF_INET6, ip_layer.src) value = int(binascii.hexlify(ip), 16) - elif value == 'dst_ip': - if ip_ver == 'v4': - ip = socket.inet_pton(socket.AF_INET, - ip_layer.dst) + elif value == "dst_ip": + if ip_ver == "v4": + ip = socket.inet_pton(socket.AF_INET, ip_layer.dst) else: - ip = socket.inet_pton(socket.AF_INET6, - ip_layer.dst) + ip = socket.inet_pton(socket.AF_INET6, ip_layer.dst) value = int(binascii.hexlify(ip), 16) - elif value == 'sport': + elif value == "sport": value = int(capture[0][UDP].sport) - elif value == 'dport': + elif value == "dport": value = int(capture[0][UDP].dport) - self.assertEqual(int(binascii.hexlify( - record[field]), 16), - value) + self.assertEqual( + int(binascii.hexlify(record[field]), 16), value + ) def verify_cflow_data_notimer(self, decoder, capture, cflows): idx = 0 @@ -292,14 +301,12 @@ class MethodHolder(VppTestCase): for rec in data: p = capture[idx] idx += 1 - self.assertEqual(p[IP].len, int( - binascii.hexlify(rec[1]), 16)) - self.assertEqual(1, int( - binascii.hexlify(rec[2]), 16)) + self.assertEqual(p[IP].len, int(binascii.hexlify(rec[1]), 16)) + self.assertEqual(1, int(binascii.hexlify(rec[2]), 16)) self.assertEqual(len(capture), idx) def wait_for_cflow_packet(self, collector_intf, set_id=2, timeout=1): - """ wait for CFLOW packet and verify its correctness + """wait for CFLOW packet and verify its correctness :param timeout: how long to wait @@ -327,7 +334,7 @@ class Flowprobe(MethodHolder): super(Flowprobe, cls).tearDownClass() def test_0001(self): - """ timer less than template timeout""" + """timer less than template timeout""" self.logger.info("FFP_TEST_START_0001") self.pg_enable_capture(self.pg_interfaces) self.pkts = [] @@ -351,7 +358,7 @@ class Flowprobe(MethodHolder): self.logger.info("FFP_TEST_FINISH_0001") def test_0002(self): - """ timer greater than template timeout""" + """timer greater than template timeout""" self.logger.info("FFP_TEST_START_0002") self.pg_enable_capture(self.pg_interfaces) self.pkts = [] @@ -384,26 +391,33 @@ class Flowprobe(MethodHolder): self.pg_enable_capture(self.pg_interfaces) self.pkts = [] - ipfix = VppCFLOW(test=self, intf='pg8', datapath="ip4", - layer='l2 l3 l4', active=2) + ipfix = VppCFLOW( + test=self, intf="pg8", datapath="ip4", layer="l2 l3 l4", active=2 + ) ipfix.add_vpp_config() - route_9001 = VppIpRoute(self, "9.0.0.0", 24, - [VppRoutePath(self.pg8._remote_hosts[0].ip4, - self.pg8.sw_if_index)]) + route_9001 = VppIpRoute( + self, + "9.0.0.0", + 24, + [VppRoutePath(self.pg8._remote_hosts[0].ip4, self.pg8.sw_if_index)], + ) route_9001.add_vpp_config() ipfix_decoder = IPFIXDecoder() templates = ipfix.verify_templates(ipfix_decoder, count=1) - self.pkts = [(Ether(dst=self.pg7.local_mac, - src=self.pg7.remote_mac) / - IP(src=self.pg7.remote_ip4, dst="9.0.0.100") / - TCP(sport=1234, dport=4321, flags=80) / - Raw(b'\xa5' * 100))] + self.pkts = [ + ( + Ether(dst=self.pg7.local_mac, src=self.pg7.remote_mac) + / IP(src=self.pg7.remote_ip4, dst="9.0.0.100") + / TCP(sport=1234, dport=4321, flags=80) + / Raw(b"\xa5" * 100) + ) + ] nowUTC = int(time.time()) - nowUNIX = nowUTC+2208988800 + nowUNIX = nowUTC + 2208988800 self.send_packets(src_if=self.pg7, dst_if=self.pg8) cflow = self.wait_for_cflow_packet(self.collector, templates[0], 10) @@ -435,11 +449,9 @@ class Flowprobe(MethodHolder): # ethernet type self.assertEqual(int(binascii.hexlify(record[256]), 16), 8) # src ip - self.assertEqual(inet_ntop(socket.AF_INET, record[8]), - self.pg7.remote_ip4) + self.assertEqual(inet_ntop(socket.AF_INET, record[8]), self.pg7.remote_ip4) # dst ip - self.assertEqual(inet_ntop(socket.AF_INET, record[12]), - "9.0.0.100") + self.assertEqual(inet_ntop(socket.AF_INET, record[12]), "9.0.0.100") # protocol (TCP) self.assertEqual(int(binascii.hexlify(record[4]), 16), 6) # src port @@ -466,11 +478,11 @@ class Datapath(MethodHolder): super(Datapath, cls).tearDownClass() def test_templatesL2(self): - """ verify template on L2 datapath""" + """verify template on L2 datapath""" self.logger.info("FFP_TEST_START_0000") self.pg_enable_capture(self.pg_interfaces) - ipfix = VppCFLOW(test=self, layer='l2') + ipfix = VppCFLOW(test=self, layer="l2") ipfix.add_vpp_config() # template packet should arrive immediately @@ -482,12 +494,12 @@ class Datapath(MethodHolder): self.logger.info("FFP_TEST_FINISH_0000") def test_L2onL2(self): - """ L2 data on L2 datapath""" + """L2 data on L2 datapath""" self.logger.info("FFP_TEST_START_0001") self.pg_enable_capture(self.pg_interfaces) self.pkts = [] - ipfix = VppCFLOW(test=self, layer='l2') + ipfix = VppCFLOW(test=self, layer="l2") ipfix.add_vpp_config() ipfix_decoder = IPFIXDecoder() @@ -500,20 +512,21 @@ class Datapath(MethodHolder): # make sure the one packet we expect actually showed up self.vapi.ipfix_flush() cflow = self.wait_for_cflow_packet(self.collector, templates[0]) - self.verify_cflow_data_detail(ipfix_decoder, capture, cflow, - {2: 'packets', 256: 8}) + self.verify_cflow_data_detail( + ipfix_decoder, capture, cflow, {2: "packets", 256: 8} + ) self.collector.get_capture(2) ipfix.remove_vpp_config() self.logger.info("FFP_TEST_FINISH_0001") def test_L3onL2(self): - """ L3 data on L2 datapath""" + """L3 data on L2 datapath""" self.logger.info("FFP_TEST_START_0002") self.pg_enable_capture(self.pg_interfaces) self.pkts = [] - ipfix = VppCFLOW(test=self, layer='l3') + ipfix = VppCFLOW(test=self, layer="l3") ipfix.add_vpp_config() ipfix_decoder = IPFIXDecoder() @@ -526,9 +539,12 @@ class Datapath(MethodHolder): # make sure the one packet we expect actually showed up self.vapi.ipfix_flush() cflow = self.wait_for_cflow_packet(self.collector, templates[0]) - self.verify_cflow_data_detail(ipfix_decoder, capture, cflow, - {2: 'packets', 4: 17, - 8: 'src_ip', 12: 'dst_ip'}) + self.verify_cflow_data_detail( + ipfix_decoder, + capture, + cflow, + {2: "packets", 4: 17, 8: "src_ip", 12: "dst_ip"}, + ) self.collector.get_capture(3) @@ -536,12 +552,12 @@ class Datapath(MethodHolder): self.logger.info("FFP_TEST_FINISH_0002") def test_L4onL2(self): - """ L4 data on L2 datapath""" + """L4 data on L2 datapath""" self.logger.info("FFP_TEST_START_0003") self.pg_enable_capture(self.pg_interfaces) self.pkts = [] - ipfix = VppCFLOW(test=self, layer='l4') + ipfix = VppCFLOW(test=self, layer="l4") ipfix.add_vpp_config() ipfix_decoder = IPFIXDecoder() @@ -554,8 +570,9 @@ class Datapath(MethodHolder): # make sure the one packet we expect actually showed up self.vapi.ipfix_flush() cflow = self.wait_for_cflow_packet(self.collector, templates[0]) - self.verify_cflow_data_detail(ipfix_decoder, capture, cflow, - {2: 'packets', 7: 'sport', 11: 'dport'}) + self.verify_cflow_data_detail( + ipfix_decoder, capture, cflow, {2: "packets", 7: "sport", 11: "dport"} + ) self.collector.get_capture(3) @@ -563,12 +580,12 @@ class Datapath(MethodHolder): self.logger.info("FFP_TEST_FINISH_0003") def test_templatesIp4(self): - """ verify templates on IP4 datapath""" + """verify templates on IP4 datapath""" self.logger.info("FFP_TEST_START_0000") self.pg_enable_capture(self.pg_interfaces) - ipfix = VppCFLOW(test=self, datapath='ip4') + ipfix = VppCFLOW(test=self, datapath="ip4") ipfix.add_vpp_config() # template packet should arrive immediately @@ -581,12 +598,12 @@ class Datapath(MethodHolder): self.logger.info("FFP_TEST_FINISH_0000") def test_L2onIP4(self): - """ L2 data on IP4 datapath""" + """L2 data on IP4 datapath""" self.logger.info("FFP_TEST_START_0001") self.pg_enable_capture(self.pg_interfaces) self.pkts = [] - ipfix = VppCFLOW(test=self, intf='pg4', layer='l2', datapath='ip4') + ipfix = VppCFLOW(test=self, intf="pg4", layer="l2", datapath="ip4") ipfix.add_vpp_config() ipfix_decoder = IPFIXDecoder() @@ -599,8 +616,9 @@ class Datapath(MethodHolder): # make sure the one packet we expect actually showed up self.vapi.ipfix_flush() cflow = self.wait_for_cflow_packet(self.collector, templates[0]) - self.verify_cflow_data_detail(ipfix_decoder, capture, cflow, - {2: 'packets', 256: 8}) + self.verify_cflow_data_detail( + ipfix_decoder, capture, cflow, {2: "packets", 256: 8} + ) # expected two templates and one cflow packet self.collector.get_capture(2) @@ -609,12 +627,12 @@ class Datapath(MethodHolder): self.logger.info("FFP_TEST_FINISH_0001") def test_L3onIP4(self): - """ L3 data on IP4 datapath""" + """L3 data on IP4 datapath""" self.logger.info("FFP_TEST_START_0002") self.pg_enable_capture(self.pg_interfaces) self.pkts = [] - ipfix = VppCFLOW(test=self, intf='pg4', layer='l3', datapath='ip4') + ipfix = VppCFLOW(test=self, intf="pg4", layer="l3", datapath="ip4") ipfix.add_vpp_config() ipfix_decoder = IPFIXDecoder() @@ -627,9 +645,12 @@ class Datapath(MethodHolder): # make sure the one packet we expect actually showed up self.vapi.ipfix_flush() cflow = self.wait_for_cflow_packet(self.collector, templates[0]) - self.verify_cflow_data_detail(ipfix_decoder, capture, cflow, - {1: 'octets', 2: 'packets', - 8: 'src_ip', 12: 'dst_ip'}) + self.verify_cflow_data_detail( + ipfix_decoder, + capture, + cflow, + {1: "octets", 2: "packets", 8: "src_ip", 12: "dst_ip"}, + ) # expected two templates and one cflow packet self.collector.get_capture(2) @@ -638,12 +659,12 @@ class Datapath(MethodHolder): self.logger.info("FFP_TEST_FINISH_0002") def test_L4onIP4(self): - """ L4 data on IP4 datapath""" + """L4 data on IP4 datapath""" self.logger.info("FFP_TEST_START_0003") self.pg_enable_capture(self.pg_interfaces) self.pkts = [] - ipfix = VppCFLOW(test=self, intf='pg4', layer='l4', datapath='ip4') + ipfix = VppCFLOW(test=self, intf="pg4", layer="l4", datapath="ip4") ipfix.add_vpp_config() ipfix_decoder = IPFIXDecoder() @@ -656,8 +677,9 @@ class Datapath(MethodHolder): # make sure the one packet we expect actually showed up self.vapi.ipfix_flush() cflow = self.wait_for_cflow_packet(self.collector, templates[0]) - self.verify_cflow_data_detail(ipfix_decoder, capture, cflow, - {2: 'packets', 7: 'sport', 11: 'dport'}) + self.verify_cflow_data_detail( + ipfix_decoder, capture, cflow, {2: "packets", 7: "sport", 11: "dport"} + ) # expected two templates and one cflow packet self.collector.get_capture(2) @@ -666,11 +688,11 @@ class Datapath(MethodHolder): self.logger.info("FFP_TEST_FINISH_0003") def test_templatesIP6(self): - """ verify templates on IP6 datapath""" + """verify templates on IP6 datapath""" self.logger.info("FFP_TEST_START_0000") self.pg_enable_capture(self.pg_interfaces) - ipfix = VppCFLOW(test=self, datapath='ip6') + ipfix = VppCFLOW(test=self, datapath="ip6") ipfix.add_vpp_config() # template packet should arrive immediately @@ -682,28 +704,27 @@ class Datapath(MethodHolder): self.logger.info("FFP_TEST_FINISH_0000") def test_L2onIP6(self): - """ L2 data on IP6 datapath""" + """L2 data on IP6 datapath""" self.logger.info("FFP_TEST_START_0001") self.pg_enable_capture(self.pg_interfaces) self.pkts = [] - ipfix = VppCFLOW(test=self, intf='pg6', layer='l2', datapath='ip6') + ipfix = VppCFLOW(test=self, intf="pg6", layer="l2", datapath="ip6") ipfix.add_vpp_config() ipfix_decoder = IPFIXDecoder() # template packet should arrive immediately templates = ipfix.verify_templates(ipfix_decoder, count=1) - self.create_stream(src_if=self.pg5, dst_if=self.pg6, packets=1, - ip_ver='IPv6') + self.create_stream(src_if=self.pg5, dst_if=self.pg6, packets=1, ip_ver="IPv6") capture = self.send_packets(src_if=self.pg5, dst_if=self.pg6) # make sure the one packet we expect actually showed up self.vapi.ipfix_flush() cflow = self.wait_for_cflow_packet(self.collector, templates[0]) - self.verify_cflow_data_detail(ipfix_decoder, capture, cflow, - {2: 'packets', 256: 56710}, - ip_ver='v6') + self.verify_cflow_data_detail( + ipfix_decoder, capture, cflow, {2: "packets", 256: 56710}, ip_ver="v6" + ) # expected two templates and one cflow packet self.collector.get_capture(2) @@ -712,29 +733,31 @@ class Datapath(MethodHolder): self.logger.info("FFP_TEST_FINISH_0001") def test_L3onIP6(self): - """ L3 data on IP6 datapath""" + """L3 data on IP6 datapath""" self.logger.info("FFP_TEST_START_0002") self.pg_enable_capture(self.pg_interfaces) self.pkts = [] - ipfix = VppCFLOW(test=self, intf='pg6', layer='l3', datapath='ip6') + ipfix = VppCFLOW(test=self, intf="pg6", layer="l3", datapath="ip6") ipfix.add_vpp_config() ipfix_decoder = IPFIXDecoder() # template packet should arrive immediately templates = ipfix.verify_templates(ipfix_decoder, count=1) - self.create_stream(src_if=self.pg5, dst_if=self.pg6, packets=1, - ip_ver='IPv6') + self.create_stream(src_if=self.pg5, dst_if=self.pg6, packets=1, ip_ver="IPv6") capture = self.send_packets(src_if=self.pg5, dst_if=self.pg6) # make sure the one packet we expect actually showed up self.vapi.ipfix_flush() cflow = self.wait_for_cflow_packet(self.collector, templates[0]) - self.verify_cflow_data_detail(ipfix_decoder, capture, cflow, - {2: 'packets', - 27: 'src_ip', 28: 'dst_ip'}, - ip_ver='v6') + self.verify_cflow_data_detail( + ipfix_decoder, + capture, + cflow, + {2: "packets", 27: "src_ip", 28: "dst_ip"}, + ip_ver="v6", + ) # expected two templates and one cflow packet self.collector.get_capture(2) @@ -743,28 +766,31 @@ class Datapath(MethodHolder): self.logger.info("FFP_TEST_FINISH_0002") def test_L4onIP6(self): - """ L4 data on IP6 datapath""" + """L4 data on IP6 datapath""" self.logger.info("FFP_TEST_START_0003") self.pg_enable_capture(self.pg_interfaces) self.pkts = [] - ipfix = VppCFLOW(test=self, intf='pg6', layer='l4', datapath='ip6') + ipfix = VppCFLOW(test=self, intf="pg6", layer="l4", datapath="ip6") ipfix.add_vpp_config() ipfix_decoder = IPFIXDecoder() # template packet should arrive immediately templates = ipfix.verify_templates(ipfix_decoder, count=1) - self.create_stream(src_if=self.pg5, dst_if=self.pg6, packets=1, - ip_ver='IPv6') + self.create_stream(src_if=self.pg5, dst_if=self.pg6, packets=1, ip_ver="IPv6") capture = self.send_packets(src_if=self.pg5, dst_if=self.pg6) # make sure the one packet we expect actually showed up self.vapi.ipfix_flush() cflow = self.wait_for_cflow_packet(self.collector, templates[0]) - self.verify_cflow_data_detail(ipfix_decoder, capture, cflow, - {2: 'packets', 7: 'sport', 11: 'dport'}, - ip_ver='v6') + self.verify_cflow_data_detail( + ipfix_decoder, + capture, + cflow, + {2: "packets", 7: "sport", 11: "dport"}, + ip_ver="v6", + ) # expected two templates and one cflow packet self.collector.get_capture(2) @@ -773,7 +799,7 @@ class Datapath(MethodHolder): self.logger.info("FFP_TEST_FINISH_0003") def test_0001(self): - """ no timers, one CFLOW packet, 9 Flows inside""" + """no timers, one CFLOW packet, 9 Flows inside""" self.logger.info("FFP_TEST_START_0001") self.pg_enable_capture(self.pg_interfaces) self.pkts = [] @@ -798,7 +824,7 @@ class Datapath(MethodHolder): self.logger.info("FFP_TEST_FINISH_0001") def test_0002(self): - """ no timers, two CFLOW packets (mtu=256), 3 Flows in each""" + """no timers, two CFLOW packets (mtu=256), 3 Flows in each""" self.logger.info("FFP_TEST_START_0002") self.pg_enable_capture(self.pg_interfaces) self.pkts = [] @@ -817,10 +843,8 @@ class Datapath(MethodHolder): # make sure the one packet we expect actually showed up cflows = [] self.vapi.ipfix_flush() - cflows.append(self.wait_for_cflow_packet(self.collector, - templates[1])) - cflows.append(self.wait_for_cflow_packet(self.collector, - templates[1])) + cflows.append(self.wait_for_cflow_packet(self.collector, templates[1])) + cflows.append(self.wait_for_cflow_packet(self.collector, templates[1])) self.verify_cflow_data_notimer(ipfix_decoder, capture, cflows) self.collector.get_capture(5) @@ -841,7 +865,7 @@ class DisableIPFIX(MethodHolder): super(DisableIPFIX, cls).tearDownClass() def test_0001(self): - """ disable IPFIX after first packets""" + """disable IPFIX after first packets""" self.logger.info("FFP_TEST_START_0001") self.pg_enable_capture(self.pg_interfaces) self.pkts = [] @@ -889,8 +913,7 @@ class ReenableIPFIX(MethodHolder): super(ReenableIPFIX, cls).tearDownClass() def test_0011(self): - """ disable IPFIX after first packets and re-enable after few packets - """ + """disable IPFIX after first packets and re-enable after few packets""" self.logger.info("FFP_TEST_START_0001") self.pg_enable_capture(self.pg_interfaces) self.pkts = [] @@ -957,7 +980,7 @@ class DisableFP(MethodHolder): super(DisableFP, cls).tearDownClass() def test_0001(self): - """ disable flowprobe feature after first packets""" + """disable flowprobe feature after first packets""" self.logger.info("FFP_TEST_START_0001") self.pg_enable_capture(self.pg_interfaces) self.pkts = [] @@ -1004,8 +1027,8 @@ class ReenableFP(MethodHolder): super(ReenableFP, cls).tearDownClass() def test_0001(self): - """ disable flowprobe feature after first packets and re-enable - after few packets """ + """disable flowprobe feature after first packets and re-enable + after few packets""" self.logger.info("FFP_TEST_START_0001") self.pg_enable_capture(self.pg_interfaces) self.pkts = [] @@ -1054,5 +1077,5 @@ class ReenableFP(MethodHolder): self.logger.info("FFP_TEST_FINISH_0001") -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_geneve.py b/test/test_geneve.py index 9ce1f8ff643..f6886c636d3 100644 --- a/test/test_geneve.py +++ b/test/test_geneve.py @@ -16,7 +16,7 @@ from vpp_ip import INVALID_INDEX class TestGeneve(BridgeDomain, VppTestCase): - """ GENEVE Test Case """ + """GENEVE Test Case""" def __init__(self, *args): BridgeDomain.__init__(self) @@ -28,14 +28,16 @@ class TestGeneve(BridgeDomain, VppTestCase): Encapsulate the original payload frame by adding GENEVE header with its UDP, IP and Ethernet fields """ - return (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / - UDP(sport=self.dport, dport=self.dport, chksum=0) / - GENEVE(vni=vni) / - pkt) + return ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / UDP(sport=self.dport, dport=self.dport, chksum=0) + / GENEVE(vni=vni) + / pkt + ) def ip_range(self, start, end): - """ range of remote ip's """ + """range of remote ip's""" return ip4_range(self.pg0.remote_ip4, start, end) def encap_mcast(self, pkt, src_ip, src_mac, vni): @@ -43,11 +45,13 @@ class TestGeneve(BridgeDomain, VppTestCase): Encapsulate the original payload frame by adding GENEVE header with its UDP, IP and Ethernet fields """ - return (Ether(src=src_mac, dst=self.mcast_mac) / - IP(src=src_ip, dst=self.mcast_ip4) / - UDP(sport=self.dport, dport=self.dport, chksum=0) / - GENEVE(vni=vni) / - pkt) + return ( + Ether(src=src_mac, dst=self.mcast_mac) + / IP(src=src_ip, dst=self.mcast_ip4) + / UDP(sport=self.dport, dport=self.dport, chksum=0) + / GENEVE(vni=vni) + / pkt + ) def decapsulate(self, pkt): """ @@ -89,19 +93,20 @@ class TestGeneve(BridgeDomain, VppTestCase): ip_range_start = 10 ip_range_end = ip_range_start + n_ucast_tunnels next_hop_address = cls.pg0.remote_ip4 - for dest_ip4 in ip4_range(next_hop_address, ip_range_start, - ip_range_end): + for dest_ip4 in ip4_range(next_hop_address, ip_range_start, ip_range_end): # add host route so dest_ip4 will not be resolved - rip = VppIpRoute(cls, dest_ip4, 32, - [VppRoutePath(next_hop_address, - INVALID_INDEX)], - register=False) + rip = VppIpRoute( + cls, + dest_ip4, + 32, + [VppRoutePath(next_hop_address, INVALID_INDEX)], + register=False, + ) rip.add_vpp_config() r = cls.vapi.geneve_add_del_tunnel( - local_address=cls.pg0.local_ip4, remote_address=dest_ip4, - vni=vni) - cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index, - bd_id=vni) + local_address=cls.pg0.local_ip4, remote_address=dest_ip4, vni=vni + ) + cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index, bd_id=vni) @classmethod def add_del_shared_mcast_dst_load(cls, is_add): @@ -115,9 +120,12 @@ class TestGeneve(BridgeDomain, VppTestCase): for vni in range(vni_start, vni_end): r = cls.vapi.geneve_add_del_tunnel( local_address=cls.pg0.local_ip4, - remote_address=cls.mcast_ip4, mcast_sw_if_index=1, - is_add=is_add, vni=vni) - if r.sw_if_index == 0xffffffff: + remote_address=cls.mcast_ip4, + mcast_sw_if_index=1, + is_add=is_add, + vni=vni, + ) + if r.sw_if_index == 0xFFFFFFFF: raise ValueError("bad sw_if_index: ~0") @classmethod @@ -136,13 +144,15 @@ class TestGeneve(BridgeDomain, VppTestCase): n_distinct_dst_tunnels = 10 ip_range_start = 10 ip_range_end = ip_range_start + n_distinct_dst_tunnels - for dest_ip4 in ip4_range(cls.mcast_ip4, ip_range_start, - ip_range_end): - vni = int(dest_ip4.split('.')[3]) - cls.vapi.geneve_add_del_tunnel(local_address=cls.pg0.local_ip4, - remote_address=dest_ip4, - mcast_sw_if_index=1, is_add=is_add, - vni=vni) + for dest_ip4 in ip4_range(cls.mcast_ip4, ip_range_start, ip_range_end): + vni = int(dest_ip4.split(".")[3]) + cls.vapi.geneve_add_del_tunnel( + local_address=cls.pg0.local_ip4, + remote_address=dest_ip4, + mcast_sw_if_index=1, + is_add=is_add, + vni=vni, + ) @classmethod def add_mcast_tunnels_load(cls): @@ -176,34 +186,41 @@ class TestGeneve(BridgeDomain, VppTestCase): cls.pg0.resolve_arp() # Our Multicast address - cls.mcast_ip4 = '239.1.1.1' + cls.mcast_ip4 = "239.1.1.1" cls.mcast_mac = util.mcast_ip_to_mac(cls.mcast_ip4) # Create GENEVE VTEP on VPP pg0, and put geneve_tunnel0 and pg1 # into BD. - cls.single_tunnel_vni = 0xabcde + cls.single_tunnel_vni = 0xABCDE cls.single_tunnel_bd = 1 r = cls.vapi.geneve_add_del_tunnel( local_address=cls.pg0.local_ip4, - remote_address=cls.pg0.remote_ip4, vni=cls.single_tunnel_vni) - cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index, - bd_id=cls.single_tunnel_bd) + remote_address=cls.pg0.remote_ip4, + vni=cls.single_tunnel_vni, + ) + cls.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=r.sw_if_index, bd_id=cls.single_tunnel_bd + ) cls.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=cls.pg1.sw_if_index, bd_id=cls.single_tunnel_bd) + rx_sw_if_index=cls.pg1.sw_if_index, bd_id=cls.single_tunnel_bd + ) # Setup vni 2 to test multicast flooding cls.n_ucast_tunnels = 10 cls.mcast_flood_bd = 2 - cls.create_geneve_flood_test_bd(cls.mcast_flood_bd, - cls.n_ucast_tunnels) + cls.create_geneve_flood_test_bd(cls.mcast_flood_bd, cls.n_ucast_tunnels) r = cls.vapi.geneve_add_del_tunnel( local_address=cls.pg0.local_ip4, - remote_address=cls.mcast_ip4, mcast_sw_if_index=1, - vni=cls.mcast_flood_bd) - cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index, - bd_id=cls.mcast_flood_bd) + remote_address=cls.mcast_ip4, + mcast_sw_if_index=1, + vni=cls.mcast_flood_bd, + ) + cls.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=r.sw_if_index, bd_id=cls.mcast_flood_bd + ) cls.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=cls.pg2.sw_if_index, bd_id=cls.mcast_flood_bd) + rx_sw_if_index=cls.pg2.sw_if_index, bd_id=cls.mcast_flood_bd + ) # Add and delete mcast tunnels to check stability cls.add_shared_mcast_dst_load() @@ -213,10 +230,10 @@ class TestGeneve(BridgeDomain, VppTestCase): # Setup vni 3 to test unicast flooding cls.ucast_flood_bd = 3 - cls.create_geneve_flood_test_bd(cls.ucast_flood_bd, - cls.n_ucast_tunnels) + cls.create_geneve_flood_test_bd(cls.ucast_flood_bd, cls.n_ucast_tunnels) cls.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=cls.pg3.sw_if_index, bd_id=cls.ucast_flood_bd) + rx_sw_if_index=cls.pg3.sw_if_index, bd_id=cls.ucast_flood_bd + ) except Exception: super(TestGeneve, cls).tearDownClass() raise @@ -235,7 +252,7 @@ class TestGeneve(BridgeDomain, VppTestCase): class TestGeneveL3(VppTestCase): - """ GENEVE L3 Test Case """ + """GENEVE L3 Test Case""" @classmethod def setUpClass(cls): @@ -265,43 +282,55 @@ class TestGeneveL3(VppTestCase): def test_l3_packet(self): vni = 1234 - r = self.vapi.add_node_next(node_name="geneve4-input", - next_name="ethernet-input") + r = self.vapi.add_node_next( + node_name="geneve4-input", next_name="ethernet-input" + ) r = self.vapi.geneve_add_del_tunnel2( is_add=1, local_address=self.pg0.local_ip4, remote_address=self.pg0.remote_ip4, vni=vni, l3_mode=1, - decap_next_index=r.next_index) + decap_next_index=r.next_index, + ) self.vapi.sw_interface_add_del_address( - sw_if_index=r.sw_if_index, prefix="10.0.0.1/24") - - pkt = (Ether(src=self.pg0.remote_mac, dst="d0:0b:ee:d0:00:00") / - IP(src='10.0.0.2', dst='10.0.0.1') / - ICMP()) - - encap = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / - UDP(sport=6081, dport=6081, chksum=0) / - GENEVE(vni=vni)) - - arp = (Ether(src=self.pg0.remote_mac, dst="d0:0b:ee:d0:00:00") / - ARP(op="is-at", hwsrc=self.pg0.remote_mac, - hwdst="d0:0b:ee:d0:00:00", psrc="10.0.0.2", - pdst="10.0.0.1")) - - rx = self.send_and_expect(self.pg0, encap/pkt*1, self.pg0) - rx = self.send_and_assert_no_replies(self.pg0, encap/arp*1, self.pg0) - rx = self.send_and_expect(self.pg0, encap/pkt*1, self.pg0) + sw_if_index=r.sw_if_index, prefix="10.0.0.1/24" + ) + + pkt = ( + Ether(src=self.pg0.remote_mac, dst="d0:0b:ee:d0:00:00") + / IP(src="10.0.0.2", dst="10.0.0.1") + / ICMP() + ) + + encap = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / UDP(sport=6081, dport=6081, chksum=0) + / GENEVE(vni=vni) + ) + + arp = Ether(src=self.pg0.remote_mac, dst="d0:0b:ee:d0:00:00") / ARP( + op="is-at", + hwsrc=self.pg0.remote_mac, + hwdst="d0:0b:ee:d0:00:00", + psrc="10.0.0.2", + pdst="10.0.0.1", + ) + + rx = self.send_and_expect(self.pg0, encap / pkt * 1, self.pg0) + rx = self.send_and_assert_no_replies(self.pg0, encap / arp * 1, self.pg0) + rx = self.send_and_expect(self.pg0, encap / pkt * 1, self.pg0) self.assertEqual(rx[0][ICMP].type, 0) # echo reply r = self.vapi.geneve_add_del_tunnel2( is_add=0, local_address=self.pg0.local_ip4, remote_address=self.pg0.remote_ip4, - vni=vni) + vni=vni, + ) + -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_gre.py b/test/test_gre.py index ba20ba8dec0..a79819ed73c 100644 --- a/test/test_gre.py +++ b/test/test_gre.py @@ -15,8 +15,13 @@ from vpp_sub_interface import L2_VTR_OP, VppDot1QSubint from vpp_gre_interface import VppGreInterface from vpp_teib import VppTeib from vpp_ip import DpoProto -from vpp_ip_route import VppIpRoute, VppRoutePath, VppIpTable, FibPathProto, \ - VppMplsLabel +from vpp_ip_route import ( + VppIpRoute, + VppRoutePath, + VppIpTable, + FibPathProto, + VppMplsLabel, +) from vpp_mpls_tunnel_interface import VppMPLSTunnelInterface from util import ppp, ppc from vpp_papi import VppEnum @@ -24,7 +29,7 @@ from vpp_papi import VppEnum @tag_fixme_vpp_workers class TestGREInputNodes(VppTestCase): - """ GRE Input Nodes Test Case """ + """GRE Input Nodes Test Case""" def setUp(self): super(TestGREInputNodes, self).setUp() @@ -43,16 +48,17 @@ class TestGREInputNodes(VppTestCase): super(TestGREInputNodes, self).tearDown() def test_gre_input_node(self): - """ GRE gre input nodes not registerd unless configured """ - pkt = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / - GRE()) + """GRE gre input nodes not registerd unless configured""" + pkt = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / GRE() + ) self.pg0.add_stream(pkt) self.pg_start() # no tunnel created, gre-input not registered - err = self.statistics.get_counter( - '/err/ip4-local/unknown ip protocol')[0] + err = self.statistics.get_counter("/err/ip4-local/unknown ip protocol")[0] self.assertEqual(err, 1) err_count = err @@ -63,14 +69,13 @@ class TestGREInputNodes(VppTestCase): self.pg0.add_stream(pkt) self.pg_start() # tunnel created, gre-input registered - err = self.statistics.get_counter( - '/err/ip4-local/unknown ip protocol')[0] + err = self.statistics.get_counter("/err/ip4-local/unknown ip protocol")[0] # expect no new errors self.assertEqual(err, err_count) class TestGRE(VppTestCase): - """ GRE Test Case """ + """GRE Test Case""" @classmethod def setUpClass(cls): @@ -118,10 +123,12 @@ class TestGRE(VppTestCase): for i in range(0, 257): info = self.create_packet_info(src_if, src_if) payload = self.info_to_payload(info) - p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - IP(src=src_ip, dst=dst_ip, tos=tos) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / IP(src=src_ip, dst=dst_ip, tos=tos) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) info.data = p.copy() pkts.append(p) return pkts @@ -132,107 +139,107 @@ class TestGRE(VppTestCase): for i in range(0, 257): info = self.create_packet_info(src_if, src_if) payload = self.info_to_payload(info) - p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - IPv6(src=src_ip, dst=dst_ip, tc=tc) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / IPv6(src=src_ip, dst=dst_ip, tc=tc) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) info.data = p.copy() pkts.append(p) return pkts - def create_tunnel_stream_4o4(self, src_if, - tunnel_src, tunnel_dst, - src_ip, dst_ip): + def create_tunnel_stream_4o4(self, src_if, tunnel_src, tunnel_dst, src_ip, dst_ip): pkts = [] for i in range(0, 257): info = self.create_packet_info(src_if, src_if) payload = self.info_to_payload(info) - p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - IP(src=tunnel_src, dst=tunnel_dst) / - GRE() / - IP(src=src_ip, dst=dst_ip) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / IP(src=tunnel_src, dst=tunnel_dst) + / GRE() + / IP(src=src_ip, dst=dst_ip) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) info.data = p.copy() pkts.append(p) return pkts - def create_tunnel_stream_6o4(self, src_if, - tunnel_src, tunnel_dst, - src_ip, dst_ip): + def create_tunnel_stream_6o4(self, src_if, tunnel_src, tunnel_dst, src_ip, dst_ip): pkts = [] for i in range(0, 257): info = self.create_packet_info(src_if, src_if) payload = self.info_to_payload(info) - p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - IP(src=tunnel_src, dst=tunnel_dst) / - GRE() / - IPv6(src=src_ip, dst=dst_ip) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / IP(src=tunnel_src, dst=tunnel_dst) + / GRE() + / IPv6(src=src_ip, dst=dst_ip) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) info.data = p.copy() pkts.append(p) return pkts - def create_tunnel_stream_6o6(self, src_if, - tunnel_src, tunnel_dst, - src_ip, dst_ip): + def create_tunnel_stream_6o6(self, src_if, tunnel_src, tunnel_dst, src_ip, dst_ip): pkts = [] for i in range(0, 257): info = self.create_packet_info(src_if, src_if) payload = self.info_to_payload(info) - p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - IPv6(src=tunnel_src, dst=tunnel_dst) / - GRE() / - IPv6(src=src_ip, dst=dst_ip) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / IPv6(src=tunnel_src, dst=tunnel_dst) + / GRE() + / IPv6(src=src_ip, dst=dst_ip) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) info.data = p.copy() pkts.append(p) return pkts - def create_tunnel_stream_l2o4(self, src_if, - tunnel_src, tunnel_dst): + def create_tunnel_stream_l2o4(self, src_if, tunnel_src, tunnel_dst): pkts = [] for i in range(0, 257): info = self.create_packet_info(src_if, src_if) payload = self.info_to_payload(info) - p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - IP(src=tunnel_src, dst=tunnel_dst) / - GRE() / - Ether(dst=RandMAC('*:*:*:*:*:*'), - src=RandMAC('*:*:*:*:*:*')) / - IP(src=scapy.compat.raw(RandIP()), - dst=scapy.compat.raw(RandIP())) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / IP(src=tunnel_src, dst=tunnel_dst) + / GRE() + / Ether(dst=RandMAC("*:*:*:*:*:*"), src=RandMAC("*:*:*:*:*:*")) + / IP(src=scapy.compat.raw(RandIP()), dst=scapy.compat.raw(RandIP())) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) info.data = p.copy() pkts.append(p) return pkts - def create_tunnel_stream_vlano4(self, src_if, - tunnel_src, tunnel_dst, vlan): + def create_tunnel_stream_vlano4(self, src_if, tunnel_src, tunnel_dst, vlan): pkts = [] for i in range(0, 257): info = self.create_packet_info(src_if, src_if) payload = self.info_to_payload(info) - p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - IP(src=tunnel_src, dst=tunnel_dst) / - GRE() / - Ether(dst=RandMAC('*:*:*:*:*:*'), - src=RandMAC('*:*:*:*:*:*')) / - Dot1Q(vlan=vlan) / - IP(src=scapy.compat.raw(RandIP()), - dst=scapy.compat.raw(RandIP())) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / IP(src=tunnel_src, dst=tunnel_dst) + / GRE() + / Ether(dst=RandMAC("*:*:*:*:*:*"), src=RandMAC("*:*:*:*:*:*")) + / Dot1Q(vlan=vlan) + / IP(src=scapy.compat.raw(RandIP()), dst=scapy.compat.raw(RandIP())) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) info.data = p.copy() pkts.append(p) return pkts - def verify_tunneled_4o4(self, src_if, capture, sent, - tunnel_src, tunnel_dst, - dscp=0, ecn=0): + def verify_tunneled_4o4( + self, src_if, capture, sent, tunnel_src, tunnel_dst, dscp=0, ecn=0 + ): self.assertEqual(len(capture), len(sent)) tos = (dscp << 2) | ecn @@ -263,9 +270,9 @@ class TestGRE(VppTestCase): self.logger.error(ppp("Tx:", tx)) raise - def verify_tunneled_6o6(self, src_if, capture, sent, - tunnel_src, tunnel_dst, - dscp=0, ecn=0): + def verify_tunneled_6o6( + self, src_if, capture, sent, tunnel_src, tunnel_dst, dscp=0, ecn=0 + ): self.assertEqual(len(capture), len(sent)) tc = (dscp << 2) | ecn @@ -296,8 +303,7 @@ class TestGRE(VppTestCase): self.logger.error(ppp("Tx:", tx)) raise - def verify_tunneled_4o6(self, src_if, capture, sent, - tunnel_src, tunnel_dst): + def verify_tunneled_4o6(self, src_if, capture, sent, tunnel_src, tunnel_dst): self.assertEqual(len(capture), len(sent)) @@ -326,8 +332,7 @@ class TestGRE(VppTestCase): self.logger.error(ppp("Tx:", tx)) raise - def verify_tunneled_6o4(self, src_if, capture, sent, - tunnel_src, tunnel_dst): + def verify_tunneled_6o4(self, src_if, capture, sent, tunnel_src, tunnel_dst): self.assertEqual(len(capture), len(sent)) @@ -354,8 +359,7 @@ class TestGRE(VppTestCase): self.logger.error(ppp("Tx:", tx)) raise - def verify_tunneled_l2o4(self, src_if, capture, sent, - tunnel_src, tunnel_dst): + def verify_tunneled_l2o4(self, src_if, capture, sent, tunnel_src, tunnel_dst): self.assertEqual(len(capture), len(sent)) for i in range(len(capture)): @@ -387,8 +391,9 @@ class TestGRE(VppTestCase): self.logger.error(ppp("Tx:", tx)) raise - def verify_tunneled_vlano4(self, src_if, capture, sent, - tunnel_src, tunnel_dst, vlan): + def verify_tunneled_vlano4( + self, src_if, capture, sent, tunnel_src, tunnel_dst, vlan + ): try: self.assertEqual(len(capture), len(sent)) except: @@ -495,7 +500,7 @@ class TestGRE(VppTestCase): raise def test_gre(self): - """ GRE IPv4 tunnel Tests """ + """GRE IPv4 tunnel Tests""" # # Create an L3 GRE tunnel. @@ -503,9 +508,7 @@ class TestGRE(VppTestCase): # - assign an IP Addres # - Add a route via the tunnel # - gre_if = VppGreInterface(self, - self.pg0.local_ip4, - "1.1.1.2") + gre_if = VppGreInterface(self, self.pg0.local_ip4, "1.1.1.2") gre_if.add_vpp_config() # @@ -522,9 +525,9 @@ class TestGRE(VppTestCase): gre_if.admin_up() gre_if.config_ip4() - route_via_tun = VppIpRoute(self, "4.4.4.4", 32, - [VppRoutePath("0.0.0.0", - gre_if.sw_if_index)]) + route_via_tun = VppIpRoute( + self, "4.4.4.4", 32, [VppRoutePath("0.0.0.0", gre_if.sw_if_index)] + ) route_via_tun.add_vpp_config() @@ -541,9 +544,12 @@ class TestGRE(VppTestCase): # # Add a route that resolves the tunnel's destination # - route_tun_dst = VppIpRoute(self, "1.1.1.2", 32, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index)]) + route_tun_dst = VppIpRoute( + self, + "1.1.1.2", + 32, + [VppRoutePath(self.pg0.remote_ip4, self.pg0.sw_if_index)], + ) route_tun_dst.add_vpp_config() # @@ -552,18 +558,19 @@ class TestGRE(VppTestCase): # tx = self.create_stream_ip4(self.pg0, "5.5.5.5", "4.4.4.4") rx = self.send_and_expect(self.pg0, tx, self.pg0) - self.verify_tunneled_4o4(self.pg0, rx, tx, - self.pg0.local_ip4, "1.1.1.2") + self.verify_tunneled_4o4(self.pg0, rx, tx, self.pg0.local_ip4, "1.1.1.2") # # Send tunneled packets that match the created tunnel and # are decapped and forwarded # - tx = self.create_tunnel_stream_4o4(self.pg0, - "1.1.1.2", - self.pg0.local_ip4, - self.pg0.local_ip4, - self.pg0.remote_ip4) + tx = self.create_tunnel_stream_4o4( + self.pg0, + "1.1.1.2", + self.pg0.local_ip4, + self.pg0.local_ip4, + self.pg0.remote_ip4, + ) rx = self.send_and_expect(self.pg0, tx, self.pg0) self.verify_decapped_4o4(self.pg0, rx, tx) @@ -571,14 +578,16 @@ class TestGRE(VppTestCase): # Send tunneled packets that do not match the tunnel's src # self.vapi.cli("clear trace") - tx = self.create_tunnel_stream_4o4(self.pg0, - "1.1.1.3", - self.pg0.local_ip4, - self.pg0.local_ip4, - self.pg0.remote_ip4) + tx = self.create_tunnel_stream_4o4( + self.pg0, + "1.1.1.3", + self.pg0.local_ip4, + self.pg0.local_ip4, + self.pg0.remote_ip4, + ) self.send_and_assert_no_replies( - self.pg0, tx, - remark="GRE packets forwarded despite no SRC address match") + self.pg0, tx, remark="GRE packets forwarded despite no SRC address match" + ) # # Configure IPv6 on the PG interface so we can route IPv6 @@ -591,14 +600,18 @@ class TestGRE(VppTestCase): # Send IPv6 tunnel encapslated packets # - dropped since IPv6 is not enabled on the tunnel # - tx = self.create_tunnel_stream_6o4(self.pg0, - "1.1.1.2", - self.pg0.local_ip4, - self.pg0.local_ip6, - self.pg0.remote_ip6) - self.send_and_assert_no_replies(self.pg0, tx, - "IPv6 GRE packets forwarded " - "despite IPv6 not enabled on tunnel") + tx = self.create_tunnel_stream_6o4( + self.pg0, + "1.1.1.2", + self.pg0.local_ip4, + self.pg0.local_ip6, + self.pg0.remote_ip6, + ) + self.send_and_assert_no_replies( + self.pg0, + tx, + "IPv6 GRE packets forwarded despite IPv6 not enabled on tunnel", + ) # # Enable IPv6 on the tunnel @@ -609,11 +622,13 @@ class TestGRE(VppTestCase): # Send IPv6 tunnel encapslated packets # - forwarded since IPv6 is enabled on the tunnel # - tx = self.create_tunnel_stream_6o4(self.pg0, - "1.1.1.2", - self.pg0.local_ip4, - self.pg0.local_ip6, - self.pg0.remote_ip6) + tx = self.create_tunnel_stream_6o4( + self.pg0, + "1.1.1.2", + self.pg0.local_ip4, + self.pg0.local_ip6, + self.pg0.remote_ip6, + ) rx = self.send_and_expect(self.pg0, tx, self.pg0) self.verify_decapped_6o4(self.pg0, rx, tx) @@ -621,31 +636,32 @@ class TestGRE(VppTestCase): # Send v6 packets for v4 encap # route6_via_tun = VppIpRoute( - self, "2001::1", 128, - [VppRoutePath("::", - gre_if.sw_if_index, - proto=DpoProto.DPO_PROTO_IP6)]) + self, + "2001::1", + 128, + [VppRoutePath("::", gre_if.sw_if_index, proto=DpoProto.DPO_PROTO_IP6)], + ) route6_via_tun.add_vpp_config() tx = self.create_stream_ip6(self.pg0, "2001::2", "2001::1") rx = self.send_and_expect(self.pg0, tx, self.pg0) - self.verify_tunneled_6o4(self.pg0, rx, tx, - self.pg0.local_ip4, "1.1.1.2") + self.verify_tunneled_6o4(self.pg0, rx, tx, self.pg0.local_ip4, "1.1.1.2") # # add a labelled route through the tunnel # - label_via_tun = VppIpRoute(self, "5.4.3.2", 32, - [VppRoutePath("0.0.0.0", - gre_if.sw_if_index, - labels=[VppMplsLabel(33)])]) + label_via_tun = VppIpRoute( + self, + "5.4.3.2", + 32, + [VppRoutePath("0.0.0.0", gre_if.sw_if_index, labels=[VppMplsLabel(33)])], + ) label_via_tun.add_vpp_config() tx = self.create_stream_ip4(self.pg0, "5.5.5.5", "5.4.3.2") rx = self.send_and_expect(self.pg0, tx, self.pg0) - self.verify_tunneled_4o4(self.pg0, rx, tx, - self.pg0.local_ip4, "1.1.1.2") + self.verify_tunneled_4o4(self.pg0, rx, tx, self.pg0.local_ip4, "1.1.1.2") # # an MPLS tunnel over the GRE tunnel add a route through @@ -653,31 +669,40 @@ class TestGRE(VppTestCase): # mpls_tun = VppMPLSTunnelInterface( self, - [VppRoutePath("0.0.0.0", - gre_if.sw_if_index, - labels=[VppMplsLabel(44), - VppMplsLabel(46)])]) + [ + VppRoutePath( + "0.0.0.0", + gre_if.sw_if_index, + labels=[VppMplsLabel(44), VppMplsLabel(46)], + ) + ], + ) mpls_tun.add_vpp_config() mpls_tun.admin_up() - label_via_mpls = VppIpRoute(self, "5.4.3.1", 32, - [VppRoutePath("0.0.0.0", - mpls_tun.sw_if_index, - labels=[VppMplsLabel(33)])]) + label_via_mpls = VppIpRoute( + self, + "5.4.3.1", + 32, + [VppRoutePath("0.0.0.0", mpls_tun.sw_if_index, labels=[VppMplsLabel(33)])], + ) label_via_mpls.add_vpp_config() tx = self.create_stream_ip4(self.pg0, "5.5.5.5", "5.4.3.1") rx = self.send_and_expect(self.pg0, tx, self.pg0) - self.verify_tunneled_4o4(self.pg0, rx, tx, - self.pg0.local_ip4, "1.1.1.2") + self.verify_tunneled_4o4(self.pg0, rx, tx, self.pg0.local_ip4, "1.1.1.2") mpls_tun_l2 = VppMPLSTunnelInterface( self, - [VppRoutePath("0.0.0.0", - gre_if.sw_if_index, - labels=[VppMplsLabel(44), - VppMplsLabel(46)])], - is_l2=1) + [ + VppRoutePath( + "0.0.0.0", + gre_if.sw_if_index, + labels=[VppMplsLabel(44), VppMplsLabel(46)], + ) + ], + is_l2=1, + ) mpls_tun_l2.add_vpp_config() mpls_tun_l2.admin_up() @@ -696,7 +721,7 @@ class TestGRE(VppTestCase): self.pg0.unconfig_ip6() def test_gre6(self): - """ GRE IPv6 tunnel Tests """ + """GRE IPv6 tunnel Tests""" self.pg1.config_ip6() self.pg1.resolve_ndp() @@ -707,16 +732,14 @@ class TestGRE(VppTestCase): # - assign an IP Address # - Add a route via the tunnel # - gre_if = VppGreInterface(self, - self.pg2.local_ip6, - "1002::1") + gre_if = VppGreInterface(self, self.pg2.local_ip6, "1002::1") gre_if.add_vpp_config() gre_if.admin_up() gre_if.config_ip6() - route_via_tun = VppIpRoute(self, "4004::1", 128, - [VppRoutePath("0::0", - gre_if.sw_if_index)]) + route_via_tun = VppIpRoute( + self, "4004::1", 128, [VppRoutePath("0::0", gre_if.sw_if_index)] + ) route_via_tun.add_vpp_config() @@ -728,15 +751,18 @@ class TestGRE(VppTestCase): # tx = self.create_stream_ip6(self.pg2, "5005::1", "4004::1") self.send_and_assert_no_replies( - self.pg2, tx, - "GRE packets forwarded without DIP resolved") + self.pg2, tx, "GRE packets forwarded without DIP resolved" + ) # # Add a route that resolves the tunnel's destination # - route_tun_dst = VppIpRoute(self, "1002::1", 128, - [VppRoutePath(self.pg2.remote_ip6, - self.pg2.sw_if_index)]) + route_tun_dst = VppIpRoute( + self, + "1002::1", + 128, + [VppRoutePath(self.pg2.remote_ip6, self.pg2.sw_if_index)], + ) route_tun_dst.add_vpp_config() # @@ -745,17 +771,14 @@ class TestGRE(VppTestCase): # tx = self.create_stream_ip6(self.pg2, "5005::1", "4004::1") rx = self.send_and_expect(self.pg2, tx, self.pg2) - self.verify_tunneled_6o6(self.pg2, rx, tx, - self.pg2.local_ip6, "1002::1") + self.verify_tunneled_6o6(self.pg2, rx, tx, self.pg2.local_ip6, "1002::1") # # Test decap. decapped packets go out pg1 # - tx = self.create_tunnel_stream_6o6(self.pg2, - "1002::1", - self.pg2.local_ip6, - "2001::1", - self.pg1.remote_ip6) + tx = self.create_tunnel_stream_6o6( + self.pg2, "1002::1", self.pg2.local_ip6, "2001::1", self.pg1.remote_ip6 + ) rx = self.send_and_expect(self.pg2, tx, self.pg1) # @@ -767,16 +790,15 @@ class TestGRE(VppTestCase): # # Send v4 over v6 # - route4_via_tun = VppIpRoute(self, "1.1.1.1", 32, - [VppRoutePath("0.0.0.0", - gre_if.sw_if_index)]) + route4_via_tun = VppIpRoute( + self, "1.1.1.1", 32, [VppRoutePath("0.0.0.0", gre_if.sw_if_index)] + ) route4_via_tun.add_vpp_config() tx = self.create_stream_ip4(self.pg0, "1.1.1.2", "1.1.1.1") rx = self.send_and_expect(self.pg0, tx, self.pg2) - self.verify_tunneled_4o6(self.pg0, rx, tx, - self.pg2.local_ip6, "1002::1") + self.verify_tunneled_4o6(self.pg0, rx, tx, self.pg2.local_ip6, "1002::1") # # test case cleanup @@ -790,7 +812,7 @@ class TestGRE(VppTestCase): self.pg1.unconfig_ip6() def test_gre_vrf(self): - """ GRE tunnel VRF Tests """ + """GRE tunnel VRF Tests""" e = VppEnum.vl_api_tunnel_encap_decap_flags_t @@ -802,11 +824,15 @@ class TestGRE(VppTestCase): # - assign an IP Addres # gre_if = VppGreInterface( - self, self.pg1.local_ip4, + self, + self.pg1.local_ip4, "2.2.2.2", outer_table_id=1, - flags=(e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP | - e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN)) + flags=( + e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP + | e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN + ), + ) gre_if.add_vpp_config() gre_if.admin_up() @@ -815,18 +841,22 @@ class TestGRE(VppTestCase): # # Add a route via the tunnel - in the overlay # - route_via_tun = VppIpRoute(self, "9.9.9.9", 32, - [VppRoutePath("0.0.0.0", - gre_if.sw_if_index)]) + route_via_tun = VppIpRoute( + self, "9.9.9.9", 32, [VppRoutePath("0.0.0.0", gre_if.sw_if_index)] + ) route_via_tun.add_vpp_config() # # Add a route that resolves the tunnel's destination - in the # underlay table # - route_tun_dst = VppIpRoute(self, "2.2.2.2", 32, table_id=1, - paths=[VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index)]) + route_tun_dst = VppIpRoute( + self, + "2.2.2.2", + 32, + table_id=1, + paths=[VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)], + ) route_tun_dst.add_vpp_config() # @@ -835,12 +865,11 @@ class TestGRE(VppTestCase): # - packets are GRE encapped # self.vapi.cli("clear trace") - tx = self.create_stream_ip4(self.pg0, "5.5.5.5", "9.9.9.9", - dscp=5, ecn=3) + tx = self.create_stream_ip4(self.pg0, "5.5.5.5", "9.9.9.9", dscp=5, ecn=3) rx = self.send_and_expect(self.pg0, tx, self.pg1) - self.verify_tunneled_4o4(self.pg1, rx, tx, - self.pg1.local_ip4, "2.2.2.2", - dscp=5, ecn=3) + self.verify_tunneled_4o4( + self.pg1, rx, tx, self.pg1.local_ip4, "2.2.2.2", dscp=5, ecn=3 + ) # # Send tunneled packets that match the created tunnel and @@ -848,11 +877,13 @@ class TestGRE(VppTestCase): # does not happen in the encap table # self.vapi.cli("clear trace") - tx = self.create_tunnel_stream_4o4(self.pg1, - "2.2.2.2", - self.pg1.local_ip4, - self.pg0.local_ip4, - self.pg0.remote_ip4) + tx = self.create_tunnel_stream_4o4( + self.pg1, + "2.2.2.2", + self.pg1.local_ip4, + self.pg0.local_ip4, + self.pg0.remote_ip4, + ) rx = self.send_and_expect(self.pg1, tx, self.pg0) self.verify_decapped_4o4(self.pg0, rx, tx) @@ -865,14 +896,16 @@ class TestGRE(VppTestCase): # self.pg2.config_ip4() self.vapi.cli("clear trace") - tx = self.create_tunnel_stream_4o4(self.pg2, - "2.2.2.2", - self.pg1.local_ip4, - self.pg0.local_ip4, - self.pg0.remote_ip4) + tx = self.create_tunnel_stream_4o4( + self.pg2, + "2.2.2.2", + self.pg1.local_ip4, + self.pg0.local_ip4, + self.pg0.remote_ip4, + ) rx = self.send_and_assert_no_replies( - self.pg2, tx, - "GRE decap packets in wrong VRF") + self.pg2, tx, "GRE decap packets in wrong VRF" + ) self.pg2.unconfig_ip4() @@ -884,17 +917,23 @@ class TestGRE(VppTestCase): gre_if.remove_vpp_config() def test_gre_l2(self): - """ GRE tunnel L2 Tests """ + """GRE tunnel L2 Tests""" # # Add routes to resolve the tunnel destinations # - route_tun1_dst = VppIpRoute(self, "2.2.2.2", 32, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index)]) - route_tun2_dst = VppIpRoute(self, "2.2.2.3", 32, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index)]) + route_tun1_dst = VppIpRoute( + self, + "2.2.2.2", + 32, + [VppRoutePath(self.pg0.remote_ip4, self.pg0.sw_if_index)], + ) + route_tun2_dst = VppIpRoute( + self, + "2.2.2.3", + 32, + [VppRoutePath(self.pg0.remote_ip4, self.pg0.sw_if_index)], + ) route_tun1_dst.add_vpp_config() route_tun2_dst.add_vpp_config() @@ -902,53 +941,49 @@ class TestGRE(VppTestCase): # # Create 2 L2 GRE tunnels and x-connect them # - gre_if1 = VppGreInterface(self, self.pg0.local_ip4, - "2.2.2.2", - type=(VppEnum.vl_api_gre_tunnel_type_t. - GRE_API_TUNNEL_TYPE_TEB)) - gre_if2 = VppGreInterface(self, self.pg0.local_ip4, - "2.2.2.3", - type=(VppEnum.vl_api_gre_tunnel_type_t. - GRE_API_TUNNEL_TYPE_TEB)) + gre_if1 = VppGreInterface( + self, + self.pg0.local_ip4, + "2.2.2.2", + type=(VppEnum.vl_api_gre_tunnel_type_t.GRE_API_TUNNEL_TYPE_TEB), + ) + gre_if2 = VppGreInterface( + self, + self.pg0.local_ip4, + "2.2.2.3", + type=(VppEnum.vl_api_gre_tunnel_type_t.GRE_API_TUNNEL_TYPE_TEB), + ) gre_if1.add_vpp_config() gre_if2.add_vpp_config() gre_if1.admin_up() gre_if2.admin_up() - self.vapi.sw_interface_set_l2_xconnect(gre_if1.sw_if_index, - gre_if2.sw_if_index, - enable=1) - self.vapi.sw_interface_set_l2_xconnect(gre_if2.sw_if_index, - gre_if1.sw_if_index, - enable=1) + self.vapi.sw_interface_set_l2_xconnect( + gre_if1.sw_if_index, gre_if2.sw_if_index, enable=1 + ) + self.vapi.sw_interface_set_l2_xconnect( + gre_if2.sw_if_index, gre_if1.sw_if_index, enable=1 + ) # # Send in tunnel encapped L2. expect out tunnel encapped L2 # in both directions # - tx = self.create_tunnel_stream_l2o4(self.pg0, - "2.2.2.2", - self.pg0.local_ip4) + tx = self.create_tunnel_stream_l2o4(self.pg0, "2.2.2.2", self.pg0.local_ip4) rx = self.send_and_expect(self.pg0, tx, self.pg0) - self.verify_tunneled_l2o4(self.pg0, rx, tx, - self.pg0.local_ip4, - "2.2.2.3") + self.verify_tunneled_l2o4(self.pg0, rx, tx, self.pg0.local_ip4, "2.2.2.3") - tx = self.create_tunnel_stream_l2o4(self.pg0, - "2.2.2.3", - self.pg0.local_ip4) + tx = self.create_tunnel_stream_l2o4(self.pg0, "2.2.2.3", self.pg0.local_ip4) rx = self.send_and_expect(self.pg0, tx, self.pg0) - self.verify_tunneled_l2o4(self.pg0, rx, tx, - self.pg0.local_ip4, - "2.2.2.2") + self.verify_tunneled_l2o4(self.pg0, rx, tx, self.pg0.local_ip4, "2.2.2.2") - self.vapi.sw_interface_set_l2_xconnect(gre_if1.sw_if_index, - gre_if2.sw_if_index, - enable=0) - self.vapi.sw_interface_set_l2_xconnect(gre_if2.sw_if_index, - gre_if1.sw_if_index, - enable=0) + self.vapi.sw_interface_set_l2_xconnect( + gre_if1.sw_if_index, gre_if2.sw_if_index, enable=0 + ) + self.vapi.sw_interface_set_l2_xconnect( + gre_if2.sw_if_index, gre_if1.sw_if_index, enable=0 + ) # # Create a VLAN sub-interfaces on the GRE TEB interfaces @@ -963,47 +998,39 @@ class TestGRE(VppTestCase): gre_if_11.admin_up() gre_if_12.admin_up() - self.vapi.sw_interface_set_l2_xconnect(gre_if_11.sw_if_index, - gre_if_12.sw_if_index, - enable=1) - self.vapi.sw_interface_set_l2_xconnect(gre_if_12.sw_if_index, - gre_if_11.sw_if_index, - enable=1) + self.vapi.sw_interface_set_l2_xconnect( + gre_if_11.sw_if_index, gre_if_12.sw_if_index, enable=1 + ) + self.vapi.sw_interface_set_l2_xconnect( + gre_if_12.sw_if_index, gre_if_11.sw_if_index, enable=1 + ) # # Configure both to pop thier respective VLAN tags, # so that during the x-coonect they will subsequently push # self.vapi.l2_interface_vlan_tag_rewrite( - sw_if_index=gre_if_12.sw_if_index, vtr_op=L2_VTR_OP.L2_POP_1, - push_dot1q=12) + sw_if_index=gre_if_12.sw_if_index, vtr_op=L2_VTR_OP.L2_POP_1, push_dot1q=12 + ) self.vapi.l2_interface_vlan_tag_rewrite( - sw_if_index=gre_if_11.sw_if_index, vtr_op=L2_VTR_OP.L2_POP_1, - push_dot1q=11) + sw_if_index=gre_if_11.sw_if_index, vtr_op=L2_VTR_OP.L2_POP_1, push_dot1q=11 + ) # # Send traffic in both directiond - expect the VLAN tags to # be swapped. # - tx = self.create_tunnel_stream_vlano4(self.pg0, - "2.2.2.2", - self.pg0.local_ip4, - 11) + tx = self.create_tunnel_stream_vlano4( + self.pg0, "2.2.2.2", self.pg0.local_ip4, 11 + ) rx = self.send_and_expect(self.pg0, tx, self.pg0) - self.verify_tunneled_vlano4(self.pg0, rx, tx, - self.pg0.local_ip4, - "2.2.2.3", - 12) - - tx = self.create_tunnel_stream_vlano4(self.pg0, - "2.2.2.3", - self.pg0.local_ip4, - 12) + self.verify_tunneled_vlano4(self.pg0, rx, tx, self.pg0.local_ip4, "2.2.2.3", 12) + + tx = self.create_tunnel_stream_vlano4( + self.pg0, "2.2.2.3", self.pg0.local_ip4, 12 + ) rx = self.send_and_expect(self.pg0, tx, self.pg0) - self.verify_tunneled_vlano4(self.pg0, rx, tx, - self.pg0.local_ip4, - "2.2.2.2", - 11) + self.verify_tunneled_vlano4(self.pg0, rx, tx, self.pg0.local_ip4, "2.2.2.2", 11) # # Cleanup Test resources @@ -1016,16 +1043,14 @@ class TestGRE(VppTestCase): route_tun2_dst.add_vpp_config() def test_gre_loop(self): - """ GRE tunnel loop Tests """ + """GRE tunnel loop Tests""" # # Create an L3 GRE tunnel. # - set it admin up # - assign an IP Addres # - gre_if = VppGreInterface(self, - self.pg0.local_ip4, - "1.1.1.2") + gre_if = VppGreInterface(self, self.pg0.local_ip4, "1.1.1.2") gre_if.add_vpp_config() gre_if.admin_up() gre_if.config_ip4() @@ -1035,9 +1060,9 @@ class TestGRE(VppTestCase): # through the tunnel, hence forming a loop in the forwarding # graph # - route_dst = VppIpRoute(self, "1.1.1.2", 32, - [VppRoutePath("0.0.0.0", - gre_if.sw_if_index)]) + route_dst = VppIpRoute( + self, "1.1.1.2", 32, [VppRoutePath("0.0.0.0", gre_if.sw_if_index)] + ) route_dst.add_vpp_config() # @@ -1051,8 +1076,7 @@ class TestGRE(VppTestCase): # # break the loop # - route_dst.modify([VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index)]) + route_dst.modify([VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)]) route_dst.add_vpp_config() rx = self.send_and_expect(self.pg0, tx, self.pg1) @@ -1060,15 +1084,14 @@ class TestGRE(VppTestCase): # # a good route throught the tunnel to check it restacked # - route_via_tun_2 = VppIpRoute(self, "2.2.2.2", 32, - [VppRoutePath("0.0.0.0", - gre_if.sw_if_index)]) + route_via_tun_2 = VppIpRoute( + self, "2.2.2.2", 32, [VppRoutePath("0.0.0.0", gre_if.sw_if_index)] + ) route_via_tun_2.add_vpp_config() tx = self.create_stream_ip4(self.pg0, "2.2.2.3", "2.2.2.2") rx = self.send_and_expect(self.pg0, tx, self.pg1) - self.verify_tunneled_4o4(self.pg1, rx, tx, - self.pg0.local_ip4, "1.1.1.2") + self.verify_tunneled_4o4(self.pg1, rx, tx, self.pg0.local_ip4, "1.1.1.2") # # cleanup @@ -1077,7 +1100,7 @@ class TestGRE(VppTestCase): gre_if.remove_vpp_config() def test_mgre(self): - """ mGRE IPv4 tunnel Tests """ + """mGRE IPv4 tunnel Tests""" for itf in self.pg_interfaces[3:]: # @@ -1092,11 +1115,12 @@ class TestGRE(VppTestCase): # - assign an IP Addres # - Add a route via the tunnel # - gre_if = VppGreInterface(self, - itf.local_ip4, - "0.0.0.0", - mode=(VppEnum.vl_api_tunnel_mode_t. - TUNNEL_API_MODE_MP)) + gre_if = VppGreInterface( + self, + itf.local_ip4, + "0.0.0.0", + mode=(VppEnum.vl_api_tunnel_mode_t.TUNNEL_API_MODE_MP), + ) gre_if.add_vpp_config() gre_if.admin_up() gre_if.config_ip4() @@ -1109,11 +1133,13 @@ class TestGRE(VppTestCase): # ensure we don't match to the tunnel if the source address # is all zeros # - tx = self.create_tunnel_stream_4o4(self.pg0, - "0.0.0.0", - itf.local_ip4, - self.pg0.local_ip4, - self.pg0.remote_ip4) + tx = self.create_tunnel_stream_4o4( + self.pg0, + "0.0.0.0", + itf.local_ip4, + self.pg0.local_ip4, + self.pg0.remote_ip4, + ) self.send_and_assert_no_replies(self.pg0, tx) # @@ -1127,9 +1153,11 @@ class TestGRE(VppTestCase): # route traffic via the peer # route_via_tun = VppIpRoute( - self, route_addr, 32, - [VppRoutePath(gre_if._remote_hosts[ii].ip4, - gre_if.sw_if_index)]) + self, + route_addr, + 32, + [VppRoutePath(gre_if._remote_hosts[ii].ip4, gre_if.sw_if_index)], + ) route_via_tun.add_vpp_config() # all packets dropped at this point @@ -1142,9 +1170,12 @@ class TestGRE(VppTestCase): # # Add a TEIB entry resolves the peer # - teib = VppTeib(self, gre_if, - gre_if._remote_hosts[ii].ip4, - itf._remote_hosts[ii].ip4) + teib = VppTeib( + self, + gre_if, + gre_if._remote_hosts[ii].ip4, + itf._remote_hosts[ii].ip4, + ) teib.add_vpp_config() # @@ -1152,15 +1183,17 @@ class TestGRE(VppTestCase): # - packets are GRE encapped # rx = self.send_and_expect(self.pg0, tx_e, itf) - self.verify_tunneled_4o4(self.pg0, rx, tx_e, - itf.local_ip4, - itf._remote_hosts[ii].ip4) - - tx_i = self.create_tunnel_stream_4o4(self.pg0, - itf._remote_hosts[ii].ip4, - itf.local_ip4, - self.pg0.local_ip4, - self.pg0.remote_ip4) + self.verify_tunneled_4o4( + self.pg0, rx, tx_e, itf.local_ip4, itf._remote_hosts[ii].ip4 + ) + + tx_i = self.create_tunnel_stream_4o4( + self.pg0, + itf._remote_hosts[ii].ip4, + itf.local_ip4, + self.pg0.local_ip4, + self.pg0.remote_ip4, + ) rx = self.send_and_expect(self.pg0, tx_i, self.pg0) self.verify_decapped_4o4(self.pg0, rx, tx_i) @@ -1173,9 +1206,9 @@ class TestGRE(VppTestCase): teib.add_vpp_config() rx = self.send_and_expect(self.pg0, tx_e, itf) - self.verify_tunneled_4o4(self.pg0, rx, tx_e, - itf.local_ip4, - itf._remote_hosts[ii].ip4) + self.verify_tunneled_4o4( + self.pg0, rx, tx_e, itf.local_ip4, itf._remote_hosts[ii].ip4 + ) rx = self.send_and_expect(self.pg0, tx_i, self.pg0) self.verify_decapped_4o4(self.pg0, rx, tx_i) @@ -1185,9 +1218,9 @@ class TestGRE(VppTestCase): gre_if.admin_down() gre_if.admin_up() rx = self.send_and_expect(self.pg0, tx_e, itf) - self.verify_tunneled_4o4(self.pg0, rx, tx_e, - itf.local_ip4, - itf._remote_hosts[ii].ip4) + self.verify_tunneled_4o4( + self.pg0, rx, tx_e, itf.local_ip4, itf._remote_hosts[ii].ip4 + ) rx = self.send_and_expect(self.pg0, tx_i, self.pg0) self.verify_decapped_4o4(self.pg0, rx, tx_i) @@ -1195,7 +1228,7 @@ class TestGRE(VppTestCase): gre_if.unconfig_ip4() def test_mgre6(self): - """ mGRE IPv6 tunnel Tests """ + """mGRE IPv6 tunnel Tests""" self.pg0.config_ip6() self.pg0.resolve_ndp() @@ -1220,9 +1253,9 @@ class TestGRE(VppTestCase): self, itf.local_ip6, "::", - mode=(VppEnum.vl_api_tunnel_mode_t. - TUNNEL_API_MODE_MP), - flags=e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP) + mode=(VppEnum.vl_api_tunnel_mode_t.TUNNEL_API_MODE_MP), + flags=e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP, + ) gre_if.add_vpp_config() gre_if.admin_up() @@ -1238,36 +1271,43 @@ class TestGRE(VppTestCase): # # Add a TEIB entry resolves the peer # - teib = VppTeib(self, gre_if, - gre_if._remote_hosts[ii].ip6, - itf._remote_hosts[ii].ip6) + teib = VppTeib( + self, + gre_if, + gre_if._remote_hosts[ii].ip6, + itf._remote_hosts[ii].ip6, + ) teib.add_vpp_config() # # route traffic via the peer # route_via_tun = VppIpRoute( - self, route_addr, 128, - [VppRoutePath(gre_if._remote_hosts[ii].ip6, - gre_if.sw_if_index)]) + self, + route_addr, + 128, + [VppRoutePath(gre_if._remote_hosts[ii].ip6, gre_if.sw_if_index)], + ) route_via_tun.add_vpp_config() # # Send a packet stream that is routed into the tunnel # - packets are GRE encapped # - tx_e = self.create_stream_ip6(self.pg0, "5::5", route_addr, - dscp=2, ecn=1) + tx_e = self.create_stream_ip6( + self.pg0, "5::5", route_addr, dscp=2, ecn=1 + ) rx = self.send_and_expect(self.pg0, tx_e, itf) - self.verify_tunneled_6o6(self.pg0, rx, tx_e, - itf.local_ip6, - itf._remote_hosts[ii].ip6, - dscp=2) - tx_i = self.create_tunnel_stream_6o6(self.pg0, - itf._remote_hosts[ii].ip6, - itf.local_ip6, - self.pg0.local_ip6, - self.pg0.remote_ip6) + self.verify_tunneled_6o6( + self.pg0, rx, tx_e, itf.local_ip6, itf._remote_hosts[ii].ip6, dscp=2 + ) + tx_i = self.create_tunnel_stream_6o6( + self.pg0, + itf._remote_hosts[ii].ip6, + itf.local_ip6, + self.pg0.local_ip6, + self.pg0.remote_ip6, + ) rx = self.send_and_expect(self.pg0, tx_i, self.pg0) self.verify_decapped_6o6(self.pg0, rx, tx_i) @@ -1279,10 +1319,9 @@ class TestGRE(VppTestCase): teib.add_vpp_config() rx = self.send_and_expect(self.pg0, tx_e, itf) - self.verify_tunneled_6o6(self.pg0, rx, tx_e, - itf.local_ip6, - itf._remote_hosts[ii].ip6, - dscp=2) + self.verify_tunneled_6o6( + self.pg0, rx, tx_e, itf.local_ip6, itf._remote_hosts[ii].ip6, dscp=2 + ) rx = self.send_and_expect(self.pg0, tx_i, self.pg0) self.verify_decapped_6o6(self.pg0, rx, tx_i) @@ -1292,5 +1331,5 @@ class TestGRE(VppTestCase): self.pg0.unconfig_ip6() -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_gro.py b/test/test_gro.py index 6c68299d7f4..7e6b03c91d4 100644 --- a/test/test_gro.py +++ b/test/test_gro.py @@ -26,7 +26,7 @@ from vpp_interface import VppInterface class TestGRO(VppTestCase): - """ GRO Test Case """ + """GRO Test Case""" @classmethod def setUpClass(self): @@ -63,17 +63,18 @@ class TestGRO(VppTestCase): i.admin_down() def test_gro(self): - """ GRO test """ + """GRO test""" n_packets = 124 # # Send 1500 bytes frame with gro disabled # - p4 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, - flags='DF') / - TCP(sport=1234, dport=4321) / - Raw(b'\xa5' * 1460)) + p4 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, flags="DF") + / TCP(sport=1234, dport=4321) + / Raw(b"\xa5" * 1460) + ) rxs = self.send_and_expect(self.pg0, n_packets * p4, self.pg1) for rx in rxs: @@ -91,11 +92,14 @@ class TestGRO(VppTestCase): p = [] s = 0 for n in range(0, n_packets): - p.append((Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg2.remote_ip4, - flags='DF') / - TCP(sport=1234, dport=4321, seq=s, ack=n, flags='A') / - Raw(b'\xa5' * 1460))) + p.append( + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg2.remote_ip4, flags="DF") + / TCP(sport=1234, dport=4321, seq=s, ack=n, flags="A") + / Raw(b"\xa5" * 1460) + ) + ) s += 1460 rxs = self.send_and_expect(self.pg0, p, self.pg2, n_rx=2) @@ -110,14 +114,15 @@ class TestGRO(VppTestCase): self.assertEqual(rx[IP].len, 64280) # 1460 * 44 + 40 < 65536 self.assertEqual(rx[TCP].sport, 1234) self.assertEqual(rx[TCP].dport, 4321) - self.assertEqual(rx[TCP].ack, (44*i - 1)) + self.assertEqual(rx[TCP].ack, (44 * i - 1)) - p4_temp = (Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) / - IP(src=self.pg2.remote_ip4, dst=self.pg0.remote_ip4, - flags='DF') / - TCP(sport=1234, dport=4321, flags='F')) + p4_temp = ( + Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) + / IP(src=self.pg2.remote_ip4, dst=self.pg0.remote_ip4, flags="DF") + / TCP(sport=1234, dport=4321, flags="F") + ) - rxs = self.send_and_expect(self.pg2, 100*[p4_temp], self.pg0, n_rx=100) + rxs = self.send_and_expect(self.pg2, 100 * [p4_temp], self.pg0, n_rx=100) rx_coalesce = self.pg2.get_capture(1, timeout=1) rx0 = rx_coalesce[0] @@ -144,12 +149,16 @@ class TestGRO(VppTestCase): p = [] s = 0 for n in range(0, 88): - p.append((Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg2.remote_ip6) / - TCP(sport=1234, dport=4321, seq=s, ack=n, flags='A') / - Raw(b'\xa5' * 1460))) + p.append( + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg2.remote_ip6) + / TCP(sport=1234, dport=4321, seq=s, ack=n, flags="A") + / Raw(b"\xa5" * 1460) + ) + ) s += 1460 - p[-1][TCP].flags = 'AP' # push to flush second packet + p[-1][TCP].flags = "AP" # push to flush second packet rxs = self.send_and_expect(self.pg0, p, self.pg2, n_rx=2) @@ -163,7 +172,7 @@ class TestGRO(VppTestCase): self.assertEqual(rx[IPv6].plen, 64260) # 1460 * 44 + 20 < 65536 self.assertEqual(rx[TCP].sport, 1234) self.assertEqual(rx[TCP].dport, 4321) - self.assertEqual(rx[TCP].ack, (44*i - 1)) + self.assertEqual(rx[TCP].ack, (44 * i - 1)) # # Send a series of 1500 bytes packets each followed by a packet with a @@ -172,18 +181,23 @@ class TestGRO(VppTestCase): p = [] s = 0 for n in range(0, n_packets): - p.append((Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg2.remote_ip4, - flags='DF') / - TCP(sport=1234, dport=4321, seq=s, ack=2*n, flags='A') / - Raw(b'\xa5' * 1460))) + p.append( + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg2.remote_ip4, flags="DF") + / TCP(sport=1234, dport=4321, seq=s, ack=2 * n, flags="A") + / Raw(b"\xa5" * 1460) + ) + ) s += 1460 - p.append((Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg2.remote_ip4, - flags='DF') / - TCP(sport=1234, dport=4321, seq=s, ack=2*n+1, - flags='AP') / - Raw(b'\xa5' * 1340))) + p.append( + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg2.remote_ip4, flags="DF") + / TCP(sport=1234, dport=4321, seq=s, ack=2 * n + 1, flags="AP") + / Raw(b"\xa5" * 1340) + ) + ) s += 1340 rxs = self.send_and_expect(self.pg0, p, self.pg2, n_rx=n_packets) @@ -197,7 +211,7 @@ class TestGRO(VppTestCase): self.assertEqual(rx[IP].len, 40 + 1460 + 1340) self.assertEqual(rx[TCP].sport, 1234) self.assertEqual(rx[TCP].dport, 4321) - self.assertEqual(rx[TCP].ack, (2*i + 1)) + self.assertEqual(rx[TCP].ack, (2 * i + 1)) i += 1 # @@ -209,20 +223,24 @@ class TestGRO(VppTestCase): s = 0 for n in range(0, n_packets): i = self.pg0 - p.append((Ether(src=i.remote_mac, dst=i.local_mac) / - IP(src=i.remote_ip4, dst=self.pg2.remote_ip4, - flags='DF') / - TCP(sport=1234, dport=4321, seq=s, ack=2*n, flags='A') / - Raw(b'\xa5' * 1459))) + p.append( + ( + Ether(src=i.remote_mac, dst=i.local_mac) + / IP(src=i.remote_ip4, dst=self.pg2.remote_ip4, flags="DF") + / TCP(sport=1234, dport=4321, seq=s, ack=2 * n, flags="A") + / Raw(b"\xa5" * 1459) + ) + ) s += 1459 - p2 = (Ether(src=i.remote_mac, dst=i.local_mac) / - IP(src=i.remote_ip4, dst=self.pg2.remote_ip4, - flags='DF', len=41) / - TCP(sport=1234, dport=4321, seq=s, ack=2*n+1, flags='A') / - Raw(b'\xa5')) + p2 = ( + Ether(src=i.remote_mac, dst=i.local_mac) + / IP(src=i.remote_ip4, dst=self.pg2.remote_ip4, flags="DF", len=41) + / TCP(sport=1234, dport=4321, seq=s, ack=2 * n + 1, flags="A") + / Raw(b"\xa5") + ) # first compute csum of pkt w/o padding to work around scapy bug p2 = Ether(bytes(p2)) - p.append(p2 / Raw(b'\xa5' * 5)) # 1 byte data + 5 bytes padding + p.append(p2 / Raw(b"\xa5" * 5)) # 1 byte data + 5 bytes padding s += 1 rxs = self.send_and_expect(self.pg0, p, self.pg2, n_rx=n_packets) @@ -236,9 +254,9 @@ class TestGRO(VppTestCase): self.assertEqual(rx[IP].len, 40 + 1459 + 1) self.assertEqual(rx[TCP].sport, 1234) self.assertEqual(rx[TCP].dport, 4321) - self.assertEqual(rx[TCP].ack, (2*i + 1)) + self.assertEqual(rx[TCP].ack, (2 * i + 1)) i += 1 -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_gso.py b/test/test_gso.py index ee676a41c4a..5368531e539 100644 --- a/test/test_gso.py +++ b/test/test_gso.py @@ -30,8 +30,12 @@ from socket import AF_INET, AF_INET6, inet_pton from util import reassemble4 from vpp_ipsec import VppIpsecSA, VppIpsecTunProtect -from template_ipsec import IPsecIPv4Params, IPsecIPv6Params, \ - mk_scapy_crypt_key, config_tun_params +from template_ipsec import ( + IPsecIPv4Params, + IPsecIPv6Params, + mk_scapy_crypt_key, + config_tun_params, +) """ Test_gso is a subclass of VPPTestCase classes. GSO tests. @@ -39,7 +43,7 @@ from template_ipsec import IPsecIPv4Params, IPsecIPv6Params, \ class TestGSO(VppTestCase): - """ GSO Test Case """ + """GSO Test Case""" def __init__(self, *args): VppTestCase.__init__(self, *args) @@ -70,18 +74,26 @@ class TestGSO(VppTestCase): i.resolve_ndp() self.single_tunnel_bd = 10 - self.vxlan = VppVxlanTunnel(self, src=self.pg0.local_ip4, - dst=self.pg0.remote_ip4, - vni=self.single_tunnel_bd) - - self.vxlan2 = VppVxlanTunnel(self, src=self.pg0.local_ip6, - dst=self.pg0.remote_ip6, - vni=self.single_tunnel_bd) - - self.ipip4 = VppIpIpTunInterface(self, self.pg0, self.pg0.local_ip4, - self.pg0.remote_ip4) - self.ipip6 = VppIpIpTunInterface(self, self.pg0, self.pg0.local_ip6, - self.pg0.remote_ip6) + self.vxlan = VppVxlanTunnel( + self, + src=self.pg0.local_ip4, + dst=self.pg0.remote_ip4, + vni=self.single_tunnel_bd, + ) + + self.vxlan2 = VppVxlanTunnel( + self, + src=self.pg0.local_ip6, + dst=self.pg0.remote_ip6, + vni=self.single_tunnel_bd, + ) + + self.ipip4 = VppIpIpTunInterface( + self, self.pg0, self.pg0.local_ip4, self.pg0.remote_ip4 + ) + self.ipip6 = VppIpIpTunInterface( + self, self.pg0, self.pg0.local_ip6, self.pg0.remote_ip6 + ) def tearDown(self): super(TestGSO, self).tearDown() @@ -92,15 +104,16 @@ class TestGSO(VppTestCase): i.admin_down() def test_gso(self): - """ GSO test """ + """GSO test""" # # Send jumbo frame with gso disabled and DF bit is set # - p4 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, - flags='DF') / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 65200)) + p4 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, flags="DF") + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 65200) + ) rxs = self.send_and_expect(self.pg0, [p4], self.pg0) @@ -115,13 +128,14 @@ class TestGSO(VppTestCase): # # Send checksum offload frames # - p40 = (Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) / - IP(src=self.pg2.remote_ip4, dst=self.pg0.remote_ip4, - flags='DF') / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 1460)) + p40 = ( + Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) + / IP(src=self.pg2.remote_ip4, dst=self.pg0.remote_ip4, flags="DF") + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 1460) + ) - rxs = self.send_and_expect(self.pg2, 100*[p40], self.pg0) + rxs = self.send_and_expect(self.pg2, 100 * [p40], self.pg0) for rx in rxs: self.assertEqual(rx[Ether].src, self.pg0.local_mac) @@ -133,12 +147,14 @@ class TestGSO(VppTestCase): self.assert_tcp_checksum_valid(rx) self.assertEqual(payload_len, len(rx[Raw])) - p60 = (Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) / - IPv6(src=self.pg2.remote_ip6, dst=self.pg0.remote_ip6) / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 1440)) + p60 = ( + Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) + / IPv6(src=self.pg2.remote_ip6, dst=self.pg0.remote_ip6) + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 1440) + ) - rxs = self.send_and_expect(self.pg2, 100*[p60], self.pg0) + rxs = self.send_and_expect(self.pg2, 100 * [p60], self.pg0) for rx in rxs: self.assertEqual(rx[Ether].src, self.pg0.local_mac) @@ -153,15 +169,17 @@ class TestGSO(VppTestCase): # Send jumbo frame with gso enabled and DF bit is set # input and output interfaces support GSO # - self.vapi.feature_gso_enable_disable(sw_if_index=self.pg3.sw_if_index, - enable_disable=1) - p41 = (Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) / - IP(src=self.pg2.remote_ip4, dst=self.pg3.remote_ip4, - flags='DF') / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 65200)) + self.vapi.feature_gso_enable_disable( + sw_if_index=self.pg3.sw_if_index, enable_disable=1 + ) + p41 = ( + Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) + / IP(src=self.pg2.remote_ip4, dst=self.pg3.remote_ip4, flags="DF") + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 65200) + ) - rxs = self.send_and_expect(self.pg2, 100*[p41], self.pg3, 100) + rxs = self.send_and_expect(self.pg2, 100 * [p41], self.pg3, 100) for rx in rxs: self.assertEqual(rx[Ether].src, self.pg3.local_mac) @@ -175,12 +193,14 @@ class TestGSO(VppTestCase): # # ipv6 # - p61 = (Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) / - IPv6(src=self.pg2.remote_ip6, dst=self.pg3.remote_ip6) / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 65200)) + p61 = ( + Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) + / IPv6(src=self.pg2.remote_ip6, dst=self.pg3.remote_ip6) + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 65200) + ) - rxs = self.send_and_expect(self.pg2, 100*[p61], self.pg3, 100) + rxs = self.send_and_expect(self.pg2, 100 * [p61], self.pg3, 100) for rx in rxs: self.assertEqual(rx[Ether].src, self.pg3.local_mac) @@ -196,15 +216,17 @@ class TestGSO(VppTestCase): # and DF bit is set. GSO packet will be chunked into gso_size # data payload # - self.vapi.feature_gso_enable_disable(sw_if_index=self.pg0.sw_if_index, - enable_disable=1) - p42 = (Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) / - IP(src=self.pg2.remote_ip4, dst=self.pg0.remote_ip4, - flags='DF') / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 65200)) - - rxs = self.send_and_expect(self.pg2, 5*[p42], self.pg0, 225) + self.vapi.feature_gso_enable_disable( + sw_if_index=self.pg0.sw_if_index, enable_disable=1 + ) + p42 = ( + Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) + / IP(src=self.pg2.remote_ip4, dst=self.pg0.remote_ip4, flags="DF") + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 65200) + ) + + rxs = self.send_and_expect(self.pg2, 5 * [p42], self.pg0, 225) size = 0 for rx in rxs: self.assertEqual(rx[Ether].src, self.pg0.local_mac) @@ -218,17 +240,19 @@ class TestGSO(VppTestCase): self.assertEqual(rx[TCP].dport, 1234) self.assertEqual(payload_len, len(rx[Raw])) size += payload_len - self.assertEqual(size, 65200*5) + self.assertEqual(size, 65200 * 5) # # ipv6 # - p62 = (Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) / - IPv6(src=self.pg2.remote_ip6, dst=self.pg0.remote_ip6) / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 65200)) + p62 = ( + Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) + / IPv6(src=self.pg2.remote_ip6, dst=self.pg0.remote_ip6) + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 65200) + ) - rxs = self.send_and_expect(self.pg2, 5*[p62], self.pg0, 225) + rxs = self.send_and_expect(self.pg2, 5 * [p62], self.pg0, 225) size = 0 for rx in rxs: self.assertEqual(rx[Ether].src, self.pg0.local_mac) @@ -241,22 +265,25 @@ class TestGSO(VppTestCase): self.assertEqual(rx[TCP].dport, 1234) self.assertEqual(payload_len, len(rx[Raw])) size += payload_len - self.assertEqual(size, 65200*5) + self.assertEqual(size, 65200 * 5) # # Send jumbo frame with gso enabled only on input interface # and DF bit is unset. GSO packet will be fragmented. # self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [576, 0, 0, 0]) - self.vapi.feature_gso_enable_disable(sw_if_index=self.pg1.sw_if_index, - enable_disable=1) + self.vapi.feature_gso_enable_disable( + sw_if_index=self.pg1.sw_if_index, enable_disable=1 + ) - p43 = (Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) / - IP(src=self.pg2.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 65200)) + p43 = ( + Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) + / IP(src=self.pg2.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 65200) + ) - rxs = self.send_and_expect(self.pg2, 5*[p43], self.pg1, 5*119) + rxs = self.send_and_expect(self.pg2, 5 * [p43], self.pg1, 5 * 119) size = 0 for rx in rxs: self.assertEqual(rx[Ether].src, self.pg1.local_mac) @@ -265,8 +292,8 @@ class TestGSO(VppTestCase): self.assertEqual(rx[IP].dst, self.pg1.remote_ip4) self.assert_ip_checksum_valid(rx) size += rx[IP].len - 20 - size -= 20*5 # TCP header - self.assertEqual(size, 65200*5) + size -= 20 * 5 # TCP header + self.assertEqual(size, 65200 * 5) # # IPv6 @@ -274,12 +301,14 @@ class TestGSO(VppTestCase): # ICMPv6 Packet Too Big will be sent back to sender. # self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [1280, 0, 0, 0]) - p63 = (Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) / - IPv6(src=self.pg2.remote_ip6, dst=self.pg1.remote_ip6) / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 65200)) - - rxs = self.send_and_expect_some(self.pg2, 5*[p63], self.pg2, 5) + p63 = ( + Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) + / IPv6(src=self.pg2.remote_ip6, dst=self.pg1.remote_ip6) + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 65200) + ) + + rxs = self.send_and_expect_some(self.pg2, 5 * [p63], self.pg2, 5) for rx in rxs: self.assertEqual(rx[Ether].src, self.pg2.local_mac) self.assertEqual(rx[Ether].dst, self.pg2.remote_mac) @@ -299,12 +328,14 @@ class TestGSO(VppTestCase): # self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [9000, 0, 0, 0]) self.vapi.sw_interface_set_mtu(self.pg4.sw_if_index, [9000, 0, 0, 0]) - p44 = (Ether(src=self.pg4.remote_mac, dst=self.pg4.local_mac) / - IP(src=self.pg4.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 65200)) - - rxs = self.send_and_expect(self.pg4, 5*[p44], self.pg1, 165) + p44 = ( + Ether(src=self.pg4.remote_mac, dst=self.pg4.local_mac) + / IP(src=self.pg4.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 65200) + ) + + rxs = self.send_and_expect(self.pg4, 5 * [p44], self.pg1, 165) size = 0 for rx in rxs: self.assertEqual(rx[Ether].src, self.pg1.local_mac) @@ -316,17 +347,19 @@ class TestGSO(VppTestCase): self.assert_tcp_checksum_valid(rx) self.assertEqual(payload_len, len(rx[Raw])) size += payload_len - self.assertEqual(size, 65200*5) + self.assertEqual(size, 65200 * 5) # # IPv6 # - p64 = (Ether(src=self.pg4.remote_mac, dst=self.pg4.local_mac) / - IPv6(src=self.pg4.remote_ip6, dst=self.pg1.remote_ip6) / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 65200)) + p64 = ( + Ether(src=self.pg4.remote_mac, dst=self.pg4.local_mac) + / IPv6(src=self.pg4.remote_ip6, dst=self.pg1.remote_ip6) + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 65200) + ) - rxs = self.send_and_expect(self.pg4, 5*[p64], self.pg1, 170) + rxs = self.send_and_expect(self.pg4, 5 * [p64], self.pg1, 170) size = 0 for rx in rxs: self.assertEqual(rx[Ether].src, self.pg1.local_mac) @@ -337,15 +370,17 @@ class TestGSO(VppTestCase): self.assert_tcp_checksum_valid(rx) self.assertEqual(payload_len, len(rx[Raw])) size += payload_len - self.assertEqual(size, 65200*5) + self.assertEqual(size, 65200 * 5) - self.vapi.feature_gso_enable_disable(sw_if_index=self.pg0.sw_if_index, - enable_disable=0) - self.vapi.feature_gso_enable_disable(sw_if_index=self.pg1.sw_if_index, - enable_disable=0) + self.vapi.feature_gso_enable_disable( + sw_if_index=self.pg0.sw_if_index, enable_disable=0 + ) + self.vapi.feature_gso_enable_disable( + sw_if_index=self.pg1.sw_if_index, enable_disable=0 + ) def test_gso_vxlan(self): - """ GSO VXLAN test """ + """GSO VXLAN test""" self.logger.info(self.vapi.cli("sh int addr")) # # Send jumbo frame with gso enabled only on input interface and @@ -358,21 +393,26 @@ class TestGSO(VppTestCase): # self.vxlan.add_vpp_config() self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.vxlan.sw_if_index, bd_id=self.single_tunnel_bd) + rx_sw_if_index=self.vxlan.sw_if_index, bd_id=self.single_tunnel_bd + ) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg2.sw_if_index, bd_id=self.single_tunnel_bd) - self.vapi.feature_gso_enable_disable(sw_if_index=self.pg0.sw_if_index, - enable_disable=1) + rx_sw_if_index=self.pg2.sw_if_index, bd_id=self.single_tunnel_bd + ) + self.vapi.feature_gso_enable_disable( + sw_if_index=self.pg0.sw_if_index, enable_disable=1 + ) # # IPv4/IPv4 - VXLAN # - p45 = (Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") / - IP(src=self.pg2.remote_ip4, dst="172.16.3.3", flags='DF') / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 65200)) + p45 = ( + Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") + / IP(src=self.pg2.remote_ip4, dst="172.16.3.3", flags="DF") + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 65200) + ) - rxs = self.send_and_expect(self.pg2, 5*[p45], self.pg0, 225) + rxs = self.send_and_expect(self.pg2, 5 * [p45], self.pg0, 225) size = 0 for rx in rxs: self.assertEqual(rx[Ether].src, self.pg0.local_mac) @@ -393,17 +433,19 @@ class TestGSO(VppTestCase): payload_len = inner[IP].len - 20 - 20 self.assertEqual(payload_len, len(inner[Raw])) size += payload_len - self.assertEqual(size, 65200*5) + self.assertEqual(size, 65200 * 5) # # IPv4/IPv6 - VXLAN # - p65 = (Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") / - IPv6(src=self.pg2.remote_ip6, dst="fd01:3::3") / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 65200)) + p65 = ( + Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") + / IPv6(src=self.pg2.remote_ip6, dst="fd01:3::3") + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 65200) + ) - rxs = self.send_and_expect(self.pg2, 5*[p65], self.pg0, 225) + rxs = self.send_and_expect(self.pg2, 5 * [p65], self.pg0, 225) size = 0 for rx in rxs: self.assertEqual(rx[Ether].src, self.pg0.local_mac) @@ -423,7 +465,7 @@ class TestGSO(VppTestCase): payload_len = inner[IPv6].plen - 20 self.assertEqual(payload_len, len(inner[Raw])) size += payload_len - self.assertEqual(size, 65200*5) + self.assertEqual(size, 65200 * 5) # # disable ipv4/vxlan @@ -435,18 +477,20 @@ class TestGSO(VppTestCase): # self.vxlan2.add_vpp_config() self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.vxlan2.sw_if_index, - bd_id=self.single_tunnel_bd) + rx_sw_if_index=self.vxlan2.sw_if_index, bd_id=self.single_tunnel_bd + ) # # IPv6/IPv4 - VXLAN # - p46 = (Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") / - IP(src=self.pg2.remote_ip4, dst="172.16.3.3", flags='DF') / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 65200)) + p46 = ( + Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") + / IP(src=self.pg2.remote_ip4, dst="172.16.3.3", flags="DF") + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 65200) + ) - rxs = self.send_and_expect(self.pg2, 5*[p46], self.pg0, 225) + rxs = self.send_and_expect(self.pg2, 5 * [p46], self.pg0, 225) size = 0 for rx in rxs: self.assertEqual(rx[Ether].src, self.pg0.local_mac) @@ -466,17 +510,19 @@ class TestGSO(VppTestCase): payload_len = inner[IP].len - 20 - 20 self.assertEqual(payload_len, len(inner[Raw])) size += payload_len - self.assertEqual(size, 65200*5) + self.assertEqual(size, 65200 * 5) # # IPv6/IPv6 - VXLAN # - p66 = (Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") / - IPv6(src=self.pg2.remote_ip6, dst="fd01:3::3") / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 65200)) + p66 = ( + Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") + / IPv6(src=self.pg2.remote_ip6, dst="fd01:3::3") + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 65200) + ) - rxs = self.send_and_expect(self.pg2, 5*[p66], self.pg0, 225) + rxs = self.send_and_expect(self.pg2, 5 * [p66], self.pg0, 225) size = 0 for rx in rxs: self.assertEqual(rx[Ether].src, self.pg0.local_mac) @@ -495,25 +541,27 @@ class TestGSO(VppTestCase): payload_len = inner[IPv6].plen - 20 self.assertEqual(payload_len, len(inner[Raw])) size += payload_len - self.assertEqual(size, 65200*5) + self.assertEqual(size, 65200 * 5) # # disable ipv4/vxlan # self.vxlan2.remove_vpp_config() - self.vapi.feature_gso_enable_disable(sw_if_index=self.pg0.sw_if_index, - enable_disable=0) + self.vapi.feature_gso_enable_disable( + sw_if_index=self.pg0.sw_if_index, enable_disable=0 + ) def test_gso_ipip(self): - """ GSO IPIP test """ + """GSO IPIP test""" self.logger.info(self.vapi.cli("sh int addr")) # # Send jumbo frame with gso enabled only on input interface and # create IPIP tunnel on VPP pg0. # - self.vapi.feature_gso_enable_disable(sw_if_index=self.pg0.sw_if_index, - enable_disable=1) + self.vapi.feature_gso_enable_disable( + sw_if_index=self.pg0.sw_if_index, enable_disable=1 + ) # # enable ipip4 @@ -526,21 +574,30 @@ class TestGSO(VppTestCase): # Add IPv4 routes via tunnel interface self.ip4_via_ip4_tunnel = VppIpRoute( - self, "172.16.10.0", 24, - [VppRoutePath("0.0.0.0", - self.ipip4.sw_if_index, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP4)]) + self, + "172.16.10.0", + 24, + [ + VppRoutePath( + "0.0.0.0", + self.ipip4.sw_if_index, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP4, + ) + ], + ) self.ip4_via_ip4_tunnel.add_vpp_config() # # IPv4/IPv4 - IPIP # - p47 = (Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") / - IP(src=self.pg2.remote_ip4, dst="172.16.10.3", flags='DF') / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 65200)) + p47 = ( + Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") + / IP(src=self.pg2.remote_ip4, dst="172.16.10.3", flags="DF") + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 65200) + ) - rxs = self.send_and_expect(self.pg2, 5*[p47], self.pg0, 225) + rxs = self.send_and_expect(self.pg2, 5 * [p47], self.pg0, 225) size = 0 for rx in rxs: self.assertEqual(rx[Ether].src, self.pg0.local_mac) @@ -558,23 +615,32 @@ class TestGSO(VppTestCase): payload_len = inner[IP].len - 20 - 20 self.assertEqual(payload_len, len(inner[Raw])) size += payload_len - self.assertEqual(size, 65200*5) + self.assertEqual(size, 65200 * 5) self.ip6_via_ip4_tunnel = VppIpRoute( - self, "fd01:10::", 64, - [VppRoutePath("::", - self.ipip4.sw_if_index, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)]) + self, + "fd01:10::", + 64, + [ + VppRoutePath( + "::", + self.ipip4.sw_if_index, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ) + ], + ) self.ip6_via_ip4_tunnel.add_vpp_config() # # IPv4/IPv6 - IPIP # - p67 = (Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") / - IPv6(src=self.pg2.remote_ip6, dst="fd01:10::3") / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 65200)) + p67 = ( + Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") + / IPv6(src=self.pg2.remote_ip6, dst="fd01:10::3") + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 65200) + ) - rxs = self.send_and_expect(self.pg2, 5*[p67], self.pg0, 225) + rxs = self.send_and_expect(self.pg2, 5 * [p67], self.pg0, 225) size = 0 for rx in rxs: self.assertEqual(rx[Ether].src, self.pg0.local_mac) @@ -591,20 +657,21 @@ class TestGSO(VppTestCase): payload_len = inner[IPv6].plen - 20 self.assertEqual(payload_len, len(inner[Raw])) size += payload_len - self.assertEqual(size, 65200*5) + self.assertEqual(size, 65200 * 5) # # Send jumbo frame with gso enabled only on input interface and # create IPIP tunnel on VPP pg0. Enable gso feature node on ipip # tunnel - IPSec use case # - self.vapi.feature_gso_enable_disable(sw_if_index=self.pg0.sw_if_index, - enable_disable=0) self.vapi.feature_gso_enable_disable( - sw_if_index=self.ipip4.sw_if_index, - enable_disable=1) + sw_if_index=self.pg0.sw_if_index, enable_disable=0 + ) + self.vapi.feature_gso_enable_disable( + sw_if_index=self.ipip4.sw_if_index, enable_disable=1 + ) - rxs = self.send_and_expect(self.pg2, 5*[p47], self.pg0, 225) + rxs = self.send_and_expect(self.pg2, 5 * [p47], self.pg0, 225) size = 0 for rx in rxs: self.assertEqual(rx[Ether].src, self.pg0.local_mac) @@ -622,14 +689,14 @@ class TestGSO(VppTestCase): payload_len = inner[IP].len - 20 - 20 self.assertEqual(payload_len, len(inner[Raw])) size += payload_len - self.assertEqual(size, 65200*5) + self.assertEqual(size, 65200 * 5) # # disable ipip4 # self.vapi.feature_gso_enable_disable( - sw_if_index=self.ipip4.sw_if_index, - enable_disable=0) + sw_if_index=self.ipip4.sw_if_index, enable_disable=0 + ) self.ip4_via_ip4_tunnel.remove_vpp_config() self.ip6_via_ip4_tunnel.remove_vpp_config() self.ipip4.remove_vpp_config() @@ -637,8 +704,9 @@ class TestGSO(VppTestCase): # # enable ipip6 # - self.vapi.feature_gso_enable_disable(sw_if_index=self.pg0.sw_if_index, - enable_disable=1) + self.vapi.feature_gso_enable_disable( + sw_if_index=self.pg0.sw_if_index, enable_disable=1 + ) self.ipip6.add_vpp_config() # Set interface up and enable IP on it @@ -647,21 +715,30 @@ class TestGSO(VppTestCase): # Add IPv4 routes via tunnel interface self.ip4_via_ip6_tunnel = VppIpRoute( - self, "172.16.10.0", 24, - [VppRoutePath("0.0.0.0", - self.ipip6.sw_if_index, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP4)]) + self, + "172.16.10.0", + 24, + [ + VppRoutePath( + "0.0.0.0", + self.ipip6.sw_if_index, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP4, + ) + ], + ) self.ip4_via_ip6_tunnel.add_vpp_config() # # IPv6/IPv4 - IPIP # - p48 = (Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") / - IP(src=self.pg2.remote_ip4, dst="172.16.10.3", flags='DF') / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 65200)) + p48 = ( + Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") + / IP(src=self.pg2.remote_ip4, dst="172.16.10.3", flags="DF") + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 65200) + ) - rxs = self.send_and_expect(self.pg2, 5*[p48], self.pg0, 225) + rxs = self.send_and_expect(self.pg2, 5 * [p48], self.pg0, 225) size = 0 for rx in rxs: self.assertEqual(rx[Ether].src, self.pg0.local_mac) @@ -678,24 +755,33 @@ class TestGSO(VppTestCase): payload_len = inner[IP].len - 20 - 20 self.assertEqual(payload_len, len(inner[Raw])) size += payload_len - self.assertEqual(size, 65200*5) + self.assertEqual(size, 65200 * 5) self.ip6_via_ip6_tunnel = VppIpRoute( - self, "fd01:10::", 64, - [VppRoutePath("::", - self.ipip6.sw_if_index, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)]) + self, + "fd01:10::", + 64, + [ + VppRoutePath( + "::", + self.ipip6.sw_if_index, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ) + ], + ) self.ip6_via_ip6_tunnel.add_vpp_config() # # IPv6/IPv6 - IPIP # - p68 = (Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") / - IPv6(src=self.pg2.remote_ip6, dst="fd01:10::3") / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 65200)) + p68 = ( + Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") + / IPv6(src=self.pg2.remote_ip6, dst="fd01:10::3") + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 65200) + ) - rxs = self.send_and_expect(self.pg2, 5*[p68], self.pg0, 225) + rxs = self.send_and_expect(self.pg2, 5 * [p68], self.pg0, 225) size = 0 for rx in rxs: self.assertEqual(rx[Ether].src, self.pg0.local_mac) @@ -711,7 +797,7 @@ class TestGSO(VppTestCase): payload_len = inner[IPv6].plen - 20 self.assertEqual(payload_len, len(inner[Raw])) size += payload_len - self.assertEqual(size, 65200*5) + self.assertEqual(size, 65200 * 5) # # disable ipip6 @@ -720,11 +806,12 @@ class TestGSO(VppTestCase): self.ip6_via_ip6_tunnel.remove_vpp_config() self.ipip6.remove_vpp_config() - self.vapi.feature_gso_enable_disable(sw_if_index=self.pg0.sw_if_index, - enable_disable=0) + self.vapi.feature_gso_enable_disable( + sw_if_index=self.pg0.sw_if_index, enable_disable=0 + ) def test_gso_ipsec(self): - """ GSO IPSEC test """ + """GSO IPSEC test""" # # Send jumbo frame with gso enabled only on input interface and # create IPIP tunnel on VPP pg0. @@ -735,14 +822,22 @@ class TestGSO(VppTestCase): # self.ipip4.add_vpp_config() self.vapi.feature_gso_enable_disable( - sw_if_index=self.ipip4.sw_if_index, enable_disable=1) + sw_if_index=self.ipip4.sw_if_index, enable_disable=1 + ) # Add IPv4 routes via tunnel interface self.ip4_via_ip4_tunnel = VppIpRoute( - self, "172.16.10.0", 24, - [VppRoutePath("0.0.0.0", - self.ipip4.sw_if_index, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP4)]) + self, + "172.16.10.0", + 24, + [ + VppRoutePath( + "0.0.0.0", + self.ipip4.sw_if_index, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP4, + ) + ], + ) self.ip4_via_ip4_tunnel.add_vpp_config() # IPSec config @@ -750,30 +845,33 @@ class TestGSO(VppTestCase): self.encryption_type = ESP config_tun_params(self.ipv4_params, self.encryption_type, self.ipip4) - self.tun_sa_in_v4 = VppIpsecSA(self, self.ipv4_params.vpp_tun_sa_id, - self.ipv4_params.vpp_tun_spi, - self.ipv4_params.auth_algo_vpp_id, - self.ipv4_params.auth_key, - self.ipv4_params.crypt_algo_vpp_id, - self.ipv4_params.crypt_key, - VppEnum.vl_api_ipsec_proto_t. - IPSEC_API_PROTO_ESP) + self.tun_sa_in_v4 = VppIpsecSA( + self, + self.ipv4_params.vpp_tun_sa_id, + self.ipv4_params.vpp_tun_spi, + self.ipv4_params.auth_algo_vpp_id, + self.ipv4_params.auth_key, + self.ipv4_params.crypt_algo_vpp_id, + self.ipv4_params.crypt_key, + VppEnum.vl_api_ipsec_proto_t.IPSEC_API_PROTO_ESP, + ) self.tun_sa_in_v4.add_vpp_config() - self.tun_sa_out_v4 = VppIpsecSA(self, self.ipv4_params.scapy_tun_sa_id, - self.ipv4_params.scapy_tun_spi, - self.ipv4_params.auth_algo_vpp_id, - self.ipv4_params.auth_key, - self.ipv4_params.crypt_algo_vpp_id, - self.ipv4_params.crypt_key, - VppEnum.vl_api_ipsec_proto_t. - IPSEC_API_PROTO_ESP) + self.tun_sa_out_v4 = VppIpsecSA( + self, + self.ipv4_params.scapy_tun_sa_id, + self.ipv4_params.scapy_tun_spi, + self.ipv4_params.auth_algo_vpp_id, + self.ipv4_params.auth_key, + self.ipv4_params.crypt_algo_vpp_id, + self.ipv4_params.crypt_key, + VppEnum.vl_api_ipsec_proto_t.IPSEC_API_PROTO_ESP, + ) self.tun_sa_out_v4.add_vpp_config() - self.tun_protect_v4 = VppIpsecTunProtect(self, - self.ipip4, - self.tun_sa_out_v4, - [self.tun_sa_in_v4]) + self.tun_protect_v4 = VppIpsecTunProtect( + self, self.ipip4, self.tun_sa_out_v4, [self.tun_sa_in_v4] + ) self.tun_protect_v4.add_vpp_config() @@ -784,10 +882,12 @@ class TestGSO(VppTestCase): # # IPv4/IPv4 - IPSEC # - ipsec44 = (Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") / - IP(src=self.pg2.remote_ip4, dst="172.16.10.3", flags='DF') / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 65200)) + ipsec44 = ( + Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") + / IP(src=self.pg2.remote_ip4, dst="172.16.10.3", flags="DF") + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 65200) + ) rxs = self.send_and_expect(self.pg2, [ipsec44], self.pg0, 45) size = 0 @@ -805,18 +905,27 @@ class TestGSO(VppTestCase): self.assertEqual(size, 65200) self.ip6_via_ip4_tunnel = VppIpRoute( - self, "fd01:10::", 64, - [VppRoutePath("::", - self.ipip4.sw_if_index, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)]) + self, + "fd01:10::", + 64, + [ + VppRoutePath( + "::", + self.ipip4.sw_if_index, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ) + ], + ) self.ip6_via_ip4_tunnel.add_vpp_config() # # IPv4/IPv6 - IPSEC # - ipsec46 = (Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") / - IPv6(src=self.pg2.remote_ip6, dst="fd01:10::3") / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 65200)) + ipsec46 = ( + Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") + / IPv6(src=self.pg2.remote_ip6, dst="fd01:10::3") + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 65200) + ) rxs = self.send_and_expect(self.pg2, [ipsec46], self.pg0, 45) size = 0 @@ -841,8 +950,7 @@ class TestGSO(VppTestCase): # # disable ipip4 # - self.vapi.feature_gso_enable_disable(self.ipip4.sw_if_index, - enable_disable=0) + self.vapi.feature_gso_enable_disable(self.ipip4.sw_if_index, enable_disable=0) self.ip4_via_ip4_tunnel.remove_vpp_config() self.ip6_via_ip4_tunnel.remove_vpp_config() self.ipip4.remove_vpp_config() @@ -851,8 +959,7 @@ class TestGSO(VppTestCase): # enable ipip6 # self.ipip6.add_vpp_config() - self.vapi.feature_gso_enable_disable(self.ipip6.sw_if_index, - enable_disable=1) + self.vapi.feature_gso_enable_disable(self.ipip6.sw_if_index, enable_disable=1) # Set interface up and enable IP on it self.ipip6.admin_up() @@ -860,50 +967,62 @@ class TestGSO(VppTestCase): # Add IPv4 routes via tunnel interface self.ip4_via_ip6_tunnel = VppIpRoute( - self, "172.16.10.0", 24, - [VppRoutePath("0.0.0.0", - self.ipip6.sw_if_index, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP4)]) + self, + "172.16.10.0", + 24, + [ + VppRoutePath( + "0.0.0.0", + self.ipip6.sw_if_index, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP4, + ) + ], + ) self.ip4_via_ip6_tunnel.add_vpp_config() # IPSec config self.ipv6_params = IPsecIPv6Params() self.encryption_type = ESP config_tun_params(self.ipv6_params, self.encryption_type, self.ipip6) - self.tun_sa_in_v6 = VppIpsecSA(self, self.ipv6_params.vpp_tun_sa_id, - self.ipv6_params.vpp_tun_spi, - self.ipv6_params.auth_algo_vpp_id, - self.ipv6_params.auth_key, - self.ipv6_params.crypt_algo_vpp_id, - self.ipv6_params.crypt_key, - VppEnum.vl_api_ipsec_proto_t. - IPSEC_API_PROTO_ESP) + self.tun_sa_in_v6 = VppIpsecSA( + self, + self.ipv6_params.vpp_tun_sa_id, + self.ipv6_params.vpp_tun_spi, + self.ipv6_params.auth_algo_vpp_id, + self.ipv6_params.auth_key, + self.ipv6_params.crypt_algo_vpp_id, + self.ipv6_params.crypt_key, + VppEnum.vl_api_ipsec_proto_t.IPSEC_API_PROTO_ESP, + ) self.tun_sa_in_v6.add_vpp_config() - self.tun_sa_out_v6 = VppIpsecSA(self, self.ipv6_params.scapy_tun_sa_id, - self.ipv6_params.scapy_tun_spi, - self.ipv6_params.auth_algo_vpp_id, - self.ipv6_params.auth_key, - self.ipv6_params.crypt_algo_vpp_id, - self.ipv6_params.crypt_key, - VppEnum.vl_api_ipsec_proto_t. - IPSEC_API_PROTO_ESP) + self.tun_sa_out_v6 = VppIpsecSA( + self, + self.ipv6_params.scapy_tun_sa_id, + self.ipv6_params.scapy_tun_spi, + self.ipv6_params.auth_algo_vpp_id, + self.ipv6_params.auth_key, + self.ipv6_params.crypt_algo_vpp_id, + self.ipv6_params.crypt_key, + VppEnum.vl_api_ipsec_proto_t.IPSEC_API_PROTO_ESP, + ) self.tun_sa_out_v6.add_vpp_config() - self.tun_protect_v6 = VppIpsecTunProtect(self, - self.ipip6, - self.tun_sa_out_v6, - [self.tun_sa_in_v6]) + self.tun_protect_v6 = VppIpsecTunProtect( + self, self.ipip6, self.tun_sa_out_v6, [self.tun_sa_in_v6] + ) self.tun_protect_v6.add_vpp_config() # # IPv6/IPv4 - IPSEC # - ipsec64 = (Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") / - IP(src=self.pg2.remote_ip4, dst="172.16.10.3", flags='DF') / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 65200)) + ipsec64 = ( + Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") + / IP(src=self.pg2.remote_ip4, dst="172.16.10.3", flags="DF") + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 65200) + ) rxs = self.send_and_expect(self.pg2, [ipsec64], self.pg0, 45) size = 0 @@ -921,19 +1040,28 @@ class TestGSO(VppTestCase): self.assertEqual(size, 65200) self.ip6_via_ip6_tunnel = VppIpRoute( - self, "fd01:10::", 64, - [VppRoutePath("::", - self.ipip6.sw_if_index, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)]) + self, + "fd01:10::", + 64, + [ + VppRoutePath( + "::", + self.ipip6.sw_if_index, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ) + ], + ) self.ip6_via_ip6_tunnel.add_vpp_config() # # IPv6/IPv6 - IPSEC # - ipsec66 = (Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") / - IPv6(src=self.pg2.remote_ip6, dst="fd01:10::3") / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 65200)) + ipsec66 = ( + Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") + / IPv6(src=self.pg2.remote_ip6, dst="fd01:10::3") + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 65200) + ) rxs = self.send_and_expect(self.pg2, [ipsec66], self.pg0, 45) size = 0 @@ -962,8 +1090,8 @@ class TestGSO(VppTestCase): self.ip6_via_ip6_tunnel.remove_vpp_config() self.ipip6.remove_vpp_config() - self.vapi.feature_gso_enable_disable(self.pg0.sw_if_index, - enable_disable=0) + self.vapi.feature_gso_enable_disable(self.pg0.sw_if_index, enable_disable=0) + -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_gtpu.py b/test/test_gtpu.py index e4a2bfa3670..a6d54f53357 100644 --- a/test/test_gtpu.py +++ b/test/test_gtpu.py @@ -21,7 +21,7 @@ from vpp_ip import INVALID_INDEX @tag_fixme_vpp_workers class TestGtpuUDP(VppTestCase): - """ GTPU UDP ports Test Case """ + """GTPU UDP ports Test Case""" def setUp(self): super(TestGtpuUDP, self).setUp() @@ -39,15 +39,16 @@ class TestGtpuUDP(VppTestCase): def _check_udp_port_ip4(self, enabled=True): - pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / - UDP(sport=self.dport, dport=self.dport, chksum=0)) + pkt = ( + Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / UDP(sport=self.dport, dport=self.dport, chksum=0) + ) self.pg0.add_stream(pkt) self.pg_start() - err = self.statistics.get_counter( - '/err/ip4-udp-lookup/no_listener')[0] + err = self.statistics.get_counter("/err/ip4-udp-lookup/no_listener")[0] if enabled: self.assertEqual(err, self.ip4_err) @@ -58,15 +59,16 @@ class TestGtpuUDP(VppTestCase): def _check_udp_port_ip6(self, enabled=True): - pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) / - UDP(sport=self.dport, dport=self.dport, chksum=0)) + pkt = ( + Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) + / UDP(sport=self.dport, dport=self.dport, chksum=0) + ) self.pg0.add_stream(pkt) self.pg_start() - err = self.statistics.get_counter( - '/err/ip6-udp-lookup/no_listener')[0] + err = self.statistics.get_counter("/err/ip6-udp-lookup/no_listener")[0] if enabled: self.assertEqual(err, self.ip6_err) @@ -76,46 +78,54 @@ class TestGtpuUDP(VppTestCase): self.ip6_err = err def test_udp_port(self): - """ test UDP ports + """test UDP ports Check if there are no udp listeners before gtpu is enabled """ # UDP ports should be disabled unless a tunnel is configured self._check_udp_port_ip4(False) self._check_udp_port_ip6(False) - r = self.vapi.gtpu_add_del_tunnel(is_add=True, - mcast_sw_if_index=0xFFFFFFFF, - decap_next_index=0xFFFFFFFF, - src_address=self.pg0.local_ip4, - dst_address=self.pg0.remote_ip4) + r = self.vapi.gtpu_add_del_tunnel( + is_add=True, + mcast_sw_if_index=0xFFFFFFFF, + decap_next_index=0xFFFFFFFF, + src_address=self.pg0.local_ip4, + dst_address=self.pg0.remote_ip4, + ) # UDP port 2152 enabled for ip4 self._check_udp_port_ip4() - r = self.vapi.gtpu_add_del_tunnel(is_add=True, - mcast_sw_if_index=0xFFFFFFFF, - decap_next_index=0xFFFFFFFF, - src_address=self.pg0.local_ip6, - dst_address=self.pg0.remote_ip6) + r = self.vapi.gtpu_add_del_tunnel( + is_add=True, + mcast_sw_if_index=0xFFFFFFFF, + decap_next_index=0xFFFFFFFF, + src_address=self.pg0.local_ip6, + dst_address=self.pg0.remote_ip6, + ) # UDP port 2152 enabled for ip6 self._check_udp_port_ip6() - r = self.vapi.gtpu_add_del_tunnel(is_add=False, - mcast_sw_if_index=0xFFFFFFFF, - decap_next_index=0xFFFFFFFF, - src_address=self.pg0.local_ip4, - dst_address=self.pg0.remote_ip4) + r = self.vapi.gtpu_add_del_tunnel( + is_add=False, + mcast_sw_if_index=0xFFFFFFFF, + decap_next_index=0xFFFFFFFF, + src_address=self.pg0.local_ip4, + dst_address=self.pg0.remote_ip4, + ) - r = self.vapi.gtpu_add_del_tunnel(is_add=False, - mcast_sw_if_index=0xFFFFFFFF, - decap_next_index=0xFFFFFFFF, - src_address=self.pg0.local_ip6, - dst_address=self.pg0.remote_ip6) + r = self.vapi.gtpu_add_del_tunnel( + is_add=False, + mcast_sw_if_index=0xFFFFFFFF, + decap_next_index=0xFFFFFFFF, + src_address=self.pg0.local_ip6, + dst_address=self.pg0.remote_ip6, + ) class TestGtpu(BridgeDomain, VppTestCase): - """ GTPU Test Case """ + """GTPU Test Case""" def __init__(self, *args): BridgeDomain.__init__(self) @@ -126,14 +136,16 @@ class TestGtpu(BridgeDomain, VppTestCase): Encapsulate the original payload frame by adding GTPU header with its UDP, IP and Ethernet fields """ - return (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / - UDP(sport=self.dport, dport=self.dport, chksum=0) / - GTP_U_Header(teid=vni, gtp_type=self.gtp_type, length=150) / - pkt) + return ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / UDP(sport=self.dport, dport=self.dport, chksum=0) + / GTP_U_Header(teid=vni, gtp_type=self.gtp_type, length=150) + / pkt + ) def ip_range(self, start, end): - """ range of remote ip's """ + """range of remote ip's""" return ip4_range(self.pg0.remote_ip4, start, end) def encap_mcast(self, pkt, src_ip, src_mac, vni): @@ -141,11 +153,13 @@ class TestGtpu(BridgeDomain, VppTestCase): Encapsulate the original payload frame by adding GTPU header with its UDP, IP and Ethernet fields """ - return (Ether(src=src_mac, dst=self.mcast_mac) / - IP(src=src_ip, dst=self.mcast_ip4) / - UDP(sport=self.dport, dport=self.dport, chksum=0) / - GTP_U_Header(teid=vni, gtp_type=self.gtp_type, length=150) / - pkt) + return ( + Ether(src=src_mac, dst=self.mcast_mac) + / IP(src=src_ip, dst=self.mcast_ip4) + / UDP(sport=self.dport, dport=self.dport, chksum=0) + / GTP_U_Header(teid=vni, gtp_type=self.gtp_type, length=150) + / pkt + ) def decapsulate(self, pkt): """ @@ -178,7 +192,7 @@ class TestGtpu(BridgeDomain, VppTestCase): self.assertEqual(pkt[GTP_U_Header].teid, vni) def test_encap(self): - """ Encapsulation test + """Encapsulation test Send frames from pg1 Verify receipt of encapsulated frames on pg0 """ @@ -197,7 +211,7 @@ class TestGtpu(BridgeDomain, VppTestCase): # self.assert_eq_pkts(payload, self.frame_reply) def test_ucast_flood(self): - """ Unicast flood test + """Unicast flood test Send frames from pg3 Verify receipt of encapsulated frames on pg0 """ @@ -215,7 +229,7 @@ class TestGtpu(BridgeDomain, VppTestCase): # self.assert_eq_pkts(payload, self.frame_reply) def test_mcast_flood(self): - """ Multicast flood test + """Multicast flood test Send frames from pg2 Verify receipt of encapsulated frames on pg0 """ @@ -228,8 +242,9 @@ class TestGtpu(BridgeDomain, VppTestCase): # Pick first received frame and check if it's correctly encapsulated. out = self.pg0.get_capture(1) pkt = out[0] - self.check_encapsulation(pkt, self.mcast_flood_bd, - local_only=False, mcast_pkt=True) + self.check_encapsulation( + pkt, self.mcast_flood_bd, local_only=False, mcast_pkt=True + ) # payload = self.decapsulate(pkt) # self.assert_eq_pkts(payload, self.frame_reply) @@ -240,13 +255,15 @@ class TestGtpu(BridgeDomain, VppTestCase): ip_range_start = 10 ip_range_end = ip_range_start + n_ucast_tunnels next_hop_address = cls.pg0.remote_ip4 - for dest_ip4 in ip4_range(next_hop_address, ip_range_start, - ip_range_end): + for dest_ip4 in ip4_range(next_hop_address, ip_range_start, ip_range_end): # add host route so dest_ip4 will not be resolved - rip = VppIpRoute(cls, dest_ip4, 32, - [VppRoutePath(next_hop_address, - INVALID_INDEX)], - register=False) + rip = VppIpRoute( + cls, + dest_ip4, + 32, + [VppRoutePath(next_hop_address, INVALID_INDEX)], + register=False, + ) rip.add_vpp_config() r = cls.vapi.gtpu_add_del_tunnel( is_add=True, @@ -254,9 +271,11 @@ class TestGtpu(BridgeDomain, VppTestCase): decap_next_index=0xFFFFFFFF, src_address=cls.pg0.local_ip4, dst_address=dest_ip4, - teid=teid) - cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index, - bd_id=teid) + teid=teid, + ) + cls.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=r.sw_if_index, bd_id=teid + ) @classmethod def add_del_shared_mcast_dst_load(cls, is_add): @@ -274,8 +293,9 @@ class TestGtpu(BridgeDomain, VppTestCase): dst_address=cls.mcast_ip4, mcast_sw_if_index=1, teid=teid, - is_add=is_add) - if r.sw_if_index == 0xffffffff: + is_add=is_add, + ) + if r.sw_if_index == 0xFFFFFFFF: raise ValueError("bad sw_if_index: ~0") @classmethod @@ -294,16 +314,16 @@ class TestGtpu(BridgeDomain, VppTestCase): n_distinct_dst_tunnels = 20 ip_range_start = 10 ip_range_end = ip_range_start + n_distinct_dst_tunnels - for dest_ip4 in ip4_range(cls.mcast_ip4, ip_range_start, - ip_range_end): - teid = int(dest_ip4.split('.')[3]) + for dest_ip4 in ip4_range(cls.mcast_ip4, ip_range_start, ip_range_end): + teid = int(dest_ip4.split(".")[3]) cls.vapi.gtpu_add_del_tunnel( decap_next_index=0xFFFFFFFF, src_address=cls.pg0.local_ip4, dst_address=dest_ip4, mcast_sw_if_index=1, teid=teid, - is_add=is_add) + is_add=is_add, + ) @classmethod def add_mcast_tunnels_load(cls): @@ -324,7 +344,7 @@ class TestGtpu(BridgeDomain, VppTestCase): try: cls.dport = 2152 - cls.gtp_type = 0xff + cls.gtp_type = 0xFF # Create 2 pg interfaces. cls.create_pg_interfaces(range(4)) @@ -338,7 +358,7 @@ class TestGtpu(BridgeDomain, VppTestCase): cls.pg0.resolve_arp() # Our Multicast address - cls.mcast_ip4 = '239.1.1.1' + cls.mcast_ip4 = "239.1.1.1" cls.mcast_mac = util.mcast_ip_to_mac(cls.mcast_ip4) # Create GTPU VTEP on VPP pg0, and put gtpu_tunnel0 and pg1 @@ -351,28 +371,33 @@ class TestGtpu(BridgeDomain, VppTestCase): decap_next_index=0xFFFFFFFF, src_address=cls.pg0.local_ip4, dst_address=cls.pg0.remote_ip4, - teid=cls.single_tunnel_vni) - cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index, - bd_id=cls.single_tunnel_bd) + teid=cls.single_tunnel_vni, + ) cls.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=cls.pg1.sw_if_index, bd_id=cls.single_tunnel_bd) + rx_sw_if_index=r.sw_if_index, bd_id=cls.single_tunnel_bd + ) + cls.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=cls.pg1.sw_if_index, bd_id=cls.single_tunnel_bd + ) # Setup teid 2 to test multicast flooding cls.n_ucast_tunnels = 10 cls.mcast_flood_bd = 12 - cls.create_gtpu_flood_test_bd(cls.mcast_flood_bd, - cls.n_ucast_tunnels) + cls.create_gtpu_flood_test_bd(cls.mcast_flood_bd, cls.n_ucast_tunnels) r = cls.vapi.gtpu_add_del_tunnel( is_add=True, src_address=cls.pg0.local_ip4, dst_address=cls.mcast_ip4, mcast_sw_if_index=1, decap_next_index=0xFFFFFFFF, - teid=cls.mcast_flood_bd) - cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index, - bd_id=cls.mcast_flood_bd) + teid=cls.mcast_flood_bd, + ) + cls.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=r.sw_if_index, bd_id=cls.mcast_flood_bd + ) cls.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=cls.pg2.sw_if_index, bd_id=cls.mcast_flood_bd) + rx_sw_if_index=cls.pg2.sw_if_index, bd_id=cls.mcast_flood_bd + ) # Add and delete mcast tunnels to check stability cls.add_shared_mcast_dst_load() @@ -382,10 +407,10 @@ class TestGtpu(BridgeDomain, VppTestCase): # Setup teid 3 to test unicast flooding cls.ucast_flood_bd = 13 - cls.create_gtpu_flood_test_bd(cls.ucast_flood_bd, - cls.n_ucast_tunnels) + cls.create_gtpu_flood_test_bd(cls.ucast_flood_bd, cls.n_ucast_tunnels) cls.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=cls.pg3.sw_if_index, bd_id=cls.ucast_flood_bd) + rx_sw_if_index=cls.pg3.sw_if_index, bd_id=cls.ucast_flood_bd + ) except Exception: super(TestGtpu, cls).tearDownClass() raise @@ -409,5 +434,5 @@ class TestGtpu(BridgeDomain, VppTestCase): self.logger.info(self.vapi.cli("show trace")) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_http.py b/test/test_http.py index 193eb010a10..30fee5b98c5 100644 --- a/test/test_http.py +++ b/test/test_http.py @@ -11,7 +11,7 @@ from vpp_devices import VppTAPInterface @unittest.skip("Requires root") class TestHttpTps(VppTestCase): - """ HTTP test class """ + """HTTP test class""" @classmethod def setUpClass(cls): @@ -22,21 +22,21 @@ class TestHttpTps(VppTestCase): super(TestHttpTps, cls).tearDownClass() def setUp(self): - self.client_ip4 = '172.0.0.2' - self.server_ip4 = '172.0.0.1' - self.vapi.cli(f'create tap id 0 host-ip4-addr {self.client_ip4}/24') - self.vapi.cli(f'set int ip addr tap0 {self.server_ip4}/24') - self.vapi.cli('set int state tap0 up') + self.client_ip4 = "172.0.0.2" + self.server_ip4 = "172.0.0.1" + self.vapi.cli(f"create tap id 0 host-ip4-addr {self.client_ip4}/24") + self.vapi.cli(f"set int ip addr tap0 {self.server_ip4}/24") + self.vapi.cli("set int state tap0 up") self.vapi.session_enable_disable(is_enable=1) def test_http_tps(self): - fname = 'test_file_1M' - self.vapi.cli('http tps uri tcp://0.0.0.0/8080') + fname = "test_file_1M" + self.vapi.cli("http tps uri tcp://0.0.0.0/8080") con = http.client.HTTPConnection(f"{self.server_ip4}", 8080) - con.request('GET', f'/{fname}') + con.request("GET", f"/{fname}") r = con.getresponse() self.assertEqual(len(r.read()), 1 << 20) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_igmp.py b/test/test_igmp.py index f99bdb25c8c..6e9defd4c1d 100644 --- a/test/test_igmp.py +++ b/test/test_igmp.py @@ -9,8 +9,15 @@ from scapy.contrib.igmpv3 import IGMPv3, IGMPv3gr, IGMPv3mq, IGMPv3mr from framework import tag_fixme_vpp_workers from framework import VppTestCase, VppTestRunner -from vpp_igmp import find_igmp_state, IGMP_FILTER, IgmpRecord, IGMP_MODE, \ - IgmpSG, VppHostState, wait_for_igmp_event +from vpp_igmp import ( + find_igmp_state, + IGMP_FILTER, + IgmpRecord, + IGMP_MODE, + IgmpSG, + VppHostState, + wait_for_igmp_event, +) from vpp_ip_route import find_mroute, VppIpTable @@ -21,7 +28,7 @@ class IgmpMode: @tag_fixme_vpp_workers class TestIgmp(VppTestCase): - """ IGMP Test Case """ + """IGMP Test Case""" @classmethod def setUpClass(cls): @@ -63,16 +70,16 @@ class TestIgmp(VppTestCase): self.pg_start() def test_igmp_flush(self): - """ IGMP Link Up/down and Flush """ + """IGMP Link Up/down and Flush""" # # FIX THIS. Link down. # def test_igmp_enable(self): - """ IGMP enable/disable on an interface + """IGMP enable/disable on an interface - check for the addition/removal of the IGMP mroutes """ + check for the addition/removal of the IGMP mroutes""" self.vapi.igmp_enable_disable(self.pg0.sw_if_index, 1, IGMP_MODE.HOST) self.vapi.igmp_enable_disable(self.pg1.sw_if_index, 1, IGMP_MODE.HOST) @@ -83,10 +90,8 @@ class TestIgmp(VppTestCase): self.vapi.igmp_enable_disable(self.pg2.sw_if_index, 1, IGMP_MODE.HOST) self.vapi.igmp_enable_disable(self.pg3.sw_if_index, 1, IGMP_MODE.HOST) - self.assertTrue(find_mroute(self, "224.0.0.1", "0.0.0.0", 32, - table_id=1)) - self.assertTrue(find_mroute(self, "224.0.0.22", "0.0.0.0", 32, - table_id=1)) + self.assertTrue(find_mroute(self, "224.0.0.1", "0.0.0.0", 32, table_id=1)) + self.assertTrue(find_mroute(self, "224.0.0.22", "0.0.0.0", 32, table_id=1)) self.vapi.igmp_enable_disable(self.pg0.sw_if_index, 0, IGMP_MODE.HOST) self.vapi.igmp_enable_disable(self.pg1.sw_if_index, 0, IGMP_MODE.HOST) self.vapi.igmp_enable_disable(self.pg2.sw_if_index, 0, IGMP_MODE.HOST) @@ -94,10 +99,8 @@ class TestIgmp(VppTestCase): self.assertTrue(find_mroute(self, "224.0.0.1", "0.0.0.0", 32)) self.assertFalse(find_mroute(self, "224.0.0.22", "0.0.0.0", 32)) - self.assertTrue(find_mroute(self, "224.0.0.1", "0.0.0.0", 32, - table_id=1)) - self.assertFalse(find_mroute(self, "224.0.0.22", "0.0.0.0", 32, - table_id=1)) + self.assertTrue(find_mroute(self, "224.0.0.1", "0.0.0.0", 32, table_id=1)) + self.assertFalse(find_mroute(self, "224.0.0.22", "0.0.0.0", 32, table_id=1)) def verify_general_query(self, p): ip = p[IP] @@ -126,8 +129,9 @@ class TestIgmp(VppTestCase): self.assertEqual(len(ip.options), 1) self.assertEqual(ip.options[0].option, 20) self.assertEqual(ip.proto, 2) - self.assertEqual(IGMPv3.igmpv3types[rx[IGMPv3].type], - "Version 3 Membership Report") + self.assertEqual( + IGMPv3.igmpv3types[rx[IGMPv3].type], "Version 3 Membership Report" + ) self.assertEqual(rx[IGMPv3mr].numgrp, len(records)) received = rx[IGMPv3mr].records @@ -140,26 +144,20 @@ class TestIgmp(VppTestCase): self.assertEqual(gr.maddr, r.sg.gaddr) self.assertEqual(len(gr.srcaddrs), len(r.sg.saddrs)) - self.assertEqual(sorted(gr.srcaddrs), - sorted(r.sg.saddrs)) + self.assertEqual(sorted(gr.srcaddrs), sorted(r.sg.saddrs)) def add_group(self, itf, sg, n_pkts=2): self.pg_enable_capture(self.pg_interfaces) self.pg_start() - hs = VppHostState(self, - IGMP_FILTER.INCLUDE, - itf.sw_if_index, - sg) + hs = VppHostState(self, IGMP_FILTER.INCLUDE, itf.sw_if_index, sg) hs.add_vpp_config() capture = itf.get_capture(n_pkts, timeout=10) # reports are transmitted twice due to default rebostness value=2 - self.verify_report(capture[0], - [IgmpRecord(sg, "Allow New Sources")]), - self.verify_report(capture[1], - [IgmpRecord(sg, "Allow New Sources")]), + self.verify_report(capture[0], [IgmpRecord(sg, "Allow New Sources")]), + self.verify_report(capture[1], [IgmpRecord(sg, "Allow New Sources")]), return hs @@ -170,18 +168,15 @@ class TestIgmp(VppTestCase): capture = self.pg0.get_capture(1, timeout=10) - self.verify_report(capture[0], - [IgmpRecord(hs.sg, "Block Old Sources")]) + self.verify_report(capture[0], [IgmpRecord(hs.sg, "Block Old Sources")]) def test_igmp_host(self): - """ IGMP Host functions """ + """IGMP Host functions""" # # Enable interface for host functions # - self.vapi.igmp_enable_disable(self.pg0.sw_if_index, - 1, - IGMP_MODE.HOST) + self.vapi.igmp_enable_disable(self.pg0.sw_if_index, 1, IGMP_MODE.HOST) # # Add one S,G of state and expect a state-change event report @@ -192,8 +187,7 @@ class TestIgmp(VppTestCase): # search for the corresponding state created in VPP dump = self.vapi.igmp_dump(self.pg0.sw_if_index) self.assertEqual(len(dump), 1) - self.assertTrue(find_igmp_state(dump, self.pg0, - "239.1.1.1", "1.1.1.1")) + self.assertTrue(find_igmp_state(dump, self.pg0, "239.1.1.1", "1.1.1.1")) # # Send a general query (to the all router's address) @@ -201,61 +195,81 @@ class TestIgmp(VppTestCase): # Pad the query with 0 - some devices in the big wild # internet are prone to this. # - p_g = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst='224.0.0.1', tos=0xc0) / - IGMPv3(type="Membership Query", mrcode=100) / - IGMPv3mq(gaddr="0.0.0.0") / - Raw(b'\x00' * 10)) + p_g = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst="224.0.0.1", tos=0xC0) + / IGMPv3(type="Membership Query", mrcode=100) + / IGMPv3mq(gaddr="0.0.0.0") + / Raw(b"\x00" * 10) + ) self.send(self.pg0, p_g) capture = self.pg0.get_capture(1, timeout=10) - self.verify_report(capture[0], - [IgmpRecord(h1.sg, "Mode Is Include")]) + self.verify_report(capture[0], [IgmpRecord(h1.sg, "Mode Is Include")]) # # Group specific query # - p_gs = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst='239.1.1.1', tos=0xc0, - options=[IPOption(copy_flag=1, optclass="control", - option="router_alert")]) / - IGMPv3(type="Membership Query", mrcode=100) / - IGMPv3mq(gaddr="239.1.1.1")) + p_gs = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP( + src=self.pg0.remote_ip4, + dst="239.1.1.1", + tos=0xC0, + options=[ + IPOption(copy_flag=1, optclass="control", option="router_alert") + ], + ) + / IGMPv3(type="Membership Query", mrcode=100) + / IGMPv3mq(gaddr="239.1.1.1") + ) self.send(self.pg0, p_gs) capture = self.pg0.get_capture(1, timeout=10) - self.verify_report(capture[0], - [IgmpRecord(h1.sg, "Mode Is Include")]) + self.verify_report(capture[0], [IgmpRecord(h1.sg, "Mode Is Include")]) # # A group and source specific query, with the source matching # the source VPP has # - p_gs1 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst='239.1.1.1', tos=0xc0, - options=[IPOption(copy_flag=1, optclass="control", - option="router_alert")]) / - IGMPv3(type="Membership Query", mrcode=100) / - IGMPv3mq(gaddr="239.1.1.1", srcaddrs=["1.1.1.1"])) + p_gs1 = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP( + src=self.pg0.remote_ip4, + dst="239.1.1.1", + tos=0xC0, + options=[ + IPOption(copy_flag=1, optclass="control", option="router_alert") + ], + ) + / IGMPv3(type="Membership Query", mrcode=100) + / IGMPv3mq(gaddr="239.1.1.1", srcaddrs=["1.1.1.1"]) + ) self.send(self.pg0, p_gs1) capture = self.pg0.get_capture(1, timeout=10) - self.verify_report(capture[0], - [IgmpRecord(h1.sg, "Mode Is Include")]) + self.verify_report(capture[0], [IgmpRecord(h1.sg, "Mode Is Include")]) # # A group and source specific query that reports more sources # than the packet actually has. # - p_gs2 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst='239.1.1.1', tos=0xc0, - options=[IPOption(copy_flag=1, optclass="control", - option="router_alert")]) / - IGMPv3(type="Membership Query", mrcode=100) / - IGMPv3mq(gaddr="239.1.1.1", numsrc=4, srcaddrs=["1.1.1.1"])) + p_gs2 = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP( + src=self.pg0.remote_ip4, + dst="239.1.1.1", + tos=0xC0, + options=[ + IPOption(copy_flag=1, optclass="control", option="router_alert") + ], + ) + / IGMPv3(type="Membership Query", mrcode=100) + / IGMPv3mq(gaddr="239.1.1.1", numsrc=4, srcaddrs=["1.1.1.1"]) + ) self.send_and_assert_no_replies(self.pg0, p_gs2, timeout=10) @@ -263,12 +277,19 @@ class TestIgmp(VppTestCase): # A group and source specific query, with the source NOT matching # the source VPP has. There should be no response. # - p_gs2 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst='239.1.1.1', tos=0xc0, - options=[IPOption(copy_flag=1, optclass="control", - option="router_alert")]) / - IGMPv3(type="Membership Query", mrcode=100) / - IGMPv3mq(gaddr="239.1.1.1", srcaddrs=["1.1.1.2"])) + p_gs2 = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP( + src=self.pg0.remote_ip4, + dst="239.1.1.1", + tos=0xC0, + options=[ + IPOption(copy_flag=1, optclass="control", option="router_alert") + ], + ) + / IGMPv3(type="Membership Query", mrcode=100) + / IGMPv3mq(gaddr="239.1.1.1", srcaddrs=["1.1.1.2"]) + ) self.send_and_assert_no_replies(self.pg0, p_gs2, timeout=10) @@ -277,19 +298,24 @@ class TestIgmp(VppTestCase): # one of which matches the source VPP has. # The report should contain only the source VPP has. # - p_gs3 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst='239.1.1.1', tos=0xc0, - options=[IPOption(copy_flag=1, optclass="control", - option="router_alert")]) / - IGMPv3(type="Membership Query", mrcode=100) / - IGMPv3mq(gaddr="239.1.1.1", - srcaddrs=["1.1.1.1", "1.1.1.2", "1.1.1.3"])) + p_gs3 = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP( + src=self.pg0.remote_ip4, + dst="239.1.1.1", + tos=0xC0, + options=[ + IPOption(copy_flag=1, optclass="control", option="router_alert") + ], + ) + / IGMPv3(type="Membership Query", mrcode=100) + / IGMPv3mq(gaddr="239.1.1.1", srcaddrs=["1.1.1.1", "1.1.1.2", "1.1.1.3"]) + ) self.send(self.pg0, p_gs3) capture = self.pg0.get_capture(1, timeout=10) - self.verify_report(capture[0], - [IgmpRecord(h1.sg, "Mode Is Include")]) + self.verify_report(capture[0], [IgmpRecord(h1.sg, "Mode Is Include")]) # # Two source and group specific queries in quick succession, the @@ -297,13 +323,11 @@ class TestIgmp(VppTestCase): # self.send(self.pg0, [p_gs2, p_gs1]) capture = self.pg0.get_capture(1, timeout=10) - self.verify_report(capture[0], - [IgmpRecord(h1.sg, "Mode Is Include")]) + self.verify_report(capture[0], [IgmpRecord(h1.sg, "Mode Is Include")]) self.send(self.pg0, [p_gs1, p_gs2]) capture = self.pg0.get_capture(1, timeout=10) - self.verify_report(capture[0], - [IgmpRecord(h1.sg, "Mode Is Include")]) + self.verify_report(capture[0], [IgmpRecord(h1.sg, "Mode Is Include")]) # # remove state, expect the report for the removal @@ -316,16 +340,15 @@ class TestIgmp(VppTestCase): # # A group with multiple sources # - h2 = self.add_group(self.pg0, - IgmpSG("239.1.1.1", - ["1.1.1.1", "1.1.1.2", "1.1.1.3"])) + h2 = self.add_group( + self.pg0, IgmpSG("239.1.1.1", ["1.1.1.1", "1.1.1.2", "1.1.1.3"]) + ) # search for the corresponding state created in VPP dump = self.vapi.igmp_dump(self.pg0.sw_if_index) self.assertEqual(len(dump), 3) for s in h2.sg.saddrs: - self.assertTrue(find_igmp_state(dump, self.pg0, - "239.1.1.1", s)) + self.assertTrue(find_igmp_state(dump, self.pg0, "239.1.1.1", s)) # # Send a general query (to the all router's address) # expect VPP to respond with a membership report will all sources @@ -333,53 +356,76 @@ class TestIgmp(VppTestCase): self.send(self.pg0, p_g) capture = self.pg0.get_capture(1, timeout=10) - self.verify_report(capture[0], - [IgmpRecord(h2.sg, "Mode Is Include")]) + self.verify_report(capture[0], [IgmpRecord(h2.sg, "Mode Is Include")]) # # Group and source specific query; some present some not # - p_gs = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst='239.1.1.1', tos=0xc0, - options=[IPOption(copy_flag=1, optclass="control", - option="router_alert")]) / - IGMPv3(type="Membership Query", mrcode=100) / - IGMPv3mq(gaddr="239.1.1.1", - srcaddrs=["1.1.1.1", "1.1.1.2", "1.1.1.4"])) + p_gs = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP( + src=self.pg0.remote_ip4, + dst="239.1.1.1", + tos=0xC0, + options=[ + IPOption(copy_flag=1, optclass="control", option="router_alert") + ], + ) + / IGMPv3(type="Membership Query", mrcode=100) + / IGMPv3mq(gaddr="239.1.1.1", srcaddrs=["1.1.1.1", "1.1.1.2", "1.1.1.4"]) + ) self.send(self.pg0, p_gs) capture = self.pg0.get_capture(1, timeout=10) - self.verify_report(capture[0], - [IgmpRecord( - IgmpSG('239.1.1.1', ["1.1.1.1", "1.1.1.2"]), - "Mode Is Include")]) + self.verify_report( + capture[0], + [ + IgmpRecord( + IgmpSG("239.1.1.1", ["1.1.1.1", "1.1.1.2"]), "Mode Is Include" + ) + ], + ) # # add loads more groups # - h3 = self.add_group(self.pg0, - IgmpSG("239.1.1.2", - ["2.1.1.1", "2.1.1.2", "2.1.1.3"])) - h4 = self.add_group(self.pg0, - IgmpSG("239.1.1.3", - ["3.1.1.1", "3.1.1.2", "3.1.1.3"])) - h5 = self.add_group(self.pg0, - IgmpSG("239.1.1.4", - ["4.1.1.1", "4.1.1.2", "4.1.1.3"])) - h6 = self.add_group(self.pg0, - IgmpSG("239.1.1.5", - ["5.1.1.1", "5.1.1.2", "5.1.1.3"])) - h7 = self.add_group(self.pg0, - IgmpSG("239.1.1.6", - ["6.1.1.1", "6.1.1.2", - "6.1.1.3", "6.1.1.4", - "6.1.1.5", "6.1.1.6", - "6.1.1.7", "6.1.1.8", - "6.1.1.9", "6.1.1.10", - "6.1.1.11", "6.1.1.12", - "6.1.1.13", "6.1.1.14", - "6.1.1.15", "6.1.1.16"])) + h3 = self.add_group( + self.pg0, IgmpSG("239.1.1.2", ["2.1.1.1", "2.1.1.2", "2.1.1.3"]) + ) + h4 = self.add_group( + self.pg0, IgmpSG("239.1.1.3", ["3.1.1.1", "3.1.1.2", "3.1.1.3"]) + ) + h5 = self.add_group( + self.pg0, IgmpSG("239.1.1.4", ["4.1.1.1", "4.1.1.2", "4.1.1.3"]) + ) + h6 = self.add_group( + self.pg0, IgmpSG("239.1.1.5", ["5.1.1.1", "5.1.1.2", "5.1.1.3"]) + ) + h7 = self.add_group( + self.pg0, + IgmpSG( + "239.1.1.6", + [ + "6.1.1.1", + "6.1.1.2", + "6.1.1.3", + "6.1.1.4", + "6.1.1.5", + "6.1.1.6", + "6.1.1.7", + "6.1.1.8", + "6.1.1.9", + "6.1.1.10", + "6.1.1.11", + "6.1.1.12", + "6.1.1.13", + "6.1.1.14", + "6.1.1.15", + "6.1.1.16", + ], + ), + ) # # general query. @@ -390,39 +436,59 @@ class TestIgmp(VppTestCase): capture = self.pg0.get_capture(1, timeout=10) - self.verify_report(capture[0], - [IgmpRecord(h3.sg, "Mode Is Include"), - IgmpRecord(h2.sg, "Mode Is Include"), - IgmpRecord(h6.sg, "Mode Is Include"), - IgmpRecord(h4.sg, "Mode Is Include"), - IgmpRecord(h5.sg, "Mode Is Include"), - IgmpRecord(h7.sg, "Mode Is Include")]) + self.verify_report( + capture[0], + [ + IgmpRecord(h3.sg, "Mode Is Include"), + IgmpRecord(h2.sg, "Mode Is Include"), + IgmpRecord(h6.sg, "Mode Is Include"), + IgmpRecord(h4.sg, "Mode Is Include"), + IgmpRecord(h5.sg, "Mode Is Include"), + IgmpRecord(h7.sg, "Mode Is Include"), + ], + ) # # modify a group to add and remove some sources # - h7.sg = IgmpSG("239.1.1.6", - ["6.1.1.1", "6.1.1.2", - "6.1.1.5", "6.1.1.6", - "6.1.1.7", "6.1.1.8", - "6.1.1.9", "6.1.1.10", - "6.1.1.11", "6.1.1.12", - "6.1.1.13", "6.1.1.14", - "6.1.1.15", "6.1.1.16", - "6.1.1.17", "6.1.1.18"]) + h7.sg = IgmpSG( + "239.1.1.6", + [ + "6.1.1.1", + "6.1.1.2", + "6.1.1.5", + "6.1.1.6", + "6.1.1.7", + "6.1.1.8", + "6.1.1.9", + "6.1.1.10", + "6.1.1.11", + "6.1.1.12", + "6.1.1.13", + "6.1.1.14", + "6.1.1.15", + "6.1.1.16", + "6.1.1.17", + "6.1.1.18", + ], + ) self.pg_enable_capture(self.pg_interfaces) self.pg_start() h7.add_vpp_config() capture = self.pg0.get_capture(1, timeout=10) - self.verify_report(capture[0], - [IgmpRecord(IgmpSG("239.1.1.6", - ["6.1.1.17", "6.1.1.18"]), - "Allow New Sources"), - IgmpRecord(IgmpSG("239.1.1.6", - ["6.1.1.3", "6.1.1.4"]), - "Block Old Sources")]) + self.verify_report( + capture[0], + [ + IgmpRecord( + IgmpSG("239.1.1.6", ["6.1.1.17", "6.1.1.18"]), "Allow New Sources" + ), + IgmpRecord( + IgmpSG("239.1.1.6", ["6.1.1.3", "6.1.1.4"]), "Block Old Sources" + ), + ], + ) # # add an additional groups with many sources so that each group @@ -435,27 +501,26 @@ class TestIgmp(VppTestCase): for i in range(128): src_list.append("10.1.1.%d" % i) - h8 = self.add_group(self.pg0, - IgmpSG("238.1.1.1", src_list)) - h9 = self.add_group(self.pg0, - IgmpSG("238.1.1.2", src_list)) + h8 = self.add_group(self.pg0, IgmpSG("238.1.1.1", src_list)) + h9 = self.add_group(self.pg0, IgmpSG("238.1.1.2", src_list)) self.send(self.pg0, p_g) capture = self.pg0.get_capture(4, timeout=10) - self.verify_report(capture[0], - [IgmpRecord(h3.sg, "Mode Is Include"), - IgmpRecord(h2.sg, "Mode Is Include"), - IgmpRecord(h6.sg, "Mode Is Include"), - IgmpRecord(h4.sg, "Mode Is Include"), - IgmpRecord(h5.sg, "Mode Is Include")]) - self.verify_report(capture[1], - [IgmpRecord(h8.sg, "Mode Is Include")]) - self.verify_report(capture[2], - [IgmpRecord(h7.sg, "Mode Is Include")]) - self.verify_report(capture[3], - [IgmpRecord(h9.sg, "Mode Is Include")]) + self.verify_report( + capture[0], + [ + IgmpRecord(h3.sg, "Mode Is Include"), + IgmpRecord(h2.sg, "Mode Is Include"), + IgmpRecord(h6.sg, "Mode Is Include"), + IgmpRecord(h4.sg, "Mode Is Include"), + IgmpRecord(h5.sg, "Mode Is Include"), + ], + ) + self.verify_report(capture[1], [IgmpRecord(h8.sg, "Mode Is Include")]) + self.verify_report(capture[2], [IgmpRecord(h7.sg, "Mode Is Include")]) + self.verify_report(capture[3], [IgmpRecord(h9.sg, "Mode Is Include")]) # # drop the MTU further (so a 128 sized group won't fit) @@ -465,10 +530,12 @@ class TestIgmp(VppTestCase): self.pg_enable_capture(self.pg_interfaces) self.pg_start() - h10 = VppHostState(self, - IGMP_FILTER.INCLUDE, - self.pg0.sw_if_index, - IgmpSG("238.1.1.3", src_list)) + h10 = VppHostState( + self, + IGMP_FILTER.INCLUDE, + self.pg0.sw_if_index, + IgmpSG("238.1.1.3", src_list), + ) h10.add_vpp_config() capture = self.pg0.get_capture(2, timeout=10) @@ -498,32 +565,51 @@ class TestIgmp(VppTestCase): # ADD STATE ON MORE INTERFACES # - self.vapi.igmp_enable_disable(self.pg0.sw_if_index, - 0, - IGMP_MODE.HOST) + self.vapi.igmp_enable_disable(self.pg0.sw_if_index, 0, IGMP_MODE.HOST) def test_igmp_router(self): - """ IGMP Router Functions """ + """IGMP Router Functions""" # # Drop reports when not enabled # - p_j = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst="224.0.0.22", tos=0xc0, ttl=1, - options=[IPOption(copy_flag=1, optclass="control", - option="router_alert")]) / - IGMPv3(type="Version 3 Membership Report") / - IGMPv3mr(numgrp=1) / - IGMPv3gr(rtype="Allow New Sources", - maddr="239.1.1.1", srcaddrs=["10.1.1.1", "10.1.1.2"])) - p_l = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst="224.0.0.22", tos=0xc0, - options=[IPOption(copy_flag=1, optclass="control", - option="router_alert")]) / - IGMPv3(type="Version 3 Membership Report") / - IGMPv3mr(numgrp=1) / - IGMPv3gr(rtype="Block Old Sources", - maddr="239.1.1.1", srcaddrs=["10.1.1.1", "10.1.1.2"])) + p_j = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP( + src=self.pg0.remote_ip4, + dst="224.0.0.22", + tos=0xC0, + ttl=1, + options=[ + IPOption(copy_flag=1, optclass="control", option="router_alert") + ], + ) + / IGMPv3(type="Version 3 Membership Report") + / IGMPv3mr(numgrp=1) + / IGMPv3gr( + rtype="Allow New Sources", + maddr="239.1.1.1", + srcaddrs=["10.1.1.1", "10.1.1.2"], + ) + ) + p_l = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP( + src=self.pg0.remote_ip4, + dst="224.0.0.22", + tos=0xC0, + options=[ + IPOption(copy_flag=1, optclass="control", option="router_alert") + ], + ) + / IGMPv3(type="Version 3 Membership Report") + / IGMPv3mr(numgrp=1) + / IGMPv3gr( + rtype="Block Old Sources", + maddr="239.1.1.1", + srcaddrs=["10.1.1.1", "10.1.1.2"], + ) + ) self.send(self.pg0, p_j) self.assertFalse(self.vapi.igmp_dump()) @@ -539,9 +625,7 @@ class TestIgmp(VppTestCase): # self.pg_enable_capture(self.pg_interfaces) self.pg_start() - self.vapi.igmp_enable_disable(self.pg0.sw_if_index, - 1, - IGMP_MODE.ROUTER) + self.vapi.igmp_enable_disable(self.pg0.sw_if_index, 1, IGMP_MODE.ROUTER) self.vapi.want_igmp_events(1) # @@ -559,26 +643,28 @@ class TestIgmp(VppTestCase): # self.send(self.pg0, p_j) - self.assertTrue(wait_for_igmp_event(self, 1, self.pg0, - "239.1.1.1", "10.1.1.1", 1)) - self.assertTrue(wait_for_igmp_event(self, 1, self.pg0, - "239.1.1.1", "10.1.1.2", 1)) + self.assertTrue( + wait_for_igmp_event(self, 1, self.pg0, "239.1.1.1", "10.1.1.1", 1) + ) + self.assertTrue( + wait_for_igmp_event(self, 1, self.pg0, "239.1.1.1", "10.1.1.2", 1) + ) dump = self.vapi.igmp_dump(self.pg0.sw_if_index) self.assertEqual(len(dump), 2) - self.assertTrue(find_igmp_state(dump, self.pg0, - "239.1.1.1", "10.1.1.1")) - self.assertTrue(find_igmp_state(dump, self.pg0, - "239.1.1.1", "10.1.1.2")) + self.assertTrue(find_igmp_state(dump, self.pg0, "239.1.1.1", "10.1.1.1")) + self.assertTrue(find_igmp_state(dump, self.pg0, "239.1.1.1", "10.1.1.2")) # # wait for the per-source timer to expire # the state should be reaped # VPP sends a notification that the group has been left # - self.assertTrue(wait_for_igmp_event(self, 4, self.pg0, - "239.1.1.1", "10.1.1.1", 0)) - self.assertTrue(wait_for_igmp_event(self, 1, self.pg0, - "239.1.1.1", "10.1.1.2", 0)) + self.assertTrue( + wait_for_igmp_event(self, 4, self.pg0, "239.1.1.1", "10.1.1.1", 0) + ) + self.assertTrue( + wait_for_igmp_event(self, 1, self.pg0, "239.1.1.1", "10.1.1.2", 0) + ) self.assertFalse(self.vapi.igmp_dump()) # @@ -589,10 +675,12 @@ class TestIgmp(VppTestCase): # expired in 3 seconds. # self.send(self.pg0, p_j) - self.assertTrue(wait_for_igmp_event(self, 1, self.pg0, - "239.1.1.1", "10.1.1.1", 1)) - self.assertTrue(wait_for_igmp_event(self, 1, self.pg0, - "239.1.1.1", "10.1.1.2", 1)) + self.assertTrue( + wait_for_igmp_event(self, 1, self.pg0, "239.1.1.1", "10.1.1.1", 1) + ) + self.assertTrue( + wait_for_igmp_event(self, 1, self.pg0, "239.1.1.1", "10.1.1.2", 1) + ) dump = self.vapi.igmp_dump(self.pg0.sw_if_index) self.assertEqual(len(dump), 2) @@ -600,33 +688,43 @@ class TestIgmp(VppTestCase): self.verify_general_query(capture[0]) self.verify_general_query(capture[1]) - p_cs = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst="224.0.0.22", tos=0xc0, - options=[IPOption(copy_flag=1, optclass="control", - option="router_alert")]) / - IGMPv3(type="Version 3 Membership Report") / - IGMPv3mr(numgrp=1) / - IGMPv3gr(rtype="Mode Is Include", - maddr="239.1.1.1", srcaddrs=["10.1.1.1", "10.1.1.2"])) + p_cs = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP( + src=self.pg0.remote_ip4, + dst="224.0.0.22", + tos=0xC0, + options=[ + IPOption(copy_flag=1, optclass="control", option="router_alert") + ], + ) + / IGMPv3(type="Version 3 Membership Report") + / IGMPv3mr(numgrp=1) + / IGMPv3gr( + rtype="Mode Is Include", + maddr="239.1.1.1", + srcaddrs=["10.1.1.1", "10.1.1.2"], + ) + ) self.send(self.pg0, p_cs) self.sleep(2) dump = self.vapi.igmp_dump(self.pg0.sw_if_index) self.assertEqual(len(dump), 2) - self.assertTrue(find_igmp_state(dump, self.pg0, - "239.1.1.1", "10.1.1.1")) - self.assertTrue(find_igmp_state(dump, self.pg0, - "239.1.1.1", "10.1.1.2")) + self.assertTrue(find_igmp_state(dump, self.pg0, "239.1.1.1", "10.1.1.1")) + self.assertTrue(find_igmp_state(dump, self.pg0, "239.1.1.1", "10.1.1.2")) # # wait for the per-source timer to expire # the state should be reaped # - self.assertTrue(wait_for_igmp_event(self, 4, self.pg0, - "239.1.1.1", "10.1.1.1", 0)) - self.assertTrue(wait_for_igmp_event(self, 1, self.pg0, - "239.1.1.1", "10.1.1.2", 0)) + self.assertTrue( + wait_for_igmp_event(self, 4, self.pg0, "239.1.1.1", "10.1.1.1", 0) + ) + self.assertTrue( + wait_for_igmp_event(self, 1, self.pg0, "239.1.1.1", "10.1.1.2", 0) + ) self.assertFalse(self.vapi.igmp_dump()) # @@ -635,203 +733,261 @@ class TestIgmp(VppTestCase): # self.send(self.pg0, p_j) - self.assertTrue(wait_for_igmp_event(self, 1, self.pg0, - "239.1.1.1", "10.1.1.1", 1)) - self.assertTrue(wait_for_igmp_event(self, 1, self.pg0, - "239.1.1.1", "10.1.1.2", 1)) + self.assertTrue( + wait_for_igmp_event(self, 1, self.pg0, "239.1.1.1", "10.1.1.1", 1) + ) + self.assertTrue( + wait_for_igmp_event(self, 1, self.pg0, "239.1.1.1", "10.1.1.2", 1) + ) dump = self.vapi.igmp_dump(self.pg0.sw_if_index) self.assertEqual(len(dump), 2) self.send(self.pg0, p_l) capture = self.pg0.get_capture(1, timeout=3) - self.verify_group_query(capture[0], "239.1.1.1", - ["10.1.1.1", "10.1.1.2"]) + self.verify_group_query(capture[0], "239.1.1.1", ["10.1.1.1", "10.1.1.2"]) # # the group specific query drops the timeout to leave (=1) seconds # - self.assertTrue(wait_for_igmp_event(self, 2, self.pg0, - "239.1.1.1", "10.1.1.1", 0)) - self.assertTrue(wait_for_igmp_event(self, 1, self.pg0, - "239.1.1.1", "10.1.1.2", 0)) + self.assertTrue( + wait_for_igmp_event(self, 2, self.pg0, "239.1.1.1", "10.1.1.1", 0) + ) + self.assertTrue( + wait_for_igmp_event(self, 1, self.pg0, "239.1.1.1", "10.1.1.2", 0) + ) self.assertFalse(self.vapi.igmp_dump()) self.assertFalse(self.vapi.igmp_dump()) # # a TO_EX({}) / IN_EX({}) is treated like a (*,G) join # - p_j = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst="224.0.0.22", tos=0xc0, ttl=1, - options=[IPOption(copy_flag=1, optclass="control", - option="router_alert")]) / - IGMPv3(type="Version 3 Membership Report") / - IGMPv3mr(numgrp=1) / - IGMPv3gr(rtype="Change To Exclude Mode", maddr="239.1.1.2")) + p_j = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP( + src=self.pg0.remote_ip4, + dst="224.0.0.22", + tos=0xC0, + ttl=1, + options=[ + IPOption(copy_flag=1, optclass="control", option="router_alert") + ], + ) + / IGMPv3(type="Version 3 Membership Report") + / IGMPv3mr(numgrp=1) + / IGMPv3gr(rtype="Change To Exclude Mode", maddr="239.1.1.2") + ) self.send(self.pg0, p_j) - self.assertTrue(wait_for_igmp_event(self, 1, self.pg0, - "239.1.1.2", "0.0.0.0", 1)) - - p_j = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst="224.0.0.22", tos=0xc0, ttl=1, - options=[IPOption(copy_flag=1, optclass="control", - option="router_alert")]) / - IGMPv3(type="Version 3 Membership Report") / - IGMPv3mr(numgrp=1) / - IGMPv3gr(rtype="Mode Is Exclude", maddr="239.1.1.3")) + self.assertTrue( + wait_for_igmp_event(self, 1, self.pg0, "239.1.1.2", "0.0.0.0", 1) + ) + + p_j = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP( + src=self.pg0.remote_ip4, + dst="224.0.0.22", + tos=0xC0, + ttl=1, + options=[ + IPOption(copy_flag=1, optclass="control", option="router_alert") + ], + ) + / IGMPv3(type="Version 3 Membership Report") + / IGMPv3mr(numgrp=1) + / IGMPv3gr(rtype="Mode Is Exclude", maddr="239.1.1.3") + ) self.send(self.pg0, p_j) - self.assertTrue(wait_for_igmp_event(self, 1, self.pg0, - "239.1.1.3", "0.0.0.0", 1)) + self.assertTrue( + wait_for_igmp_event(self, 1, self.pg0, "239.1.1.3", "0.0.0.0", 1) + ) # # A 'allow sources' for {} should be ignored as it should # never be sent. # - p_j = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst="224.0.0.22", tos=0xc0, ttl=1, - options=[IPOption(copy_flag=1, optclass="control", - option="router_alert")]) / - IGMPv3(type="Version 3 Membership Report") / - IGMPv3mr(numgrp=1) / - IGMPv3gr(rtype="Allow New Sources", maddr="239.1.1.4")) + p_j = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP( + src=self.pg0.remote_ip4, + dst="224.0.0.22", + tos=0xC0, + ttl=1, + options=[ + IPOption(copy_flag=1, optclass="control", option="router_alert") + ], + ) + / IGMPv3(type="Version 3 Membership Report") + / IGMPv3mr(numgrp=1) + / IGMPv3gr(rtype="Allow New Sources", maddr="239.1.1.4") + ) self.send(self.pg0, p_j) dump = self.vapi.igmp_dump(self.pg0.sw_if_index) - self.assertTrue(find_igmp_state(dump, self.pg0, - "239.1.1.2", "0.0.0.0")) - self.assertTrue(find_igmp_state(dump, self.pg0, - "239.1.1.3", "0.0.0.0")) - self.assertFalse(find_igmp_state(dump, self.pg0, - "239.1.1.4", "0.0.0.0")) + self.assertTrue(find_igmp_state(dump, self.pg0, "239.1.1.2", "0.0.0.0")) + self.assertTrue(find_igmp_state(dump, self.pg0, "239.1.1.3", "0.0.0.0")) + self.assertFalse(find_igmp_state(dump, self.pg0, "239.1.1.4", "0.0.0.0")) # # a TO_IN({}) and IS_IN({}) are treated like a (*,G) leave # self.vapi.cli("set logging class igmp level debug") - p_l = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst="224.0.0.22", tos=0xc0, ttl=1, - options=[IPOption(copy_flag=1, optclass="control", - option="router_alert")]) / - IGMPv3(type="Version 3 Membership Report") / - IGMPv3mr(numgrp=1) / - IGMPv3gr(rtype="Change To Include Mode", maddr="239.1.1.2")) + p_l = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP( + src=self.pg0.remote_ip4, + dst="224.0.0.22", + tos=0xC0, + ttl=1, + options=[ + IPOption(copy_flag=1, optclass="control", option="router_alert") + ], + ) + / IGMPv3(type="Version 3 Membership Report") + / IGMPv3mr(numgrp=1) + / IGMPv3gr(rtype="Change To Include Mode", maddr="239.1.1.2") + ) self.send(self.pg0, p_l) - self.assertTrue(wait_for_igmp_event(self, 2, self.pg0, - "239.1.1.2", "0.0.0.0", 0)) - - p_l = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst="224.0.0.22", tos=0xc0, ttl=1, - options=[IPOption(copy_flag=1, optclass="control", - option="router_alert")]) / - IGMPv3(type="Version 3 Membership Report") / - IGMPv3mr(numgrp=1) / - IGMPv3gr(rtype="Mode Is Include", maddr="239.1.1.3")) + self.assertTrue( + wait_for_igmp_event(self, 2, self.pg0, "239.1.1.2", "0.0.0.0", 0) + ) + + p_l = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP( + src=self.pg0.remote_ip4, + dst="224.0.0.22", + tos=0xC0, + ttl=1, + options=[ + IPOption(copy_flag=1, optclass="control", option="router_alert") + ], + ) + / IGMPv3(type="Version 3 Membership Report") + / IGMPv3mr(numgrp=1) + / IGMPv3gr(rtype="Mode Is Include", maddr="239.1.1.3") + ) self.send(self.pg0, p_l) - self.assertTrue(wait_for_igmp_event(self, 2, self.pg0, - "239.1.1.3", "0.0.0.0", 0)) + self.assertTrue( + wait_for_igmp_event(self, 2, self.pg0, "239.1.1.3", "0.0.0.0", 0) + ) self.assertFalse(self.vapi.igmp_dump(self.pg0.sw_if_index)) # # disable router config # - self.vapi.igmp_enable_disable(self.pg0.sw_if_index, - 0, - IGMP_MODE.ROUTER) + self.vapi.igmp_enable_disable(self.pg0.sw_if_index, 0, IGMP_MODE.ROUTER) def _create_igmpv3_pck(self, itf, rtype, maddr, srcaddrs): - p = (Ether(dst=itf.local_mac, src=itf.remote_mac) / - IP(src=itf.remote_ip4, dst="224.0.0.22", tos=0xc0, ttl=1, - options=[IPOption(copy_flag=1, optclass="control", - option="router_alert")]) / - IGMPv3(type="Version 3 Membership Report") / - IGMPv3mr(numgrp=1) / - IGMPv3gr(rtype=rtype, - maddr=maddr, srcaddrs=srcaddrs)) + p = ( + Ether(dst=itf.local_mac, src=itf.remote_mac) + / IP( + src=itf.remote_ip4, + dst="224.0.0.22", + tos=0xC0, + ttl=1, + options=[ + IPOption(copy_flag=1, optclass="control", option="router_alert") + ], + ) + / IGMPv3(type="Version 3 Membership Report") + / IGMPv3mr(numgrp=1) + / IGMPv3gr(rtype=rtype, maddr=maddr, srcaddrs=srcaddrs) + ) return p def test_igmp_proxy_device(self): - """ IGMP proxy device """ + """IGMP proxy device""" self.pg2.admin_down() self.pg2.unconfig_ip4() self.pg2.set_table_ip4(0) self.pg2.config_ip4() self.pg2.admin_up() - self.vapi.cli('test igmp timers query 10 src 3 leave 1') + self.vapi.cli("test igmp timers query 10 src 3 leave 1") # enable IGMP self.vapi.igmp_enable_disable(self.pg0.sw_if_index, 1, IGMP_MODE.HOST) - self.vapi.igmp_enable_disable(self.pg1.sw_if_index, 1, - IGMP_MODE.ROUTER) - self.vapi.igmp_enable_disable(self.pg2.sw_if_index, 1, - IGMP_MODE.ROUTER) + self.vapi.igmp_enable_disable(self.pg1.sw_if_index, 1, IGMP_MODE.ROUTER) + self.vapi.igmp_enable_disable(self.pg2.sw_if_index, 1, IGMP_MODE.ROUTER) # create IGMP proxy device self.vapi.igmp_proxy_device_add_del(0, self.pg0.sw_if_index, 1) - self.vapi.igmp_proxy_device_add_del_interface(0, - self.pg1.sw_if_index, 1) - self.vapi.igmp_proxy_device_add_del_interface(0, - self.pg2.sw_if_index, 1) + self.vapi.igmp_proxy_device_add_del_interface(0, self.pg1.sw_if_index, 1) + self.vapi.igmp_proxy_device_add_del_interface(0, self.pg2.sw_if_index, 1) # send join on pg1. join should be proxied by pg0 - p_j = self._create_igmpv3_pck(self.pg1, "Allow New Sources", - "239.1.1.1", ["10.1.1.1", "10.1.1.2"]) + p_j = self._create_igmpv3_pck( + self.pg1, "Allow New Sources", "239.1.1.1", ["10.1.1.1", "10.1.1.2"] + ) self.send(self.pg1, p_j) capture = self.pg0.get_capture(1, timeout=1) - self.verify_report(capture[0], [IgmpRecord(IgmpSG("239.1.1.1", - ["10.1.1.1", "10.1.1.2"]), "Allow New Sources")]) + self.verify_report( + capture[0], + [ + IgmpRecord( + IgmpSG("239.1.1.1", ["10.1.1.1", "10.1.1.2"]), "Allow New Sources" + ) + ], + ) self.assertTrue(find_mroute(self, "239.1.1.1", "0.0.0.0", 32)) # send join on pg2. join should be proxied by pg0. # the group should contain only 10.1.1.3 as # 10.1.1.1 was already reported - p_j = self._create_igmpv3_pck(self.pg2, "Allow New Sources", - "239.1.1.1", ["10.1.1.1", "10.1.1.3"]) + p_j = self._create_igmpv3_pck( + self.pg2, "Allow New Sources", "239.1.1.1", ["10.1.1.1", "10.1.1.3"] + ) self.send(self.pg2, p_j) capture = self.pg0.get_capture(1, timeout=1) - self.verify_report(capture[0], [IgmpRecord(IgmpSG("239.1.1.1", - ["10.1.1.3"]), "Allow New Sources")]) + self.verify_report( + capture[0], + [IgmpRecord(IgmpSG("239.1.1.1", ["10.1.1.3"]), "Allow New Sources")], + ) self.assertTrue(find_mroute(self, "239.1.1.1", "0.0.0.0", 32)) # send leave on pg2. leave for 10.1.1.3 should be proxyed # as pg2 was the only interface interested in 10.1.1.3 - p_l = self._create_igmpv3_pck(self.pg2, "Block Old Sources", - "239.1.1.1", ["10.1.1.3"]) + p_l = self._create_igmpv3_pck( + self.pg2, "Block Old Sources", "239.1.1.1", ["10.1.1.3"] + ) self.send(self.pg2, p_l) capture = self.pg0.get_capture(1, timeout=2) - self.verify_report(capture[0], [IgmpRecord(IgmpSG("239.1.1.1", - ["10.1.1.3"]), "Block Old Sources")]) + self.verify_report( + capture[0], + [IgmpRecord(IgmpSG("239.1.1.1", ["10.1.1.3"]), "Block Old Sources")], + ) self.assertTrue(find_mroute(self, "239.1.1.1", "0.0.0.0", 32)) # disable igmp on pg1 (also removes interface from proxy device) # proxy leave for 10.1.1.2. pg2 is still interested in 10.1.1.1 self.pg_enable_capture(self.pg_interfaces) - self.vapi.igmp_enable_disable(self.pg1.sw_if_index, 0, - IGMP_MODE.ROUTER) + self.vapi.igmp_enable_disable(self.pg1.sw_if_index, 0, IGMP_MODE.ROUTER) capture = self.pg0.get_capture(1, timeout=1) - self.verify_report(capture[0], [IgmpRecord(IgmpSG("239.1.1.1", - ["10.1.1.2"]), "Block Old Sources")]) + self.verify_report( + capture[0], + [IgmpRecord(IgmpSG("239.1.1.1", ["10.1.1.2"]), "Block Old Sources")], + ) self.assertTrue(find_mroute(self, "239.1.1.1", "0.0.0.0", 32)) # disable IGMP on pg0 and pg1. # disabling IGMP on pg0 (proxy device upstream interface) # removes this proxy device self.vapi.igmp_enable_disable(self.pg0.sw_if_index, 0, IGMP_MODE.HOST) - self.vapi.igmp_enable_disable(self.pg2.sw_if_index, 0, - IGMP_MODE.ROUTER) + self.vapi.igmp_enable_disable(self.pg2.sw_if_index, 0, IGMP_MODE.ROUTER) self.assertFalse(find_mroute(self, "239.1.1.1", "0.0.0.0", 32)) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_ikev2.py b/test/test_ikev2.py index 58a7ec3cd9a..5b699dd0d8d 100644 --- a/test/test_ikev2.py +++ b/test/test_ikev2.py @@ -38,7 +38,9 @@ GCM_IV_SIZE = 8 # defined in rfc3526 # tuple structure is (p, g, key_len) DH = { - '2048MODPgr': (long_converter(""" + "2048MODPgr": ( + long_converter( + """ FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1 29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245 @@ -49,9 +51,14 @@ DH = { 670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9 DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510 - 15728E5A 8AACAA68 FFFFFFFF FFFFFFFF"""), 2, 256), - - '3072MODPgr': (long_converter(""" + 15728E5A 8AACAA68 FFFFFFFF FFFFFFFF""" + ), + 2, + 256, + ), + "3072MODPgr": ( + long_converter( + """ FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1 29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245 @@ -67,7 +74,11 @@ DH = { ABF5AE8C DB0933D7 1E8C94E0 4A25619D CEE3D226 1AD2EE6B F12FFA06 D98A0864 D8760273 3EC86A64 521F2B18 177B200C BBE11757 7A615D6C 770988C0 BAD946E2 08E24FA0 74E5AB31 - 43DB5BFC E0FD108E 4B82D120 A93AD2CA FFFFFFFF FFFFFFFF"""), 2, 384) + 43DB5BFC E0FD108E 4B82D120 A93AD2CA FFFFFFFF FFFFFFFF""" + ), + 2, + 384, + ), } @@ -79,7 +90,7 @@ class CryptoAlgo(object): if self.cipher is not None: self.bs = self.cipher.block_size // 8 - if self.name == 'AES-GCM-16ICV': + if self.name == "AES-GCM-16ICV": self.iv_len = GCM_IV_SIZE else: self.iv_len = self.bs @@ -87,14 +98,16 @@ class CryptoAlgo(object): def encrypt(self, data, key, aad=None): iv = os.urandom(self.iv_len) if aad is None: - encryptor = Cipher(self.cipher(key), self.mode(iv), - default_backend()).encryptor() + encryptor = Cipher( + self.cipher(key), self.mode(iv), default_backend() + ).encryptor() return iv + encryptor.update(data) + encryptor.finalize() else: salt = key[-SALT_SIZE:] nonce = salt + iv - encryptor = Cipher(self.cipher(key[:-SALT_SIZE]), self.mode(nonce), - default_backend()).encryptor() + encryptor = Cipher( + self.cipher(key[:-SALT_SIZE]), self.mode(nonce), default_backend() + ).encryptor() encryptor.authenticate_additional_data(aad) data = encryptor.update(data) + encryptor.finalize() data += encryptor.tag[:GCM_ICV_SIZE] @@ -102,26 +115,26 @@ class CryptoAlgo(object): def decrypt(self, data, key, aad=None, icv=None): if aad is None: - iv = data[:self.iv_len] - ct = data[self.iv_len:] - decryptor = Cipher(algorithms.AES(key), - self.mode(iv), - default_backend()).decryptor() + iv = data[: self.iv_len] + ct = data[self.iv_len :] + decryptor = Cipher( + algorithms.AES(key), self.mode(iv), default_backend() + ).decryptor() return decryptor.update(ct) + decryptor.finalize() else: salt = key[-SALT_SIZE:] nonce = salt + data[:GCM_IV_SIZE] ct = data[GCM_IV_SIZE:] key = key[:-SALT_SIZE] - decryptor = Cipher(algorithms.AES(key), - self.mode(nonce, icv, len(icv)), - default_backend()).decryptor() + decryptor = Cipher( + algorithms.AES(key), self.mode(nonce, icv, len(icv)), default_backend() + ).decryptor() decryptor.authenticate_additional_data(aad) return decryptor.update(ct) + decryptor.finalize() def pad(self, data): pad_len = (len(data) // self.bs + 1) * self.bs - len(data) - data = data + b'\x00' * (pad_len - 1) + data = data + b"\x00" * (pad_len - 1) return data + bytes([pad_len - 1]) @@ -135,36 +148,34 @@ class AuthAlgo(object): CRYPTO_ALGOS = { - 'NULL': CryptoAlgo('NULL', cipher=None, mode=None), - 'AES-CBC': CryptoAlgo('AES-CBC', cipher=algorithms.AES, mode=modes.CBC), - 'AES-GCM-16ICV': CryptoAlgo('AES-GCM-16ICV', cipher=algorithms.AES, - mode=modes.GCM), + "NULL": CryptoAlgo("NULL", cipher=None, mode=None), + "AES-CBC": CryptoAlgo("AES-CBC", cipher=algorithms.AES, mode=modes.CBC), + "AES-GCM-16ICV": CryptoAlgo("AES-GCM-16ICV", cipher=algorithms.AES, mode=modes.GCM), } AUTH_ALGOS = { - 'NULL': AuthAlgo('NULL', mac=None, mod=None, key_len=0, trunc_len=0), - 'HMAC-SHA1-96': AuthAlgo('HMAC-SHA1-96', hmac.HMAC, hashes.SHA1, 20, 12), - 'SHA2-256-128': AuthAlgo('SHA2-256-128', hmac.HMAC, hashes.SHA256, 32, 16), - 'SHA2-384-192': AuthAlgo('SHA2-384-192', hmac.HMAC, hashes.SHA256, 48, 24), - 'SHA2-512-256': AuthAlgo('SHA2-512-256', hmac.HMAC, hashes.SHA256, 64, 32), + "NULL": AuthAlgo("NULL", mac=None, mod=None, key_len=0, trunc_len=0), + "HMAC-SHA1-96": AuthAlgo("HMAC-SHA1-96", hmac.HMAC, hashes.SHA1, 20, 12), + "SHA2-256-128": AuthAlgo("SHA2-256-128", hmac.HMAC, hashes.SHA256, 32, 16), + "SHA2-384-192": AuthAlgo("SHA2-384-192", hmac.HMAC, hashes.SHA256, 48, 24), + "SHA2-512-256": AuthAlgo("SHA2-512-256", hmac.HMAC, hashes.SHA256, 64, 32), } PRF_ALGOS = { - 'NULL': AuthAlgo('NULL', mac=None, mod=None, key_len=0, trunc_len=0), - 'PRF_HMAC_SHA2_256': AuthAlgo('PRF_HMAC_SHA2_256', hmac.HMAC, - hashes.SHA256, 32), + "NULL": AuthAlgo("NULL", mac=None, mod=None, key_len=0, trunc_len=0), + "PRF_HMAC_SHA2_256": AuthAlgo("PRF_HMAC_SHA2_256", hmac.HMAC, hashes.SHA256, 32), } CRYPTO_IDS = { - 12: 'AES-CBC', - 20: 'AES-GCM-16ICV', + 12: "AES-CBC", + 20: "AES-GCM-16ICV", } INTEG_IDS = { - 2: 'HMAC-SHA1-96', - 12: 'SHA2-256-128', - 13: 'SHA2-384-192', - 14: 'SHA2-512-256', + 2: "HMAC-SHA1-96", + 12: "SHA2-256-128", + 13: "SHA2-384-192", + 14: "SHA2-512-256", } @@ -182,11 +193,24 @@ class IKEv2ChildSA(object): class IKEv2SA(object): - def __init__(self, test, is_initiator=True, i_id=None, r_id=None, - spi=b'\x01\x02\x03\x04\x05\x06\x07\x08', id_type='fqdn', - nonce=None, auth_data=None, local_ts=None, remote_ts=None, - auth_method='shared-key', priv_key=None, i_natt=False, - r_natt=False, udp_encap=False): + def __init__( + self, + test, + is_initiator=True, + i_id=None, + r_id=None, + spi=b"\x01\x02\x03\x04\x05\x06\x07\x08", + id_type="fqdn", + nonce=None, + auth_data=None, + local_ts=None, + remote_ts=None, + auth_method="shared-key", + priv_key=None, + i_natt=False, + r_natt=False, + udp_encap=False, + ): self.udp_encap = udp_encap self.i_natt = i_natt self.r_natt = r_natt @@ -211,15 +235,14 @@ class IKEv2SA(object): self.id_type = id_type self.auth_method = auth_method if self.is_initiator: - self.rspi = 8 * b'\x00' + self.rspi = 8 * b"\x00" self.ispi = spi self.i_nonce = nonce else: self.rspi = spi - self.ispi = 8 * b'\x00' + self.ispi = 8 * b"\x00" self.r_nonce = nonce - self.child_sas = [IKEv2ChildSA(local_ts, remote_ts, - self.is_initiator)] + self.child_sas = [IKEv2ChildSA(local_ts, remote_ts, self.is_initiator)] def new_msg_id(self): self.msg_id += 1 @@ -245,13 +268,14 @@ class IKEv2SA(object): priv = self.dh_private_key peer = self.peer_dh_pub_key p, g, l = self.ike_group - return pow(int.from_bytes(peer, 'big'), - int.from_bytes(priv, 'big'), p).to_bytes(l, 'big') + return pow( + int.from_bytes(peer, "big"), int.from_bytes(priv, "big"), p + ).to_bytes(l, "big") def generate_dh_data(self): # generate DH keys if self.ike_dh not in DH: - raise NotImplementedError('%s not in DH group' % self.ike_dh) + raise NotImplementedError("%s not in DH group" % self.ike_dh) if self.dh_params is None: dhg = DH[self.ike_dh] @@ -261,13 +285,13 @@ class IKEv2SA(object): priv = self.dh_params.generate_private_key() pub = priv.public_key() x = priv.private_numbers().x - self.dh_private_key = x.to_bytes(priv.key_size // 8, 'big') + self.dh_private_key = x.to_bytes(priv.key_size // 8, "big") y = pub.public_numbers().y if self.is_initiator: - self.i_dh_data = y.to_bytes(pub.key_size // 8, 'big') + self.i_dh_data = y.to_bytes(pub.key_size // 8, "big") else: - self.r_dh_data = y.to_bytes(pub.key_size // 8, 'big') + self.r_dh_data = y.to_bytes(pub.key_size // 8, "big") def complete_dh_data(self): self.dh_shared_secret = self.compute_secret() @@ -281,41 +305,39 @@ class IKEv2SA(object): integ_key_len = self.esp_integ_alg.key_len salt_len = 0 if integ_key_len else 4 - l = (integ_key_len * 2 + - encr_key_len * 2 + - salt_len * 2) + l = integ_key_len * 2 + encr_key_len * 2 + salt_len * 2 keymat = self.calc_prfplus(prf, self.sk_d, s, l) pos = 0 - c.sk_ei = keymat[pos:pos+encr_key_len] + c.sk_ei = keymat[pos : pos + encr_key_len] pos += encr_key_len if integ_key_len: - c.sk_ai = keymat[pos:pos+integ_key_len] + c.sk_ai = keymat[pos : pos + integ_key_len] pos += integ_key_len else: - c.salt_ei = keymat[pos:pos+salt_len] + c.salt_ei = keymat[pos : pos + salt_len] pos += salt_len - c.sk_er = keymat[pos:pos+encr_key_len] + c.sk_er = keymat[pos : pos + encr_key_len] pos += encr_key_len if integ_key_len: - c.sk_ar = keymat[pos:pos+integ_key_len] + c.sk_ar = keymat[pos : pos + integ_key_len] pos += integ_key_len else: - c.salt_er = keymat[pos:pos+salt_len] + c.salt_er = keymat[pos : pos + salt_len] pos += salt_len def calc_prfplus(self, prf, key, seed, length): - r = b'' + r = b"" t = None x = 1 while len(r) < length and x < 255: if t is not None: s = t else: - s = b'' + s = b"" s = s + seed + bytes([x]) t = self.calc_prf(prf, key, s) r = r + t @@ -348,30 +370,32 @@ class IKEv2SA(object): else: salt_size = 0 - l = (prf_key_trunc + - integ_key_len * 2 + - encr_key_len * 2 + - tr_prf_key_len * 2 + - salt_size * 2) + l = ( + prf_key_trunc + + integ_key_len * 2 + + encr_key_len * 2 + + tr_prf_key_len * 2 + + salt_size * 2 + ) keymat = self.calc_prfplus(prf, self.skeyseed, s, l) pos = 0 - self.sk_d = keymat[:pos+prf_key_trunc] + self.sk_d = keymat[: pos + prf_key_trunc] pos += prf_key_trunc - self.sk_ai = keymat[pos:pos+integ_key_len] + self.sk_ai = keymat[pos : pos + integ_key_len] pos += integ_key_len - self.sk_ar = keymat[pos:pos+integ_key_len] + self.sk_ar = keymat[pos : pos + integ_key_len] pos += integ_key_len - self.sk_ei = keymat[pos:pos+encr_key_len + salt_size] + self.sk_ei = keymat[pos : pos + encr_key_len + salt_size] pos += encr_key_len + salt_size - self.sk_er = keymat[pos:pos+encr_key_len + salt_size] + self.sk_er = keymat[pos : pos + encr_key_len + salt_size] pos += encr_key_len + salt_size - self.sk_pi = keymat[pos:pos+tr_prf_key_len] + self.sk_pi = keymat[pos : pos + tr_prf_key_len] pos += tr_prf_key_len - self.sk_pr = keymat[pos:pos+tr_prf_key_len] + self.sk_pr = keymat[pos : pos + tr_prf_key_len] def generate_authmsg(self, prf, packet): if self.is_initiator: @@ -393,14 +417,15 @@ class IKEv2SA(object): else: packet = self.init_resp_packet authmsg = self.generate_authmsg(prf, raw(packet)) - if self.auth_method == 'shared-key': + if self.auth_method == "shared-key": psk = self.calc_prf(prf, self.auth_data, KEY_PAD) self.auth_data = self.calc_prf(prf, psk, authmsg) - elif self.auth_method == 'rsa-sig': - self.auth_data = self.priv_key.sign(authmsg, padding.PKCS1v15(), - hashes.SHA1()) + elif self.auth_method == "rsa-sig": + self.auth_data = self.priv_key.sign( + authmsg, padding.PKCS1v15(), hashes.SHA1() + ) else: - raise TypeError('unknown auth method type!') + raise TypeError("unknown auth method type!") def encrypt(self, data, aad=None): data = self.ike_crypto_alg.pad(data) @@ -431,7 +456,7 @@ class IKEv2SA(object): return self.sk_ei def concat(self, alg, key_len): - return alg + '-' + str(key_len * 8) + return alg + "-" + str(key_len * 8) @property def vpp_ike_cypto_alg(self): @@ -445,8 +470,9 @@ class IKEv2SA(object): integ_trunc = self.ike_integ_alg.trunc_len exp_hmac = ikemsg[-integ_trunc:] data = ikemsg[:-integ_trunc] - computed_hmac = self.compute_hmac(self.ike_integ_alg.mod(), - self.peer_authkey, data) + computed_hmac = self.compute_hmac( + self.ike_integ_alg.mod(), self.peer_authkey, data + ) self.test.assertEqual(computed_hmac[:integ_trunc], exp_hmac) def compute_hmac(self, integ, key, data): @@ -459,7 +485,7 @@ class IKEv2SA(object): def hmac_and_decrypt(self, ike): ep = ike[ikev2.IKEv2_payload_Encrypted] - if self.ike_crypto == 'AES-GCM-16ICV': + if self.ike_crypto == "AES-GCM-16ICV": aad_len = len(ikev2.IKEv2_payload_Encrypted()) + len(ikev2.IKEv2()) ct = ep.load[:-GCM_ICV_SIZE] tag = ep.load[-GCM_ICV_SIZE:] @@ -473,26 +499,26 @@ class IKEv2SA(object): plain = self.decrypt(ct) # remove padding pad_len = plain[-1] - return plain[:-pad_len - 1] + return plain[: -pad_len - 1] def build_ts_addr(self, ts, version): - return {'starting_address_v' + version: ts['start_addr'], - 'ending_address_v' + version: ts['end_addr']} + return { + "starting_address_v" + version: ts["start_addr"], + "ending_address_v" + version: ts["end_addr"], + } def generate_ts(self, is_ip4): c = self.child_sas[0] - ts_data = {'IP_protocol_ID': 0, - 'start_port': 0, - 'end_port': 0xffff} + ts_data = {"IP_protocol_ID": 0, "start_port": 0, "end_port": 0xFFFF} if is_ip4: - ts_data.update(self.build_ts_addr(c.local_ts, '4')) + ts_data.update(self.build_ts_addr(c.local_ts, "4")) ts1 = ikev2.IPv4TrafficSelector(**ts_data) - ts_data.update(self.build_ts_addr(c.remote_ts, '4')) + ts_data.update(self.build_ts_addr(c.remote_ts, "4")) ts2 = ikev2.IPv4TrafficSelector(**ts_data) else: - ts_data.update(self.build_ts_addr(c.local_ts, '6')) + ts_data.update(self.build_ts_addr(c.local_ts, "6")) ts1 = ikev2.IPv6TrafficSelector(**ts_data) - ts_data.update(self.build_ts_addr(c.remote_ts, '6')) + ts_data.update(self.build_ts_addr(c.remote_ts, "6")) ts2 = ikev2.IPv6TrafficSelector(**ts_data) if self.is_initiator: @@ -501,18 +527,18 @@ class IKEv2SA(object): def set_ike_props(self, crypto, crypto_key_len, integ, prf, dh): if crypto not in CRYPTO_ALGOS: - raise TypeError('unsupported encryption algo %r' % crypto) + raise TypeError("unsupported encryption algo %r" % crypto) self.ike_crypto = crypto self.ike_crypto_alg = CRYPTO_ALGOS[crypto] self.ike_crypto_key_len = crypto_key_len if integ not in AUTH_ALGOS: - raise TypeError('unsupported auth algo %r' % integ) - self.ike_integ = None if integ == 'NULL' else integ + raise TypeError("unsupported auth algo %r" % integ) + self.ike_integ = None if integ == "NULL" else integ self.ike_integ_alg = AUTH_ALGOS[integ] if prf not in PRF_ALGOS: - raise TypeError('unsupported prf algo %r' % prf) + raise TypeError("unsupported prf algo %r" % prf) self.ike_prf = prf self.ike_prf_alg = PRF_ALGOS[prf] self.ike_dh = dh @@ -521,20 +547,20 @@ class IKEv2SA(object): def set_esp_props(self, crypto, crypto_key_len, integ): self.esp_crypto_key_len = crypto_key_len if crypto not in CRYPTO_ALGOS: - raise TypeError('unsupported encryption algo %r' % crypto) + raise TypeError("unsupported encryption algo %r" % crypto) self.esp_crypto = crypto self.esp_crypto_alg = CRYPTO_ALGOS[crypto] if integ not in AUTH_ALGOS: - raise TypeError('unsupported auth algo %r' % integ) - self.esp_integ = None if integ == 'NULL' else integ + raise TypeError("unsupported auth algo %r" % integ) + self.esp_integ = None if integ == "NULL" else integ self.esp_integ_alg = AUTH_ALGOS[integ] def crypto_attr(self, key_len): - if self.ike_crypto in ['AES-CBC', 'AES-GCM-16ICV']: - return (0x800e << 16 | key_len << 3, 12) + if self.ike_crypto in ["AES-CBC", "AES-GCM-16ICV"]: + return (0x800E << 16 | key_len << 3, 12) else: - raise Exception('unsupported attribute type') + raise Exception("unsupported attribute type") def ike_crypto_attr(self): return self.crypto_attr(self.ike_crypto_key_len) @@ -545,19 +571,20 @@ class IKEv2SA(object): def compute_nat_sha1(self, ip, port, rspi=None): if rspi is None: rspi = self.rspi - data = self.ispi + rspi + ip + (port).to_bytes(2, 'big') + data = self.ispi + rspi + ip + (port).to_bytes(2, "big") digest = hashes.Hash(hashes.SHA1(), backend=default_backend()) digest.update(data) return digest.finalize() class IkePeer(VppTestCase): - """ common class for initiator and responder """ + """common class for initiator and responder""" @classmethod def setUpClass(cls): import scapy.contrib.ikev2 as _ikev2 - globals()['ikev2'] = _ikev2 + + globals()["ikev2"] = _ikev2 super(IkePeer, cls).setUpClass() cls.create_pg_interfaces(range(2)) for i in cls.pg_interfaces: @@ -591,36 +618,46 @@ class IkePeer(VppTestCase): self.assertIsNotNone(self.p.query_vpp_config()) if self.sa.is_initiator: self.sa.generate_dh_data() - self.vapi.cli('ikev2 set logging level 4') - self.vapi.cli('event-lo clear') + self.vapi.cli("ikev2 set logging level 4") + self.vapi.cli("event-lo clear") - def assert_counter(self, count, name, version='ip4'): - node_name = '/err/ikev2-%s/' % version + name + def assert_counter(self, count, name, version="ip4"): + node_name = "/err/ikev2-%s/" % version + name self.assertEqual(count, self.statistics.get_err_counter(node_name)) def create_rekey_request(self): sa, first_payload = self.generate_auth_payload(is_rekey=True) header = ikev2.IKEv2( - init_SPI=self.sa.ispi, - resp_SPI=self.sa.rspi, id=self.sa.new_msg_id(), - flags='Initiator', exch_type='CREATE_CHILD_SA') + init_SPI=self.sa.ispi, + resp_SPI=self.sa.rspi, + id=self.sa.new_msg_id(), + flags="Initiator", + exch_type="CREATE_CHILD_SA", + ) ike_msg = self.encrypt_ike_msg(header, sa, first_payload) - return self.create_packet(self.pg0, ike_msg, self.sa.sport, - self.sa.dport, self.sa.natt, self.ip6) + return self.create_packet( + self.pg0, ike_msg, self.sa.sport, self.sa.dport, self.sa.natt, self.ip6 + ) def create_empty_request(self): - header = ikev2.IKEv2(init_SPI=self.sa.ispi, resp_SPI=self.sa.rspi, - id=self.sa.new_msg_id(), flags='Initiator', - exch_type='INFORMATIONAL', - next_payload='Encrypted') - - msg = self.encrypt_ike_msg(header, b'', None) - return self.create_packet(self.pg0, msg, self.sa.sport, - self.sa.dport, self.sa.natt, self.ip6) - - def create_packet(self, src_if, msg, sport=500, dport=500, natt=False, - use_ip6=False): + header = ikev2.IKEv2( + init_SPI=self.sa.ispi, + resp_SPI=self.sa.rspi, + id=self.sa.new_msg_id(), + flags="Initiator", + exch_type="INFORMATIONAL", + next_payload="Encrypted", + ) + + msg = self.encrypt_ike_msg(header, b"", None) + return self.create_packet( + self.pg0, msg, self.sa.sport, self.sa.dport, self.sa.natt, self.ip6 + ) + + def create_packet( + self, src_if, msg, sport=500, dport=500, natt=False, use_ip6=False + ): if use_ip6: src_ip = src_if.remote_ip6 dst_ip = src_if.local_ip6 @@ -629,12 +666,14 @@ class IkePeer(VppTestCase): src_ip = src_if.remote_ip4 dst_ip = src_if.local_ip4 ip_layer = IP - res = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - ip_layer(src=src_ip, dst=dst_ip) / - UDP(sport=sport, dport=dport)) + res = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / ip_layer(src=src_ip, dst=dst_ip) + / UDP(sport=sport, dport=dport) + ) if natt: # insert non ESP marker - res = res / Raw(b'\x00' * 4) + res = res / Raw(b"\x00" * 4) return res / msg def verify_udp(self, udp): @@ -651,7 +690,7 @@ class IkePeer(VppTestCase): esp = packet[ESP] ih = self.verify_and_remove_non_esp_marker(esp) self.assertEqual(ih.version, 0x20) - self.assertNotIn('Version', ih.flags) + self.assertNotIn("Version", ih.flags) return ih def verify_and_remove_non_esp_marker(self, packet): @@ -659,26 +698,32 @@ class IkePeer(VppTestCase): # if we are in nat traversal mode check for non esp marker # and remove it data = raw(packet) - self.assertEqual(data[:4], b'\x00' * 4) + self.assertEqual(data[:4], b"\x00" * 4) return ikev2.IKEv2(data[4:]) else: return packet def encrypt_ike_msg(self, header, plain, first_payload): - if self.sa.ike_crypto == 'AES-GCM-16ICV': + if self.sa.ike_crypto == "AES-GCM-16ICV": data = self.sa.ike_crypto_alg.pad(raw(plain)) - plen = len(data) + GCM_IV_SIZE + GCM_ICV_SIZE +\ - len(ikev2.IKEv2_payload_Encrypted()) + plen = ( + len(data) + + GCM_IV_SIZE + + GCM_ICV_SIZE + + len(ikev2.IKEv2_payload_Encrypted()) + ) tlen = plen + len(ikev2.IKEv2()) # prepare aad data - sk_p = ikev2.IKEv2_payload_Encrypted(next_payload=first_payload, - length=plen) + sk_p = ikev2.IKEv2_payload_Encrypted( + next_payload=first_payload, length=plen + ) header.length = tlen res = header / sk_p encr = self.sa.encrypt(raw(plain), raw(res)) - sk_p = ikev2.IKEv2_payload_Encrypted(next_payload=first_payload, - length=plen, load=encr) + sk_p = ikev2.IKEv2_payload_Encrypted( + next_payload=first_payload, length=plen, load=encr + ) res = header / sk_p else: encr = self.sa.encrypt(raw(plain)) @@ -686,16 +731,18 @@ class IkePeer(VppTestCase): plen = len(encr) + len(ikev2.IKEv2_payload_Encrypted()) + trunc_len tlen = plen + len(ikev2.IKEv2()) - sk_p = ikev2.IKEv2_payload_Encrypted(next_payload=first_payload, - length=plen, load=encr) + sk_p = ikev2.IKEv2_payload_Encrypted( + next_payload=first_payload, length=plen, load=encr + ) header.length = tlen res = header / sk_p integ_data = raw(res) - hmac_data = self.sa.compute_hmac(self.sa.ike_integ_alg.mod(), - self.sa.my_authkey, integ_data) + hmac_data = self.sa.compute_hmac( + self.sa.ike_integ_alg.mod(), self.sa.my_authkey, integ_data + ) res = res / Raw(hmac_data[:trunc_len]) - assert(len(res) == tlen) + assert len(res) == tlen return res def verify_udp_encap(self, ipsec_sa): @@ -747,37 +794,37 @@ class IkePeer(VppTestCase): # verify crypto keys self.assertEqual(sa0.crypto_key.length, len(c.sk_er)) self.assertEqual(sa1.crypto_key.length, len(c.sk_ei)) - self.assertEqual(sa0.crypto_key.data[:len(c.sk_er)], c.sk_er) - self.assertEqual(sa1.crypto_key.data[:len(c.sk_ei)], c.sk_ei) + self.assertEqual(sa0.crypto_key.data[: len(c.sk_er)], c.sk_er) + self.assertEqual(sa1.crypto_key.data[: len(c.sk_ei)], c.sk_ei) # verify integ keys if vpp_integ_alg: self.assertEqual(sa0.integrity_key.length, len(c.sk_ar)) self.assertEqual(sa1.integrity_key.length, len(c.sk_ai)) - self.assertEqual(sa0.integrity_key.data[:len(c.sk_ar)], c.sk_ar) - self.assertEqual(sa1.integrity_key.data[:len(c.sk_ai)], c.sk_ai) + self.assertEqual(sa0.integrity_key.data[: len(c.sk_ar)], c.sk_ar) + self.assertEqual(sa1.integrity_key.data[: len(c.sk_ai)], c.sk_ai) else: - self.assertEqual(sa0.salt.to_bytes(4, 'little'), c.salt_er) - self.assertEqual(sa1.salt.to_bytes(4, 'little'), c.salt_ei) + self.assertEqual(sa0.salt.to_bytes(4, "little"), c.salt_er) + self.assertEqual(sa1.salt.to_bytes(4, "little"), c.salt_ei) def verify_keymat(self, api_keys, keys, name): km = getattr(keys, name) api_km = getattr(api_keys, name) - api_km_len = getattr(api_keys, name + '_len') + api_km_len = getattr(api_keys, name + "_len") self.assertEqual(len(km), api_km_len) self.assertEqual(km, api_km[:api_km_len]) def verify_id(self, api_id, exp_id): self.assertEqual(api_id.type, IDType.value(exp_id.type)) self.assertEqual(api_id.data_len, exp_id.data_len) - self.assertEqual(bytes(api_id.data, 'ascii'), exp_id.type) + self.assertEqual(bytes(api_id.data, "ascii"), exp_id.type) def verify_ike_sas(self): r = self.vapi.ikev2_sa_dump() self.assertEqual(len(r), 1) sa = r[0].sa - self.assertEqual(self.sa.ispi, (sa.ispi).to_bytes(8, 'big')) - self.assertEqual(self.sa.rspi, (sa.rspi).to_bytes(8, 'big')) + self.assertEqual(self.sa.ispi, (sa.ispi).to_bytes(8, "big")) + self.assertEqual(self.sa.rspi, (sa.rspi).to_bytes(8, "big")) if self.ip6: if self.sa.is_initiator: self.assertEqual(sa.iaddr, IPv6Address(self.pg0.remote_ip6)) @@ -792,55 +839,53 @@ class IkePeer(VppTestCase): else: self.assertEqual(sa.iaddr, IPv4Address(self.pg0.local_ip4)) self.assertEqual(sa.raddr, IPv4Address(self.pg0.remote_ip4)) - self.verify_keymat(sa.keys, self.sa, 'sk_d') - self.verify_keymat(sa.keys, self.sa, 'sk_ai') - self.verify_keymat(sa.keys, self.sa, 'sk_ar') - self.verify_keymat(sa.keys, self.sa, 'sk_ei') - self.verify_keymat(sa.keys, self.sa, 'sk_er') - self.verify_keymat(sa.keys, self.sa, 'sk_pi') - self.verify_keymat(sa.keys, self.sa, 'sk_pr') + self.verify_keymat(sa.keys, self.sa, "sk_d") + self.verify_keymat(sa.keys, self.sa, "sk_ai") + self.verify_keymat(sa.keys, self.sa, "sk_ar") + self.verify_keymat(sa.keys, self.sa, "sk_ei") + self.verify_keymat(sa.keys, self.sa, "sk_er") + self.verify_keymat(sa.keys, self.sa, "sk_pi") + self.verify_keymat(sa.keys, self.sa, "sk_pr") self.assertEqual(sa.i_id.type, self.sa.id_type) self.assertEqual(sa.r_id.type, self.sa.id_type) self.assertEqual(sa.i_id.data_len, len(self.sa.i_id)) self.assertEqual(sa.r_id.data_len, len(self.idr)) - self.assertEqual(bytes(sa.i_id.data, 'ascii'), self.sa.i_id) - self.assertEqual(bytes(sa.r_id.data, 'ascii'), self.idr) + self.assertEqual(bytes(sa.i_id.data, "ascii"), self.sa.i_id) + self.assertEqual(bytes(sa.r_id.data, "ascii"), self.idr) r = self.vapi.ikev2_child_sa_dump(sa_index=sa.sa_index) self.assertEqual(len(r), 1) csa = r[0].child_sa self.assertEqual(csa.sa_index, sa.sa_index) c = self.sa.child_sas[0] - if hasattr(c, 'sk_ai'): - self.verify_keymat(csa.keys, c, 'sk_ai') - self.verify_keymat(csa.keys, c, 'sk_ar') - self.verify_keymat(csa.keys, c, 'sk_ei') - self.verify_keymat(csa.keys, c, 'sk_er') - self.assertEqual(csa.i_spi.to_bytes(4, 'big'), c.ispi) - self.assertEqual(csa.r_spi.to_bytes(4, 'big'), c.rspi) + if hasattr(c, "sk_ai"): + self.verify_keymat(csa.keys, c, "sk_ai") + self.verify_keymat(csa.keys, c, "sk_ar") + self.verify_keymat(csa.keys, c, "sk_ei") + self.verify_keymat(csa.keys, c, "sk_er") + self.assertEqual(csa.i_spi.to_bytes(4, "big"), c.ispi) + self.assertEqual(csa.r_spi.to_bytes(4, "big"), c.rspi) tsi, tsr = self.sa.generate_ts(self.p.ts_is_ip4) tsi = tsi[0] tsr = tsr[0] r = self.vapi.ikev2_traffic_selector_dump( - is_initiator=True, sa_index=sa.sa_index, - child_sa_index=csa.child_sa_index) + is_initiator=True, sa_index=sa.sa_index, child_sa_index=csa.child_sa_index + ) self.assertEqual(len(r), 1) ts = r[0].ts self.verify_ts(r[0].ts, tsi[0], True) r = self.vapi.ikev2_traffic_selector_dump( - is_initiator=False, sa_index=sa.sa_index, - child_sa_index=csa.child_sa_index) + is_initiator=False, sa_index=sa.sa_index, child_sa_index=csa.child_sa_index + ) self.assertEqual(len(r), 1) self.verify_ts(r[0].ts, tsr[0], False) - n = self.vapi.ikev2_nonce_get(is_initiator=True, - sa_index=sa.sa_index) + n = self.vapi.ikev2_nonce_get(is_initiator=True, sa_index=sa.sa_index) self.verify_nonce(n, self.sa.i_nonce) - n = self.vapi.ikev2_nonce_get(is_initiator=False, - sa_index=sa.sa_index) + n = self.vapi.ikev2_nonce_get(is_initiator=False, sa_index=sa.sa_index) self.verify_nonce(n, self.sa.r_nonce) def verify_nonce(self, api_nonce, nonce): @@ -854,61 +899,65 @@ class IkePeer(VppTestCase): self.assertFalse(api_ts.is_local) if self.p.ts_is_ip4: - self.assertEqual(api_ts.start_addr, - IPv4Address(ts.starting_address_v4)) - self.assertEqual(api_ts.end_addr, - IPv4Address(ts.ending_address_v4)) + self.assertEqual(api_ts.start_addr, IPv4Address(ts.starting_address_v4)) + self.assertEqual(api_ts.end_addr, IPv4Address(ts.ending_address_v4)) else: - self.assertEqual(api_ts.start_addr, - IPv6Address(ts.starting_address_v6)) - self.assertEqual(api_ts.end_addr, - IPv6Address(ts.ending_address_v6)) + self.assertEqual(api_ts.start_addr, IPv6Address(ts.starting_address_v6)) + self.assertEqual(api_ts.end_addr, IPv6Address(ts.ending_address_v6)) self.assertEqual(api_ts.start_port, ts.start_port) self.assertEqual(api_ts.end_port, ts.end_port) self.assertEqual(api_ts.protocol_id, ts.IP_protocol_ID) class TemplateInitiator(IkePeer): - """ initiator test template """ + """initiator test template""" def initiate_del_sa_from_initiator(self): - ispi = int.from_bytes(self.sa.ispi, 'little') + ispi = int.from_bytes(self.sa.ispi, "little") self.pg0.enable_capture() self.pg_start() self.vapi.ikev2_initiate_del_ike_sa(ispi=ispi) capture = self.pg0.get_capture(1) ih = self.get_ike_header(capture[0]) - self.assertNotIn('Response', ih.flags) - self.assertIn('Initiator', ih.flags) + self.assertNotIn("Response", ih.flags) + self.assertIn("Initiator", ih.flags) self.assertEqual(ih.init_SPI, self.sa.ispi) self.assertEqual(ih.resp_SPI, self.sa.rspi) plain = self.sa.hmac_and_decrypt(ih) d = ikev2.IKEv2_payload_Delete(plain) self.assertEqual(d.proto, 1) # proto=IKEv2 - header = ikev2.IKEv2(init_SPI=self.sa.ispi, resp_SPI=self.sa.rspi, - flags='Response', exch_type='INFORMATIONAL', - id=ih.id, next_payload='Encrypted') - resp = self.encrypt_ike_msg(header, b'', None) + header = ikev2.IKEv2( + init_SPI=self.sa.ispi, + resp_SPI=self.sa.rspi, + flags="Response", + exch_type="INFORMATIONAL", + id=ih.id, + next_payload="Encrypted", + ) + resp = self.encrypt_ike_msg(header, b"", None) self.send_and_assert_no_replies(self.pg0, resp) def verify_del_sa(self, packet): ih = self.get_ike_header(packet) self.assertEqual(ih.id, self.sa.msg_id) self.assertEqual(ih.exch_type, 37) # exchange informational - self.assertIn('Response', ih.flags) - self.assertIn('Initiator', ih.flags) + self.assertIn("Response", ih.flags) + self.assertIn("Initiator", ih.flags) plain = self.sa.hmac_and_decrypt(ih) - self.assertEqual(plain, b'') + self.assertEqual(plain, b"") def initiate_del_sa_from_responder(self): - header = ikev2.IKEv2(init_SPI=self.sa.ispi, resp_SPI=self.sa.rspi, - exch_type='INFORMATIONAL', - id=self.sa.new_msg_id()) - del_sa = ikev2.IKEv2_payload_Delete(proto='IKEv2') - ike_msg = self.encrypt_ike_msg(header, del_sa, 'Delete') - packet = self.create_packet(self.pg0, ike_msg, - self.sa.sport, self.sa.dport, - self.sa.natt, self.ip6) + header = ikev2.IKEv2( + init_SPI=self.sa.ispi, + resp_SPI=self.sa.rspi, + exch_type="INFORMATIONAL", + id=self.sa.new_msg_id(), + ) + del_sa = ikev2.IKEv2_payload_Delete(proto="IKEv2") + ike_msg = self.encrypt_ike_msg(header, del_sa, "Delete") + packet = self.create_packet( + self.pg0, ike_msg, self.sa.sport, self.sa.dport, self.sa.natt, self.ip6 + ) self.pg0.add_stream(packet) self.pg0.enable_capture() self.pg_start() @@ -935,26 +984,28 @@ class TemplateInitiator(IkePeer): s = self.find_notify_payload(packet, 16388) self.assertIsNotNone(s) src_sha = self.sa.compute_nat_sha1( - inet_pton(socket.AF_INET, iph.src), udp.sport, b'\x00' * 8) + inet_pton(socket.AF_INET, iph.src), udp.sport, b"\x00" * 8 + ) self.assertEqual(s.load, src_sha) # NAT_DETECTION_DESTINATION_IP s = self.find_notify_payload(packet, 16389) self.assertIsNotNone(s) dst_sha = self.sa.compute_nat_sha1( - inet_pton(socket.AF_INET, iph.dst), udp.dport, b'\x00' * 8) + inet_pton(socket.AF_INET, iph.dst), udp.dport, b"\x00" * 8 + ) self.assertEqual(s.load, dst_sha) def verify_sa_init_request(self, packet): udp = packet[UDP] self.sa.dport = udp.sport ih = packet[ikev2.IKEv2] - self.assertNotEqual(ih.init_SPI, 8 * b'\x00') + self.assertNotEqual(ih.init_SPI, 8 * b"\x00") self.assertEqual(ih.exch_type, 34) # SA_INIT self.sa.ispi = ih.init_SPI - self.assertEqual(ih.resp_SPI, 8 * b'\x00') - self.assertIn('Initiator', ih.flags) - self.assertNotIn('Response', ih.flags) + self.assertEqual(ih.resp_SPI, 8 * b"\x00") + self.assertIn("Initiator", ih.flags) + self.assertNotIn("Response", ih.flags) self.sa.i_nonce = ih[ikev2.IKEv2_payload_Nonce].load self.sa.i_dh_data = ih[ikev2.IKEv2_payload_KE].load @@ -962,20 +1013,23 @@ class TemplateInitiator(IkePeer): self.assertEqual(prop.proto, 1) # proto = ikev2 self.assertEqual(prop.proposal, 1) self.assertEqual(prop.trans[0].transform_type, 1) # encryption - self.assertEqual(prop.trans[0].transform_id, - self.p.ike_transforms['crypto_alg']) + self.assertEqual( + prop.trans[0].transform_id, self.p.ike_transforms["crypto_alg"] + ) self.assertEqual(prop.trans[1].transform_type, 2) # prf self.assertEqual(prop.trans[1].transform_id, 5) # "hmac-sha2-256" self.assertEqual(prop.trans[2].transform_type, 4) # dh - self.assertEqual(prop.trans[2].transform_id, - self.p.ike_transforms['dh_group']) + self.assertEqual(prop.trans[2].transform_id, self.p.ike_transforms["dh_group"]) self.verify_nat_detection(packet) self.sa.set_ike_props( - crypto='AES-GCM-16ICV', crypto_key_len=32, - integ='NULL', prf='PRF_HMAC_SHA2_256', dh='3072MODPgr') - self.sa.set_esp_props(crypto='AES-CBC', crypto_key_len=32, - integ='SHA2-256-128') + crypto="AES-GCM-16ICV", + crypto_key_len=32, + integ="NULL", + prf="PRF_HMAC_SHA2_256", + dh="3072MODPgr", + ) + self.sa.set_esp_props(crypto="AES-CBC", crypto_key_len=32, integ="SHA2-256-128") self.sa.generate_dh_data() self.sa.complete_dh_data() self.sa.calc_keys() @@ -995,8 +1049,8 @@ class TemplateInitiator(IkePeer): self.assertEqual(ih.resp_SPI, self.sa.rspi) self.assertEqual(ih.init_SPI, self.sa.ispi) self.assertEqual(ih.exch_type, 35) # IKE_AUTH - self.assertIn('Initiator', ih.flags) - self.assertNotIn('Response', ih.flags) + self.assertIn("Initiator", ih.flags) + self.assertNotIn("Response", ih.flags) udp = packet[UDP] self.verify_udp(udp) @@ -1013,48 +1067,67 @@ class TemplateInitiator(IkePeer): prop = idi[ikev2.IKEv2_payload_Proposal] c = self.sa.child_sas[0] c.ispi = prop.SPI - self.update_esp_transforms( - prop[ikev2.IKEv2_payload_Transform], self.sa) + self.update_esp_transforms(prop[ikev2.IKEv2_payload_Transform], self.sa) def send_init_response(self): tr_attr = self.sa.ike_crypto_attr() - trans = (ikev2.IKEv2_payload_Transform(transform_type='Encryption', - transform_id=self.sa.ike_crypto, length=tr_attr[1], - key_length=tr_attr[0]) / - ikev2.IKEv2_payload_Transform(transform_type='Integrity', - transform_id=self.sa.ike_integ) / - ikev2.IKEv2_payload_Transform(transform_type='PRF', - transform_id=self.sa.ike_prf_alg.name) / - ikev2.IKEv2_payload_Transform(transform_type='GroupDesc', - transform_id=self.sa.ike_dh)) - props = (ikev2.IKEv2_payload_Proposal(proposal=1, proto='IKEv2', - trans_nb=4, trans=trans)) + trans = ( + ikev2.IKEv2_payload_Transform( + transform_type="Encryption", + transform_id=self.sa.ike_crypto, + length=tr_attr[1], + key_length=tr_attr[0], + ) + / ikev2.IKEv2_payload_Transform( + transform_type="Integrity", transform_id=self.sa.ike_integ + ) + / ikev2.IKEv2_payload_Transform( + transform_type="PRF", transform_id=self.sa.ike_prf_alg.name + ) + / ikev2.IKEv2_payload_Transform( + transform_type="GroupDesc", transform_id=self.sa.ike_dh + ) + ) + props = ikev2.IKEv2_payload_Proposal( + proposal=1, proto="IKEv2", trans_nb=4, trans=trans + ) src_address = inet_pton(socket.AF_INET, self.pg0.remote_ip4) if self.sa.natt: - dst_address = b'\x0a\x0a\x0a\x0a' + dst_address = b"\x0a\x0a\x0a\x0a" else: dst_address = inet_pton(socket.AF_INET, self.pg0.local_ip4) src_nat = self.sa.compute_nat_sha1(src_address, self.sa.sport) dst_nat = self.sa.compute_nat_sha1(dst_address, self.sa.dport) self.sa.init_resp_packet = ( - ikev2.IKEv2(init_SPI=self.sa.ispi, resp_SPI=self.sa.rspi, - exch_type='IKE_SA_INIT', flags='Response') / - ikev2.IKEv2_payload_SA(next_payload='KE', prop=props) / - ikev2.IKEv2_payload_KE(next_payload='Nonce', - group=self.sa.ike_dh, - load=self.sa.my_dh_pub_key) / - ikev2.IKEv2_payload_Nonce(load=self.sa.r_nonce, - next_payload='Notify') / - ikev2.IKEv2_payload_Notify( - type='NAT_DETECTION_SOURCE_IP', load=src_nat, - next_payload='Notify') / ikev2.IKEv2_payload_Notify( - type='NAT_DETECTION_DESTINATION_IP', load=dst_nat)) - - ike_msg = self.create_packet(self.pg0, self.sa.init_resp_packet, - self.sa.sport, self.sa.dport, - False, self.ip6) + ikev2.IKEv2( + init_SPI=self.sa.ispi, + resp_SPI=self.sa.rspi, + exch_type="IKE_SA_INIT", + flags="Response", + ) + / ikev2.IKEv2_payload_SA(next_payload="KE", prop=props) + / ikev2.IKEv2_payload_KE( + next_payload="Nonce", group=self.sa.ike_dh, load=self.sa.my_dh_pub_key + ) + / ikev2.IKEv2_payload_Nonce(load=self.sa.r_nonce, next_payload="Notify") + / ikev2.IKEv2_payload_Notify( + type="NAT_DETECTION_SOURCE_IP", load=src_nat, next_payload="Notify" + ) + / ikev2.IKEv2_payload_Notify( + type="NAT_DETECTION_DESTINATION_IP", load=dst_nat + ) + ) + + ike_msg = self.create_packet( + self.pg0, + self.sa.init_resp_packet, + self.sa.sport, + self.sa.dport, + False, + self.ip6, + ) self.pg_send(self.pg0, ike_msg) capture = self.pg0.get_capture(1) self.verify_sa_auth_req(capture[0]) @@ -1070,47 +1143,64 @@ class TemplateInitiator(IkePeer): def send_auth_response(self): tr_attr = self.sa.esp_crypto_attr() - trans = (ikev2.IKEv2_payload_Transform(transform_type='Encryption', - transform_id=self.sa.esp_crypto, length=tr_attr[1], - key_length=tr_attr[0]) / - ikev2.IKEv2_payload_Transform(transform_type='Integrity', - transform_id=self.sa.esp_integ) / - ikev2.IKEv2_payload_Transform( - transform_type='Extended Sequence Number', - transform_id='No ESN') / - ikev2.IKEv2_payload_Transform( - transform_type='Extended Sequence Number', - transform_id='ESN')) + trans = ( + ikev2.IKEv2_payload_Transform( + transform_type="Encryption", + transform_id=self.sa.esp_crypto, + length=tr_attr[1], + key_length=tr_attr[0], + ) + / ikev2.IKEv2_payload_Transform( + transform_type="Integrity", transform_id=self.sa.esp_integ + ) + / ikev2.IKEv2_payload_Transform( + transform_type="Extended Sequence Number", transform_id="No ESN" + ) + / ikev2.IKEv2_payload_Transform( + transform_type="Extended Sequence Number", transform_id="ESN" + ) + ) c = self.sa.child_sas[0] - props = (ikev2.IKEv2_payload_Proposal(proposal=1, proto='ESP', - SPIsize=4, SPI=c.rspi, trans_nb=4, trans=trans)) + props = ikev2.IKEv2_payload_Proposal( + proposal=1, proto="ESP", SPIsize=4, SPI=c.rspi, trans_nb=4, trans=trans + ) tsi, tsr = self.sa.generate_ts(self.p.ts_is_ip4) - plain = (ikev2.IKEv2_payload_IDi(next_payload='IDr', - IDtype=self.sa.id_type, load=self.sa.i_id) / - ikev2.IKEv2_payload_IDr(next_payload='AUTH', - IDtype=self.sa.id_type, load=self.sa.r_id) / - ikev2.IKEv2_payload_AUTH(next_payload='SA', - auth_type=AuthMethod.value(self.sa.auth_method), - load=self.sa.auth_data) / - ikev2.IKEv2_payload_SA(next_payload='TSi', prop=props) / - ikev2.IKEv2_payload_TSi(next_payload='TSr', - number_of_TSs=len(tsi), - traffic_selector=tsi) / - ikev2.IKEv2_payload_TSr(next_payload='Notify', - number_of_TSs=len(tsr), - traffic_selector=tsr) / - ikev2.IKEv2_payload_Notify(type='INITIAL_CONTACT')) + plain = ( + ikev2.IKEv2_payload_IDi( + next_payload="IDr", IDtype=self.sa.id_type, load=self.sa.i_id + ) + / ikev2.IKEv2_payload_IDr( + next_payload="AUTH", IDtype=self.sa.id_type, load=self.sa.r_id + ) + / ikev2.IKEv2_payload_AUTH( + next_payload="SA", + auth_type=AuthMethod.value(self.sa.auth_method), + load=self.sa.auth_data, + ) + / ikev2.IKEv2_payload_SA(next_payload="TSi", prop=props) + / ikev2.IKEv2_payload_TSi( + next_payload="TSr", number_of_TSs=len(tsi), traffic_selector=tsi + ) + / ikev2.IKEv2_payload_TSr( + next_payload="Notify", number_of_TSs=len(tsr), traffic_selector=tsr + ) + / ikev2.IKEv2_payload_Notify(type="INITIAL_CONTACT") + ) header = ikev2.IKEv2( - init_SPI=self.sa.ispi, - resp_SPI=self.sa.rspi, id=self.sa.new_msg_id(), - flags='Response', exch_type='IKE_AUTH') - - ike_msg = self.encrypt_ike_msg(header, plain, 'IDi') - packet = self.create_packet(self.pg0, ike_msg, self.sa.sport, - self.sa.dport, self.sa.natt, self.ip6) + init_SPI=self.sa.ispi, + resp_SPI=self.sa.rspi, + id=self.sa.new_msg_id(), + flags="Response", + exch_type="IKE_AUTH", + ) + + ike_msg = self.encrypt_ike_msg(header, plain, "IDi") + packet = self.create_packet( + self.pg0, ike_msg, self.sa.sport, self.sa.dport, self.sa.natt, self.ip6 + ) self.pg_send(self.pg0, packet) def test_initiator(self): @@ -1122,51 +1212,58 @@ class TemplateInitiator(IkePeer): class TemplateResponder(IkePeer): - """ responder test template """ + """responder test template""" def initiate_del_sa_from_responder(self): self.pg0.enable_capture() self.pg_start() - self.vapi.ikev2_initiate_del_ike_sa( - ispi=int.from_bytes(self.sa.ispi, 'little')) + self.vapi.ikev2_initiate_del_ike_sa(ispi=int.from_bytes(self.sa.ispi, "little")) capture = self.pg0.get_capture(1) ih = self.get_ike_header(capture[0]) - self.assertNotIn('Response', ih.flags) - self.assertNotIn('Initiator', ih.flags) + self.assertNotIn("Response", ih.flags) + self.assertNotIn("Initiator", ih.flags) self.assertEqual(ih.exch_type, 37) # INFORMATIONAL plain = self.sa.hmac_and_decrypt(ih) d = ikev2.IKEv2_payload_Delete(plain) self.assertEqual(d.proto, 1) # proto=IKEv2 self.assertEqual(ih.init_SPI, self.sa.ispi) self.assertEqual(ih.resp_SPI, self.sa.rspi) - header = ikev2.IKEv2(init_SPI=self.sa.ispi, resp_SPI=self.sa.rspi, - flags='Initiator+Response', - exch_type='INFORMATIONAL', - id=ih.id, next_payload='Encrypted') - resp = self.encrypt_ike_msg(header, b'', None) + header = ikev2.IKEv2( + init_SPI=self.sa.ispi, + resp_SPI=self.sa.rspi, + flags="Initiator+Response", + exch_type="INFORMATIONAL", + id=ih.id, + next_payload="Encrypted", + ) + resp = self.encrypt_ike_msg(header, b"", None) self.send_and_assert_no_replies(self.pg0, resp) def verify_del_sa(self, packet): ih = self.get_ike_header(packet) self.assertEqual(ih.id, self.sa.msg_id) self.assertEqual(ih.exch_type, 37) # exchange informational - self.assertIn('Response', ih.flags) - self.assertNotIn('Initiator', ih.flags) + self.assertIn("Response", ih.flags) + self.assertNotIn("Initiator", ih.flags) self.assertEqual(ih.next_payload, 46) # Encrypted self.assertEqual(ih.init_SPI, self.sa.ispi) self.assertEqual(ih.resp_SPI, self.sa.rspi) plain = self.sa.hmac_and_decrypt(ih) - self.assertEqual(plain, b'') + self.assertEqual(plain, b"") def initiate_del_sa_from_initiator(self): - header = ikev2.IKEv2(init_SPI=self.sa.ispi, resp_SPI=self.sa.rspi, - flags='Initiator', exch_type='INFORMATIONAL', - id=self.sa.new_msg_id()) - del_sa = ikev2.IKEv2_payload_Delete(proto='IKEv2') - ike_msg = self.encrypt_ike_msg(header, del_sa, 'Delete') - packet = self.create_packet(self.pg0, ike_msg, - self.sa.sport, self.sa.dport, - self.sa.natt, self.ip6) + header = ikev2.IKEv2( + init_SPI=self.sa.ispi, + resp_SPI=self.sa.rspi, + flags="Initiator", + exch_type="INFORMATIONAL", + id=self.sa.new_msg_id(), + ) + del_sa = ikev2.IKEv2_payload_Delete(proto="IKEv2") + ike_msg = self.encrypt_ike_msg(header, del_sa, "Delete") + packet = self.create_packet( + self.pg0, ike_msg, self.sa.sport, self.sa.dport, self.sa.natt, self.ip6 + ) self.pg0.add_stream(packet) self.pg0.enable_capture() self.pg_start() @@ -1175,56 +1272,72 @@ class TemplateResponder(IkePeer): def send_sa_init_req(self): tr_attr = self.sa.ike_crypto_attr() - trans = (ikev2.IKEv2_payload_Transform(transform_type='Encryption', - transform_id=self.sa.ike_crypto, length=tr_attr[1], - key_length=tr_attr[0]) / - ikev2.IKEv2_payload_Transform(transform_type='Integrity', - transform_id=self.sa.ike_integ) / - ikev2.IKEv2_payload_Transform(transform_type='PRF', - transform_id=self.sa.ike_prf_alg.name) / - ikev2.IKEv2_payload_Transform(transform_type='GroupDesc', - transform_id=self.sa.ike_dh)) - - props = (ikev2.IKEv2_payload_Proposal(proposal=1, proto='IKEv2', - trans_nb=4, trans=trans)) - - next_payload = None if self.ip6 else 'Notify' + trans = ( + ikev2.IKEv2_payload_Transform( + transform_type="Encryption", + transform_id=self.sa.ike_crypto, + length=tr_attr[1], + key_length=tr_attr[0], + ) + / ikev2.IKEv2_payload_Transform( + transform_type="Integrity", transform_id=self.sa.ike_integ + ) + / ikev2.IKEv2_payload_Transform( + transform_type="PRF", transform_id=self.sa.ike_prf_alg.name + ) + / ikev2.IKEv2_payload_Transform( + transform_type="GroupDesc", transform_id=self.sa.ike_dh + ) + ) + + props = ikev2.IKEv2_payload_Proposal( + proposal=1, proto="IKEv2", trans_nb=4, trans=trans + ) + + next_payload = None if self.ip6 else "Notify" self.sa.init_req_packet = ( - ikev2.IKEv2(init_SPI=self.sa.ispi, - flags='Initiator', exch_type='IKE_SA_INIT') / - ikev2.IKEv2_payload_SA(next_payload='KE', prop=props) / - ikev2.IKEv2_payload_KE(next_payload='Nonce', - group=self.sa.ike_dh, - load=self.sa.my_dh_pub_key) / - ikev2.IKEv2_payload_Nonce(next_payload=next_payload, - load=self.sa.i_nonce)) + ikev2.IKEv2( + init_SPI=self.sa.ispi, flags="Initiator", exch_type="IKE_SA_INIT" + ) + / ikev2.IKEv2_payload_SA(next_payload="KE", prop=props) + / ikev2.IKEv2_payload_KE( + next_payload="Nonce", group=self.sa.ike_dh, load=self.sa.my_dh_pub_key + ) + / ikev2.IKEv2_payload_Nonce(next_payload=next_payload, load=self.sa.i_nonce) + ) if not self.ip6: if self.sa.i_natt: - src_address = b'\x0a\x0a\x0a\x01' + src_address = b"\x0a\x0a\x0a\x01" else: src_address = inet_pton(socket.AF_INET, self.pg0.remote_ip4) if self.sa.r_natt: - dst_address = b'\x0a\x0a\x0a\x0a' + dst_address = b"\x0a\x0a\x0a\x0a" else: dst_address = inet_pton(socket.AF_INET, self.pg0.local_ip4) src_nat = self.sa.compute_nat_sha1(src_address, self.sa.sport) dst_nat = self.sa.compute_nat_sha1(dst_address, self.sa.dport) nat_src_detection = ikev2.IKEv2_payload_Notify( - type='NAT_DETECTION_SOURCE_IP', load=src_nat, - next_payload='Notify') + type="NAT_DETECTION_SOURCE_IP", load=src_nat, next_payload="Notify" + ) nat_dst_detection = ikev2.IKEv2_payload_Notify( - type='NAT_DETECTION_DESTINATION_IP', load=dst_nat) - self.sa.init_req_packet = (self.sa.init_req_packet / - nat_src_detection / - nat_dst_detection) - - ike_msg = self.create_packet(self.pg0, self.sa.init_req_packet, - self.sa.sport, self.sa.dport, - self.sa.natt, self.ip6) + type="NAT_DETECTION_DESTINATION_IP", load=dst_nat + ) + self.sa.init_req_packet = ( + self.sa.init_req_packet / nat_src_detection / nat_dst_detection + ) + + ike_msg = self.create_packet( + self.pg0, + self.sa.init_req_packet, + self.sa.sport, + self.sa.dport, + self.sa.natt, + self.ip6, + ) self.pg0.add_stream(ike_msg) self.pg0.enable_capture() self.pg_start() @@ -1233,65 +1346,83 @@ class TemplateResponder(IkePeer): def generate_auth_payload(self, last_payload=None, is_rekey=False): tr_attr = self.sa.esp_crypto_attr() - last_payload = last_payload or 'Notify' - trans = (ikev2.IKEv2_payload_Transform(transform_type='Encryption', - transform_id=self.sa.esp_crypto, length=tr_attr[1], - key_length=tr_attr[0]) / - ikev2.IKEv2_payload_Transform(transform_type='Integrity', - transform_id=self.sa.esp_integ) / - ikev2.IKEv2_payload_Transform( - transform_type='Extended Sequence Number', - transform_id='No ESN') / - ikev2.IKEv2_payload_Transform( - transform_type='Extended Sequence Number', - transform_id='ESN')) + last_payload = last_payload or "Notify" + trans = ( + ikev2.IKEv2_payload_Transform( + transform_type="Encryption", + transform_id=self.sa.esp_crypto, + length=tr_attr[1], + key_length=tr_attr[0], + ) + / ikev2.IKEv2_payload_Transform( + transform_type="Integrity", transform_id=self.sa.esp_integ + ) + / ikev2.IKEv2_payload_Transform( + transform_type="Extended Sequence Number", transform_id="No ESN" + ) + / ikev2.IKEv2_payload_Transform( + transform_type="Extended Sequence Number", transform_id="ESN" + ) + ) c = self.sa.child_sas[0] - props = (ikev2.IKEv2_payload_Proposal(proposal=1, proto='ESP', - SPIsize=4, SPI=c.ispi, trans_nb=4, trans=trans)) + props = ikev2.IKEv2_payload_Proposal( + proposal=1, proto="ESP", SPIsize=4, SPI=c.ispi, trans_nb=4, trans=trans + ) tsi, tsr = self.sa.generate_ts(self.p.ts_is_ip4) - plain = (ikev2.IKEv2_payload_AUTH(next_payload='SA', - auth_type=AuthMethod.value(self.sa.auth_method), - load=self.sa.auth_data) / - ikev2.IKEv2_payload_SA(next_payload='TSi', prop=props) / - ikev2.IKEv2_payload_TSi(next_payload='TSr', - number_of_TSs=len(tsi), traffic_selector=tsi) / - ikev2.IKEv2_payload_TSr(next_payload=last_payload, - number_of_TSs=len(tsr), traffic_selector=tsr)) + plain = ( + ikev2.IKEv2_payload_AUTH( + next_payload="SA", + auth_type=AuthMethod.value(self.sa.auth_method), + load=self.sa.auth_data, + ) + / ikev2.IKEv2_payload_SA(next_payload="TSi", prop=props) + / ikev2.IKEv2_payload_TSi( + next_payload="TSr", number_of_TSs=len(tsi), traffic_selector=tsi + ) + / ikev2.IKEv2_payload_TSr( + next_payload=last_payload, number_of_TSs=len(tsr), traffic_selector=tsr + ) + ) if is_rekey: - first_payload = 'Nonce' - plain = (ikev2.IKEv2_payload_Nonce(load=self.sa.i_nonce, - next_payload='SA') / plain / - ikev2.IKEv2_payload_Notify(type='REKEY_SA', - proto='ESP', SPI=c.ispi)) + first_payload = "Nonce" + plain = ( + ikev2.IKEv2_payload_Nonce(load=self.sa.i_nonce, next_payload="SA") + / plain + / ikev2.IKEv2_payload_Notify(type="REKEY_SA", proto="ESP", SPI=c.ispi) + ) else: - first_payload = 'IDi' + first_payload = "IDi" if self.no_idr_auth: - ids = ikev2.IKEv2_payload_IDi(next_payload='AUTH', - IDtype=self.sa.id_type, - load=self.sa.i_id) + ids = ikev2.IKEv2_payload_IDi( + next_payload="AUTH", IDtype=self.sa.id_type, load=self.sa.i_id + ) else: - ids = (ikev2.IKEv2_payload_IDi(next_payload='IDr', - IDtype=self.sa.id_type, load=self.sa.i_id) / - ikev2.IKEv2_payload_IDr(next_payload='AUTH', - IDtype=self.sa.id_type, load=self.sa.r_id)) + ids = ikev2.IKEv2_payload_IDi( + next_payload="IDr", IDtype=self.sa.id_type, load=self.sa.i_id + ) / ikev2.IKEv2_payload_IDr( + next_payload="AUTH", IDtype=self.sa.id_type, load=self.sa.r_id + ) plain = ids / plain return plain, first_payload def send_sa_auth(self): - plain, first_payload = self.generate_auth_payload( - last_payload='Notify') - plain = plain / ikev2.IKEv2_payload_Notify(type='INITIAL_CONTACT') + plain, first_payload = self.generate_auth_payload(last_payload="Notify") + plain = plain / ikev2.IKEv2_payload_Notify(type="INITIAL_CONTACT") header = ikev2.IKEv2( - init_SPI=self.sa.ispi, - resp_SPI=self.sa.rspi, id=self.sa.new_msg_id(), - flags='Initiator', exch_type='IKE_AUTH') + init_SPI=self.sa.ispi, + resp_SPI=self.sa.rspi, + id=self.sa.new_msg_id(), + flags="Initiator", + exch_type="IKE_AUTH", + ) ike_msg = self.encrypt_ike_msg(header, plain, first_payload) - packet = self.create_packet(self.pg0, ike_msg, self.sa.sport, - self.sa.dport, self.sa.natt, self.ip6) + packet = self.create_packet( + self.pg0, ike_msg, self.sa.sport, self.sa.dport, self.sa.natt, self.ip6 + ) self.pg0.add_stream(packet) self.pg0.enable_capture() self.pg_start() @@ -1303,7 +1434,7 @@ class TemplateResponder(IkePeer): self.assertEqual(ih.id, self.sa.msg_id) self.assertEqual(ih.exch_type, 34) - self.assertIn('Response', ih.flags) + self.assertIn("Response", ih.flags) self.assertEqual(ih.init_SPI, self.sa.ispi) self.assertNotEqual(ih.resp_SPI, 0) self.sa.rspi = ih.resp_SPI @@ -1331,12 +1462,12 @@ class TemplateResponder(IkePeer): self.sa.child_sas[0].rspi = prop.SPI self.sa.calc_child_keys() - IKE_NODE_SUFFIX = 'ip4' + IKE_NODE_SUFFIX = "ip4" def verify_counters(self): - self.assert_counter(2, 'processed', self.IKE_NODE_SUFFIX) - self.assert_counter(1, 'init_sa_req', self.IKE_NODE_SUFFIX) - self.assert_counter(1, 'ike_auth_req', self.IKE_NODE_SUFFIX) + self.assert_counter(2, "processed", self.IKE_NODE_SUFFIX) + self.assert_counter(1, "init_sa_req", self.IKE_NODE_SUFFIX) + self.assert_counter(1, "ike_auth_req", self.IKE_NODE_SUFFIX) r = self.vapi.ikev2_sa_dump() s = r[0].sa.stats @@ -1356,59 +1487,60 @@ class Ikev2Params(object): ec = VppEnum.vl_api_ipsec_crypto_alg_t ei = VppEnum.vl_api_ipsec_integ_alg_t self.vpp_enums = { - 'AES-CBC-128': ec.IPSEC_API_CRYPTO_ALG_AES_CBC_128, - 'AES-CBC-192': ec.IPSEC_API_CRYPTO_ALG_AES_CBC_192, - 'AES-CBC-256': ec.IPSEC_API_CRYPTO_ALG_AES_CBC_256, - 'AES-GCM-16ICV-128': ec.IPSEC_API_CRYPTO_ALG_AES_GCM_128, - 'AES-GCM-16ICV-192': ec.IPSEC_API_CRYPTO_ALG_AES_GCM_192, - 'AES-GCM-16ICV-256': ec.IPSEC_API_CRYPTO_ALG_AES_GCM_256, - - 'HMAC-SHA1-96': ei.IPSEC_API_INTEG_ALG_SHA1_96, - 'SHA2-256-128': ei.IPSEC_API_INTEG_ALG_SHA_256_128, - 'SHA2-384-192': ei.IPSEC_API_INTEG_ALG_SHA_384_192, - 'SHA2-512-256': ei.IPSEC_API_INTEG_ALG_SHA_512_256} - - dpd_disabled = True if 'dpd_disabled' not in params else\ - params['dpd_disabled'] + "AES-CBC-128": ec.IPSEC_API_CRYPTO_ALG_AES_CBC_128, + "AES-CBC-192": ec.IPSEC_API_CRYPTO_ALG_AES_CBC_192, + "AES-CBC-256": ec.IPSEC_API_CRYPTO_ALG_AES_CBC_256, + "AES-GCM-16ICV-128": ec.IPSEC_API_CRYPTO_ALG_AES_GCM_128, + "AES-GCM-16ICV-192": ec.IPSEC_API_CRYPTO_ALG_AES_GCM_192, + "AES-GCM-16ICV-256": ec.IPSEC_API_CRYPTO_ALG_AES_GCM_256, + "HMAC-SHA1-96": ei.IPSEC_API_INTEG_ALG_SHA1_96, + "SHA2-256-128": ei.IPSEC_API_INTEG_ALG_SHA_256_128, + "SHA2-384-192": ei.IPSEC_API_INTEG_ALG_SHA_384_192, + "SHA2-512-256": ei.IPSEC_API_INTEG_ALG_SHA_512_256, + } + + dpd_disabled = True if "dpd_disabled" not in params else params["dpd_disabled"] if dpd_disabled: - self.vapi.cli('ikev2 dpd disable') - self.del_sa_from_responder = False if 'del_sa_from_responder'\ - not in params else params['del_sa_from_responder'] - i_natt = False if 'i_natt' not in params else params['i_natt'] - r_natt = False if 'r_natt' not in params else params['r_natt'] - self.p = Profile(self, 'pr1') - self.ip6 = False if 'ip6' not in params else params['ip6'] - - if 'auth' in params and params['auth'] == 'rsa-sig': - auth_method = 'rsa-sig' + self.vapi.cli("ikev2 dpd disable") + self.del_sa_from_responder = ( + False + if "del_sa_from_responder" not in params + else params["del_sa_from_responder"] + ) + i_natt = False if "i_natt" not in params else params["i_natt"] + r_natt = False if "r_natt" not in params else params["r_natt"] + self.p = Profile(self, "pr1") + self.ip6 = False if "ip6" not in params else params["ip6"] + + if "auth" in params and params["auth"] == "rsa-sig": + auth_method = "rsa-sig" work_dir = f"{config.vpp_ws_dir}/src/plugins/ikev2/test/certs/" - self.vapi.ikev2_set_local_key( - key_file=work_dir + params['server-key']) - - client_file = work_dir + params['client-cert'] - server_pem = open(work_dir + params['server-cert']).read() - client_priv = open(work_dir + params['client-key']).read() - client_priv = load_pem_private_key(str.encode(client_priv), None, - default_backend()) + self.vapi.ikev2_set_local_key(key_file=work_dir + params["server-key"]) + + client_file = work_dir + params["client-cert"] + server_pem = open(work_dir + params["server-cert"]).read() + client_priv = open(work_dir + params["client-key"]).read() + client_priv = load_pem_private_key( + str.encode(client_priv), None, default_backend() + ) self.peer_cert = x509.load_pem_x509_certificate( - str.encode(server_pem), - default_backend()) - self.p.add_auth(method='rsa-sig', data=str.encode(client_file)) + str.encode(server_pem), default_backend() + ) + self.p.add_auth(method="rsa-sig", data=str.encode(client_file)) auth_data = None else: - auth_data = b'$3cr3tpa$$w0rd' - self.p.add_auth(method='shared-key', data=auth_data) - auth_method = 'shared-key' + auth_data = b"$3cr3tpa$$w0rd" + self.p.add_auth(method="shared-key", data=auth_data) + auth_method = "shared-key" client_priv = None - is_init = True if 'is_initiator' not in params else\ - params['is_initiator'] - self.no_idr_auth = params.get('no_idr_in_auth', False) + is_init = True if "is_initiator" not in params else params["is_initiator"] + self.no_idr_auth = params.get("no_idr_in_auth", False) - idr = {'id_type': 'fqdn', 'data': b'vpp.home'} - idi = {'id_type': 'fqdn', 'data': b'roadwarrior.example.com'} - r_id = self.idr = idr['data'] - i_id = self.idi = idi['data'] + idr = {"id_type": "fqdn", "data": b"vpp.home"} + idi = {"id_type": "fqdn", "data": b"roadwarrior.example.com"} + r_id = self.idr = idr["data"] + i_id = self.idi = idi["data"] if is_init: # scapy is initiator, VPP is responder self.p.add_local_id(**idr) @@ -1421,70 +1553,90 @@ class Ikev2Params(object): if not self.no_idr_auth: self.p.add_remote_id(**idr) - loc_ts = {'start_addr': '10.10.10.0', 'end_addr': '10.10.10.255'} if\ - 'loc_ts' not in params else params['loc_ts'] - rem_ts = {'start_addr': '10.0.0.0', 'end_addr': '10.0.0.255'} if\ - 'rem_ts' not in params else params['rem_ts'] + loc_ts = ( + {"start_addr": "10.10.10.0", "end_addr": "10.10.10.255"} + if "loc_ts" not in params + else params["loc_ts"] + ) + rem_ts = ( + {"start_addr": "10.0.0.0", "end_addr": "10.0.0.255"} + if "rem_ts" not in params + else params["rem_ts"] + ) self.p.add_local_ts(**loc_ts) self.p.add_remote_ts(**rem_ts) - if 'responder' in params: - self.p.add_responder(params['responder']) - if 'ike_transforms' in params: - self.p.add_ike_transforms(params['ike_transforms']) - if 'esp_transforms' in params: - self.p.add_esp_transforms(params['esp_transforms']) - - udp_encap = False if 'udp_encap' not in params else\ - params['udp_encap'] + if "responder" in params: + self.p.add_responder(params["responder"]) + if "ike_transforms" in params: + self.p.add_ike_transforms(params["ike_transforms"]) + if "esp_transforms" in params: + self.p.add_esp_transforms(params["esp_transforms"]) + + udp_encap = False if "udp_encap" not in params else params["udp_encap"] if udp_encap: self.p.set_udp_encap(True) - if 'responder_hostname' in params: - hn = params['responder_hostname'] + if "responder_hostname" in params: + hn = params["responder_hostname"] self.p.add_responder_hostname(hn) # configure static dns record self.vapi.dns_name_server_add_del( - is_ip6=0, is_add=1, - server_address=IPv4Address(u'8.8.8.8').packed) + is_ip6=0, is_add=1, server_address=IPv4Address("8.8.8.8").packed + ) self.vapi.dns_enable_disable(enable=1) - cmd = "dns cache add {} {}".format(hn['hostname'], - self.pg0.remote_ip4) + cmd = "dns cache add {} {}".format(hn["hostname"], self.pg0.remote_ip4) self.vapi.cli(cmd) - self.sa = IKEv2SA(self, i_id=i_id, r_id=r_id, - is_initiator=is_init, - id_type=self.p.local_id['id_type'], - i_natt=i_natt, r_natt=r_natt, - priv_key=client_priv, auth_method=auth_method, - nonce=params.get('nonce'), - auth_data=auth_data, udp_encap=udp_encap, - local_ts=self.p.remote_ts, remote_ts=self.p.local_ts) + self.sa = IKEv2SA( + self, + i_id=i_id, + r_id=r_id, + is_initiator=is_init, + id_type=self.p.local_id["id_type"], + i_natt=i_natt, + r_natt=r_natt, + priv_key=client_priv, + auth_method=auth_method, + nonce=params.get("nonce"), + auth_data=auth_data, + udp_encap=udp_encap, + local_ts=self.p.remote_ts, + remote_ts=self.p.local_ts, + ) if is_init: - ike_crypto = ('AES-CBC', 32) if 'ike-crypto' not in params else\ - params['ike-crypto'] - ike_integ = 'HMAC-SHA1-96' if 'ike-integ' not in params else\ - params['ike-integ'] - ike_dh = '2048MODPgr' if 'ike-dh' not in params else\ - params['ike-dh'] - - esp_crypto = ('AES-CBC', 32) if 'esp-crypto' not in params else\ - params['esp-crypto'] - esp_integ = 'HMAC-SHA1-96' if 'esp-integ' not in params else\ - params['esp-integ'] + ike_crypto = ( + ("AES-CBC", 32) if "ike-crypto" not in params else params["ike-crypto"] + ) + ike_integ = ( + "HMAC-SHA1-96" if "ike-integ" not in params else params["ike-integ"] + ) + ike_dh = "2048MODPgr" if "ike-dh" not in params else params["ike-dh"] + + esp_crypto = ( + ("AES-CBC", 32) if "esp-crypto" not in params else params["esp-crypto"] + ) + esp_integ = ( + "HMAC-SHA1-96" if "esp-integ" not in params else params["esp-integ"] + ) self.sa.set_ike_props( - crypto=ike_crypto[0], crypto_key_len=ike_crypto[1], - integ=ike_integ, prf='PRF_HMAC_SHA2_256', dh=ike_dh) + crypto=ike_crypto[0], + crypto_key_len=ike_crypto[1], + integ=ike_integ, + prf="PRF_HMAC_SHA2_256", + dh=ike_dh, + ) self.sa.set_esp_props( - crypto=esp_crypto[0], crypto_key_len=esp_crypto[1], - integ=esp_integ) + crypto=esp_crypto[0], crypto_key_len=esp_crypto[1], integ=esp_integ + ) class TestApi(VppTestCase): - """ Test IKEV2 API """ + """Test IKEV2 API""" + @classmethod def setUpClass(cls): super(TestApi, cls).setUpClass() @@ -1501,241 +1653,249 @@ class TestApi(VppTestCase): self.assertEqual(len(r), 0) def configure_profile(self, cfg): - p = Profile(self, cfg['name']) - p.add_local_id(id_type=cfg['loc_id'][0], data=cfg['loc_id'][1]) - p.add_remote_id(id_type=cfg['rem_id'][0], data=cfg['rem_id'][1]) - p.add_local_ts(**cfg['loc_ts']) - p.add_remote_ts(**cfg['rem_ts']) - p.add_responder(cfg['responder']) - p.add_ike_transforms(cfg['ike_ts']) - p.add_esp_transforms(cfg['esp_ts']) - p.add_auth(**cfg['auth']) - p.set_udp_encap(cfg['udp_encap']) - p.set_ipsec_over_udp_port(cfg['ipsec_over_udp_port']) - if 'lifetime_data' in cfg: - p.set_lifetime_data(cfg['lifetime_data']) - if 'tun_itf' in cfg: - p.set_tunnel_interface(cfg['tun_itf']) - if 'natt_disabled' in cfg and cfg['natt_disabled']: + p = Profile(self, cfg["name"]) + p.add_local_id(id_type=cfg["loc_id"][0], data=cfg["loc_id"][1]) + p.add_remote_id(id_type=cfg["rem_id"][0], data=cfg["rem_id"][1]) + p.add_local_ts(**cfg["loc_ts"]) + p.add_remote_ts(**cfg["rem_ts"]) + p.add_responder(cfg["responder"]) + p.add_ike_transforms(cfg["ike_ts"]) + p.add_esp_transforms(cfg["esp_ts"]) + p.add_auth(**cfg["auth"]) + p.set_udp_encap(cfg["udp_encap"]) + p.set_ipsec_over_udp_port(cfg["ipsec_over_udp_port"]) + if "lifetime_data" in cfg: + p.set_lifetime_data(cfg["lifetime_data"]) + if "tun_itf" in cfg: + p.set_tunnel_interface(cfg["tun_itf"]) + if "natt_disabled" in cfg and cfg["natt_disabled"]: p.disable_natt() p.add_vpp_config() return p def test_profile_api(self): - """ test profile dump API """ + """test profile dump API""" loc_ts4 = { - 'proto': 8, - 'start_port': 1, - 'end_port': 19, - 'start_addr': '3.3.3.2', - 'end_addr': '3.3.3.3', - } + "proto": 8, + "start_port": 1, + "end_port": 19, + "start_addr": "3.3.3.2", + "end_addr": "3.3.3.3", + } rem_ts4 = { - 'proto': 9, - 'start_port': 10, - 'end_port': 119, - 'start_addr': '4.5.76.80', - 'end_addr': '2.3.4.6', - } + "proto": 9, + "start_port": 10, + "end_port": 119, + "start_addr": "4.5.76.80", + "end_addr": "2.3.4.6", + } loc_ts6 = { - 'proto': 8, - 'start_port': 1, - 'end_port': 19, - 'start_addr': 'ab::1', - 'end_addr': 'ab::4', - } + "proto": 8, + "start_port": 1, + "end_port": 19, + "start_addr": "ab::1", + "end_addr": "ab::4", + } rem_ts6 = { - 'proto': 9, - 'start_port': 10, - 'end_port': 119, - 'start_addr': 'cd::12', - 'end_addr': 'cd::13', - } + "proto": 9, + "start_port": 10, + "end_port": 119, + "start_addr": "cd::12", + "end_addr": "cd::13", + } conf = { - 'p1': { - 'name': 'p1', - 'natt_disabled': True, - 'loc_id': ('fqdn', b'vpp.home'), - 'rem_id': ('fqdn', b'roadwarrior.example.com'), - 'loc_ts': loc_ts4, - 'rem_ts': rem_ts4, - 'responder': {'sw_if_index': 0, 'addr': '5.6.7.8'}, - 'ike_ts': { - 'crypto_alg': 20, - 'crypto_key_size': 32, - 'integ_alg': 0, - 'dh_group': 1}, - 'esp_ts': { - 'crypto_alg': 13, - 'crypto_key_size': 24, - 'integ_alg': 2}, - 'auth': {'method': 'shared-key', 'data': b'sharedkeydata'}, - 'udp_encap': True, - 'ipsec_over_udp_port': 4501, - 'lifetime_data': { - 'lifetime': 123, - 'lifetime_maxdata': 20192, - 'lifetime_jitter': 9, - 'handover': 132}, + "p1": { + "name": "p1", + "natt_disabled": True, + "loc_id": ("fqdn", b"vpp.home"), + "rem_id": ("fqdn", b"roadwarrior.example.com"), + "loc_ts": loc_ts4, + "rem_ts": rem_ts4, + "responder": {"sw_if_index": 0, "addr": "5.6.7.8"}, + "ike_ts": { + "crypto_alg": 20, + "crypto_key_size": 32, + "integ_alg": 0, + "dh_group": 1, + }, + "esp_ts": {"crypto_alg": 13, "crypto_key_size": 24, "integ_alg": 2}, + "auth": {"method": "shared-key", "data": b"sharedkeydata"}, + "udp_encap": True, + "ipsec_over_udp_port": 4501, + "lifetime_data": { + "lifetime": 123, + "lifetime_maxdata": 20192, + "lifetime_jitter": 9, + "handover": 132, + }, + }, + "p2": { + "name": "p2", + "loc_id": ("ip4-addr", b"192.168.2.1"), + "rem_id": ("ip6-addr", b"abcd::1"), + "loc_ts": loc_ts6, + "rem_ts": rem_ts6, + "responder": {"sw_if_index": 4, "addr": "def::10"}, + "ike_ts": { + "crypto_alg": 12, + "crypto_key_size": 16, + "integ_alg": 3, + "dh_group": 3, + }, + "esp_ts": {"crypto_alg": 9, "crypto_key_size": 24, "integ_alg": 4}, + "auth": {"method": "shared-key", "data": b"sharedkeydata"}, + "udp_encap": False, + "ipsec_over_udp_port": 4600, + "tun_itf": 0, }, - 'p2': { - 'name': 'p2', - 'loc_id': ('ip4-addr', b'192.168.2.1'), - 'rem_id': ('ip6-addr', b'abcd::1'), - 'loc_ts': loc_ts6, - 'rem_ts': rem_ts6, - 'responder': {'sw_if_index': 4, 'addr': 'def::10'}, - 'ike_ts': { - 'crypto_alg': 12, - 'crypto_key_size': 16, - 'integ_alg': 3, - 'dh_group': 3}, - 'esp_ts': { - 'crypto_alg': 9, - 'crypto_key_size': 24, - 'integ_alg': 4}, - 'auth': {'method': 'shared-key', 'data': b'sharedkeydata'}, - 'udp_encap': False, - 'ipsec_over_udp_port': 4600, - 'tun_itf': 0} } - self.p1 = self.configure_profile(conf['p1']) - self.p2 = self.configure_profile(conf['p2']) + self.p1 = self.configure_profile(conf["p1"]) + self.p2 = self.configure_profile(conf["p2"]) r = self.vapi.ikev2_profile_dump() self.assertEqual(len(r), 2) - self.verify_profile(r[0].profile, conf['p1']) - self.verify_profile(r[1].profile, conf['p2']) + self.verify_profile(r[0].profile, conf["p1"]) + self.verify_profile(r[1].profile, conf["p2"]) def verify_id(self, api_id, cfg_id): self.assertEqual(api_id.type, IDType.value(cfg_id[0])) - self.assertEqual(bytes(api_id.data, 'ascii'), cfg_id[1]) + self.assertEqual(bytes(api_id.data, "ascii"), cfg_id[1]) def verify_ts(self, api_ts, cfg_ts): - self.assertEqual(api_ts.protocol_id, cfg_ts['proto']) - self.assertEqual(api_ts.start_port, cfg_ts['start_port']) - self.assertEqual(api_ts.end_port, cfg_ts['end_port']) - self.assertEqual(api_ts.start_addr, - ip_address(text_type(cfg_ts['start_addr']))) - self.assertEqual(api_ts.end_addr, - ip_address(text_type(cfg_ts['end_addr']))) + self.assertEqual(api_ts.protocol_id, cfg_ts["proto"]) + self.assertEqual(api_ts.start_port, cfg_ts["start_port"]) + self.assertEqual(api_ts.end_port, cfg_ts["end_port"]) + self.assertEqual(api_ts.start_addr, ip_address(text_type(cfg_ts["start_addr"]))) + self.assertEqual(api_ts.end_addr, ip_address(text_type(cfg_ts["end_addr"]))) def verify_responder(self, api_r, cfg_r): - self.assertEqual(api_r.sw_if_index, cfg_r['sw_if_index']) - self.assertEqual(api_r.addr, ip_address(cfg_r['addr'])) + self.assertEqual(api_r.sw_if_index, cfg_r["sw_if_index"]) + self.assertEqual(api_r.addr, ip_address(cfg_r["addr"])) def verify_transforms(self, api_ts, cfg_ts): - self.assertEqual(api_ts.crypto_alg, cfg_ts['crypto_alg']) - self.assertEqual(api_ts.crypto_key_size, cfg_ts['crypto_key_size']) - self.assertEqual(api_ts.integ_alg, cfg_ts['integ_alg']) + self.assertEqual(api_ts.crypto_alg, cfg_ts["crypto_alg"]) + self.assertEqual(api_ts.crypto_key_size, cfg_ts["crypto_key_size"]) + self.assertEqual(api_ts.integ_alg, cfg_ts["integ_alg"]) def verify_ike_transforms(self, api_ts, cfg_ts): self.verify_transforms(api_ts, cfg_ts) - self.assertEqual(api_ts.dh_group, cfg_ts['dh_group']) + self.assertEqual(api_ts.dh_group, cfg_ts["dh_group"]) def verify_esp_transforms(self, api_ts, cfg_ts): self.verify_transforms(api_ts, cfg_ts) def verify_auth(self, api_auth, cfg_auth): - self.assertEqual(api_auth.method, AuthMethod.value(cfg_auth['method'])) - self.assertEqual(api_auth.data, cfg_auth['data']) - self.assertEqual(api_auth.data_len, len(cfg_auth['data'])) + self.assertEqual(api_auth.method, AuthMethod.value(cfg_auth["method"])) + self.assertEqual(api_auth.data, cfg_auth["data"]) + self.assertEqual(api_auth.data_len, len(cfg_auth["data"])) def verify_lifetime_data(self, p, ld): - self.assertEqual(p.lifetime, ld['lifetime']) - self.assertEqual(p.lifetime_maxdata, ld['lifetime_maxdata']) - self.assertEqual(p.lifetime_jitter, ld['lifetime_jitter']) - self.assertEqual(p.handover, ld['handover']) + self.assertEqual(p.lifetime, ld["lifetime"]) + self.assertEqual(p.lifetime_maxdata, ld["lifetime_maxdata"]) + self.assertEqual(p.lifetime_jitter, ld["lifetime_jitter"]) + self.assertEqual(p.handover, ld["handover"]) def verify_profile(self, ap, cp): - self.assertEqual(ap.name, cp['name']) - self.assertEqual(ap.udp_encap, cp['udp_encap']) - self.verify_id(ap.loc_id, cp['loc_id']) - self.verify_id(ap.rem_id, cp['rem_id']) - self.verify_ts(ap.loc_ts, cp['loc_ts']) - self.verify_ts(ap.rem_ts, cp['rem_ts']) - self.verify_responder(ap.responder, cp['responder']) - self.verify_ike_transforms(ap.ike_ts, cp['ike_ts']) - self.verify_esp_transforms(ap.esp_ts, cp['esp_ts']) - self.verify_auth(ap.auth, cp['auth']) - natt_dis = False if 'natt_disabled' not in cp else cp['natt_disabled'] + self.assertEqual(ap.name, cp["name"]) + self.assertEqual(ap.udp_encap, cp["udp_encap"]) + self.verify_id(ap.loc_id, cp["loc_id"]) + self.verify_id(ap.rem_id, cp["rem_id"]) + self.verify_ts(ap.loc_ts, cp["loc_ts"]) + self.verify_ts(ap.rem_ts, cp["rem_ts"]) + self.verify_responder(ap.responder, cp["responder"]) + self.verify_ike_transforms(ap.ike_ts, cp["ike_ts"]) + self.verify_esp_transforms(ap.esp_ts, cp["esp_ts"]) + self.verify_auth(ap.auth, cp["auth"]) + natt_dis = False if "natt_disabled" not in cp else cp["natt_disabled"] self.assertTrue(natt_dis == ap.natt_disabled) - if 'lifetime_data' in cp: - self.verify_lifetime_data(ap, cp['lifetime_data']) - self.assertEqual(ap.ipsec_over_udp_port, cp['ipsec_over_udp_port']) - if 'tun_itf' in cp: - self.assertEqual(ap.tun_itf, cp['tun_itf']) + if "lifetime_data" in cp: + self.verify_lifetime_data(ap, cp["lifetime_data"]) + self.assertEqual(ap.ipsec_over_udp_port, cp["ipsec_over_udp_port"]) + if "tun_itf" in cp: + self.assertEqual(ap.tun_itf, cp["tun_itf"]) else: - self.assertEqual(ap.tun_itf, 0xffffffff) + self.assertEqual(ap.tun_itf, 0xFFFFFFFF) @tag_fixme_vpp_workers class TestResponderBehindNAT(TemplateResponder, Ikev2Params): - """ test responder - responder behind NAT """ + """test responder - responder behind NAT""" - IKE_NODE_SUFFIX = 'ip4-natt' + IKE_NODE_SUFFIX = "ip4-natt" def config_tc(self): - self.config_params({'r_natt': True}) + self.config_params({"r_natt": True}) @tag_fixme_vpp_workers class TestInitiatorNATT(TemplateInitiator, Ikev2Params): - """ test ikev2 initiator - NAT traversal (intitiator behind NAT) """ + """test ikev2 initiator - NAT traversal (intitiator behind NAT)""" def config_tc(self): - self.config_params({ - 'i_natt': True, - 'is_initiator': False, # seen from test case perspective - # thus vpp is initiator - 'responder': {'sw_if_index': self.pg0.sw_if_index, - 'addr': self.pg0.remote_ip4}, - 'ike-crypto': ('AES-GCM-16ICV', 32), - 'ike-integ': 'NULL', - 'ike-dh': '3072MODPgr', - 'ike_transforms': { - 'crypto_alg': 20, # "aes-gcm-16" - 'crypto_key_size': 256, - 'dh_group': 15, # "modp-3072" - }, - 'esp_transforms': { - 'crypto_alg': 12, # "aes-cbc" - 'crypto_key_size': 256, - # "hmac-sha2-256-128" - 'integ_alg': 12}}) + self.config_params( + { + "i_natt": True, + "is_initiator": False, # seen from test case perspective + # thus vpp is initiator + "responder": { + "sw_if_index": self.pg0.sw_if_index, + "addr": self.pg0.remote_ip4, + }, + "ike-crypto": ("AES-GCM-16ICV", 32), + "ike-integ": "NULL", + "ike-dh": "3072MODPgr", + "ike_transforms": { + "crypto_alg": 20, # "aes-gcm-16" + "crypto_key_size": 256, + "dh_group": 15, # "modp-3072" + }, + "esp_transforms": { + "crypto_alg": 12, # "aes-cbc" + "crypto_key_size": 256, + # "hmac-sha2-256-128" + "integ_alg": 12, + }, + } + ) @tag_fixme_vpp_workers class TestInitiatorPsk(TemplateInitiator, Ikev2Params): - """ test ikev2 initiator - pre shared key auth """ + """test ikev2 initiator - pre shared key auth""" def config_tc(self): - self.config_params({ - 'is_initiator': False, # seen from test case perspective - # thus vpp is initiator - 'ike-crypto': ('AES-GCM-16ICV', 32), - 'ike-integ': 'NULL', - 'ike-dh': '3072MODPgr', - 'ike_transforms': { - 'crypto_alg': 20, # "aes-gcm-16" - 'crypto_key_size': 256, - 'dh_group': 15, # "modp-3072" - }, - 'esp_transforms': { - 'crypto_alg': 12, # "aes-cbc" - 'crypto_key_size': 256, - # "hmac-sha2-256-128" - 'integ_alg': 12}, - 'responder_hostname': {'hostname': 'vpp.responder.org', - 'sw_if_index': self.pg0.sw_if_index}}) + self.config_params( + { + "is_initiator": False, # seen from test case perspective + # thus vpp is initiator + "ike-crypto": ("AES-GCM-16ICV", 32), + "ike-integ": "NULL", + "ike-dh": "3072MODPgr", + "ike_transforms": { + "crypto_alg": 20, # "aes-gcm-16" + "crypto_key_size": 256, + "dh_group": 15, # "modp-3072" + }, + "esp_transforms": { + "crypto_alg": 12, # "aes-cbc" + "crypto_key_size": 256, + # "hmac-sha2-256-128" + "integ_alg": 12, + }, + "responder_hostname": { + "hostname": "vpp.responder.org", + "sw_if_index": self.pg0.sw_if_index, + }, + } + ) @tag_fixme_vpp_workers class TestInitiatorRequestWindowSize(TestInitiatorPsk): - """ test initiator - request window size (1) """ + """test initiator - request window size (1)""" def rekey_respond(self, req, update_child_sa_data): ih = self.get_ike_header(req) @@ -1749,19 +1909,25 @@ class TestInitiatorRequestWindowSize(TestInitiatorPsk): self.sa.child_sas[0].rspi = prop.SPI self.sa.calc_child_keys() - header = ikev2.IKEv2(init_SPI=self.sa.ispi, resp_SPI=self.sa.rspi, - flags='Response', exch_type=36, - id=ih.id, next_payload='Encrypted') - resp = self.encrypt_ike_msg(header, sa, 'SA') - packet = self.create_packet(self.pg0, resp, self.sa.sport, - self.sa.dport, self.sa.natt, self.ip6) + header = ikev2.IKEv2( + init_SPI=self.sa.ispi, + resp_SPI=self.sa.rspi, + flags="Response", + exch_type=36, + id=ih.id, + next_payload="Encrypted", + ) + resp = self.encrypt_ike_msg(header, sa, "SA") + packet = self.create_packet( + self.pg0, resp, self.sa.sport, self.sa.dport, self.sa.natt, self.ip6 + ) self.send_and_assert_no_replies(self.pg0, packet) def test_initiator(self): super(TestInitiatorRequestWindowSize, self).test_initiator() self.pg0.enable_capture() self.pg_start() - ispi = int.from_bytes(self.sa.child_sas[0].ispi, 'little') + ispi = int.from_bytes(self.sa.child_sas[0].ispi, "little") self.vapi.ikev2_initiate_rekey_child_sa(ispi=ispi) self.vapi.ikev2_initiate_rekey_child_sa(ispi=ispi) capture = self.pg0.get_capture(2) @@ -1777,18 +1943,18 @@ class TestInitiatorRequestWindowSize(TestInitiatorPsk): @tag_fixme_vpp_workers class TestInitiatorRekey(TestInitiatorPsk): - """ test ikev2 initiator - rekey """ + """test ikev2 initiator - rekey""" def rekey_from_initiator(self): - ispi = int.from_bytes(self.sa.child_sas[0].ispi, 'little') + ispi = int.from_bytes(self.sa.child_sas[0].ispi, "little") self.pg0.enable_capture() self.pg_start() self.vapi.ikev2_initiate_rekey_child_sa(ispi=ispi) capture = self.pg0.get_capture(1) ih = self.get_ike_header(capture[0]) self.assertEqual(ih.exch_type, 36) # CHILD_SA - self.assertNotIn('Response', ih.flags) - self.assertIn('Initiator', ih.flags) + self.assertNotIn("Response", ih.flags) + self.assertIn("Initiator", ih.flags) plain = self.sa.hmac_and_decrypt(ih) sa = ikev2.IKEv2_payload_SA(plain) prop = sa[ikev2.IKEv2_payload_Proposal] @@ -1798,12 +1964,18 @@ class TestInitiatorRekey(TestInitiatorPsk): self.sa.child_sas[0].ispi = prop.SPI self.sa.child_sas[0].rspi = prop.SPI self.sa.calc_child_keys() - header = ikev2.IKEv2(init_SPI=self.sa.ispi, resp_SPI=self.sa.rspi, - flags='Response', exch_type=36, - id=ih.id, next_payload='Encrypted') - resp = self.encrypt_ike_msg(header, sa, 'SA') - packet = self.create_packet(self.pg0, resp, self.sa.sport, - self.sa.dport, self.sa.natt, self.ip6) + header = ikev2.IKEv2( + init_SPI=self.sa.ispi, + resp_SPI=self.sa.rspi, + flags="Response", + exch_type=36, + id=ih.id, + next_payload="Encrypted", + ) + resp = self.encrypt_ike_msg(header, sa, "SA") + packet = self.create_packet( + self.pg0, resp, self.sa.sport, self.sa.dport, self.sa.natt, self.ip6 + ) self.send_and_assert_no_replies(self.pg0, packet) def test_initiator(self): @@ -1815,45 +1987,51 @@ class TestInitiatorRekey(TestInitiatorPsk): @tag_fixme_vpp_workers class TestInitiatorDelSAFromResponder(TemplateInitiator, Ikev2Params): - """ test ikev2 initiator - delete IKE SA from responder """ + """test ikev2 initiator - delete IKE SA from responder""" def config_tc(self): - self.config_params({ - 'del_sa_from_responder': True, - 'is_initiator': False, # seen from test case perspective - # thus vpp is initiator - 'responder': {'sw_if_index': self.pg0.sw_if_index, - 'addr': self.pg0.remote_ip4}, - 'ike-crypto': ('AES-GCM-16ICV', 32), - 'ike-integ': 'NULL', - 'ike-dh': '3072MODPgr', - 'ike_transforms': { - 'crypto_alg': 20, # "aes-gcm-16" - 'crypto_key_size': 256, - 'dh_group': 15, # "modp-3072" - }, - 'esp_transforms': { - 'crypto_alg': 12, # "aes-cbc" - 'crypto_key_size': 256, - # "hmac-sha2-256-128" - 'integ_alg': 12}, - 'no_idr_in_auth': True}) + self.config_params( + { + "del_sa_from_responder": True, + "is_initiator": False, # seen from test case perspective + # thus vpp is initiator + "responder": { + "sw_if_index": self.pg0.sw_if_index, + "addr": self.pg0.remote_ip4, + }, + "ike-crypto": ("AES-GCM-16ICV", 32), + "ike-integ": "NULL", + "ike-dh": "3072MODPgr", + "ike_transforms": { + "crypto_alg": 20, # "aes-gcm-16" + "crypto_key_size": 256, + "dh_group": 15, # "modp-3072" + }, + "esp_transforms": { + "crypto_alg": 12, # "aes-cbc" + "crypto_key_size": 256, + # "hmac-sha2-256-128" + "integ_alg": 12, + }, + "no_idr_in_auth": True, + } + ) @tag_fixme_vpp_workers class TestResponderInitBehindNATT(TemplateResponder, Ikev2Params): - """ test ikev2 responder - initiator behind NAT """ + """test ikev2 responder - initiator behind NAT""" - IKE_NODE_SUFFIX = 'ip4-natt' + IKE_NODE_SUFFIX = "ip4-natt" def config_tc(self): - self.config_params( - {'i_natt': True}) + self.config_params({"i_natt": True}) @tag_fixme_vpp_workers class TestResponderPsk(TemplateResponder, Ikev2Params): - """ test ikev2 responder - pre shared key auth """ + """test ikev2 responder - pre shared key auth""" + def config_tc(self): self.config_params() @@ -1863,8 +2041,9 @@ class TestResponderDpd(TestResponderPsk): """ Dead peer detection test """ + def config_tc(self): - self.config_params({'dpd_disabled': False}) + self.config_params({"dpd_disabled": False}) def tearDown(self): pass @@ -1879,7 +2058,7 @@ class TestResponderDpd(TestResponderPsk): ih = self.get_ike_header(capture[0]) self.assertEqual(ih.exch_type, 37) # INFORMATIONAL plain = self.sa.hmac_and_decrypt(ih) - self.assertEqual(plain, b'') + self.assertEqual(plain, b"") # wait for SA expiration time.sleep(3) ike_sas = self.vapi.ikev2_sa_dump() @@ -1890,7 +2069,7 @@ class TestResponderDpd(TestResponderPsk): @tag_fixme_vpp_workers class TestResponderRekey(TestResponderPsk): - """ test ikev2 responder - rekey """ + """test ikev2 responder - rekey""" def rekey_from_initiator(self): packet = self.create_rekey_request() @@ -1912,18 +2091,19 @@ class TestResponderRekey(TestResponderPsk): self.sa.calc_child_keys() self.verify_ike_sas() self.verify_ipsec_sas(is_rekey=True) - self.assert_counter(1, 'rekey_req', 'ip4') + self.assert_counter(1, "rekey_req", "ip4") r = self.vapi.ikev2_sa_dump() self.assertEqual(r[0].sa.stats.n_rekey_req, 1) class TestResponderVrf(TestResponderPsk, Ikev2Params): - """ test ikev2 responder - non-default table id """ + """test ikev2 responder - non-default table id""" @classmethod def setUpClass(cls): import scapy.contrib.ikev2 as _ikev2 - globals()['ikev2'] = _ikev2 + + globals()["ikev2"] = _ikev2 super(IkePeer, cls).setUpClass() cls.create_pg_interfaces(range(1)) cls.vapi.cli("ip table add 1") @@ -1936,7 +2116,7 @@ class TestResponderVrf(TestResponderPsk, Ikev2Params): i.resolve_ndp() def config_tc(self): - self.config_params({'dpd_disabled': False}) + self.config_params({"dpd_disabled": False}) def test_responder(self): self.vapi.ikev2_profile_set_liveness(period=2, max_retries=1) @@ -1947,53 +2127,67 @@ class TestResponderVrf(TestResponderPsk, Ikev2Params): ih = self.get_ike_header(capture[0]) self.assertEqual(ih.exch_type, 37) # INFORMATIONAL plain = self.sa.hmac_and_decrypt(ih) - self.assertEqual(plain, b'') + self.assertEqual(plain, b"") @tag_fixme_vpp_workers class TestResponderRsaSign(TemplateResponder, Ikev2Params): - """ test ikev2 responder - cert based auth """ + """test ikev2 responder - cert based auth""" + def config_tc(self): - self.config_params({ - 'udp_encap': True, - 'auth': 'rsa-sig', - 'server-key': 'server-key.pem', - 'client-key': 'client-key.pem', - 'client-cert': 'client-cert.pem', - 'server-cert': 'server-cert.pem'}) + self.config_params( + { + "udp_encap": True, + "auth": "rsa-sig", + "server-key": "server-key.pem", + "client-key": "client-key.pem", + "client-cert": "client-cert.pem", + "server-cert": "server-cert.pem", + } + ) @tag_fixme_vpp_workers -class Test_IKE_AES_CBC_128_SHA256_128_MODP2048_ESP_AES_CBC_192_SHA_384_192\ - (TemplateResponder, Ikev2Params): +class Test_IKE_AES_CBC_128_SHA256_128_MODP2048_ESP_AES_CBC_192_SHA_384_192( + TemplateResponder, Ikev2Params +): """ IKE:AES_CBC_128_SHA256_128,DH=modp2048 ESP:AES_CBC_192_SHA_384_192 """ + def config_tc(self): - self.config_params({ - 'ike-crypto': ('AES-CBC', 16), - 'ike-integ': 'SHA2-256-128', - 'esp-crypto': ('AES-CBC', 24), - 'esp-integ': 'SHA2-384-192', - 'ike-dh': '2048MODPgr', - 'nonce': os.urandom(256), - 'no_idr_in_auth': True}) + self.config_params( + { + "ike-crypto": ("AES-CBC", 16), + "ike-integ": "SHA2-256-128", + "esp-crypto": ("AES-CBC", 24), + "esp-integ": "SHA2-384-192", + "ike-dh": "2048MODPgr", + "nonce": os.urandom(256), + "no_idr_in_auth": True, + } + ) @tag_fixme_vpp_workers -class TestAES_CBC_128_SHA256_128_MODP3072_ESP_AES_GCM_16\ - (TemplateResponder, Ikev2Params): +class TestAES_CBC_128_SHA256_128_MODP3072_ESP_AES_GCM_16( + TemplateResponder, Ikev2Params +): """ IKE:AES_CBC_128_SHA256_128,DH=modp3072 ESP:AES_GCM_16 """ + def config_tc(self): - self.config_params({ - 'ike-crypto': ('AES-CBC', 32), - 'ike-integ': 'SHA2-256-128', - 'esp-crypto': ('AES-GCM-16ICV', 32), - 'esp-integ': 'NULL', - 'ike-dh': '3072MODPgr'}) + self.config_params( + { + "ike-crypto": ("AES-CBC", 32), + "ike-integ": "SHA2-256-128", + "esp-crypto": ("AES-GCM-16ICV", 32), + "esp-integ": "NULL", + "ike-dh": "3072MODPgr", + } + ) @tag_fixme_vpp_workers @@ -2002,20 +2196,21 @@ class Test_IKE_AES_GCM_16_256(TemplateResponder, Ikev2Params): IKE:AES_GCM_16_256 """ - IKE_NODE_SUFFIX = 'ip6' + IKE_NODE_SUFFIX = "ip6" def config_tc(self): - self.config_params({ - 'del_sa_from_responder': True, - 'ip6': True, - 'natt': True, - 'ike-crypto': ('AES-GCM-16ICV', 32), - 'ike-integ': 'NULL', - 'ike-dh': '2048MODPgr', - 'loc_ts': {'start_addr': 'ab:cd::0', - 'end_addr': 'ab:cd::10'}, - 'rem_ts': {'start_addr': '11::0', - 'end_addr': '11::100'}}) + self.config_params( + { + "del_sa_from_responder": True, + "ip6": True, + "natt": True, + "ike-crypto": ("AES-GCM-16ICV", 32), + "ike-integ": "NULL", + "ike-dh": "2048MODPgr", + "loc_ts": {"start_addr": "ab:cd::0", "end_addr": "ab:cd::10"}, + "rem_ts": {"start_addr": "11::0", "end_addr": "11::100"}, + } + ) @tag_fixme_vpp_workers @@ -2033,8 +2228,8 @@ class TestInitiatorKeepaliveMsg(TestInitiatorPsk): ih = self.get_ike_header(capture[0]) self.assertEqual(ih.id, self.sa.msg_id) plain = self.sa.hmac_and_decrypt(ih) - self.assertEqual(plain, b'') - self.assert_counter(1, 'keepalive', 'ip4') + self.assertEqual(plain, b"") + self.assert_counter(1, "keepalive", "ip4") r = self.vapi.ikev2_sa_dump() self.assertEqual(1, r[0].sa.stats.n_keepalives) @@ -2044,7 +2239,7 @@ class TestInitiatorKeepaliveMsg(TestInitiatorPsk): class TestMalformedMessages(TemplateResponder, Ikev2Params): - """ malformed packet test """ + """malformed packet test""" def tearDown(self): pass @@ -2053,23 +2248,26 @@ class TestMalformedMessages(TemplateResponder, Ikev2Params): self.config_params() def create_ike_init_msg(self, length=None, payload=None): - msg = ikev2.IKEv2(length=length, init_SPI='\x11' * 8, - flags='Initiator', exch_type='IKE_SA_INIT') + msg = ikev2.IKEv2( + length=length, + init_SPI="\x11" * 8, + flags="Initiator", + exch_type="IKE_SA_INIT", + ) if payload is not None: msg /= payload - return self.create_packet(self.pg0, msg, self.sa.sport, - self.sa.dport) + return self.create_packet(self.pg0, msg, self.sa.sport, self.sa.dport) def verify_bad_packet_length(self): - ike_msg = self.create_ike_init_msg(length=0xdead) + ike_msg = self.create_ike_init_msg(length=0xDEAD) self.send_and_assert_no_replies(self.pg0, ike_msg * self.pkt_count) - self.assert_counter(self.pkt_count, 'bad_length') + self.assert_counter(self.pkt_count, "bad_length") def verify_bad_sa_payload_length(self): - p = ikev2.IKEv2_payload_SA(length=0xdead) + p = ikev2.IKEv2_payload_SA(length=0xDEAD) ike_msg = self.create_ike_init_msg(payload=p) self.send_and_assert_no_replies(self.pg0, ike_msg * self.pkt_count) - self.assert_counter(self.pkt_count, 'malformed_packet') + self.assert_counter(self.pkt_count, "malformed_packet") def test_responder(self): self.pkt_count = 254 @@ -2077,5 +2275,5 @@ class TestMalformedMessages(TemplateResponder, Ikev2Params): self.verify_bad_sa_payload_length() -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_interface_crud.py b/test/test_interface_crud.py index 2f08f33c704..c79999b5bc5 100644 --- a/test/test_interface_crud.py +++ b/test/test_interface_crud.py @@ -20,9 +20,7 @@ from framework import VppTestCase, VppTestRunner class TestLoopbackInterfaceCRUD(VppTestCase): - """CRUD Loopback - - """ + """CRUD Loopback""" @classmethod def setUpClass(cls): @@ -51,9 +49,11 @@ class TestLoopbackInterfaceCRUD(VppTestCase): """ pkts = [] for i in dst_ifs: - p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - IP(src=src_if.remote_ip4, dst=i.local_ip4) / - ICMP(id=i.sw_if_index, type='echo-request')) + p = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / IP(src=src_if.remote_ip4, dst=i.local_ip4) + / ICMP(id=i.sw_if_index, type="echo-request") + ) pkts.append(p) return pkts @@ -88,15 +88,17 @@ class TestLoopbackInterfaceCRUD(VppTestCase): i.config_ip4().admin_up() # read (check sw if dump, ip4 fib, ip6 fib) - if_dump = self.vapi.sw_interface_dump(name_filter_valid=True, - name_filter='loop') + if_dump = self.vapi.sw_interface_dump( + name_filter_valid=True, name_filter="loop" + ) fib4_dump = self.vapi.ip_route_dump(0) for i in loopbacks: self.assertTrue(i.is_interface_config_in_dump(if_dump)) self.assertTrue(i.is_ip4_entry_in_fib_dump(fib4_dump)) - if_dump = self.vapi.sw_interface_dump(name_filter_valid=True, - name_filter='loopXYZ') + if_dump = self.vapi.sw_interface_dump( + name_filter_valid=True, name_filter="loopXYZ" + ) self.assertEqual(len(if_dump), 0) # check ping @@ -160,31 +162,29 @@ class TestInterfaceDumpApiLocalOnly(VppTestCase): self.assertEqual(rv[0].sw_if_index, 0) def test_sw_if_index_twiddle0(self): - rv = self.vapi.sw_interface_dump(sw_if_index=0xffffffff) + rv = self.vapi.sw_interface_dump(sw_if_index=0xFFFFFFFF) self.assertEqual(rv[0].sw_if_index, 0) def test_sw_if_index_1_not_existing(self): rv = self.vapi.sw_interface_dump(sw_if_index=1) - self.assertEqual(len(rv), 0, 'expected no records.') + self.assertEqual(len(rv), 0, "expected no records.") class TestInterfaceDumpApi(VppTestCase): """test_interface_crud.TestInterfaceDumpApi""" def test_sw_if_index_1(self): - self.vapi.create_loopback_instance(is_specified=1, - user_instance=10) - self.vapi.create_loopback_instance(is_specified=1, - user_instance=5) + self.vapi.create_loopback_instance(is_specified=1, user_instance=10) + self.vapi.create_loopback_instance(is_specified=1, user_instance=5) # Can I get back the specified record? rv = self.vapi.sw_interface_dump(sw_if_index=1) self.assertEqual(rv[0].sw_if_index, 1, rv) # verify 3 interfaces - rv = self.vapi.sw_interface_dump(sw_if_index=0xffffffff) - self.assertEqual(len(rv), 3, 'Expected 3 interfaces.') + rv = self.vapi.sw_interface_dump(sw_if_index=0xFFFFFFFF) + self.assertEqual(len(rv), 3, "Expected 3 interfaces.") -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_ip4.py b/test/test_ip4.py index 3a48274691a..9079e54366a 100644 --- a/test/test_ip4.py +++ b/test/test_ip4.py @@ -15,10 +15,20 @@ from six import moves from framework import tag_fixme_vpp_workers from framework import VppTestCase, VppTestRunner from util import ppp -from vpp_ip_route import VppIpRoute, VppRoutePath, VppIpMRoute, \ - VppMRoutePath, VppMplsIpBind, \ - VppMplsTable, VppIpTable, FibPathType, find_route, \ - VppIpInterfaceAddress, find_route_in_dump, find_mroute_in_dump +from vpp_ip_route import ( + VppIpRoute, + VppRoutePath, + VppIpMRoute, + VppMRoutePath, + VppMplsIpBind, + VppMplsTable, + VppIpTable, + FibPathType, + find_route, + VppIpInterfaceAddress, + find_route_in_dump, + find_mroute_in_dump, +) from vpp_ip import VppIpPuntPolicer, VppIpPuntRedirect, VppIpPathMtu from vpp_sub_interface import VppSubInterface, VppDot1QSubint, VppDot1ADSubint from vpp_papi import vpp_papi, VppEnum @@ -30,7 +40,7 @@ NUM_PKTS = 67 class TestIPv4(VppTestCase): - """ IPv4 Test Case """ + """IPv4 Test Case""" @classmethod def setUpClass(cls): @@ -66,7 +76,8 @@ class TestIPv4(VppTestCase): # create 2 subinterfaces for pg1 and pg2 self.sub_interfaces = [ VppDot1QSubint(self, self.pg1, 100), - VppDot1ADSubint(self, self.pg2, 200, 300, 400)] + VppDot1ADSubint(self, self.pg2, 200, 300, 400), + ] # packet flows mapping pg0 -> pg1.sub, pg2.sub, etc. self.flows = dict() @@ -108,7 +119,7 @@ class TestIPv4(VppTestCase): dst_if = self.flows[src_if][dst_if_idx] info = self.create_packet_info(src_if, dst_if) payload = self.info_to_payload(info) - p = pkt/Raw(payload) + p = pkt / Raw(payload) p[IP].dst = dst_if.remote_ip4 info.data = p.copy() if isinstance(src_if, VppSubInterface): @@ -123,17 +134,26 @@ class TestIPv4(VppTestCase): :param VppInterface src_if: Interface to create packet stream for. """ hdr_ext = 4 if isinstance(src_if, VppSubInterface) else 0 - pkt_tmpl = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - IP(src=src_if.remote_ip4) / - UDP(sport=1234, dport=1234)) - - pkts = [self.modify_packet(src_if, i, pkt_tmpl) - for i in moves.range(self.pg_if_packet_sizes[0], - self.pg_if_packet_sizes[1], 10)] - pkts_b = [self.modify_packet(src_if, i, pkt_tmpl) - for i in moves.range(self.pg_if_packet_sizes[1] + hdr_ext, - self.pg_if_packet_sizes[2] + hdr_ext, - 50)] + pkt_tmpl = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / IP(src=src_if.remote_ip4) + / UDP(sport=1234, dport=1234) + ) + + pkts = [ + self.modify_packet(src_if, i, pkt_tmpl) + for i in moves.range( + self.pg_if_packet_sizes[0], self.pg_if_packet_sizes[1], 10 + ) + ] + pkts_b = [ + self.modify_packet(src_if, i, pkt_tmpl) + for i in moves.range( + self.pg_if_packet_sizes[1] + hdr_ext, + self.pg_if_packet_sizes[2] + hdr_ext, + 50, + ) + ] pkts.extend(pkts_b) return pkts @@ -151,7 +171,7 @@ class TestIPv4(VppTestCase): last_info[i.sw_if_index] = None is_sub_if = False dst_sw_if_index = dst_if.sw_if_index - if hasattr(dst_if, 'parent'): + if hasattr(dst_if, "parent"): is_sub_if = True for packet in capture: if is_sub_if: @@ -165,11 +185,12 @@ class TestIPv4(VppTestCase): packet_index = payload_info.index self.assertEqual(payload_info.dst, dst_sw_if_index) self.logger.debug( - "Got packet on port %s: src=%u (id=%u)" % - (dst_if.name, payload_info.src, packet_index)) + "Got packet on port %s: src=%u (id=%u)" + % (dst_if.name, payload_info.src, packet_index) + ) next_info = self.get_next_packet_info_for_interface2( - payload_info.src, dst_sw_if_index, - last_info[payload_info.src]) + payload_info.src, dst_sw_if_index, last_info[payload_info.src] + ) last_info[payload_info.src] = next_info self.assertTrue(next_info is not None) self.assertEqual(packet_index, next_info.index) @@ -184,13 +205,16 @@ class TestIPv4(VppTestCase): raise for i in self.interfaces: remaining_packet = self.get_next_packet_info_for_interface2( - i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index]) - self.assertTrue(remaining_packet is None, - "Interface %s: Packet expected from interface %s " - "didn't arrive" % (dst_if.name, i.name)) + i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index] + ) + self.assertTrue( + remaining_packet is None, + "Interface %s: Packet expected from interface %s " + "didn't arrive" % (dst_if.name, i.name), + ) def test_fib(self): - """ IPv4 FIB test + """IPv4 FIB test Test scenario: @@ -218,16 +242,19 @@ class TestIPv4(VppTestCase): class TestIPv4RouteLookup(VppTestCase): - """ IPv4 Route Lookup Test Case """ + """IPv4 Route Lookup Test Case""" + routes = [] def route_lookup(self, prefix, exact): - return self.vapi.api(self.vapi.papi.ip_route_lookup, - { - 'table_id': 0, - 'exact': exact, - 'prefix': prefix, - }) + return self.vapi.api( + self.vapi.papi.ip_route_lookup, + { + "table_id": 0, + "exact": exact, + "prefix": prefix, + }, + ) @classmethod def setUpClass(cls): @@ -240,8 +267,9 @@ class TestIPv4RouteLookup(VppTestCase): def setUp(self): super(TestIPv4RouteLookup, self).setUp() - drop_nh = VppRoutePath("127.0.0.1", 0xffffffff, - type=FibPathType.FIB_PATH_TYPE_DROP) + drop_nh = VppRoutePath( + "127.0.0.1", 0xFFFFFFFF, type=FibPathType.FIB_PATH_TYPE_DROP + ) # Add 3 routes r = VppIpRoute(self, "1.1.0.0", 16, [drop_nh]) @@ -267,12 +295,12 @@ class TestIPv4RouteLookup(VppTestCase): # Verify we find the host route prefix = "1.1.1.1/32" result = self.route_lookup(prefix, True) - assert (prefix == str(result.route.prefix)) + assert prefix == str(result.route.prefix) # Verify we find a middle prefix route prefix = "1.1.1.0/24" result = self.route_lookup(prefix, True) - assert (prefix == str(result.route.prefix)) + assert prefix == str(result.route.prefix) # Verify we do not find an available LPM. with self.vapi.assert_negative_api_retval(): @@ -282,17 +310,17 @@ class TestIPv4RouteLookup(VppTestCase): # verify we find lpm lpm_prefix = "1.1.1.0/24" result = self.route_lookup("1.1.1.2/32", False) - assert (lpm_prefix == str(result.route.prefix)) + assert lpm_prefix == str(result.route.prefix) # Verify we find the exact when not requested result = self.route_lookup(lpm_prefix, False) - assert (lpm_prefix == str(result.route.prefix)) + assert lpm_prefix == str(result.route.prefix) # Can't seem to delete the default route so no negative LPM test. class TestIPv4IfAddrRoute(VppTestCase): - """ IPv4 Interface Addr Route Test Case """ + """IPv4 Interface Addr Route Test Case""" @classmethod def setUpClass(cls): @@ -320,7 +348,7 @@ class TestIPv4IfAddrRoute(VppTestCase): i.admin_down() def test_ipv4_ifaddrs_same_prefix(self): - """ IPv4 Interface Addresses Same Prefix test + """IPv4 Interface Addresses Same Prefix test Test scenario: @@ -370,7 +398,7 @@ class TestIPv4IfAddrRoute(VppTestCase): self.assertFalse(find_route(self, "10.10.10.0", 32)) def test_ipv4_ifaddr_route(self): - """ IPv4 Interface Address Route test + """IPv4 Interface Address Route test Test scenario: @@ -415,7 +443,7 @@ class TestIPv4IfAddrRoute(VppTestCase): self.assertTrue(lo_if.is_ip4_entry_in_fib_dump(fib4_dump)) def test_ipv4_ifaddr_del(self): - """ Delete an interface address that does not exist """ + """Delete an interface address that does not exist""" loopbacks = self.create_loopback_interfaces(1) lo = self.lo_interfaces[0] @@ -428,13 +456,12 @@ class TestIPv4IfAddrRoute(VppTestCase): # with self.vapi.assert_negative_api_retval(): self.vapi.sw_interface_add_del_address( - sw_if_index=lo.sw_if_index, - prefix=self.pg0.local_ip4_prefix, - is_add=0) + sw_if_index=lo.sw_if_index, prefix=self.pg0.local_ip4_prefix, is_add=0 + ) class TestICMPEcho(VppTestCase): - """ ICMP Echo Test Case """ + """ICMP Echo Test Case""" @classmethod def setUpClass(cls): @@ -462,7 +489,7 @@ class TestICMPEcho(VppTestCase): i.admin_down() def test_icmp_echo(self): - """ VPP replies to ICMP Echo Request + """VPP replies to ICMP Echo Request Test scenario: @@ -470,14 +497,15 @@ class TestICMPEcho(VppTestCase): - Check outgoing ICMP Echo Reply message on pg0 interface. """ - icmp_id = 0xb + icmp_id = 0xB icmp_seq = 5 - icmp_load = b'\x0a' * 18 - p_echo_request = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / - ICMP(id=icmp_id, seq=icmp_seq) / - Raw(load=icmp_load)) + icmp_load = b"\x0a" * 18 + p_echo_request = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / ICMP(id=icmp_id, seq=icmp_seq) + / Raw(load=icmp_load) + ) self.pg0.add_stream(p_echo_request) self.pg_enable_capture(self.pg_interfaces) @@ -502,7 +530,7 @@ class TestICMPEcho(VppTestCase): class TestIPv4FibCrud(VppTestCase): - """ FIB - add/update/delete - ip4 routes + """FIB - add/update/delete - ip4 routes Test scenario: - add 1k, @@ -513,8 +541,7 @@ class TestIPv4FibCrud(VppTestCase): ..note:: Python API is too slow to add many routes, needs replacement. """ - def config_fib_many_to_one(self, start_dest_addr, next_hop_addr, - count, start=0): + def config_fib_many_to_one(self, start_dest_addr, next_hop_addr, count, start=0): """ :param start_dest_addr: @@ -524,19 +551,26 @@ class TestIPv4FibCrud(VppTestCase): """ routes = [] for i in range(count): - r = VppIpRoute(self, start_dest_addr % (i + start), 32, - [VppRoutePath(next_hop_addr, 0xffffffff)]) + r = VppIpRoute( + self, + start_dest_addr % (i + start), + 32, + [VppRoutePath(next_hop_addr, 0xFFFFFFFF)], + ) r.add_vpp_config() routes.append(r) return routes - def unconfig_fib_many_to_one(self, start_dest_addr, next_hop_addr, - count, start=0): + def unconfig_fib_many_to_one(self, start_dest_addr, next_hop_addr, count, start=0): routes = [] for i in range(count): - r = VppIpRoute(self, start_dest_addr % (i + start), 32, - [VppRoutePath(next_hop_addr, 0xffffffff)]) + r = VppIpRoute( + self, + start_dest_addr % (i + start), + 32, + [VppRoutePath(next_hop_addr, 0xFFFFFFFF)], + ) r.remove_vpp_config() routes.append(r) return routes @@ -548,10 +582,12 @@ class TestIPv4FibCrud(VppTestCase): dst_addr = random.choice(routes).prefix.network_address info = self.create_packet_info(src_if, dst_if) payload = self.info_to_payload(info) - p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - IP(src=src_if.remote_ip4, dst=str(dst_addr)) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / IP(src=src_if.remote_ip4, dst=str(dst_addr)) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) info.data = p.copy() self.extend_packet(p, random.choice(self.pg_if_packet_sizes)) pkts.append(p) @@ -560,8 +596,7 @@ class TestIPv4FibCrud(VppTestCase): def _find_ip_match(self, find_in, pkt): for p in find_in: - if self.payload_to_info(p[Raw]) == \ - self.payload_to_info(pkt[Raw]): + if self.payload_to_info(p[Raw]) == self.payload_to_info(pkt[Raw]): if p[IP].src != pkt[IP].src: break if p[IP].dst != pkt[IP].dst: @@ -585,15 +620,15 @@ class TestIPv4FibCrud(VppTestCase): def verify_route_dump(self, routes): for r in routes: - self.assertTrue(find_route(self, - r.prefix.network_address, - r.prefix.prefixlen)) + self.assertTrue( + find_route(self, r.prefix.network_address, r.prefix.prefixlen) + ) def verify_not_in_route_dump(self, routes): for r in routes: - self.assertFalse(find_route(self, - r.prefix.network_address, - r.prefix.prefixlen)) + self.assertFalse( + find_route(self, r.prefix.network_address, r.prefix.prefixlen) + ) @classmethod def setUpClass(cls): @@ -636,18 +671,21 @@ class TestIPv4FibCrud(VppTestCase): self.deleted_routes = [] def test_1_add_routes(self): - """ Add 1k routes """ + """Add 1k routes""" # add 100 routes check with traffic script. - self.configured_routes.extend(self.config_fib_many_to_one( - "10.0.0.%d", self.pg0.remote_ip4, 100)) + self.configured_routes.extend( + self.config_fib_many_to_one("10.0.0.%d", self.pg0.remote_ip4, 100) + ) self.verify_route_dump(self.configured_routes) self.stream_1 = self.create_stream( - self.pg1, self.pg0, self.configured_routes, 100) + self.pg1, self.pg0, self.configured_routes, 100 + ) self.stream_2 = self.create_stream( - self.pg2, self.pg0, self.configured_routes, 100) + self.pg2, self.pg0, self.configured_routes, 100 + ) self.pg1.add_stream(self.stream_1) self.pg2.add_stream(self.stream_2) @@ -658,28 +696,32 @@ class TestIPv4FibCrud(VppTestCase): self.verify_capture(self.pg0, pkts, self.stream_1 + self.stream_2) def test_2_del_routes(self): - """ Delete 100 routes + """Delete 100 routes - delete 10 routes check with traffic script. """ # config 1M FIB entries - self.configured_routes.extend(self.config_fib_many_to_one( - "10.0.0.%d", self.pg0.remote_ip4, 100)) - self.deleted_routes.extend(self.unconfig_fib_many_to_one( - "10.0.0.%d", self.pg0.remote_ip4, 10, start=10)) + self.configured_routes.extend( + self.config_fib_many_to_one("10.0.0.%d", self.pg0.remote_ip4, 100) + ) + self.deleted_routes.extend( + self.unconfig_fib_many_to_one( + "10.0.0.%d", self.pg0.remote_ip4, 10, start=10 + ) + ) for x in self.deleted_routes: self.configured_routes.remove(x) self.verify_route_dump(self.configured_routes) self.stream_1 = self.create_stream( - self.pg1, self.pg0, self.configured_routes, 100) + self.pg1, self.pg0, self.configured_routes, 100 + ) self.stream_2 = self.create_stream( - self.pg2, self.pg0, self.configured_routes, 100) - self.stream_3 = self.create_stream( - self.pg1, self.pg0, self.deleted_routes, 100) - self.stream_4 = self.create_stream( - self.pg2, self.pg0, self.deleted_routes, 100) + self.pg2, self.pg0, self.configured_routes, 100 + ) + self.stream_3 = self.create_stream(self.pg1, self.pg0, self.deleted_routes, 100) + self.stream_4 = self.create_stream(self.pg2, self.pg0, self.deleted_routes, 100) self.pg1.add_stream(self.stream_1 + self.stream_3) self.pg2.add_stream(self.stream_2 + self.stream_4) self.pg_enable_capture(self.pg_interfaces) @@ -689,38 +731,42 @@ class TestIPv4FibCrud(VppTestCase): self.verify_capture(self.pg0, pkts, self.stream_1 + self.stream_2) def test_3_add_new_routes(self): - """ Add 1k routes + """Add 1k routes - re-add 5 routes check with traffic script. - add 100 routes check with traffic script. """ # config 1M FIB entries - self.configured_routes.extend(self.config_fib_many_to_one( - "10.0.0.%d", self.pg0.remote_ip4, 100)) - self.deleted_routes.extend(self.unconfig_fib_many_to_one( - "10.0.0.%d", self.pg0.remote_ip4, 10, start=10)) + self.configured_routes.extend( + self.config_fib_many_to_one("10.0.0.%d", self.pg0.remote_ip4, 100) + ) + self.deleted_routes.extend( + self.unconfig_fib_many_to_one( + "10.0.0.%d", self.pg0.remote_ip4, 10, start=10 + ) + ) for x in self.deleted_routes: self.configured_routes.remove(x) - tmp = self.config_fib_many_to_one( - "10.0.0.%d", self.pg0.remote_ip4, 5, start=10) + tmp = self.config_fib_many_to_one("10.0.0.%d", self.pg0.remote_ip4, 5, start=10) self.configured_routes.extend(tmp) for x in tmp: self.deleted_routes.remove(x) - self.configured_routes.extend(self.config_fib_many_to_one( - "10.0.1.%d", self.pg0.remote_ip4, 100)) + self.configured_routes.extend( + self.config_fib_many_to_one("10.0.1.%d", self.pg0.remote_ip4, 100) + ) self.verify_route_dump(self.configured_routes) self.stream_1 = self.create_stream( - self.pg1, self.pg0, self.configured_routes, 300) + self.pg1, self.pg0, self.configured_routes, 300 + ) self.stream_2 = self.create_stream( - self.pg2, self.pg0, self.configured_routes, 300) - self.stream_3 = self.create_stream( - self.pg1, self.pg0, self.deleted_routes, 100) - self.stream_4 = self.create_stream( - self.pg2, self.pg0, self.deleted_routes, 100) + self.pg2, self.pg0, self.configured_routes, 300 + ) + self.stream_3 = self.create_stream(self.pg1, self.pg0, self.deleted_routes, 100) + self.stream_4 = self.create_stream(self.pg2, self.pg0, self.deleted_routes, 100) self.pg1.add_stream(self.stream_1 + self.stream_3) self.pg2.add_stream(self.stream_2 + self.stream_4) @@ -732,17 +778,20 @@ class TestIPv4FibCrud(VppTestCase): # delete 5 routes check with traffic script. # add 100 routes check with traffic script. - self.deleted_routes.extend(self.unconfig_fib_many_to_one( - "10.0.0.%d", self.pg0.remote_ip4, 15)) - self.deleted_routes.extend(self.unconfig_fib_many_to_one( - "10.0.0.%d", self.pg0.remote_ip4, 85)) - self.deleted_routes.extend(self.unconfig_fib_many_to_one( - "10.0.1.%d", self.pg0.remote_ip4, 100)) + self.deleted_routes.extend( + self.unconfig_fib_many_to_one("10.0.0.%d", self.pg0.remote_ip4, 15) + ) + self.deleted_routes.extend( + self.unconfig_fib_many_to_one("10.0.0.%d", self.pg0.remote_ip4, 85) + ) + self.deleted_routes.extend( + self.unconfig_fib_many_to_one("10.0.1.%d", self.pg0.remote_ip4, 100) + ) self.verify_not_in_route_dump(self.deleted_routes) class TestIPNull(VppTestCase): - """ IPv4 routes via NULL """ + """IPv4 routes via NULL""" @classmethod def setUpClass(cls): @@ -770,23 +819,29 @@ class TestIPNull(VppTestCase): i.admin_down() def test_ip_null(self): - """ IP NULL route """ + """IP NULL route""" # # A route via IP NULL that will reply with ICMP unreachables # ip_unreach = VppIpRoute( - self, "10.0.0.1", 32, - [VppRoutePath("0.0.0.0", - 0xffffffff, - type=FibPathType.FIB_PATH_TYPE_ICMP_UNREACH)]) + self, + "10.0.0.1", + 32, + [ + VppRoutePath( + "0.0.0.0", 0xFFFFFFFF, type=FibPathType.FIB_PATH_TYPE_ICMP_UNREACH + ) + ], + ) ip_unreach.add_vpp_config() - p_unreach = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst="10.0.0.1") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p_unreach = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst="10.0.0.1") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) self.pg0.add_stream(p_unreach) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -809,17 +864,23 @@ class TestIPNull(VppTestCase): # A route via IP NULL that will reply with ICMP prohibited # ip_prohibit = VppIpRoute( - self, "10.0.0.2", 32, - [VppRoutePath("0.0.0.0", - 0xffffffff, - type=FibPathType.FIB_PATH_TYPE_ICMP_PROHIBIT)]) + self, + "10.0.0.2", + 32, + [ + VppRoutePath( + "0.0.0.0", 0xFFFFFFFF, type=FibPathType.FIB_PATH_TYPE_ICMP_PROHIBIT + ) + ], + ) ip_prohibit.add_vpp_config() - p_prohibit = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst="10.0.0.2") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p_prohibit = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst="10.0.0.2") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) self.pg0.add_stream(p_prohibit) self.pg_enable_capture(self.pg_interfaces) @@ -836,17 +897,21 @@ class TestIPNull(VppTestCase): self.assertEqual(icmp.dst, "10.0.0.2") def test_ip_drop(self): - """ IP Drop Routes """ + """IP Drop Routes""" - p = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst="1.1.1.1") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst="1.1.1.1") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) - r1 = VppIpRoute(self, "1.1.1.0", 24, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index)]) + r1 = VppIpRoute( + self, + "1.1.1.0", + 24, + [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)], + ) r1.add_vpp_config() rx = self.send_and_expect(self.pg0, p * NUM_PKTS, self.pg1) @@ -854,10 +919,12 @@ class TestIPNull(VppTestCase): # # insert a more specific as a drop # - r2 = VppIpRoute(self, "1.1.1.1", 32, - [VppRoutePath("0.0.0.0", - 0xffffffff, - type=FibPathType.FIB_PATH_TYPE_DROP)]) + r2 = VppIpRoute( + self, + "1.1.1.1", + 32, + [VppRoutePath("0.0.0.0", 0xFFFFFFFF, type=FibPathType.FIB_PATH_TYPE_DROP)], + ) r2.add_vpp_config() self.send_and_assert_no_replies(self.pg0, p * NUM_PKTS, "Drop Route") @@ -866,7 +933,7 @@ class TestIPNull(VppTestCase): class TestIPDisabled(VppTestCase): - """ IPv4 disabled """ + """IPv4 disabled""" @classmethod def setUpClass(cls): @@ -897,7 +964,7 @@ class TestIPDisabled(VppTestCase): i.admin_down() def test_ip_disabled(self): - """ IP Disabled """ + """IP Disabled""" MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t @@ -909,24 +976,32 @@ class TestIPDisabled(VppTestCase): route_232_1_1_1 = VppIpMRoute( self, "0.0.0.0", - "232.1.1.1", 32, + "232.1.1.1", + 32, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - [VppMRoutePath(self.pg1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT), - VppMRoutePath(self.pg0.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)]) + [ + VppMRoutePath( + self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT + ), + VppMRoutePath( + self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ), + ], + ) route_232_1_1_1.add_vpp_config() - pu = (Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) / - IP(src="10.10.10.10", dst=self.pg0.remote_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - pm = (Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) / - IP(src="10.10.10.10", dst="232.1.1.1") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + pu = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src="10.10.10.10", dst=self.pg0.remote_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + pm = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src="10.10.10.10", dst="232.1.1.1") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) # # PG1 does not forward IP traffic @@ -965,7 +1040,7 @@ class TestIPDisabled(VppTestCase): class TestIPSubNets(VppTestCase): - """ IPv4 Subnets """ + """IPv4 Subnets""" @classmethod def setUpClass(cls): @@ -995,22 +1070,26 @@ class TestIPSubNets(VppTestCase): i.admin_down() def test_ip_sub_nets(self): - """ IP Sub Nets """ + """IP Sub Nets""" # # Configure a covering route to forward so we know # when we are dropping # - cover_route = VppIpRoute(self, "10.0.0.0", 8, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index)]) + cover_route = VppIpRoute( + self, + "10.0.0.0", + 8, + [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)], + ) cover_route.add_vpp_config() - p = (Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) / - IP(dst="10.10.10.10", src=self.pg0.local_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(dst="10.10.10.10", src=self.pg0.local_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) @@ -1023,28 +1102,29 @@ class TestIPSubNets(VppTestCase): ip_addr_n = socket.inet_pton(socket.AF_INET, "10.10.10.10") self.vapi.sw_interface_add_del_address( - sw_if_index=self.pg0.sw_if_index, - prefix="10.10.10.10/16") - - pn = (Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) / - IP(dst="10.10.0.0", src=self.pg0.local_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - pb = (Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) / - IP(dst="10.10.255.255", src=self.pg0.local_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + sw_if_index=self.pg0.sw_if_index, prefix="10.10.10.10/16" + ) + + pn = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(dst="10.10.0.0", src=self.pg0.local_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + pb = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(dst="10.10.255.255", src=self.pg0.local_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) self.send_and_assert_no_replies(self.pg1, pn, "IP Network address") self.send_and_assert_no_replies(self.pg1, pb, "IP Broadcast address") # remove the sub-net and we are forwarding via the cover again self.vapi.sw_interface_add_del_address( - sw_if_index=self.pg0.sw_if_index, - prefix="10.10.10.10/16", - is_add=0) + sw_if_index=self.pg0.sw_if_index, prefix="10.10.10.10/16", is_add=0 + ) self.pg1.add_stream(pn) self.pg_enable_capture(self.pg_interfaces) @@ -1062,14 +1142,15 @@ class TestIPSubNets(VppTestCase): ip_addr_n = socket.inet_pton(socket.AF_INET, "10.10.10.10") self.vapi.sw_interface_add_del_address( - sw_if_index=self.pg0.sw_if_index, - prefix="10.10.10.10/31") + sw_if_index=self.pg0.sw_if_index, prefix="10.10.10.10/31" + ) - pn = (Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) / - IP(dst="10.10.10.11", src=self.pg0.local_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + pn = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(dst="10.10.10.11", src=self.pg0.local_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) self.pg1.add_stream(pn) self.pg_enable_capture(self.pg_interfaces) @@ -1079,8 +1160,8 @@ class TestIPSubNets(VppTestCase): # remove the sub-net and we are forwarding via the cover again self.vapi.sw_interface_add_del_address( - sw_if_index=self.pg0.sw_if_index, - prefix="10.10.10.10/31", is_add=0) + sw_if_index=self.pg0.sw_if_index, prefix="10.10.10.10/31", is_add=0 + ) self.pg1.add_stream(pn) self.pg_enable_capture(self.pg_interfaces) @@ -1089,7 +1170,7 @@ class TestIPSubNets(VppTestCase): class TestIPLoadBalance(VppTestCase): - """ IPv4 Load-Balancing """ + """IPv4 Load-Balancing""" @classmethod def setUpClass(cls): @@ -1126,7 +1207,7 @@ class TestIPLoadBalance(VppTestCase): return n def test_ip_load_balance(self): - """ IP Load-Balancing """ + """IP Load-Balancing""" fhc = VppEnum.vl_api_ip_flow_hash_config_t af = VppEnum.vl_api_address_family_t @@ -1144,33 +1225,47 @@ class TestIPLoadBalance(VppTestCase): src_mpls_pkts = [] for ii in range(NUM_PKTS): - port_ip_hdr = (IP(dst="10.0.0.1", src="20.0.0.1") / - UDP(sport=1234, dport=1234 + ii) / - Raw(b'\xa5' * 100)) - port_ip_pkts.append((Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - port_ip_hdr)) - port_mpls_pkts.append((Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - MPLS(label=66, ttl=2) / - port_ip_hdr)) - - src_ip_hdr = (IP(dst="10.0.0.1", src="20.0.0.%d" % ii) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - src_ip_pkts.append((Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - src_ip_hdr)) - src_mpls_pkts.append((Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - MPLS(label=66, ttl=2) / - src_ip_hdr)) - - route_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index), - VppRoutePath(self.pg2.remote_ip4, - self.pg2.sw_if_index)]) + port_ip_hdr = ( + IP(dst="10.0.0.1", src="20.0.0.1") + / UDP(sport=1234, dport=1234 + ii) + / Raw(b"\xa5" * 100) + ) + port_ip_pkts.append( + (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / port_ip_hdr) + ) + port_mpls_pkts.append( + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / MPLS(label=66, ttl=2) + / port_ip_hdr + ) + ) + + src_ip_hdr = ( + IP(dst="10.0.0.1", src="20.0.0.%d" % ii) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + src_ip_pkts.append( + (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / src_ip_hdr) + ) + src_mpls_pkts.append( + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / MPLS(label=66, ttl=2) + / src_ip_hdr + ) + ) + + route_10_0_0_1 = VppIpRoute( + self, + "10.0.0.1", + 32, + [ + VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index), + VppRoutePath(self.pg2.remote_ip4, self.pg2.sw_if_index), + ], + ) route_10_0_0_1.add_vpp_config() binding = VppMplsIpBind(self, 66, "10.0.0.1", 32) @@ -1185,15 +1280,17 @@ class TestIPLoadBalance(VppTestCase): # be guaranteed. But with 64 different packets we do expect some # balancing. So instead just ensure there is traffic on each link. # - rx = self.send_and_expect_load_balancing(self.pg0, port_ip_pkts, - [self.pg1, self.pg2]) + rx = self.send_and_expect_load_balancing( + self.pg0, port_ip_pkts, [self.pg1, self.pg2] + ) n_ip_pg0 = len(rx[0]) - self.send_and_expect_load_balancing(self.pg0, src_ip_pkts, - [self.pg1, self.pg2]) - self.send_and_expect_load_balancing(self.pg0, port_mpls_pkts, - [self.pg1, self.pg2]) - rx = self.send_and_expect_load_balancing(self.pg0, src_mpls_pkts, - [self.pg1, self.pg2]) + self.send_and_expect_load_balancing(self.pg0, src_ip_pkts, [self.pg1, self.pg2]) + self.send_and_expect_load_balancing( + self.pg0, port_mpls_pkts, [self.pg1, self.pg2] + ) + rx = self.send_and_expect_load_balancing( + self.pg0, src_mpls_pkts, [self.pg1, self.pg2] + ) n_mpls_pg0 = len(rx[0]) # @@ -1201,12 +1298,14 @@ class TestIPLoadBalance(VppTestCase): # self.vapi.set_ip_flow_hash_router_id(router_id=0x11111111) - rx = self.send_and_expect_load_balancing(self.pg0, port_ip_pkts, - [self.pg1, self.pg2]) + rx = self.send_and_expect_load_balancing( + self.pg0, port_ip_pkts, [self.pg1, self.pg2] + ) self.assertNotEqual(n_ip_pg0, len(rx[0])) - rx = self.send_and_expect_load_balancing(self.pg0, src_mpls_pkts, - [self.pg1, self.pg2]) + rx = self.send_and_expect_load_balancing( + self.pg0, src_mpls_pkts, [self.pg1, self.pg2] + ) self.assertNotEqual(n_mpls_pg0, len(rx[0])) # @@ -1217,22 +1316,24 @@ class TestIPLoadBalance(VppTestCase): self.vapi.set_ip_flow_hash_v2( af=af.ADDRESS_IP4, table_id=0, - flow_hash_config=(fhc.IP_API_FLOW_HASH_SRC_IP | - fhc.IP_API_FLOW_HASH_DST_IP | - fhc.IP_API_FLOW_HASH_PROTO)) - - self.send_and_expect_load_balancing(self.pg0, src_ip_pkts, - [self.pg1, self.pg2]) - self.send_and_expect_load_balancing(self.pg0, src_mpls_pkts, - [self.pg1, self.pg2]) + flow_hash_config=( + fhc.IP_API_FLOW_HASH_SRC_IP + | fhc.IP_API_FLOW_HASH_DST_IP + | fhc.IP_API_FLOW_HASH_PROTO + ), + ) + + self.send_and_expect_load_balancing(self.pg0, src_ip_pkts, [self.pg1, self.pg2]) + self.send_and_expect_load_balancing( + self.pg0, src_mpls_pkts, [self.pg1, self.pg2] + ) self.send_and_expect_only(self.pg0, port_ip_pkts, self.pg2) # # change the flow hash config back to defaults # - self.vapi.set_ip_flow_hash(vrf_id=0, src=1, dst=1, - proto=1, sport=1, dport=1) + self.vapi.set_ip_flow_hash(vrf_id=0, src=1, dst=1, proto=1, sport=1, dport=1) # # Recursive prefixes @@ -1243,48 +1344,64 @@ class TestIPLoadBalance(VppTestCase): src_pkts = [] for ii in range(257): - port_pkts.append((Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(dst="1.1.1.1", src="20.0.0.1") / - UDP(sport=1234, dport=1234 + ii) / - Raw(b'\xa5' * 100))) - src_pkts.append((Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(dst="1.1.1.1", src="20.0.0.%d" % ii) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100))) - - route_10_0_0_2 = VppIpRoute(self, "10.0.0.2", 32, - [VppRoutePath(self.pg3.remote_ip4, - self.pg3.sw_if_index), - VppRoutePath(self.pg4.remote_ip4, - self.pg4.sw_if_index)]) + port_pkts.append( + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(dst="1.1.1.1", src="20.0.0.1") + / UDP(sport=1234, dport=1234 + ii) + / Raw(b"\xa5" * 100) + ) + ) + src_pkts.append( + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(dst="1.1.1.1", src="20.0.0.%d" % ii) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + ) + + route_10_0_0_2 = VppIpRoute( + self, + "10.0.0.2", + 32, + [ + VppRoutePath(self.pg3.remote_ip4, self.pg3.sw_if_index), + VppRoutePath(self.pg4.remote_ip4, self.pg4.sw_if_index), + ], + ) route_10_0_0_2.add_vpp_config() - route_1_1_1_1 = VppIpRoute(self, "1.1.1.1", 32, - [VppRoutePath("10.0.0.2", 0xffffffff), - VppRoutePath("10.0.0.1", 0xffffffff)]) + route_1_1_1_1 = VppIpRoute( + self, + "1.1.1.1", + 32, + [ + VppRoutePath("10.0.0.2", 0xFFFFFFFF), + VppRoutePath("10.0.0.1", 0xFFFFFFFF), + ], + ) route_1_1_1_1.add_vpp_config() # # inject the packet on pg0 - expect load-balancing across all 4 paths # self.vapi.cli("clear trace") - self.send_and_expect_load_balancing(self.pg0, port_pkts, - [self.pg1, self.pg2, - self.pg3, self.pg4]) - self.send_and_expect_load_balancing(self.pg0, src_pkts, - [self.pg1, self.pg2, - self.pg3, self.pg4]) + self.send_and_expect_load_balancing( + self.pg0, port_pkts, [self.pg1, self.pg2, self.pg3, self.pg4] + ) + self.send_and_expect_load_balancing( + self.pg0, src_pkts, [self.pg1, self.pg2, self.pg3, self.pg4] + ) # # bring down pg1 expect LB to adjust to use only those that are up # self.pg1.link_down() - rx = self.send_and_expect_load_balancing(self.pg0, src_pkts, - [self.pg2, self.pg3, - self.pg4]) + rx = self.send_and_expect_load_balancing( + self.pg0, src_pkts, [self.pg2, self.pg3, self.pg4] + ) self.assertEqual(len(src_pkts), self.total_len(rx)) # @@ -1292,8 +1409,9 @@ class TestIPLoadBalance(VppTestCase): # self.pg2.link_down() - rx = self.send_and_expect_load_balancing(self.pg0, src_pkts, - [self.pg3, self.pg4]) + rx = self.send_and_expect_load_balancing( + self.pg0, src_pkts, [self.pg3, self.pg4] + ) self.assertEqual(len(src_pkts), self.total_len(rx)) # @@ -1302,9 +1420,9 @@ class TestIPLoadBalance(VppTestCase): self.pg1.link_up() self.pg2.link_up() - rx = self.send_and_expect_load_balancing(self.pg0, src_pkts, - [self.pg1, self.pg2, - self.pg3, self.pg4]) + rx = self.send_and_expect_load_balancing( + self.pg0, src_pkts, [self.pg1, self.pg2, self.pg3, self.pg4] + ) self.assertEqual(len(src_pkts), self.total_len(rx)) # @@ -1312,16 +1430,17 @@ class TestIPLoadBalance(VppTestCase): # self.pg1.admin_down() self.pg2.admin_down() - rx = self.send_and_expect_load_balancing(self.pg0, src_pkts, - [self.pg3, self.pg4]) + rx = self.send_and_expect_load_balancing( + self.pg0, src_pkts, [self.pg3, self.pg4] + ) self.assertEqual(len(src_pkts), self.total_len(rx)) self.pg1.admin_up() self.pg2.admin_up() self.pg1.resolve_arp() self.pg2.resolve_arp() - rx = self.send_and_expect_load_balancing(self.pg0, src_pkts, - [self.pg1, self.pg2, - self.pg3, self.pg4]) + rx = self.send_and_expect_load_balancing( + self.pg0, src_pkts, [self.pg1, self.pg2, self.pg3, self.pg4] + ) self.assertEqual(len(src_pkts), self.total_len(rx)) # @@ -1331,19 +1450,26 @@ class TestIPLoadBalance(VppTestCase): port_pkts = [] for ii in range(257): - port_pkts.append((Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(dst="1.1.1.2", src="20.0.0.2") / - UDP(sport=1234, dport=1234 + ii) / - Raw(b'\xa5' * 100))) - - route_10_0_0_3 = VppIpRoute(self, "10.0.0.3", 32, - [VppRoutePath(self.pg3.remote_ip4, - self.pg3.sw_if_index)]) + port_pkts.append( + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(dst="1.1.1.2", src="20.0.0.2") + / UDP(sport=1234, dport=1234 + ii) + / Raw(b"\xa5" * 100) + ) + ) + + route_10_0_0_3 = VppIpRoute( + self, + "10.0.0.3", + 32, + [VppRoutePath(self.pg3.remote_ip4, self.pg3.sw_if_index)], + ) route_10_0_0_3.add_vpp_config() - route_1_1_1_2 = VppIpRoute(self, "1.1.1.2", 32, - [VppRoutePath("10.0.0.3", 0xffffffff)]) + route_1_1_1_2 = VppIpRoute( + self, "1.1.1.2", 32, [VppRoutePath("10.0.0.3", 0xFFFFFFFF)] + ) route_1_1_1_2.add_vpp_config() # @@ -1358,33 +1484,39 @@ class TestIPLoadBalance(VppTestCase): # self.pg3.link_down() - route_10_0_0_3 = VppIpRoute(self, "10.0.0.3", 32, - [VppRoutePath(self.pg3.remote_ip4, - self.pg3.sw_if_index), - VppRoutePath(self.pg4.remote_ip4, - self.pg4.sw_if_index)]) + route_10_0_0_3 = VppIpRoute( + self, + "10.0.0.3", + 32, + [ + VppRoutePath(self.pg3.remote_ip4, self.pg3.sw_if_index), + VppRoutePath(self.pg4.remote_ip4, self.pg4.sw_if_index), + ], + ) route_10_0_0_3.add_vpp_config() port_pkts = [] for ii in range(257): - port_pkts.append(Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(dst="10.0.0.3", src="20.0.0.2") / - UDP(sport=1234, dport=1234 + ii) / - Raw(b'\xa5' * 100)) + port_pkts.append( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(dst="10.0.0.3", src="20.0.0.2") + / UDP(sport=1234, dport=1234 + ii) + / Raw(b"\xa5" * 100) + ) self.send_and_expect_only(self.pg0, port_pkts, self.pg4) # bring the link back up self.pg3.link_up() - rx = self.send_and_expect_load_balancing(self.pg0, port_pkts, - [self.pg3, self.pg4]) + rx = self.send_and_expect_load_balancing( + self.pg0, port_pkts, [self.pg3, self.pg4] + ) self.assertEqual(len(src_pkts), self.total_len(rx)) class TestIPVlan0(VppTestCase): - """ IPv4 VLAN-0 """ + """IPv4 VLAN-0""" @classmethod def setUpClass(cls): @@ -1415,15 +1547,15 @@ class TestIPVlan0(VppTestCase): super(TestIPVlan0, self).tearDown() def test_ip_vlan_0(self): - """ IP VLAN-0 """ + """IP VLAN-0""" - pkts = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - Dot1Q(vlan=0) / - IP(dst=self.pg1.remote_ip4, - src=self.pg0.remote_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) * NUM_PKTS + pkts = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / Dot1Q(vlan=0) + / IP(dst=self.pg1.remote_ip4, src=self.pg0.remote_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) * NUM_PKTS # # Expect that packets sent on VLAN-0 are forwarded on the @@ -1433,7 +1565,7 @@ class TestIPVlan0(VppTestCase): class IPPuntSetup(object): - """ Setup for IPv4 Punt Police/Redirect """ + """Setup for IPv4 Punt Police/Redirect""" def punt_setup(self): self.create_pg_interfaces(range(4)) @@ -1449,37 +1581,38 @@ class IPPuntSetup(object): af_ip4 = VppEnum.vl_api_address_family_t.ADDRESS_IP4 udp_proto = VppEnum.vl_api_ip_proto_t.IP_API_PROTO_UDP punt_udp = { - 'type': pt_l4, - 'punt': { - 'l4': { - 'af': af_ip4, - 'protocol': udp_proto, - 'port': 1234, + "type": pt_l4, + "punt": { + "l4": { + "af": af_ip4, + "protocol": udp_proto, + "port": 1234, } - } + }, } self.vapi.set_punt(is_add=1, punt=punt_udp) af_ip6 = VppEnum.vl_api_address_family_t.ADDRESS_IP6 punt_udp = { - 'type': pt_l4, - 'punt': { - 'l4': { - 'af': af_ip6, - 'protocol': udp_proto, - 'port': 1236, + "type": pt_l4, + "punt": { + "l4": { + "af": af_ip6, + "protocol": udp_proto, + "port": 1236, } - } + }, } self.vapi.set_punt(is_add=1, punt=punt_udp) - self.pkt = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + self.pkt = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) def punt_teardown(self): for i in self.pg_interfaces: @@ -1488,7 +1621,7 @@ class IPPuntSetup(object): class TestIPPunt(IPPuntSetup, VppTestCase): - """ IPv4 Punt Police/Redirect """ + """IPv4 Punt Police/Redirect""" def setUp(self): super().setUp() @@ -1499,26 +1632,30 @@ class TestIPPunt(IPPuntSetup, VppTestCase): super().tearDown() def test_ip_punt_api_validation(self): - """ IP punt API parameter validation """ + """IP punt API parameter validation""" nh_addr = self.pg1.remote_ip4 - punt = {"rx_sw_if_index": self.pg0.sw_if_index, - "af": VppEnum.vl_api_address_family_t.ADDRESS_IP4, - "n_paths": 1000000, - "paths": []} + punt = { + "rx_sw_if_index": self.pg0.sw_if_index, + "af": VppEnum.vl_api_address_family_t.ADDRESS_IP4, + "n_paths": 1000000, + "paths": [], + } with self.assertRaises(vpp_papi.VPPIOError): self.vapi.add_del_ip_punt_redirect_v2(punt=punt, is_add=True) - punt = {"rx_sw_if_index": self.pg0.sw_if_index, - "af": VppEnum.vl_api_address_family_t.ADDRESS_IP4, - "n_paths": 0, - "paths": []} + punt = { + "rx_sw_if_index": self.pg0.sw_if_index, + "af": VppEnum.vl_api_address_family_t.ADDRESS_IP4, + "n_paths": 0, + "paths": [], + } self.vapi.add_del_ip_punt_redirect_v2(punt=punt, is_add=True) def test_ip_punt(self): - """ IP punt police and redirect """ + """IP punt police and redirect""" pkts = self.pkt * 1025 @@ -1526,8 +1663,9 @@ class TestIPPunt(IPPuntSetup, VppTestCase): # Configure a punt redirect via pg1. # nh_addr = self.pg1.remote_ip4 - ip_punt_redirect = VppIpPuntRedirect(self, self.pg0.sw_if_index, - self.pg1.sw_if_index, nh_addr) + ip_punt_redirect = VppIpPuntRedirect( + self, self.pg0.sw_if_index, self.pg1.sw_if_index, nh_addr + ) ip_punt_redirect.add_vpp_config() self.send_and_expect(self.pg0, pkts, self.pg1) @@ -1554,9 +1692,9 @@ class TestIPPunt(IPPuntSetup, VppTestCase): stats = policer.get_stats() # Single rate policer - expect conform, violate but no exceed - self.assertGreater(stats['conform_packets'], 0) - self.assertEqual(stats['exceed_packets'], 0) - self.assertGreater(stats['violate_packets'], 0) + self.assertGreater(stats["conform_packets"], 0) + self.assertEqual(stats["exceed_packets"], 0) + self.assertGreater(stats["violate_packets"], 0) self.assertGreater(len(rx), 0) self.assertLess(len(rx), len(pkts)) @@ -1572,32 +1710,28 @@ class TestIPPunt(IPPuntSetup, VppTestCase): # remove the redirect. expect full drop. # ip_punt_redirect.remove_vpp_config() - self.send_and_assert_no_replies(self.pg0, pkts, - "IP no punt config") + self.send_and_assert_no_replies(self.pg0, pkts, "IP no punt config") # # Add a redirect that is not input port selective # - ip_punt_redirect = VppIpPuntRedirect(self, 0xffffffff, - self.pg1.sw_if_index, nh_addr) + ip_punt_redirect = VppIpPuntRedirect( + self, 0xFFFFFFFF, self.pg1.sw_if_index, nh_addr + ) ip_punt_redirect.add_vpp_config() self.send_and_expect(self.pg0, pkts, self.pg1) ip_punt_redirect.remove_vpp_config() def test_ip_punt_vrf(self): - """ IP punt/local with VRFs """ + """IP punt/local with VRFs""" # use a punt redirect to test if for-us packets are accepted pkts = self.pkt * 1025 - vlans_pg0 = [VppDot1QSubint(self, self.pg0, v) - for v in range(100, 104)] - vlans_pg1 = [VppDot1QSubint(self, self.pg1, v) - for v in range(100, 104)] - tbl4 = [VppIpTable(self, v).add_vpp_config() - for v in range(100, 104)] - tbl6 = [VppIpTable(self, v, True).add_vpp_config() - for v in range(100, 104)] + vlans_pg0 = [VppDot1QSubint(self, self.pg0, v) for v in range(100, 104)] + vlans_pg1 = [VppDot1QSubint(self, self.pg1, v) for v in range(100, 104)] + tbl4 = [VppIpTable(self, v).add_vpp_config() for v in range(100, 104)] + tbl6 = [VppIpTable(self, v, True).add_vpp_config() for v in range(100, 104)] for v in vlans_pg0 + vlans_pg1: v.admin_up() @@ -1608,27 +1742,35 @@ class TestIPPunt(IPPuntSetup, VppTestCase): v.resolve_arp() v.resolve_ndp() - [VppIpPuntRedirect - (self, - vlans_pg0[i].sw_if_index, - vlans_pg1[i].sw_if_index, - vlans_pg1[i].remote_ip4).add_vpp_config() - for i in range(4)] - [VppIpPuntRedirect - (self, - vlans_pg0[i].sw_if_index, - vlans_pg1[i].sw_if_index, - vlans_pg1[i].remote_ip6).add_vpp_config() - for i in range(4)] - - pkts = [(Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - Dot1Q(vlan=i.vlan) / - IP(src=i.remote_ip4, - dst=i.local_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - for i in vlans_pg0] + [ + VppIpPuntRedirect( + self, + vlans_pg0[i].sw_if_index, + vlans_pg1[i].sw_if_index, + vlans_pg1[i].remote_ip4, + ).add_vpp_config() + for i in range(4) + ] + [ + VppIpPuntRedirect( + self, + vlans_pg0[i].sw_if_index, + vlans_pg1[i].sw_if_index, + vlans_pg1[i].remote_ip6, + ).add_vpp_config() + for i in range(4) + ] + + pkts = [ + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / Dot1Q(vlan=i.vlan) + / IP(src=i.remote_ip4, dst=i.local_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + for i in vlans_pg0 + ] self.send_and_expect(self.pg0, pkts, self.pg1) @@ -1637,33 +1779,37 @@ class TestIPPunt(IPPuntSetup, VppTestCase): # # we reject packets for source addresses in the wrong vlan/VRF - pkts = [(Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - Dot1Q(vlan=i.vlan) / - IP(src="1.1.1.1", - dst=i.local_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - for i in vlans_pg0] + pkts = [ + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / Dot1Q(vlan=i.vlan) + / IP(src="1.1.1.1", dst=i.local_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + for i in vlans_pg0 + ] # single and dual loop self.send_and_assert_no_replies(self.pg0, [pkts[0]]) self.send_and_assert_no_replies(self.pg0, pkts) self.assert_error_counter_equal( - "/err/ip4-local/ip4 source lookup miss", - len(pkts) + 1) + "/err/ip4-local/ip4 source lookup miss", len(pkts) + 1 + ) # using the same source in different tables, should reject # for the table that the source is not present in # the first packet in the stream is drop - pkts = [(Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - Dot1Q(vlan=i.vlan) / - IP(src=vlans_pg0[0].remote_ip4, - dst=i.local_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - for i in vlans_pg0] + pkts = [ + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / Dot1Q(vlan=i.vlan) + / IP(src=vlans_pg0[0].remote_ip4, dst=i.local_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + for i in vlans_pg0 + ] # single loop accept and drop # followed by both in the same frame/loop self.send_and_expect(self.pg0, [pkts[0]], self.pg1) @@ -1673,14 +1819,16 @@ class TestIPPunt(IPPuntSetup, VppTestCase): # using the same source in different tables, should reject # for the table that the source is not present in # the first packet in the stream is accept - pkts = [(Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - Dot1Q(vlan=i.vlan) / - IP(src=vlans_pg0[3].remote_ip4, - dst=i.local_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - for i in vlans_pg0] + pkts = [ + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / Dot1Q(vlan=i.vlan) + / IP(src=vlans_pg0[3].remote_ip4, dst=i.local_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + for i in vlans_pg0 + ] # single loop accept and drop # followed by both in the same frame/loop @@ -1693,33 +1841,37 @@ class TestIPPunt(IPPuntSetup, VppTestCase): # # we reject packets for source addresses in the wrong vlan/VRF - pkts = [(Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - Dot1Q(vlan=i.vlan) / - IPv6(src="1::1", - dst=i.local_ip6) / - UDP(sport=1236, dport=1236) / - Raw(b'\xa5' * 100)) - for i in vlans_pg0] + pkts = [ + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / Dot1Q(vlan=i.vlan) + / IPv6(src="1::1", dst=i.local_ip6) + / UDP(sport=1236, dport=1236) + / Raw(b"\xa5" * 100) + ) + for i in vlans_pg0 + ] # single and dual loop self.send_and_assert_no_replies(self.pg0, [pkts[0]]) self.send_and_assert_no_replies(self.pg0, pkts) self.assert_error_counter_equal( - "/err/ip6-input/ip6 source lookup miss", - len(pkts) + 1) + "/err/ip6-input/ip6 source lookup miss", len(pkts) + 1 + ) # using the same source in different tables, should reject # for the table that the source is not present in # the first packet in the stream is drop - pkts = [(Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - Dot1Q(vlan=i.vlan) / - IPv6(src=vlans_pg0[0].remote_ip6, - dst=i.local_ip6) / - UDP(sport=1236, dport=1236) / - Raw(b'\xa5' * 100)) - for i in vlans_pg0] + pkts = [ + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / Dot1Q(vlan=i.vlan) + / IPv6(src=vlans_pg0[0].remote_ip6, dst=i.local_ip6) + / UDP(sport=1236, dport=1236) + / Raw(b"\xa5" * 100) + ) + for i in vlans_pg0 + ] # single loop accept and drop # followed by both in the same frame/loop self.send_and_expect(self.pg0, [pkts[0]], self.pg1) @@ -1729,14 +1881,16 @@ class TestIPPunt(IPPuntSetup, VppTestCase): # using the same source in different tables, should reject # for the table that the source is not present in # the first packet in the stream is accept - pkts = [(Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - Dot1Q(vlan=i.vlan) / - IPv6(src=vlans_pg0[3].remote_ip6, - dst=i.local_ip6) / - UDP(sport=1236, dport=1236) / - Raw(b'\xa5' * 100)) - for i in vlans_pg0] + pkts = [ + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / Dot1Q(vlan=i.vlan) + / IPv6(src=vlans_pg0[3].remote_ip6, dst=i.local_ip6) + / UDP(sport=1236, dport=1236) + / Raw(b"\xa5" * 100) + ) + for i in vlans_pg0 + ] # single loop accept and drop # followed by both in the same frame/loop @@ -1751,18 +1905,21 @@ class TestIPPunt(IPPuntSetup, VppTestCase): v.set_table_ip6(0) def test_ip_punt_dump(self): - """ IP4 punt redirect dump""" + """IP4 punt redirect dump""" # # Configure a punt redirects # nh_address = self.pg3.remote_ip4 - ipr_03 = VppIpPuntRedirect(self, self.pg0.sw_if_index, - self.pg3.sw_if_index, nh_address) - ipr_13 = VppIpPuntRedirect(self, self.pg1.sw_if_index, - self.pg3.sw_if_index, nh_address) - ipr_23 = VppIpPuntRedirect(self, self.pg2.sw_if_index, - self.pg3.sw_if_index, "0.0.0.0") + ipr_03 = VppIpPuntRedirect( + self, self.pg0.sw_if_index, self.pg3.sw_if_index, nh_address + ) + ipr_13 = VppIpPuntRedirect( + self, self.pg1.sw_if_index, self.pg3.sw_if_index, nh_address + ) + ipr_23 = VppIpPuntRedirect( + self, self.pg2.sw_if_index, self.pg3.sw_if_index, "0.0.0.0" + ) ipr_03.add_vpp_config() ipr_13.add_vpp_config() ipr_23.add_vpp_config() @@ -1777,16 +1934,17 @@ class TestIPPunt(IPPuntSetup, VppTestCase): # # Dump punt redirects for all interfaces # - punts = self.vapi.ip_punt_redirect_dump(0xffffffff) + punts = self.vapi.ip_punt_redirect_dump(0xFFFFFFFF) self.assertEqual(len(punts), 3) for p in punts: self.assertEqual(p.punt.tx_sw_if_index, self.pg3.sw_if_index) self.assertNotEqual(punts[1].punt.nh, self.pg3.remote_ip4) - self.assertEqual(str(punts[2].punt.nh), '0.0.0.0') + self.assertEqual(str(punts[2].punt.nh), "0.0.0.0") class TestIPPuntHandoff(IPPuntSetup, VppTestCase): - """ IPv4 Punt Policer thread handoff """ + """IPv4 Punt Policer thread handoff""" + vpp_worker_count = 2 def setUp(self): @@ -1798,26 +1956,40 @@ class TestIPPuntHandoff(IPPuntSetup, VppTestCase): super(TestIPPuntHandoff, self).tearDown() def test_ip_punt_policer_handoff(self): - """ IP4 punt policer thread handoff """ + """IP4 punt policer thread handoff""" pkts = self.pkt * NUM_PKTS # # Configure a punt redirect via pg1. # nh_addr = self.pg1.remote_ip4 - ip_punt_redirect = VppIpPuntRedirect(self, self.pg0.sw_if_index, - self.pg1.sw_if_index, nh_addr) + ip_punt_redirect = VppIpPuntRedirect( + self, self.pg0.sw_if_index, self.pg1.sw_if_index, nh_addr + ) ip_punt_redirect.add_vpp_config() action_tx = PolicerAction( - VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT, - 0) + VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT, 0 + ) # # This policer drops no packets, we are just # testing that they get to the right thread. # - policer = VppPolicer(self, "ip4-punt", 400, 0, 10, 0, 1, - 0, 0, False, action_tx, action_tx, action_tx) + policer = VppPolicer( + self, + "ip4-punt", + 400, + 0, + 10, + 0, + 1, + 0, + 0, + False, + action_tx, + action_tx, + action_tx, + ) policer.add_vpp_config() ip_punt_policer = VppIpPuntPolicer(self, policer.policer_index) ip_punt_policer.add_vpp_config() @@ -1830,9 +2002,9 @@ class TestIPPuntHandoff(IPPuntSetup, VppTestCase): stats = policer.get_stats() # Single rate policer - expect conform, violate but no exceed - self.assertGreater(stats['conform_packets'], 0) - self.assertEqual(stats['exceed_packets'], 0) - self.assertGreater(stats['violate_packets'], 0) + self.assertGreater(stats["conform_packets"], 0) + self.assertEqual(stats["exceed_packets"], 0) + self.assertGreater(stats["violate_packets"], 0) # Worker 0, should have done all the policing stats0 = policer.get_stats(worker=0) @@ -1840,9 +2012,9 @@ class TestIPPuntHandoff(IPPuntSetup, VppTestCase): # Worker 1, should have handed everything off stats1 = policer.get_stats(worker=1) - self.assertEqual(stats1['conform_packets'], 0) - self.assertEqual(stats1['exceed_packets'], 0) - self.assertEqual(stats1['violate_packets'], 0) + self.assertEqual(stats1["conform_packets"], 0) + self.assertEqual(stats1["exceed_packets"], 0) + self.assertEqual(stats1["violate_packets"], 0) # Bind the policer to worker 1 and repeat policer.bind_vpp_config(1, True) @@ -1855,19 +2027,23 @@ class TestIPPuntHandoff(IPPuntSetup, VppTestCase): stats0 = policer.get_stats(worker=0) stats1 = policer.get_stats(worker=1) - self.assertGreater(stats0['conform_packets'], 0) - self.assertEqual(stats0['exceed_packets'], 0) - self.assertGreater(stats0['violate_packets'], 0) + self.assertGreater(stats0["conform_packets"], 0) + self.assertEqual(stats0["exceed_packets"], 0) + self.assertGreater(stats0["violate_packets"], 0) - self.assertGreater(stats1['conform_packets'], 0) - self.assertEqual(stats1['exceed_packets'], 0) - self.assertGreater(stats1['violate_packets'], 0) + self.assertGreater(stats1["conform_packets"], 0) + self.assertEqual(stats1["exceed_packets"], 0) + self.assertGreater(stats1["violate_packets"], 0) - self.assertEqual(stats0['conform_packets'] + stats1['conform_packets'], - stats['conform_packets']) + self.assertEqual( + stats0["conform_packets"] + stats1["conform_packets"], + stats["conform_packets"], + ) - self.assertEqual(stats0['violate_packets'] + stats1['violate_packets'], - stats['violate_packets']) + self.assertEqual( + stats0["violate_packets"] + stats1["violate_packets"], + stats["violate_packets"], + ) # Unbind the policer and repeat policer.bind_vpp_config(1, False) @@ -1880,11 +2056,9 @@ class TestIPPuntHandoff(IPPuntSetup, VppTestCase): stats0new = policer.get_stats(worker=0) stats1new = policer.get_stats(worker=1) - self.assertGreater(stats0new['conform_packets'], - stats0['conform_packets']) - self.assertEqual(stats0new['exceed_packets'], 0) - self.assertGreater(stats0new['violate_packets'], - stats0['violate_packets']) + self.assertGreater(stats0new["conform_packets"], stats0["conform_packets"]) + self.assertEqual(stats0new["exceed_packets"], 0) + self.assertGreater(stats0new["violate_packets"], stats0["violate_packets"]) self.assertEqual(stats1, stats1new) @@ -1897,7 +2071,7 @@ class TestIPPuntHandoff(IPPuntSetup, VppTestCase): class TestIPDeag(VppTestCase): - """ IPv4 Deaggregate Routes """ + """IPv4 Deaggregate Routes""" @classmethod def setUpClass(cls): @@ -1924,7 +2098,7 @@ class TestIPDeag(VppTestCase): i.admin_down() def test_ip_deag(self): - """ IP Deag Routes """ + """IP Deag Routes""" # # Create a table to be used for: @@ -1940,16 +2114,22 @@ class TestIPDeag(VppTestCase): # Add a route in the default table to point to a deag/ # second lookup in each of these tables # - route_to_dst = VppIpRoute(self, "1.1.1.1", 32, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_table_id=1)]) + route_to_dst = VppIpRoute( + self, "1.1.1.1", 32, [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=1)] + ) route_to_src = VppIpRoute( - self, "1.1.1.2", 32, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_table_id=2, - type=FibPathType.FIB_PATH_TYPE_SOURCE_LOOKUP)]) + self, + "1.1.1.2", + 32, + [ + VppRoutePath( + "0.0.0.0", + 0xFFFFFFFF, + nh_table_id=2, + type=FibPathType.FIB_PATH_TYPE_SOURCE_LOOKUP, + ) + ], + ) route_to_dst.add_vpp_config() route_to_src.add_vpp_config() @@ -1957,31 +2137,34 @@ class TestIPDeag(VppTestCase): # packets to these destination are dropped, since they'll # hit the respective default routes in the second table # - p_dst = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src="5.5.5.5", dst="1.1.1.1") / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - p_src = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src="2.2.2.2", dst="1.1.1.2") / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p_dst = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src="5.5.5.5", dst="1.1.1.1") + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + p_src = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src="2.2.2.2", dst="1.1.1.2") + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) pkts_dst = p_dst * 257 pkts_src = p_src * 257 - self.send_and_assert_no_replies(self.pg0, pkts_dst, - "IP in dst table") - self.send_and_assert_no_replies(self.pg0, pkts_src, - "IP in src table") + self.send_and_assert_no_replies(self.pg0, pkts_dst, "IP in dst table") + self.send_and_assert_no_replies(self.pg0, pkts_src, "IP in src table") # # add a route in the dst table to forward via pg1 # - route_in_dst = VppIpRoute(self, "1.1.1.1", 32, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index)], - table_id=1) + route_in_dst = VppIpRoute( + self, + "1.1.1.1", + 32, + [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)], + table_id=1, + ) route_in_dst.add_vpp_config() self.send_and_expect(self.pg0, pkts_dst, self.pg1) @@ -1989,34 +2172,36 @@ class TestIPDeag(VppTestCase): # # add a route in the src table to forward via pg2 # - route_in_src = VppIpRoute(self, "2.2.2.2", 32, - [VppRoutePath(self.pg2.remote_ip4, - self.pg2.sw_if_index)], - table_id=2) + route_in_src = VppIpRoute( + self, + "2.2.2.2", + 32, + [VppRoutePath(self.pg2.remote_ip4, self.pg2.sw_if_index)], + table_id=2, + ) route_in_src.add_vpp_config() self.send_and_expect(self.pg0, pkts_src, self.pg2) # # loop in the lookup DP # - route_loop = VppIpRoute(self, "2.2.2.3", 32, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_table_id=0)]) + route_loop = VppIpRoute( + self, "2.2.2.3", 32, [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=0)] + ) route_loop.add_vpp_config() - p_l = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src="2.2.2.4", dst="2.2.2.3") / - TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p_l = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src="2.2.2.4", dst="2.2.2.3") + / TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) - self.send_and_assert_no_replies(self.pg0, p_l * 257, - "IP lookup loop") + self.send_and_assert_no_replies(self.pg0, p_l * 257, "IP lookup loop") class TestIPInput(VppTestCase): - """ IPv4 Input Exceptions """ + """IPv4 Input Exceptions""" @classmethod def setUpClass(cls): @@ -2043,7 +2228,7 @@ class TestIPInput(VppTestCase): i.admin_down() def test_ip_input(self): - """ IP Input Exceptions """ + """IP Input Exceptions""" # i can't find a way in scapy to construct an IP packet # with a length less than the IP header length @@ -2051,103 +2236,95 @@ class TestIPInput(VppTestCase): # # Packet too short - this is forwarded # - p_short = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, - dst=self.pg1.remote_ip4, - len=40) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p_short = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, len=40) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) rx = self.send_and_expect(self.pg0, p_short * NUM_PKTS, self.pg1) # # Packet too long - this is dropped # - p_long = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, - dst=self.pg1.remote_ip4, - len=400) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p_long = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, len=400) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) - rx = self.send_and_assert_no_replies(self.pg0, p_long * NUM_PKTS, - "too long") + rx = self.send_and_assert_no_replies(self.pg0, p_long * NUM_PKTS, "too long") # # bad chksum - this is dropped # - p_chksum = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, - dst=self.pg1.remote_ip4, - chksum=400) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p_chksum = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, chksum=400) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) - rx = self.send_and_assert_no_replies(self.pg0, p_chksum * NUM_PKTS, - "bad checksum") + rx = self.send_and_assert_no_replies( + self.pg0, p_chksum * NUM_PKTS, "bad checksum" + ) # # bad version - this is dropped # - p_ver = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, - dst=self.pg1.remote_ip4, - version=3) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p_ver = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, version=3) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) - rx = self.send_and_assert_no_replies(self.pg0, p_ver * NUM_PKTS, - "funky version") + rx = self.send_and_assert_no_replies( + self.pg0, p_ver * NUM_PKTS, "funky version" + ) # # fragment offset 1 - this is dropped # - p_frag = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, - dst=self.pg1.remote_ip4, - frag=1) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p_frag = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, frag=1) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) - rx = self.send_and_assert_no_replies(self.pg0, p_frag * NUM_PKTS, - "frag offset") + rx = self.send_and_assert_no_replies(self.pg0, p_frag * NUM_PKTS, "frag offset") # # TTL expired packet # - p_ttl = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, - dst=self.pg1.remote_ip4, - ttl=1) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p_ttl = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, ttl=1) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) rxs = self.send_and_expect_some(self.pg0, p_ttl * NUM_PKTS, self.pg0) for rx in rxs: icmp = rx[ICMP] self.assertEqual(icmptypes[icmp.type], "time-exceeded") - self.assertEqual(icmpcodes[icmp.type][icmp.code], - "ttl-zero-during-transit") + self.assertEqual(icmpcodes[icmp.type][icmp.code], "ttl-zero-during-transit") self.assertEqual(icmp.src, self.pg0.remote_ip4) self.assertEqual(icmp.dst, self.pg1.remote_ip4) # # MTU exceeded # - p_mtu = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, - dst=self.pg1.remote_ip4, - ttl=10, flags='DF') / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 2000)) + p_mtu = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, ttl=10, flags="DF") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 2000) + ) self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [1500, 0, 0, 0]) @@ -2156,8 +2333,7 @@ class TestIPInput(VppTestCase): for rx in rxs: icmp = rx[ICMP] self.assertEqual(icmptypes[icmp.type], "dest-unreach") - self.assertEqual(icmpcodes[icmp.type][icmp.code], - "fragmentation-needed") + self.assertEqual(icmpcodes[icmp.type][icmp.code], "fragmentation-needed") self.assertEqual(icmp.nexthopmtu, 1500) self.assertEqual(icmp.src, self.pg0.remote_ip4) self.assertEqual(icmp.dst, self.pg1.remote_ip4) @@ -2171,25 +2347,25 @@ class TestIPInput(VppTestCase): # # source address 0.0.0.0 and 25.255.255.255 and for-us # - p_s0 = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src="0.0.0.0", - dst=self.pg0.local_ip4) / - ICMP(id=4, seq=4) / - Raw(load=b'\x0a' * 18)) + p_s0 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src="0.0.0.0", dst=self.pg0.local_ip4) + / ICMP(id=4, seq=4) + / Raw(load=b"\x0a" * 18) + ) rx = self.send_and_assert_no_replies(self.pg0, p_s0 * 17) - p_s0 = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src="255.255.255.255", - dst=self.pg0.local_ip4) / - ICMP(id=4, seq=4) / - Raw(load=b'\x0a' * 18)) + p_s0 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src="255.255.255.255", dst=self.pg0.local_ip4) + / ICMP(id=4, seq=4) + / Raw(load=b"\x0a" * 18) + ) rx = self.send_and_assert_no_replies(self.pg0, p_s0 * 17) class TestIPDirectedBroadcast(VppTestCase): - """ IPv4 Directed Broadcast """ + """IPv4 Directed Broadcast""" @classmethod def setUpClass(cls): @@ -2213,26 +2389,25 @@ class TestIPDirectedBroadcast(VppTestCase): i.admin_down() def test_ip_input(self): - """ IP Directed Broadcast """ + """IP Directed Broadcast""" # # set the directed broadcast on pg0 first, then config IP4 addresses # for pg1 directed broadcast is always disabled - self.vapi.sw_interface_set_ip_directed_broadcast( - self.pg0.sw_if_index, 1) - - p0 = (Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) / - IP(src="1.1.1.1", - dst=self.pg0._local_ip4_bcast) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 2000)) - p1 = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src="1.1.1.1", - dst=self.pg1._local_ip4_bcast) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 2000)) + self.vapi.sw_interface_set_ip_directed_broadcast(self.pg0.sw_if_index, 1) + + p0 = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src="1.1.1.1", dst=self.pg0._local_ip4_bcast) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 2000) + ) + p1 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src="1.1.1.1", dst=self.pg1._local_ip4_bcast) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 2000) + ) self.pg0.config_ip4() self.pg0.resolve_arp() @@ -2245,19 +2420,19 @@ class TestIPDirectedBroadcast(VppTestCase): rx = self.send_and_expect(self.pg1, p0 * NUM_PKTS, self.pg0) self.assertTrue(rx[0][Ether].dst, "ff:ff:ff:ff:ff:ff") - self.send_and_assert_no_replies(self.pg0, p1 * NUM_PKTS, - "directed broadcast disabled") + self.send_and_assert_no_replies( + self.pg0, p1 * NUM_PKTS, "directed broadcast disabled" + ) # # toggle directed broadcast on pg0 # - self.vapi.sw_interface_set_ip_directed_broadcast( - self.pg0.sw_if_index, 0) - self.send_and_assert_no_replies(self.pg1, p0 * NUM_PKTS, - "directed broadcast disabled") + self.vapi.sw_interface_set_ip_directed_broadcast(self.pg0.sw_if_index, 0) + self.send_and_assert_no_replies( + self.pg1, p0 * NUM_PKTS, "directed broadcast disabled" + ) - self.vapi.sw_interface_set_ip_directed_broadcast( - self.pg0.sw_if_index, 1) + self.vapi.sw_interface_set_ip_directed_broadcast(self.pg0.sw_if_index, 1) rx = self.send_and_expect(self.pg1, p0 * NUM_PKTS, self.pg0) self.pg0.unconfig_ip4() @@ -2265,7 +2440,7 @@ class TestIPDirectedBroadcast(VppTestCase): class TestIPLPM(VppTestCase): - """ IPv4 longest Prefix Match """ + """IPv4 longest Prefix Match""" @classmethod def setUpClass(cls): @@ -2292,29 +2467,35 @@ class TestIPLPM(VppTestCase): i.unconfig_ip4() def test_ip_lpm(self): - """ IP longest Prefix Match """ + """IP longest Prefix Match""" - s_24 = VppIpRoute(self, "10.1.2.0", 24, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index)]) + s_24 = VppIpRoute( + self, + "10.1.2.0", + 24, + [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)], + ) s_24.add_vpp_config() - s_8 = VppIpRoute(self, "10.0.0.0", 8, - [VppRoutePath(self.pg2.remote_ip4, - self.pg2.sw_if_index)]) + s_8 = VppIpRoute( + self, + "10.0.0.0", + 8, + [VppRoutePath(self.pg2.remote_ip4, self.pg2.sw_if_index)], + ) s_8.add_vpp_config() - p_8 = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src="1.1.1.1", - dst="10.1.1.1") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 2000)) - p_24 = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src="1.1.1.1", - dst="10.1.2.1") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 2000)) + p_8 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src="1.1.1.1", dst="10.1.1.1") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 2000) + ) + p_24 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src="1.1.1.1", dst="10.1.2.1") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 2000) + ) self.logger.info(self.vapi.cli("sh ip fib mtrie")) rx = self.send_and_expect(self.pg0, p_8 * NUM_PKTS, self.pg2) @@ -2323,7 +2504,7 @@ class TestIPLPM(VppTestCase): @tag_fixme_vpp_workers class TestIPv4Frag(VppTestCase): - """ IPv4 fragmentation """ + """IPv4 fragmentation""" @classmethod def setUpClass(cls): @@ -2344,25 +2525,29 @@ class TestIPv4Frag(VppTestCase): super(TestIPv4Frag, cls).tearDownClass() def test_frag_large_packets(self): - """ Fragmentation of large packets """ + """Fragmentation of large packets""" self.vapi.cli("adjacency counters enable") - p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / - IP(src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) / - UDP(sport=1234, dport=5678) / Raw()) + p = ( + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IP(src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) + / UDP(sport=1234, dport=5678) + / Raw() + ) self.extend_packet(p, 6000, "abcde") saved_payload = p[Raw].load - nbr = VppNeighbor(self, - self.dst_if.sw_if_index, - self.dst_if.remote_mac, - self.dst_if.remote_ip4).add_vpp_config() + nbr = VppNeighbor( + self, + self.dst_if.sw_if_index, + self.dst_if.remote_mac, + self.dst_if.remote_ip4, + ).add_vpp_config() # Force fragmentation by setting MTU of output interface # lower than packet size - self.vapi.sw_interface_set_mtu(self.dst_if.sw_if_index, - [5000, 0, 0, 0]) + self.vapi.sw_interface_set_mtu(self.dst_if.sw_if_index, [5000, 0, 0, 0]) self.pg_enable_capture() self.src_if.add_stream(p) @@ -2373,10 +2558,10 @@ class TestIPv4Frag(VppTestCase): packets = self.dst_if.get_capture(3) # we should show 3 packets thru the neighbor - self.assertEqual(3, nbr.get_stats()['packets']) + self.assertEqual(3, nbr.get_stats()["packets"]) # Assume VPP sends the fragments in order - payload = b'' + payload = b"" for p in packets: payload_offset = p.frag * 8 if payload_offset > 0: @@ -2387,7 +2572,7 @@ class TestIPv4Frag(VppTestCase): class TestIPReplace(VppTestCase): - """ IPv4 Table Replace """ + """IPv4 Table Replace""" @classmethod def setUpClass(cls): @@ -2420,7 +2605,7 @@ class TestIPReplace(VppTestCase): i.unconfig_ip4() def test_replace(self): - """ IP Table Replace """ + """IP Table Replace""" MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t @@ -2432,27 +2617,46 @@ class TestIPReplace(VppTestCase): for ii, t in enumerate(self.tables): for jj in range(N_ROUTES): uni = VppIpRoute( - self, "10.0.0.%d" % jj, 32, - [VppRoutePath(links[ii].remote_hosts[0].ip4, - links[ii].sw_if_index), - VppRoutePath(links[ii].remote_hosts[1].ip4, - links[ii].sw_if_index)], - table_id=t.table_id).add_vpp_config() + self, + "10.0.0.%d" % jj, + 32, + [ + VppRoutePath( + links[ii].remote_hosts[0].ip4, links[ii].sw_if_index + ), + VppRoutePath( + links[ii].remote_hosts[1].ip4, links[ii].sw_if_index + ), + ], + table_id=t.table_id, + ).add_vpp_config() multi = VppIpMRoute( - self, "0.0.0.0", - "239.0.0.%d" % jj, 32, + self, + "0.0.0.0", + "239.0.0.%d" % jj, + 32, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - [VppMRoutePath(self.pg0.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT), - VppMRoutePath(self.pg1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD), - VppMRoutePath(self.pg2.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD), - VppMRoutePath(self.pg3.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)], - table_id=t.table_id).add_vpp_config() - routes[ii].append({'uni': uni, - 'multi': multi}) + [ + VppMRoutePath( + self.pg0.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT, + ), + VppMRoutePath( + self.pg1.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + ), + VppMRoutePath( + self.pg2.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + ), + VppMRoutePath( + self.pg3.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + ), + ], + table_id=t.table_id, + ).add_vpp_config() + routes[ii].append({"uni": uni, "multi": multi}) # # replace the tables a few times @@ -2467,14 +2671,14 @@ class TestIPReplace(VppTestCase): dump = t.dump() mdump = t.mdump() for r in routes[ii]: - self.assertTrue(find_route_in_dump(dump, r['uni'], t)) - self.assertTrue(find_mroute_in_dump(mdump, r['multi'], t)) + self.assertTrue(find_route_in_dump(dump, r["uni"], t)) + self.assertTrue(find_mroute_in_dump(mdump, r["multi"], t)) # redownload the even numbered routes for ii, t in enumerate(self.tables): for jj in range(0, N_ROUTES, 2): - routes[ii][jj]['uni'].add_vpp_config() - routes[ii][jj]['multi'].add_vpp_config() + routes[ii][jj]["uni"].add_vpp_config() + routes[ii][jj]["multi"].add_vpp_config() # signal each table replace_end for t in self.tables: @@ -2485,29 +2689,29 @@ class TestIPReplace(VppTestCase): dump = t.dump() mdump = t.mdump() for jj in range(0, N_ROUTES, 2): - self.assertTrue(find_route_in_dump( - dump, routes[ii][jj]['uni'], t)) - self.assertTrue(find_mroute_in_dump( - mdump, routes[ii][jj]['multi'], t)) + self.assertTrue(find_route_in_dump(dump, routes[ii][jj]["uni"], t)) + self.assertTrue( + find_mroute_in_dump(mdump, routes[ii][jj]["multi"], t) + ) for jj in range(1, N_ROUTES - 1, 2): - self.assertFalse(find_route_in_dump( - dump, routes[ii][jj]['uni'], t)) - self.assertFalse(find_mroute_in_dump( - mdump, routes[ii][jj]['multi'], t)) + self.assertFalse(find_route_in_dump(dump, routes[ii][jj]["uni"], t)) + self.assertFalse( + find_mroute_in_dump(mdump, routes[ii][jj]["multi"], t) + ) # reload all the routes for ii, t in enumerate(self.tables): for r in routes[ii]: - r['uni'].add_vpp_config() - r['multi'].add_vpp_config() + r["uni"].add_vpp_config() + r["multi"].add_vpp_config() # all the routes are still there for ii, t in enumerate(self.tables): dump = t.dump() mdump = t.mdump() for r in routes[ii]: - self.assertTrue(find_route_in_dump(dump, r['uni'], t)) - self.assertTrue(find_mroute_in_dump(mdump, r['multi'], t)) + self.assertTrue(find_route_in_dump(dump, r["uni"], t)) + self.assertTrue(find_mroute_in_dump(mdump, r["multi"], t)) # # finally flush the tables for good measure @@ -2519,7 +2723,7 @@ class TestIPReplace(VppTestCase): class TestIPCover(VppTestCase): - """ IPv4 Table Cover """ + """IPv4 Table Cover""" @classmethod def setUpClass(cls): @@ -2552,7 +2756,7 @@ class TestIPCover(VppTestCase): i.unconfig_ip4() def test_cover(self): - """ IP Table Cover """ + """IP Table Cover""" # add a loop back with a /32 prefix lo = VppLoInterface(self) @@ -2560,21 +2764,23 @@ class TestIPCover(VppTestCase): a = VppIpInterfaceAddress(self, lo, "127.0.0.1", 32).add_vpp_config() # add a neighbour that matches the loopback's /32 - nbr = VppNeighbor(self, - lo.sw_if_index, - lo.remote_mac, - "127.0.0.1").add_vpp_config() + nbr = VppNeighbor( + self, lo.sw_if_index, lo.remote_mac, "127.0.0.1" + ).add_vpp_config() # add the default route which will be the cover for /32 - r = VppIpRoute(self, "0.0.0.0", 0, - [VppRoutePath("127.0.0.1", - lo.sw_if_index)], - register=False).add_vpp_config() + r = VppIpRoute( + self, + "0.0.0.0", + 0, + [VppRoutePath("127.0.0.1", lo.sw_if_index)], + register=False, + ).add_vpp_config() # add/remove/add a longer mask cover - r8 = VppIpRoute(self, "127.0.0.0", 8, - [VppRoutePath("127.0.0.1", - lo.sw_if_index)]).add_vpp_config() + r8 = VppIpRoute( + self, "127.0.0.0", 8, [VppRoutePath("127.0.0.1", lo.sw_if_index)] + ).add_vpp_config() r8.remove_vpp_config() r8.add_vpp_config() r8.remove_vpp_config() @@ -2587,7 +2793,7 @@ class TestIPCover(VppTestCase): class TestIP4Replace(VppTestCase): - """ IPv4 Interface Address Replace """ + """IPv4 Interface Address Replace""" @classmethod def setUpClass(cls): @@ -2614,7 +2820,7 @@ class TestIP4Replace(VppTestCase): return len(self.vapi.ip_address_dump(intf.sw_if_index)) def test_replace(self): - """ IP interface address replace """ + """IP interface address replace""" intf_pfxs = [[], [], [], []] @@ -2698,8 +2904,7 @@ class TestIP4Replace(VppTestCase): for intf in self.pg_interfaces: # 172.18.x.1/24 addr = "172.18.%d.1" % intf.sw_if_index - pfxs.append(VppIpInterfaceAddress(self, intf, addr, - 24).add_vpp_config()) + pfxs.append(VppIpInterfaceAddress(self, intf, addr, 24).add_vpp_config()) self.vapi.sw_interface_address_replace_end() @@ -2734,8 +2939,7 @@ class TestIP4Replace(VppTestCase): for intf in self.pg_interfaces: # 172.18.x.1/24 addr = "172.18.%d.1" % (intf.sw_if_index + 1) - pfxs.append(VppIpInterfaceAddress(self, intf, - addr, 24).add_vpp_config()) + pfxs.append(VppIpInterfaceAddress(self, intf, addr, 24).add_vpp_config()) self.vapi.sw_interface_address_replace_end() @@ -2748,7 +2952,7 @@ class TestIP4Replace(VppTestCase): class TestIPv4PathMTU(VppTestCase): - """ IPv4 Path MTU """ + """IPv4 Path MTU""" @classmethod def setUpClass(cls): @@ -2767,7 +2971,7 @@ class TestIPv4PathMTU(VppTestCase): super(TestIPv4PathMTU, cls).tearDownClass() def test_path_mtu(self): - """ Path MTU """ + """Path MTU""" # # The goal here is not to test that fragmentation works correctly, @@ -2777,28 +2981,26 @@ class TestIPv4PathMTU(VppTestCase): self.vapi.cli("adjacency counters enable") # set the interface MTU to a reasonable value - self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, - [1800, 0, 0, 0]) + self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [1800, 0, 0, 0]) self.pg1.generate_remote_hosts(4) - p_2k = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, - dst=self.pg1.remote_ip4) / - UDP(sport=1234, dport=5678) / - Raw(b'0xa' * 640)) - p_1k = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, - dst=self.pg1.remote_ip4) / - UDP(sport=1234, dport=5678) / - Raw(b'0xa' * 320)) - - nbr = VppNeighbor(self, - self.pg1.sw_if_index, - self.pg1.remote_mac, - self.pg1.remote_ip4).add_vpp_config() + p_2k = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / UDP(sport=1234, dport=5678) + / Raw(b"0xa" * 640) + ) + p_1k = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / UDP(sport=1234, dport=5678) + / Raw(b"0xa" * 320) + ) + + nbr = VppNeighbor( + self, self.pg1.sw_if_index, self.pg1.remote_mac, self.pg1.remote_ip4 + ).add_vpp_config() # this is now the interface MTU frags self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=2) @@ -2832,21 +3034,18 @@ class TestIPv4PathMTU(VppTestCase): # raise the interface's MTU # should still use that of the path - self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, - [2000, 0, 0, 0]) + self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [2000, 0, 0, 0]) self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3) self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2) # set path high and interface low pmtu.modify(2000) - self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, - [900, 0, 0, 0]) + self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [900, 0, 0, 0]) self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3) self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2) # remove the path MTU using the mark-n-sweep semantics - self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, - [1800, 0, 0, 0]) + self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [1800, 0, 0, 0]) self.vapi.ip_path_mtu_replace_begin() self.vapi.ip_path_mtu_replace_end() @@ -2856,27 +3055,27 @@ class TestIPv4PathMTU(VppTestCase): # # set path MTU for a neighbour that doesn't exist, yet # - pmtu2 = VppIpPathMtu(self, - self.pg1.remote_hosts[2].ip4, - 900).add_vpp_config() - - p_2k = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, - dst=self.pg1.remote_hosts[2].ip4) / - UDP(sport=1234, dport=5678) / - Raw(b'0xa' * 640)) - p_1k = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, - dst=self.pg1.remote_hosts[2].ip4) / - UDP(sport=1234, dport=5678) / - Raw(b'0xa' * 320)) - - nbr2 = VppNeighbor(self, - self.pg1.sw_if_index, - self.pg1.remote_hosts[2].mac, - self.pg1.remote_hosts[2].ip4).add_vpp_config() + pmtu2 = VppIpPathMtu(self, self.pg1.remote_hosts[2].ip4, 900).add_vpp_config() + + p_2k = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_hosts[2].ip4) + / UDP(sport=1234, dport=5678) + / Raw(b"0xa" * 640) + ) + p_1k = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_hosts[2].ip4) + / UDP(sport=1234, dport=5678) + / Raw(b"0xa" * 320) + ) + + nbr2 = VppNeighbor( + self, + self.pg1.sw_if_index, + self.pg1.remote_hosts[2].mac, + self.pg1.remote_hosts[2].ip4, + ).add_vpp_config() # should frag to the path MTU self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3) @@ -2916,7 +3115,7 @@ class TestIPv4PathMTU(VppTestCase): class TestIPv4ItfRebind(VppTestCase): - """ IPv4 Interface Bind w/ attached routes """ + """IPv4 Interface Bind w/ attached routes""" def setUp(self): super(TestIPv4ItfRebind, self).setUp() @@ -2927,7 +3126,7 @@ class TestIPv4ItfRebind(VppTestCase): super(TestIPv4ItfRebind, self).tearDown() def test_rebind(self): - """ Import to no import """ + """Import to no import""" TABLE_ID = 1 tbl = VppIpTable(self, TABLE_ID).add_vpp_config() @@ -2940,17 +3139,20 @@ class TestIPv4ItfRebind(VppTestCase): # add an attached route via an pg0 # in a different table. this prefix should import - rt = VppIpRoute(self, self.pg0.local_ip4, 24, - [VppRoutePath("0.0.0.0", - self.pg0.sw_if_index)], - table_id=TABLE_ID).add_vpp_config() - - p = (Ether(dst=self.pg1.local_mac, - src=self.pg1.remote_mac) / - IP(src=self.pg1.remote_ip4, - dst=self.pg0.remote_ip4) / - UDP(sport=1234, dport=5678) / - Raw(b'0xa' * 640)) + rt = VppIpRoute( + self, + self.pg0.local_ip4, + 24, + [VppRoutePath("0.0.0.0", self.pg0.sw_if_index)], + table_id=TABLE_ID, + ).add_vpp_config() + + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src=self.pg1.remote_ip4, dst=self.pg0.remote_ip4) + / UDP(sport=1234, dport=5678) + / Raw(b"0xa" * 640) + ) rx = self.send_and_expect(self.pg1, [p], self.pg0) self.assertFalse(rx[0].haslayer(ARP)) @@ -2984,7 +3186,7 @@ class TestIPv4ItfRebind(VppTestCase): tbl.remove_vpp_config() def test_delete(self): - """ Swap import tables """ + """Swap import tables""" TABLE_ID1 = 1 tbl1_4 = VppIpTable(self, TABLE_ID1).add_vpp_config() @@ -3006,19 +3208,25 @@ class TestIPv4ItfRebind(VppTestCase): # add an attached route in the default table via pg0 # this should import to table 1 - rt4 = VppIpRoute(self, self.pg1.local_ip4, 24, - [VppRoutePath("0.0.0.0", - self.pg1.sw_if_index)]).add_vpp_config() - rt6 = VppIpRoute(self, self.pg1.local_ip6, 64, - [VppRoutePath("0.0.0.0", - self.pg1.sw_if_index)]).add_vpp_config() - - p1 = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IP(src=self.pg1.remote_ip4, - dst=self.pg1.remote_ip4) / - UDP(sport=1234, dport=5678) / - Raw(b'0xa' * 640)) + rt4 = VppIpRoute( + self, + self.pg1.local_ip4, + 24, + [VppRoutePath("0.0.0.0", self.pg1.sw_if_index)], + ).add_vpp_config() + rt6 = VppIpRoute( + self, + self.pg1.local_ip6, + 64, + [VppRoutePath("0.0.0.0", self.pg1.sw_if_index)], + ).add_vpp_config() + + p1 = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg1.remote_ip4, dst=self.pg1.remote_ip4) + / UDP(sport=1234, dport=5678) + / Raw(b"0xa" * 640) + ) # inject into table 0 rx = self.send_and_expect(self.pg0, [p1], self.pg1) @@ -3050,5 +3258,5 @@ class TestIPv4ItfRebind(VppTestCase): i.admin_down() -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_ip4_irb.py b/test/test_ip4_irb.py index de5231c7dca..ac3b30ba71d 100644 --- a/test/test_ip4_irb.py +++ b/test/test_ip4_irb.py @@ -66,12 +66,16 @@ class TestIpIrb(VppTestCase): # Create BD with MAC learning enabled and put interfaces to this BD cls.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=cls.bvi0.sw_if_index, bd_id=cls.bd_id, - port_type=L2_PORT_TYPE.BVI) - cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=cls.pg0.sw_if_index, - bd_id=cls.bd_id) - cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=cls.pg1.sw_if_index, - bd_id=cls.bd_id) + rx_sw_if_index=cls.bvi0.sw_if_index, + bd_id=cls.bd_id, + port_type=L2_PORT_TYPE.BVI, + ) + cls.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=cls.pg0.sw_if_index, bd_id=cls.bd_id + ) + cls.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=cls.pg1.sw_if_index, bd_id=cls.bd_id + ) # Configure IPv4 addresses on BVI interface and routed interface cls.bvi0.config_ip4() @@ -103,8 +107,7 @@ class TestIpIrb(VppTestCase): def show_commands_at_teardown(self): self.logger.info(self.vapi.cli("show l2patch")) self.logger.info(self.vapi.cli("show l2fib verbose")) - self.logger.info(self.vapi.cli("show bridge-domain %s detail" % - self.bd_id)) + self.logger.info(self.vapi.cli("show bridge-domain %s detail" % self.bd_id)) self.logger.info(self.vapi.cli("show ip neighbors")) def create_stream(self, src_ip_if, dst_ip_if, packet_sizes): @@ -113,19 +116,19 @@ class TestIpIrb(VppTestCase): remote_dst_host = choice(dst_ip_if.remote_hosts) info = self.create_packet_info(src_ip_if, dst_ip_if) payload = self.info_to_payload(info) - p = (Ether(dst=src_ip_if.local_mac, src=src_ip_if.remote_mac) / - IP(src=src_ip_if.remote_ip4, - dst=remote_dst_host.ip4) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + Ether(dst=src_ip_if.local_mac, src=src_ip_if.remote_mac) + / IP(src=src_ip_if.remote_ip4, dst=remote_dst_host.ip4) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) info.data = p.copy() size = packet_sizes[(i // 2) % len(packet_sizes)] self.extend_packet(p, size) pkts.append(p) return pkts - def create_stream_l2_to_ip(self, src_l2_if, src_ip_if, dst_ip_if, - packet_sizes): + def create_stream_l2_to_ip(self, src_l2_if, src_ip_if, dst_ip_if, packet_sizes): pkts = [] for i in range(0, 257): info = self.create_packet_info(src_ip_if, dst_ip_if) @@ -133,12 +136,12 @@ class TestIpIrb(VppTestCase): host = choice(src_l2_if.remote_hosts) - p = (Ether(src=host.mac, - dst=src_ip_if.local_mac) / - IP(src=host.ip4, - dst=dst_ip_if.remote_ip4) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + Ether(src=host.mac, dst=src_ip_if.local_mac) + / IP(src=host.ip4, dst=dst_ip_if.remote_ip4) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) info.data = p.copy() size = packet_sizes[(i // 2) % len(packet_sizes)] @@ -162,8 +165,8 @@ class TestIpIrb(VppTestCase): self.assertEqual(payload_info.dst, dst_ip_sw_if_index) next_info = self.get_next_packet_info_for_interface2( - payload_info.src, dst_ip_sw_if_index, - last_info[payload_info.src]) + payload_info.src, dst_ip_sw_if_index, last_info[payload_info.src] + ) last_info[payload_info.src] = next_info self.assertTrue(next_info is not None) saved_packet = next_info.data @@ -199,8 +202,8 @@ class TestIpIrb(VppTestCase): self.assertEqual(payload_info.dst, dst_ip_sw_if_index) next_info = self.get_next_packet_info_for_interface2( - payload_info.src, dst_ip_sw_if_index, - last_info[payload_info.src]) + payload_info.src, dst_ip_sw_if_index, last_info[payload_info.src] + ) last_info[payload_info.src] = next_info self.assertTrue(next_info is not None) self.assertEqual(packet_index, next_info.index) @@ -221,7 +224,7 @@ class TestIpIrb(VppTestCase): self.assertEqual(udp.dport, saved_packet[UDP].dport) def test_ip4_irb_1(self): - """ IPv4 IRB test 1 + """IPv4 IRB test 1 Test scenario: - ip traffic from pg2 interface must ends in both pg0 and pg1 @@ -229,8 +232,7 @@ class TestIpIrb(VppTestCase): - no l2 entry configured, pg0 and pg1 are same """ - stream = self.create_stream( - self.pg2, self.bvi0, self.pg_if_packet_sizes) + stream = self.create_stream(self.pg2, self.bvi0, self.pg_if_packet_sizes) self.pg2.add_stream(stream) self.pg_enable_capture(self.pg_interfaces) @@ -248,9 +250,11 @@ class TestIpIrb(VppTestCase): def send_and_verify_l2_to_ip(self): stream1 = self.create_stream_l2_to_ip( - self.pg0, self.bvi0, self.pg2, self.pg_if_packet_sizes) + self.pg0, self.bvi0, self.pg2, self.pg_if_packet_sizes + ) stream2 = self.create_stream_l2_to_ip( - self.pg1, self.bvi0, self.pg2, self.pg_if_packet_sizes) + self.pg1, self.bvi0, self.pg2, self.pg_if_packet_sizes + ) self.vapi.cli("clear trace") self.pg0.add_stream(stream1) self.pg1.add_stream(stream2) @@ -262,7 +266,7 @@ class TestIpIrb(VppTestCase): self.verify_capture_l2_to_ip(self.pg2, self.bvi0, rcvd) def test_ip4_irb_2(self): - """ IPv4 IRB test 2 + """IPv4 IRB test 2 Test scenario: - ip traffic from pg0 and pg1 ends on pg2 @@ -277,5 +281,5 @@ class TestIpIrb(VppTestCase): self.pg1.assert_nothing_captured(remark="UU Flood") -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_ip4_vrf_multi_instance.py b/test/test_ip4_vrf_multi_instance.py index acef6c4ff09..48c04f70e96 100644 --- a/test/test_ip4_vrf_multi_instance.py +++ b/test/test_ip4_vrf_multi_instance.py @@ -77,14 +77,14 @@ from vrf import VRFState def is_ipv4_misc(p): - """ Is packet one of uninteresting IPv4 broadcasts? """ + """Is packet one of uninteresting IPv4 broadcasts?""" if p.haslayer(ARP): return True return False class TestIp4VrfMultiInst(VppTestCase): - """ IP4 VRF Multi-instance Test Case """ + """IP4 VRF Multi-instance Test Case""" @classmethod def setUpClass(cls): @@ -102,8 +102,7 @@ class TestIp4VrfMultiInst(VppTestCase): try: # Create pg interfaces - cls.create_pg_interfaces( - range(cls.nr_of_vrfs * cls.pg_ifs_per_vrf)) + cls.create_pg_interfaces(range(cls.nr_of_vrfs * cls.pg_ifs_per_vrf)) # Packet flows mapping pg0 -> pg1, pg2 etc. cls.flows = dict() @@ -112,7 +111,8 @@ class TestIp4VrfMultiInst(VppTestCase): pg_list = [ cls.pg_interfaces[multiplicand * cls.pg_ifs_per_vrf + j] for j in range(cls.pg_ifs_per_vrf) - if (multiplicand * cls.pg_ifs_per_vrf + j) != i] + if (multiplicand * cls.pg_ifs_per_vrf + j) != i + ] cls.flows[cls.pg_interfaces[i]] = pg_list # Packet sizes - jumbo packet (9018 bytes) skipped @@ -141,7 +141,8 @@ class TestIp4VrfMultiInst(VppTestCase): set_id = i + 1 pg_list = [ cls.pg_interfaces[i * cls.pg_ifs_per_vrf + j] - for j in range(cls.pg_ifs_per_vrf)] + for j in range(cls.pg_ifs_per_vrf) + ] cls.pg_if_sets[set_id] = pg_list except Exception: @@ -173,8 +174,9 @@ class TestIp4VrfMultiInst(VppTestCase): for i in range(self.pg_ifs_per_vrf): pg_if = self.pg_if_sets[if_set_id][i] pg_if.set_table_ip4(vrf_id) - self.logger.info("pg-interface %s added to IPv4 VRF ID %d" - % (pg_if.name, vrf_id)) + self.logger.info( + "pg-interface %s added to IPv4 VRF ID %d" % (pg_if.name, vrf_id) + ) if pg_if not in self.pg_in_vrf: self.pg_in_vrf.append(pg_if) if pg_if in self.pg_not_in_vrf: @@ -194,7 +196,7 @@ class TestIp4VrfMultiInst(VppTestCase): for i in range(count): vrf_id = i + start - self.vapi.ip_table_add_del(is_add=1, table={'table_id': vrf_id}) + self.vapi.ip_table_add_del(is_add=1, table={"table_id": vrf_id}) self.logger.info("IPv4 VRF ID %d created" % vrf_id) if vrf_id not in self.vrf_list: self.vrf_list.append(vrf_id) @@ -204,8 +206,7 @@ class TestIp4VrfMultiInst(VppTestCase): self.logger.debug(self.vapi.ppcli("show ip fib")) self.logger.debug(self.vapi.ppcli("show ip4 neighbors")) - def create_vrf_by_id_and_assign_interfaces(self, set_id, - vrf_id=0xffffffff): + def create_vrf_by_id_and_assign_interfaces(self, set_id, vrf_id=0xFFFFFFFF): """ Create a FIB table / VRF by vrf_id, put 3 pg-ip4 interfaces to FIB table / VRF. @@ -213,7 +214,7 @@ class TestIp4VrfMultiInst(VppTestCase): :param int vrf_id: Required table ID / VRF ID. \ (Default value = 0xffffffff, ID will be selected automatically) """ - ret = self.vapi.ip_table_allocate(table={'table_id': vrf_id}) + ret = self.vapi.ip_table_allocate(table={"table_id": vrf_id}) vrf_id = ret.table.table_id self.logger.info("IPv4 VRF ID %d created" % vrf_id) if vrf_id not in self.vrf_list: @@ -234,7 +235,7 @@ class TestIp4VrfMultiInst(VppTestCase): """ if if_set_id is None: if_set_id = vrf_id - self.vapi.ip_table_flush(table={'table_id': vrf_id}) + self.vapi.ip_table_flush(table={"table_id": vrf_id}) if vrf_id in self.vrf_list: self.vrf_list.remove(vrf_id) if vrf_id not in self.vrf_reset_list: @@ -249,7 +250,7 @@ class TestIp4VrfMultiInst(VppTestCase): self.logger.info("IPv4 VRF ID %d reset finished" % vrf_id) self.logger.debug(self.vapi.ppcli("show ip fib")) self.logger.debug(self.vapi.ppcli("show ip neighbors")) - self.vapi.ip_table_add_del(is_add=0, table={'table_id': vrf_id}) + self.vapi.ip_table_add_del(is_add=0, table={"table_id": vrf_id}) def create_stream(self, src_if, packet_sizes): """ @@ -266,16 +267,20 @@ class TestIp4VrfMultiInst(VppTestCase): src_host = random.choice(src_hosts) pkt_info = self.create_packet_info(src_if, dst_if) payload = self.info_to_payload(pkt_info) - p = (Ether(dst=src_if.local_mac, src=src_host.mac) / - IP(src=src_host.ip4, dst=dst_host.ip4) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=src_host.mac) + / IP(src=src_host.ip4, dst=dst_host.ip4) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) pkt_info.data = p.copy() size = random.choice(packet_sizes) self.extend_packet(p, size) pkts.append(p) - self.logger.debug("Input stream created for port %s. Length: %u pkt(s)" - % (src_if.name, len(pkts))) + self.logger.debug( + "Input stream created for port %s. Length: %u pkt(s)" + % (src_if.name, len(pkts)) + ) return pkts def create_stream_crosswise_vrf(self, src_if, vrf_id, packet_sizes): @@ -298,16 +303,20 @@ class TestIp4VrfMultiInst(VppTestCase): src_host = random.choice(src_hosts) pkt_info = self.create_packet_info(src_if, dst_if) payload = self.info_to_payload(pkt_info) - p = (Ether(dst=src_if.local_mac, src=src_host.mac) / - IP(src=src_host.ip4, dst=dst_host.ip4) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=src_host.mac) + / IP(src=src_host.ip4, dst=dst_host.ip4) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) pkt_info.data = p.copy() size = random.choice(packet_sizes) self.extend_packet(p, size) pkts.append(p) - self.logger.debug("Input stream created for port %s. Length: %u pkt(s)" - % (src_if.name, len(pkts))) + self.logger.debug( + "Input stream created for port %s. Length: %u pkt(s)" + % (src_if.name, len(pkts)) + ) return pkts def verify_capture(self, pg_if, capture): @@ -328,11 +337,13 @@ class TestIp4VrfMultiInst(VppTestCase): payload_info = self.payload_to_info(packet[Raw]) packet_index = payload_info.index self.assertEqual(payload_info.dst, dst_sw_if_index) - self.logger.debug("Got packet on port %s: src=%u (id=%u)" % - (pg_if.name, payload_info.src, packet_index)) + self.logger.debug( + "Got packet on port %s: src=%u (id=%u)" + % (pg_if.name, payload_info.src, packet_index) + ) next_info = self.get_next_packet_info_for_interface2( - payload_info.src, dst_sw_if_index, - last_info[payload_info.src]) + payload_info.src, dst_sw_if_index, last_info[payload_info.src] + ) last_info[payload_info.src] = next_info self.assertIsNotNone(next_info) self.assertEqual(packet_index, next_info.index) @@ -347,11 +358,13 @@ class TestIp4VrfMultiInst(VppTestCase): raise for i in self.pg_interfaces: remaining_packet = self.get_next_packet_info_for_interface2( - i, dst_sw_if_index, last_info[i.sw_if_index]) + i, dst_sw_if_index, last_info[i.sw_if_index] + ) self.assertIsNone( remaining_packet, - "Port %u: Packet expected from source %u didn't arrive" % - (dst_sw_if_index, i.sw_if_index)) + "Port %u: Packet expected from source %u didn't arrive" + % (dst_sw_if_index, i.sw_if_index), + ) def verify_vrf(self, vrf_id, if_set_id=None): """ @@ -415,8 +428,9 @@ class TestIp4VrfMultiInst(VppTestCase): capture = pg_if.get_capture(remark="interface is in VRF") self.verify_capture(pg_if, capture) elif pg_if in self.pg_not_in_vrf: - pg_if.assert_nothing_captured(remark="interface is not in VRF", - filter_out_fn=is_ipv4_misc) + pg_if.assert_nothing_captured( + remark="interface is not in VRF", filter_out_fn=is_ipv4_misc + ) self.logger.debug("No capture for interface %s" % pg_if.name) else: raise Exception("Unknown interface: %s" % pg_if.name) @@ -436,7 +450,8 @@ class TestIp4VrfMultiInst(VppTestCase): for vrf_id in self.vrf_list: for pg_if in self.pg_if_sets[vrf_id]: pkts = self.create_stream_crosswise_vrf( - pg_if, vrf_id, self.pg_if_packet_sizes) + pg_if, vrf_id, self.pg_if_packet_sizes + ) pg_if.add_stream(pkts) # Enable packet capture and start packet sending @@ -446,29 +461,27 @@ class TestIp4VrfMultiInst(VppTestCase): # Verify # Verify outgoing packet streams per packet-generator interface for pg_if in self.pg_interfaces: - pg_if.assert_nothing_captured(remark="interface is in other VRF", - filter_out_fn=is_ipv4_misc) + pg_if.assert_nothing_captured( + remark="interface is in other VRF", filter_out_fn=is_ipv4_misc + ) self.logger.debug("No capture for interface %s" % pg_if.name) def test_ip4_vrf_01(self): - """ IP4 VRF Multi-instance test 1 - create 4 VRFs - """ + """IP4 VRF Multi-instance test 1 - create 4 VRFs""" # Config 1 # Create 4 VRFs self.create_vrf_and_assign_interfaces(4) # Verify 1 for vrf_id in self.vrf_list: - self.assert_equal(self.verify_vrf(vrf_id), - VRFState.configured, VRFState) + self.assert_equal(self.verify_vrf(vrf_id), VRFState.configured, VRFState) # Test 1 self.run_verify_test() self.run_crosswise_vrf_test() def test_ip4_vrf_02(self): - """ IP4 VRF Multi-instance test 2 - reset 2 VRFs - """ + """IP4 VRF Multi-instance test 2 - reset 2 VRFs""" # Config 2 # Reset 2 VRFs self.reset_vrf_and_remove_from_vrf_list(1) @@ -476,19 +489,16 @@ class TestIp4VrfMultiInst(VppTestCase): # Verify 2 for vrf_id in self.vrf_reset_list: - self.assert_equal(self.verify_vrf(vrf_id), - VRFState.reset, VRFState) + self.assert_equal(self.verify_vrf(vrf_id), VRFState.reset, VRFState) for vrf_id in self.vrf_list: - self.assert_equal(self.verify_vrf(vrf_id), - VRFState.configured, VRFState) + self.assert_equal(self.verify_vrf(vrf_id), VRFState.configured, VRFState) # Test 2 self.run_verify_test() self.run_crosswise_vrf_test() def test_ip4_vrf_03(self): - """ IP4 VRF Multi-instance 3 - add 2 VRFs - """ + """IP4 VRF Multi-instance 3 - add 2 VRFs""" # Config 3 # Add 1 of reset VRFs and 1 new VRF self.create_vrf_and_assign_interfaces(1) @@ -496,19 +506,16 @@ class TestIp4VrfMultiInst(VppTestCase): # Verify 3 for vrf_id in self.vrf_reset_list: - self.assert_equal(self.verify_vrf(vrf_id), - VRFState.reset, VRFState) + self.assert_equal(self.verify_vrf(vrf_id), VRFState.reset, VRFState) for vrf_id in self.vrf_list: - self.assert_equal(self.verify_vrf(vrf_id), - VRFState.configured, VRFState) + self.assert_equal(self.verify_vrf(vrf_id), VRFState.configured, VRFState) # Test 3 self.run_verify_test() self.run_crosswise_vrf_test() def test_ip4_vrf_04(self): - """ IP4 VRF Multi-instance test 4 - reset 4 VRFs - """ + """IP4 VRF Multi-instance test 4 - reset 4 VRFs""" # Config 4 # Reset all VRFs (i.e. no VRF except VRF=0 configured) for i in range(len(self.vrf_list)): @@ -516,20 +523,20 @@ class TestIp4VrfMultiInst(VppTestCase): # Verify 4 for vrf_id in self.vrf_reset_list: - self.assert_equal(self.verify_vrf(vrf_id), - VRFState.reset, VRFState) + self.assert_equal(self.verify_vrf(vrf_id), VRFState.reset, VRFState) vrf_list_length = len(self.vrf_list) self.assertEqual( - vrf_list_length, 0, - "List of configured VRFs is not empty: %s != 0" % vrf_list_length) + vrf_list_length, + 0, + "List of configured VRFs is not empty: %s != 0" % vrf_list_length, + ) # Test 4 self.run_verify_test() self.run_crosswise_vrf_test() def test_ip4_vrf_05(self): - """ IP4 VRF Multi-instance test 5 - id allocation - """ + """IP4 VRF Multi-instance test 5 - id allocation""" # Config 5 # Create several VRFs # Set vrf_id manually first @@ -542,8 +549,9 @@ class TestIp4VrfMultiInst(VppTestCase): # Verify 5 self.assert_equal(self.verify_vrf(1, 1), VRFState.configured, VRFState) for i, vrf in enumerate(auto_vrf_id): - self.assert_equal(self.verify_vrf(vrf, i+2), - VRFState.configured, VRFState) + self.assert_equal( + self.verify_vrf(vrf, i + 2), VRFState.configured, VRFState + ) # Test 5 self.run_verify_test() @@ -552,18 +560,20 @@ class TestIp4VrfMultiInst(VppTestCase): # Reset VRFs self.reset_vrf_and_remove_from_vrf_list(1) for i, vrf in enumerate(auto_vrf_id): - self.reset_vrf_and_remove_from_vrf_list(vrf, i+2) + self.reset_vrf_and_remove_from_vrf_list(vrf, i + 2) # Verify 5.1 self.assert_equal(self.verify_vrf(1, 1), VRFState.reset, VRFState) for i, vrf in enumerate(auto_vrf_id): - self.assert_equal(self.verify_vrf(vrf, i+2), - VRFState.reset, VRFState) + self.assert_equal(self.verify_vrf(vrf, i + 2), VRFState.reset, VRFState) vrf_list_length = len(self.vrf_list) self.assertEqual( - vrf_list_length, 0, - "List of configured VRFs is not empty: %s != 0" % vrf_list_length) + vrf_list_length, + 0, + "List of configured VRFs is not empty: %s != 0" % vrf_list_length, + ) + -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_ip6.py b/test/test_ip6.py index c86cb777aed..ca153dba0e6 100644 --- a/test/test_ip6.py +++ b/test/test_ip6.py @@ -9,26 +9,58 @@ import scapy.compat import scapy.layers.inet6 as inet6 from scapy.layers.inet import UDP, IP from scapy.contrib.mpls import MPLS -from scapy.layers.inet6 import IPv6, ICMPv6ND_NS, ICMPv6ND_RS, \ - ICMPv6ND_RA, ICMPv6NDOptMTU, ICMPv6NDOptSrcLLAddr, ICMPv6NDOptPrefixInfo, \ - ICMPv6ND_NA, ICMPv6NDOptDstLLAddr, ICMPv6DestUnreach, icmp6types, \ - ICMPv6TimeExceeded, ICMPv6EchoRequest, ICMPv6EchoReply, \ - IPv6ExtHdrHopByHop, ICMPv6MLReport2, ICMPv6MLDMultAddrRec +from scapy.layers.inet6 import ( + IPv6, + ICMPv6ND_NS, + ICMPv6ND_RS, + ICMPv6ND_RA, + ICMPv6NDOptMTU, + ICMPv6NDOptSrcLLAddr, + ICMPv6NDOptPrefixInfo, + ICMPv6ND_NA, + ICMPv6NDOptDstLLAddr, + ICMPv6DestUnreach, + icmp6types, + ICMPv6TimeExceeded, + ICMPv6EchoRequest, + ICMPv6EchoReply, + IPv6ExtHdrHopByHop, + ICMPv6MLReport2, + ICMPv6MLDMultAddrRec, +) from scapy.layers.l2 import Ether, Dot1Q, GRE from scapy.packet import Raw -from scapy.utils6 import in6_getnsma, in6_getnsmac, in6_ptop, in6_islladdr, \ - in6_mactoifaceid +from scapy.utils6 import ( + in6_getnsma, + in6_getnsmac, + in6_ptop, + in6_islladdr, + in6_mactoifaceid, +) from six import moves from framework import VppTestCase, VppTestRunner, tag_run_solo from util import ppp, ip6_normalize, mk_ll_addr from vpp_papi import VppEnum from vpp_ip import DpoProto, VppIpPuntPolicer, VppIpPuntRedirect, VppIpPathMtu -from vpp_ip_route import VppIpRoute, VppRoutePath, find_route, VppIpMRoute, \ - VppMRoutePath, VppMplsIpBind, \ - VppMplsRoute, VppMplsTable, VppIpTable, FibPathType, FibPathProto, \ - VppIpInterfaceAddress, find_route_in_dump, find_mroute_in_dump, \ - VppIp6LinkLocalAddress, VppIpRouteV2 +from vpp_ip_route import ( + VppIpRoute, + VppRoutePath, + find_route, + VppIpMRoute, + VppMRoutePath, + VppMplsIpBind, + VppMplsRoute, + VppMplsTable, + VppIpTable, + FibPathType, + FibPathProto, + VppIpInterfaceAddress, + find_route_in_dump, + find_mroute_in_dump, + VppIp6LinkLocalAddress, + VppIpRouteV2, +) from vpp_neighbor import find_nbr, VppNeighbor from vpp_ipip_tun_interface import VppIpIpTunInterface from vpp_pg_interface import is_ipv6_misc @@ -61,13 +93,11 @@ class TestIPv6ND(VppTestCase): # the rx'd RA should be addressed to the sender's source self.assertTrue(rx.haslayer(ICMPv6ND_RA)) - self.assertEqual(in6_ptop(rx[IPv6].dst), - in6_ptop(dst_ip)) + self.assertEqual(in6_ptop(rx[IPv6].dst), in6_ptop(dst_ip)) # and come from the router's link local self.assertTrue(in6_islladdr(rx[IPv6].src)) - self.assertEqual(in6_ptop(rx[IPv6].src), - in6_ptop(mk_ll_addr(intf.local_mac))) + self.assertEqual(in6_ptop(rx[IPv6].src), in6_ptop(mk_ll_addr(intf.local_mac))) def validate_na(self, intf, rx, dst_ip=None, tgt_ip=None): if not dst_ip: @@ -83,12 +113,10 @@ class TestIPv6ND(VppTestCase): # the rx'd NA should be addressed to the sender's source self.assertTrue(rx.haslayer(ICMPv6ND_NA)) - self.assertEqual(in6_ptop(rx[IPv6].dst), - in6_ptop(dst_ip)) + self.assertEqual(in6_ptop(rx[IPv6].dst), in6_ptop(dst_ip)) # and come from the target address - self.assertEqual( - in6_ptop(rx[IPv6].src), in6_ptop(tgt_ip)) + self.assertEqual(in6_ptop(rx[IPv6].src), in6_ptop(tgt_ip)) # Dest link-layer options should have the router's MAC dll = rx[ICMPv6NDOptDstLLAddr] @@ -106,23 +134,22 @@ class TestIPv6ND(VppTestCase): # the rx'd NS should be addressed to an mcast address # derived from the target address - self.assertEqual( - in6_ptop(rx[IPv6].dst), in6_ptop(dst_ip)) + self.assertEqual(in6_ptop(rx[IPv6].dst), in6_ptop(dst_ip)) # expect the tgt IP in the NS header ns = rx[ICMPv6ND_NS] self.assertEqual(in6_ptop(ns.tgt), in6_ptop(tgt_ip)) # packet is from the router's local address - self.assertEqual( - in6_ptop(rx[IPv6].src), intf.local_ip6) + self.assertEqual(in6_ptop(rx[IPv6].src), intf.local_ip6) # Src link-layer options should have the router's MAC sll = rx[ICMPv6NDOptSrcLLAddr] self.assertEqual(sll.lladdr, intf.local_mac) - def send_and_expect_ra(self, intf, pkts, remark, dst_ip=None, - filter_out_fn=is_ipv6_misc): + def send_and_expect_ra( + self, intf, pkts, remark, dst_ip=None, filter_out_fn=is_ipv6_misc + ): intf.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -132,9 +159,9 @@ class TestIPv6ND(VppTestCase): rx = rx[0] self.validate_ra(intf, rx, dst_ip) - def send_and_expect_na(self, intf, pkts, remark, dst_ip=None, - tgt_ip=None, - filter_out_fn=is_ipv6_misc): + def send_and_expect_na( + self, intf, pkts, remark, dst_ip=None, tgt_ip=None, filter_out_fn=is_ipv6_misc + ): intf.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -144,8 +171,9 @@ class TestIPv6ND(VppTestCase): rx = rx[0] self.validate_na(intf, rx, dst_ip, tgt_ip) - def send_and_expect_ns(self, tx_intf, rx_intf, pkts, tgt_ip, - filter_out_fn=is_ipv6_misc): + def send_and_expect_ns( + self, tx_intf, rx_intf, pkts, tgt_ip, filter_out_fn=is_ipv6_misc + ): self.vapi.cli("clear trace") tx_intf.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) @@ -168,7 +196,7 @@ class TestIPv6ND(VppTestCase): @tag_run_solo class TestIPv6(TestIPv6ND): - """ IPv6 Test Case """ + """IPv6 Test Case""" @classmethod def setUpClass(cls): @@ -268,17 +296,26 @@ class TestIPv6(TestIPv6ND): :param VppInterface src_if: Interface to create packet stream for. """ hdr_ext = 4 if isinstance(src_if, VppSubInterface) else 0 - pkt_tmpl = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - IPv6(src=src_if.remote_ip6) / - inet6.UDP(sport=1234, dport=1234)) - - pkts = [self.modify_packet(src_if, i, pkt_tmpl) - for i in moves.range(self.pg_if_packet_sizes[0], - self.pg_if_packet_sizes[1], 10)] - pkts_b = [self.modify_packet(src_if, i, pkt_tmpl) - for i in moves.range(self.pg_if_packet_sizes[1] + hdr_ext, - self.pg_if_packet_sizes[2] + hdr_ext, - 50)] + pkt_tmpl = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / IPv6(src=src_if.remote_ip6) + / inet6.UDP(sport=1234, dport=1234) + ) + + pkts = [ + self.modify_packet(src_if, i, pkt_tmpl) + for i in moves.range( + self.pg_if_packet_sizes[0], self.pg_if_packet_sizes[1], 10 + ) + ] + pkts_b = [ + self.modify_packet(src_if, i, pkt_tmpl) + for i in moves.range( + self.pg_if_packet_sizes[1] + hdr_ext, + self.pg_if_packet_sizes[2] + hdr_ext, + 50, + ) + ] pkts.extend(pkts_b) return pkts @@ -296,7 +333,7 @@ class TestIPv6(TestIPv6ND): last_info[i.sw_if_index] = None is_sub_if = False dst_sw_if_index = dst_if.sw_if_index - if hasattr(dst_if, 'parent'): + if hasattr(dst_if, "parent"): is_sub_if = True for packet in capture: if is_sub_if: @@ -310,45 +347,47 @@ class TestIPv6(TestIPv6ND): packet_index = payload_info.index self.assertEqual(payload_info.dst, dst_sw_if_index) self.logger.debug( - "Got packet on port %s: src=%u (id=%u)" % - (dst_if.name, payload_info.src, packet_index)) + "Got packet on port %s: src=%u (id=%u)" + % (dst_if.name, payload_info.src, packet_index) + ) next_info = self.get_next_packet_info_for_interface2( - payload_info.src, dst_sw_if_index, - last_info[payload_info.src]) + payload_info.src, dst_sw_if_index, last_info[payload_info.src] + ) last_info[payload_info.src] = next_info self.assertTrue(next_info is not None) self.assertEqual(packet_index, next_info.index) saved_packet = next_info.data # Check standard fields - self.assertEqual( - ip.src, saved_packet[IPv6].src) - self.assertEqual( - ip.dst, saved_packet[IPv6].dst) - self.assertEqual( - udp.sport, saved_packet[inet6.UDP].sport) - self.assertEqual( - udp.dport, saved_packet[inet6.UDP].dport) + self.assertEqual(ip.src, saved_packet[IPv6].src) + self.assertEqual(ip.dst, saved_packet[IPv6].dst) + self.assertEqual(udp.sport, saved_packet[inet6.UDP].sport) + self.assertEqual(udp.dport, saved_packet[inet6.UDP].dport) except: self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise for i in self.interfaces: remaining_packet = self.get_next_packet_info_for_interface2( - i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index]) - self.assertTrue(remaining_packet is None, - "Interface %s: Packet expected from interface %s " - "didn't arrive" % (dst_if.name, i.name)) + i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index] + ) + self.assertTrue( + remaining_packet is None, + "Interface %s: Packet expected from interface %s " + "didn't arrive" % (dst_if.name, i.name), + ) def test_next_header_anomaly(self): - """ IPv6 next header anomaly test + """IPv6 next header anomaly test Test scenario: - ipv6 next header field = Fragment Header (44) - next header is ICMPv6 Echo Request - wait for reassembly """ - pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6, nh=44) / - ICMPv6EchoRequest()) + pkt = ( + Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6, nh=44) + / ICMPv6EchoRequest() + ) self.pg0.add_stream(pkt) self.pg_start() @@ -357,7 +396,7 @@ class TestIPv6(TestIPv6ND): self.sleep(10) def test_fib(self): - """ IPv6 FIB test + """IPv6 FIB test Test scenario: - Create IPv6 stream for pg0 interface @@ -383,7 +422,7 @@ class TestIPv6(TestIPv6ND): self.verify_capture(i, pkts) def test_ns(self): - """ IPv6 Neighbour Solicitation Exceptions + """IPv6 Neighbour Solicitation Exceptions Test scenario: - Send an NS Sourced from an address not covered by the link sub-net @@ -397,16 +436,17 @@ class TestIPv6(TestIPv6ND): nsma = in6_getnsma(inet_pton(AF_INET6, self.pg0.local_ip6)) d = inet_ntop(AF_INET6, nsma) - p = (Ether(dst=in6_getnsmac(nsma)) / - IPv6(dst=d, src="2002::2") / - ICMPv6ND_NS(tgt=self.pg0.local_ip6) / - ICMPv6NDOptSrcLLAddr( - lladdr=self.pg0.remote_mac)) + p = ( + Ether(dst=in6_getnsmac(nsma)) + / IPv6(dst=d, src="2002::2") + / ICMPv6ND_NS(tgt=self.pg0.local_ip6) + / ICMPv6NDOptSrcLLAddr(lladdr=self.pg0.remote_mac) + ) pkts = [p] self.send_and_assert_no_replies( - self.pg0, pkts, - "No response to NS source by address not on sub-net") + self.pg0, pkts, "No response to NS source by address not on sub-net" + ) # # An NS for sent to a solicited mcast group the router is @@ -416,16 +456,17 @@ class TestIPv6(TestIPv6ND): nsma = in6_getnsma(inet_pton(AF_INET6, "fd::ffff")) d = inet_ntop(AF_INET6, nsma) - p = (Ether(dst=in6_getnsmac(nsma)) / - IPv6(dst=d, src=self.pg0.remote_ip6) / - ICMPv6ND_NS(tgt=self.pg0.local_ip6) / - ICMPv6NDOptSrcLLAddr( - lladdr=self.pg0.remote_mac)) + p = ( + Ether(dst=in6_getnsmac(nsma)) + / IPv6(dst=d, src=self.pg0.remote_ip6) + / ICMPv6ND_NS(tgt=self.pg0.local_ip6) + / ICMPv6NDOptSrcLLAddr(lladdr=self.pg0.remote_mac) + ) pkts = [p] self.send_and_assert_no_replies( - self.pg0, pkts, - "No response to NS sent to unjoined mcast address") + self.pg0, pkts, "No response to NS sent to unjoined mcast address" + ) # # An NS whose target address is one the router does not own @@ -433,88 +474,94 @@ class TestIPv6(TestIPv6ND): nsma = in6_getnsma(inet_pton(AF_INET6, self.pg0.local_ip6)) d = inet_ntop(AF_INET6, nsma) - p = (Ether(dst=in6_getnsmac(nsma)) / - IPv6(dst=d, src=self.pg0.remote_ip6) / - ICMPv6ND_NS(tgt="fd::ffff") / - ICMPv6NDOptSrcLLAddr( - lladdr=self.pg0.remote_mac)) + p = ( + Ether(dst=in6_getnsmac(nsma)) + / IPv6(dst=d, src=self.pg0.remote_ip6) + / ICMPv6ND_NS(tgt="fd::ffff") + / ICMPv6NDOptSrcLLAddr(lladdr=self.pg0.remote_mac) + ) pkts = [p] - self.send_and_assert_no_replies(self.pg0, pkts, - "No response to NS for unknown target") + self.send_and_assert_no_replies( + self.pg0, pkts, "No response to NS for unknown target" + ) # # A neighbor entry that has no associated FIB-entry # self.pg0.generate_remote_hosts(4) - nd_entry = VppNeighbor(self, - self.pg0.sw_if_index, - self.pg0.remote_hosts[2].mac, - self.pg0.remote_hosts[2].ip6, - is_no_fib_entry=1) + nd_entry = VppNeighbor( + self, + self.pg0.sw_if_index, + self.pg0.remote_hosts[2].mac, + self.pg0.remote_hosts[2].ip6, + is_no_fib_entry=1, + ) nd_entry.add_vpp_config() # # check we have the neighbor, but no route # - self.assertTrue(find_nbr(self, - self.pg0.sw_if_index, - self.pg0._remote_hosts[2].ip6)) - self.assertFalse(find_route(self, - self.pg0._remote_hosts[2].ip6, - 128)) + self.assertTrue( + find_nbr(self, self.pg0.sw_if_index, self.pg0._remote_hosts[2].ip6) + ) + self.assertFalse(find_route(self, self.pg0._remote_hosts[2].ip6, 128)) # # send an NS from a link local address to the interface's global # address # - p = (Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac) / - IPv6( - dst=d, src=self.pg0._remote_hosts[2].ip6_ll) / - ICMPv6ND_NS(tgt=self.pg0.local_ip6) / - ICMPv6NDOptSrcLLAddr( - lladdr=self.pg0.remote_mac)) + p = ( + Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac) + / IPv6(dst=d, src=self.pg0._remote_hosts[2].ip6_ll) + / ICMPv6ND_NS(tgt=self.pg0.local_ip6) + / ICMPv6NDOptSrcLLAddr(lladdr=self.pg0.remote_mac) + ) - self.send_and_expect_na(self.pg0, p, - "NS from link-local", - dst_ip=self.pg0._remote_hosts[2].ip6_ll, - tgt_ip=self.pg0.local_ip6) + self.send_and_expect_na( + self.pg0, + p, + "NS from link-local", + dst_ip=self.pg0._remote_hosts[2].ip6_ll, + tgt_ip=self.pg0.local_ip6, + ) # # we should have learned an ND entry for the peer's link-local # but not inserted a route to it in the FIB # - self.assertTrue(find_nbr(self, - self.pg0.sw_if_index, - self.pg0._remote_hosts[2].ip6_ll)) - self.assertFalse(find_route(self, - self.pg0._remote_hosts[2].ip6_ll, - 128)) + self.assertTrue( + find_nbr(self, self.pg0.sw_if_index, self.pg0._remote_hosts[2].ip6_ll) + ) + self.assertFalse(find_route(self, self.pg0._remote_hosts[2].ip6_ll, 128)) # # An NS to the router's own Link-local # - p = (Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac) / - IPv6( - dst=d, src=self.pg0._remote_hosts[3].ip6_ll) / - ICMPv6ND_NS(tgt=self.pg0.local_ip6_ll) / - ICMPv6NDOptSrcLLAddr( - lladdr=self.pg0.remote_mac)) + p = ( + Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac) + / IPv6(dst=d, src=self.pg0._remote_hosts[3].ip6_ll) + / ICMPv6ND_NS(tgt=self.pg0.local_ip6_ll) + / ICMPv6NDOptSrcLLAddr(lladdr=self.pg0.remote_mac) + ) - self.send_and_expect_na(self.pg0, p, - "NS to/from link-local", - dst_ip=self.pg0._remote_hosts[3].ip6_ll, - tgt_ip=self.pg0.local_ip6_ll) + self.send_and_expect_na( + self.pg0, + p, + "NS to/from link-local", + dst_ip=self.pg0._remote_hosts[3].ip6_ll, + tgt_ip=self.pg0.local_ip6_ll, + ) # # do not respond to a NS for the peer's address # - p = (Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac) / - IPv6(dst=d, - src=self.pg0._remote_hosts[3].ip6_ll) / - ICMPv6ND_NS(tgt=self.pg0._remote_hosts[3].ip6_ll) / - ICMPv6NDOptSrcLLAddr( - lladdr=self.pg0.remote_mac)) + p = ( + Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac) + / IPv6(dst=d, src=self.pg0._remote_hosts[3].ip6_ll) + / ICMPv6ND_NS(tgt=self.pg0._remote_hosts[3].ip6_ll) + / ICMPv6NDOptSrcLLAddr(lladdr=self.pg0.remote_mac) + ) self.send_and_assert_no_replies(self.pg0, p) @@ -522,15 +569,13 @@ class TestIPv6(TestIPv6ND): # we should have learned an ND entry for the peer's link-local # but not inserted a route to it in the FIB # - self.assertTrue(find_nbr(self, - self.pg0.sw_if_index, - self.pg0._remote_hosts[3].ip6_ll)) - self.assertFalse(find_route(self, - self.pg0._remote_hosts[3].ip6_ll, - 128)) + self.assertTrue( + find_nbr(self, self.pg0.sw_if_index, self.pg0._remote_hosts[3].ip6_ll) + ) + self.assertFalse(find_route(self, self.pg0._remote_hosts[3].ip6_ll, 128)) def test_ns_duplicates(self): - """ ND Duplicates""" + """ND Duplicates""" # # Generate some hosts on the LAN @@ -540,26 +585,30 @@ class TestIPv6(TestIPv6ND): # # Add host 1 on pg1 and pg2 # - ns_pg1 = VppNeighbor(self, - self.pg1.sw_if_index, - self.pg1.remote_hosts[1].mac, - self.pg1.remote_hosts[1].ip6) + ns_pg1 = VppNeighbor( + self, + self.pg1.sw_if_index, + self.pg1.remote_hosts[1].mac, + self.pg1.remote_hosts[1].ip6, + ) ns_pg1.add_vpp_config() - ns_pg2 = VppNeighbor(self, - self.pg2.sw_if_index, - self.pg2.remote_mac, - self.pg1.remote_hosts[1].ip6) + ns_pg2 = VppNeighbor( + self, + self.pg2.sw_if_index, + self.pg2.remote_mac, + self.pg1.remote_hosts[1].ip6, + ) ns_pg2.add_vpp_config() # # IP packet destined for pg1 remote host arrives on pg1 again. # - p = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, - dst=self.pg1.remote_hosts[1].ip6) / - inet6.UDP(sport=1234, dport=1234) / - Raw()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_hosts[1].ip6) + / inet6.UDP(sport=1234, dport=1234) + / Raw() + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) @@ -567,11 +616,13 @@ class TestIPv6(TestIPv6ND): rx1 = self.pg1.get_capture(1) - self.verify_ip(rx1[0], - self.pg1.local_mac, - self.pg1.remote_hosts[1].mac, - self.pg0.remote_ip6, - self.pg1.remote_hosts[1].ip6) + self.verify_ip( + rx1[0], + self.pg1.local_mac, + self.pg1.remote_hosts[1].mac, + self.pg0.remote_ip6, + self.pg1.remote_hosts[1].ip6, + ) # # remove the duplicate on pg1 @@ -579,8 +630,7 @@ class TestIPv6(TestIPv6ND): # ns_pg1.remove_vpp_config() - self.send_and_expect_ns(self.pg0, self.pg1, - p, self.pg1.remote_hosts[1].ip6) + self.send_and_expect_ns(self.pg0, self.pg1, p, self.pg1.remote_hosts[1].ip6) # # Add it back @@ -593,14 +643,15 @@ class TestIPv6(TestIPv6ND): rx1 = self.pg1.get_capture(1) - self.verify_ip(rx1[0], - self.pg1.local_mac, - self.pg1.remote_hosts[1].mac, - self.pg0.remote_ip6, - self.pg1.remote_hosts[1].ip6) + self.verify_ip( + rx1[0], + self.pg1.local_mac, + self.pg1.remote_hosts[1].mac, + self.pg0.remote_ip6, + self.pg1.remote_hosts[1].ip6, + ) - def validate_ra(self, intf, rx, dst_ip=None, src_ip=None, - mtu=9000, pi_opt=None): + def validate_ra(self, intf, rx, dst_ip=None, src_ip=None, mtu=9000, pi_opt=None): if not dst_ip: dst_ip = intf.remote_ip6 if not src_ip: @@ -614,8 +665,7 @@ class TestIPv6(TestIPv6ND): # the rx'd RA should be addressed to the sender's source self.assertTrue(rx.haslayer(ICMPv6ND_RA)) - self.assertEqual(in6_ptop(rx[IPv6].dst), - in6_ptop(dst_ip)) + self.assertEqual(in6_ptop(rx[IPv6].dst), in6_ptop(dst_ip)) # and come from the router's link local self.assertTrue(in6_islladdr(rx[IPv6].src)) @@ -631,8 +681,7 @@ class TestIPv6(TestIPv6ND): if not pi_opt: # the RA should not contain prefix information - self.assertFalse(ra.haslayer( - ICMPv6NDOptPrefixInfo)) + self.assertFalse(ra.haslayer(ICMPv6NDOptPrefixInfo)) else: raos = rx.getlayer(ICMPv6NDOptPrefixInfo, 1) @@ -642,24 +691,30 @@ class TestIPv6(TestIPv6ND): # however, the getlayer(.., 2) does give one instance. # so we cheat here and construct a new opt instance for comparison rd = ICMPv6NDOptPrefixInfo( - prefixlen=raos.prefixlen, - prefix=raos.prefix, - L=raos.L, - A=raos.A) + prefixlen=raos.prefixlen, prefix=raos.prefix, L=raos.L, A=raos.A + ) if type(pi_opt) is list: for ii in range(len(pi_opt)): self.assertEqual(pi_opt[ii], rd) - rd = rx.getlayer( - ICMPv6NDOptPrefixInfo, ii + 2) + rd = rx.getlayer(ICMPv6NDOptPrefixInfo, ii + 2) else: - self.assertEqual(pi_opt, raos, 'Expected: %s, received: %s' - % (pi_opt.show(dump=True), - raos.show(dump=True))) - - def send_and_expect_ra(self, intf, pkts, remark, dst_ip=None, - filter_out_fn=is_ipv6_misc, - opt=None, - src_ip=None): + self.assertEqual( + pi_opt, + raos, + "Expected: %s, received: %s" + % (pi_opt.show(dump=True), raos.show(dump=True)), + ) + + def send_and_expect_ra( + self, + intf, + pkts, + remark, + dst_ip=None, + filter_out_fn=is_ipv6_misc, + opt=None, + src_ip=None, + ): self.vapi.cli("clear trace") intf.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) @@ -671,7 +726,7 @@ class TestIPv6(TestIPv6ND): self.validate_ra(intf, rx, dst_ip, src_ip=src_ip, pi_opt=opt) def test_rs(self): - """ IPv6 Router Solicitation Exceptions + """IPv6 Router Solicitation Exceptions Test scenario: """ @@ -692,9 +747,11 @@ class TestIPv6(TestIPv6ND): # An RS from a link source address # - expect an RA in return # - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) / - ICMPv6ND_RS()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) + / ICMPv6ND_RS() + ) pkts = [p] self.send_and_expect_ra(self.pg0, pkts, "Genuine RS") @@ -716,26 +773,26 @@ class TestIPv6(TestIPv6ND): # An RS sent from a non-link local source # self.pg0.ip6_ra_config(send_unicast=1) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(dst=self.pg0.local_ip6, - src="2002::ffff") / - ICMPv6ND_RS()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(dst=self.pg0.local_ip6, src="2002::ffff") + / ICMPv6ND_RS() + ) pkts = [p] - self.send_and_assert_no_replies(self.pg0, pkts, - "RS from non-link source") + self.send_and_assert_no_replies(self.pg0, pkts, "RS from non-link source") # # Source an RS from a link local address # self.pg0.ip6_ra_config(send_unicast=1) ll = mk_ll_addr(self.pg0.remote_mac) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(dst=self.pg0.local_ip6, src=ll) / - ICMPv6ND_RS()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(dst=self.pg0.local_ip6, src=ll) + / ICMPv6ND_RS() + ) pkts = [p] - self.send_and_expect_ra(self.pg0, pkts, - "RS sourced from link-local", - dst_ip=ll) + self.send_and_expect_ra(self.pg0, pkts, "RS sourced from link-local", dst_ip=ll) # # Source an RS from a link local address @@ -743,12 +800,13 @@ class TestIPv6(TestIPv6ND): # self.pg0.ip6_ra_config(send_unicast=1, suppress=1) ll = mk_ll_addr(self.pg0.remote_mac) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(dst=self.pg0.local_ip6, src=ll) / - ICMPv6ND_RS()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(dst=self.pg0.local_ip6, src=ll) + / ICMPv6ND_RS() + ) pkts = [p] - self.send_and_assert_no_replies(self.pg0, pkts, - "Suppressed RS from link-local") + self.send_and_assert_no_replies(self.pg0, pkts, "Suppressed RS from link-local") # # Send the RS multicast @@ -757,13 +815,13 @@ class TestIPv6(TestIPv6ND): self.pg0.ip6_ra_config(send_unicast=1) dmac = in6_getnsmac(inet_pton(AF_INET6, "ff02::2")) ll = mk_ll_addr(self.pg0.remote_mac) - p = (Ether(dst=dmac, src=self.pg0.remote_mac) / - IPv6(dst="ff02::2", src=ll) / - ICMPv6ND_RS()) + p = ( + Ether(dst=dmac, src=self.pg0.remote_mac) + / IPv6(dst="ff02::2", src=ll) + / ICMPv6ND_RS() + ) pkts = [p] - self.send_and_expect_ra(self.pg0, pkts, - "RS sourced from link-local", - dst_ip=ll) + self.send_and_expect_ra(self.pg0, pkts, "RS sourced from link-local", dst_ip=ll) # # Source from the unspecified address ::. This happens when the RS @@ -774,209 +832,204 @@ class TestIPv6(TestIPv6ND): # it's not an error. # self.pg0.ip6_ra_config(send_unicast=1) - p = (Ether(dst=dmac, src=self.pg0.remote_mac) / - IPv6(dst="ff02::2", src="::") / - ICMPv6ND_RS()) + p = ( + Ether(dst=dmac, src=self.pg0.remote_mac) + / IPv6(dst="ff02::2", src="::") + / ICMPv6ND_RS() + ) pkts = [p] - self.send_and_expect_ra(self.pg0, pkts, - "RS sourced from unspecified", - dst_ip="ff02::1", - filter_out_fn=None) + self.send_and_expect_ra( + self.pg0, + pkts, + "RS sourced from unspecified", + dst_ip="ff02::1", + filter_out_fn=None, + ) # # Configure The RA to announce the links prefix # - self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6, - self.pg0.local_ip6_prefix_len)) + self.pg0.ip6_ra_prefix( + "%s/%s" % (self.pg0.local_ip6, self.pg0.local_ip6_prefix_len) + ) # # RAs should now contain the prefix information option # opt = ICMPv6NDOptPrefixInfo( - prefixlen=self.pg0.local_ip6_prefix_len, - prefix=self.pg0.local_ip6, - L=1, - A=1) + prefixlen=self.pg0.local_ip6_prefix_len, prefix=self.pg0.local_ip6, L=1, A=1 + ) self.pg0.ip6_ra_config(send_unicast=1) ll = mk_ll_addr(self.pg0.remote_mac) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(dst=self.pg0.local_ip6, src=ll) / - ICMPv6ND_RS()) - self.send_and_expect_ra(self.pg0, p, - "RA with prefix-info", - dst_ip=ll, - opt=opt) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(dst=self.pg0.local_ip6, src=ll) + / ICMPv6ND_RS() + ) + self.send_and_expect_ra(self.pg0, p, "RA with prefix-info", dst_ip=ll, opt=opt) # # Change the prefix info to not off-link # L-flag is clear # - self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6, - self.pg0.local_ip6_prefix_len), - off_link=1) + self.pg0.ip6_ra_prefix( + "%s/%s" % (self.pg0.local_ip6, self.pg0.local_ip6_prefix_len), off_link=1 + ) opt = ICMPv6NDOptPrefixInfo( - prefixlen=self.pg0.local_ip6_prefix_len, - prefix=self.pg0.local_ip6, - L=0, - A=1) + prefixlen=self.pg0.local_ip6_prefix_len, prefix=self.pg0.local_ip6, L=0, A=1 + ) self.pg0.ip6_ra_config(send_unicast=1) - self.send_and_expect_ra(self.pg0, p, - "RA with Prefix info with L-flag=0", - dst_ip=ll, - opt=opt) + self.send_and_expect_ra( + self.pg0, p, "RA with Prefix info with L-flag=0", dst_ip=ll, opt=opt + ) # # Change the prefix info to not off-link, no-autoconfig # L and A flag are clear in the advert # - self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6, - self.pg0.local_ip6_prefix_len), - off_link=1, - no_autoconfig=1) + self.pg0.ip6_ra_prefix( + "%s/%s" % (self.pg0.local_ip6, self.pg0.local_ip6_prefix_len), + off_link=1, + no_autoconfig=1, + ) opt = ICMPv6NDOptPrefixInfo( - prefixlen=self.pg0.local_ip6_prefix_len, - prefix=self.pg0.local_ip6, - L=0, - A=0) + prefixlen=self.pg0.local_ip6_prefix_len, prefix=self.pg0.local_ip6, L=0, A=0 + ) self.pg0.ip6_ra_config(send_unicast=1) - self.send_and_expect_ra(self.pg0, p, - "RA with Prefix info with A & L-flag=0", - dst_ip=ll, - opt=opt) + self.send_and_expect_ra( + self.pg0, p, "RA with Prefix info with A & L-flag=0", dst_ip=ll, opt=opt + ) # # Change the flag settings back to the defaults # L and A flag are set in the advert # - self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6, - self.pg0.local_ip6_prefix_len)) + self.pg0.ip6_ra_prefix( + "%s/%s" % (self.pg0.local_ip6, self.pg0.local_ip6_prefix_len) + ) opt = ICMPv6NDOptPrefixInfo( - prefixlen=self.pg0.local_ip6_prefix_len, - prefix=self.pg0.local_ip6, - L=1, - A=1) + prefixlen=self.pg0.local_ip6_prefix_len, prefix=self.pg0.local_ip6, L=1, A=1 + ) self.pg0.ip6_ra_config(send_unicast=1) - self.send_and_expect_ra(self.pg0, p, - "RA with Prefix info", - dst_ip=ll, - opt=opt) + self.send_and_expect_ra(self.pg0, p, "RA with Prefix info", dst_ip=ll, opt=opt) # # Change the prefix info to not off-link, no-autoconfig # L and A flag are clear in the advert # - self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6, - self.pg0.local_ip6_prefix_len), - off_link=1, - no_autoconfig=1) + self.pg0.ip6_ra_prefix( + "%s/%s" % (self.pg0.local_ip6, self.pg0.local_ip6_prefix_len), + off_link=1, + no_autoconfig=1, + ) opt = ICMPv6NDOptPrefixInfo( - prefixlen=self.pg0.local_ip6_prefix_len, - prefix=self.pg0.local_ip6, - L=0, - A=0) + prefixlen=self.pg0.local_ip6_prefix_len, prefix=self.pg0.local_ip6, L=0, A=0 + ) self.pg0.ip6_ra_config(send_unicast=1) - self.send_and_expect_ra(self.pg0, p, - "RA with Prefix info with A & L-flag=0", - dst_ip=ll, - opt=opt) + self.send_and_expect_ra( + self.pg0, p, "RA with Prefix info with A & L-flag=0", dst_ip=ll, opt=opt + ) # # Use the reset to defaults option to revert to defaults # L and A flag are clear in the advert # - self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6, - self.pg0.local_ip6_prefix_len), - use_default=1) + self.pg0.ip6_ra_prefix( + "%s/%s" % (self.pg0.local_ip6, self.pg0.local_ip6_prefix_len), use_default=1 + ) opt = ICMPv6NDOptPrefixInfo( - prefixlen=self.pg0.local_ip6_prefix_len, - prefix=self.pg0.local_ip6, - L=1, - A=1) + prefixlen=self.pg0.local_ip6_prefix_len, prefix=self.pg0.local_ip6, L=1, A=1 + ) self.pg0.ip6_ra_config(send_unicast=1) - self.send_and_expect_ra(self.pg0, p, - "RA with Prefix reverted to defaults", - dst_ip=ll, - opt=opt) + self.send_and_expect_ra( + self.pg0, p, "RA with Prefix reverted to defaults", dst_ip=ll, opt=opt + ) # # Advertise Another prefix. With no L-flag/A-flag # - self.pg0.ip6_ra_prefix('%s/%s' % (self.pg1.local_ip6, - self.pg1.local_ip6_prefix_len), - off_link=1, - no_autoconfig=1) + self.pg0.ip6_ra_prefix( + "%s/%s" % (self.pg1.local_ip6, self.pg1.local_ip6_prefix_len), + off_link=1, + no_autoconfig=1, + ) - opt = [ICMPv6NDOptPrefixInfo( - prefixlen=self.pg0.local_ip6_prefix_len, - prefix=self.pg0.local_ip6, - L=1, - A=1), + opt = [ + ICMPv6NDOptPrefixInfo( + prefixlen=self.pg0.local_ip6_prefix_len, + prefix=self.pg0.local_ip6, + L=1, + A=1, + ), ICMPv6NDOptPrefixInfo( prefixlen=self.pg1.local_ip6_prefix_len, prefix=self.pg1.local_ip6, L=0, - A=0)] + A=0, + ), + ] self.pg0.ip6_ra_config(send_unicast=1) ll = mk_ll_addr(self.pg0.remote_mac) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(dst=self.pg0.local_ip6, src=ll) / - ICMPv6ND_RS()) - self.send_and_expect_ra(self.pg0, p, - "RA with multiple Prefix infos", - dst_ip=ll, - opt=opt) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(dst=self.pg0.local_ip6, src=ll) + / ICMPv6ND_RS() + ) + self.send_and_expect_ra( + self.pg0, p, "RA with multiple Prefix infos", dst_ip=ll, opt=opt + ) # # Remove the first prefix-info - expect the second is still in the # advert # - self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6, - self.pg0.local_ip6_prefix_len), - is_no=1) + self.pg0.ip6_ra_prefix( + "%s/%s" % (self.pg0.local_ip6, self.pg0.local_ip6_prefix_len), is_no=1 + ) opt = ICMPv6NDOptPrefixInfo( - prefixlen=self.pg1.local_ip6_prefix_len, - prefix=self.pg1.local_ip6, - L=0, - A=0) + prefixlen=self.pg1.local_ip6_prefix_len, prefix=self.pg1.local_ip6, L=0, A=0 + ) self.pg0.ip6_ra_config(send_unicast=1) - self.send_and_expect_ra(self.pg0, p, - "RA with Prefix reverted to defaults", - dst_ip=ll, - opt=opt) + self.send_and_expect_ra( + self.pg0, p, "RA with Prefix reverted to defaults", dst_ip=ll, opt=opt + ) # # Remove the second prefix-info - expect no prefix-info in the adverts # - self.pg0.ip6_ra_prefix('%s/%s' % (self.pg1.local_ip6, - self.pg1.local_ip6_prefix_len), - is_no=1) + self.pg0.ip6_ra_prefix( + "%s/%s" % (self.pg1.local_ip6, self.pg1.local_ip6_prefix_len), is_no=1 + ) # # change the link's link local, so we know that works too. # self.vapi.sw_interface_ip6_set_link_local_address( - sw_if_index=self.pg0.sw_if_index, - ip="fe80::88") + sw_if_index=self.pg0.sw_if_index, ip="fe80::88" + ) self.pg0.ip6_ra_config(send_unicast=1) - self.send_and_expect_ra(self.pg0, p, - "RA with Prefix reverted to defaults", - dst_ip=ll, - src_ip="fe80::88") + self.send_and_expect_ra( + self.pg0, + p, + "RA with Prefix reverted to defaults", + dst_ip=ll, + src_ip="fe80::88", + ) # # Reset the periodic advertisements back to default values @@ -985,7 +1038,7 @@ class TestIPv6(TestIPv6ND): self.pg0.ip6_ra_config(no=1, send_unicast=1) def test_mld(self): - """ MLD Report """ + """MLD Report""" # # test one MLD is sent after applying an IPv6 Address on an interface # @@ -1006,25 +1059,30 @@ class TestIPv6(TestIPv6ND): # make sure ipv6 packets with hop by hop options have # correct checksums self.assert_packet_checksums_valid(rx) - if rx.haslayer(IPv6ExtHdrHopByHop) and \ - rx.haslayer(Dot1Q) and \ - rx[Dot1Q].vlan == 99: + if ( + rx.haslayer(IPv6ExtHdrHopByHop) + and rx.haslayer(Dot1Q) + and rx[Dot1Q].vlan == 99 + ): mld = rx[ICMPv6MLReport2] self.assertEqual(mld.records_number, 4) class TestIPv6RouteLookup(VppTestCase): - """ IPv6 Route Lookup Test Case """ + """IPv6 Route Lookup Test Case""" + routes = [] def route_lookup(self, prefix, exact): - return self.vapi.api(self.vapi.papi.ip_route_lookup, - { - 'table_id': 0, - 'exact': exact, - 'prefix': prefix, - }) + return self.vapi.api( + self.vapi.papi.ip_route_lookup, + { + "table_id": 0, + "exact": exact, + "prefix": prefix, + }, + ) @classmethod def setUpClass(cls): @@ -1037,8 +1095,7 @@ class TestIPv6RouteLookup(VppTestCase): def setUp(self): super(TestIPv6RouteLookup, self).setUp() - drop_nh = VppRoutePath("::1", 0xffffffff, - type=FibPathType.FIB_PATH_TYPE_DROP) + drop_nh = VppRoutePath("::1", 0xFFFFFFFF, type=FibPathType.FIB_PATH_TYPE_DROP) # Add 3 routes r = VppIpRoute(self, "2001:1111::", 32, [drop_nh]) @@ -1064,12 +1121,12 @@ class TestIPv6RouteLookup(VppTestCase): # Verify we find the host route prefix = "2001:1111:2222::1/128" result = self.route_lookup(prefix, True) - assert (prefix == str(result.route.prefix)) + assert prefix == str(result.route.prefix) # Verify we find a middle prefix route prefix = "2001:1111:2222::/48" result = self.route_lookup(prefix, True) - assert (prefix == str(result.route.prefix)) + assert prefix == str(result.route.prefix) # Verify we do not find an available LPM. with self.vapi.assert_negative_api_retval(): @@ -1079,17 +1136,17 @@ class TestIPv6RouteLookup(VppTestCase): # verify we find lpm lpm_prefix = "2001:1111:2222::/48" result = self.route_lookup("2001:1111:2222::2/128", False) - assert (lpm_prefix == str(result.route.prefix)) + assert lpm_prefix == str(result.route.prefix) # Verify we find the exact when not requested result = self.route_lookup(lpm_prefix, False) - assert (lpm_prefix == str(result.route.prefix)) + assert lpm_prefix == str(result.route.prefix) # Can't seem to delete the default route so no negative LPM test. class TestIPv6IfAddrRoute(VppTestCase): - """ IPv6 Interface Addr Route Test Case """ + """IPv6 Interface Addr Route Test Case""" @classmethod def setUpClass(cls): @@ -1117,7 +1174,7 @@ class TestIPv6IfAddrRoute(VppTestCase): i.admin_down() def test_ipv6_ifaddrs_same_prefix(self): - """ IPv6 Interface Addresses Same Prefix test + """IPv6 Interface Addresses Same Prefix test Test scenario: @@ -1161,7 +1218,7 @@ class TestIPv6IfAddrRoute(VppTestCase): self.assertFalse(find_route(self, addr2, 128)) def test_ipv6_ifaddr_del(self): - """ Delete an interface address that does not exist """ + """Delete an interface address that does not exist""" loopbacks = self.create_loopback_interfaces(1) lo = self.lo_interfaces[0] @@ -1174,13 +1231,12 @@ class TestIPv6IfAddrRoute(VppTestCase): # with self.vapi.assert_negative_api_retval(): self.vapi.sw_interface_add_del_address( - sw_if_index=lo.sw_if_index, - prefix=self.pg0.local_ip6_prefix, - is_add=0) + sw_if_index=lo.sw_if_index, prefix=self.pg0.local_ip6_prefix, is_add=0 + ) class TestICMPv6Echo(VppTestCase): - """ ICMPv6 Echo Test Case """ + """ICMPv6 Echo Test Case""" @classmethod def setUpClass(cls): @@ -1209,7 +1265,7 @@ class TestICMPv6Echo(VppTestCase): i.admin_down() def test_icmpv6_echo(self): - """ VPP replies to ICMPv6 Echo Request + """VPP replies to ICMPv6 Echo Request Test scenario: @@ -1219,14 +1275,18 @@ class TestICMPv6Echo(VppTestCase): # test both with global and local ipv6 addresses dsts = (self.pg0.local_ip6, self.pg0.local_ip6_ll) - id = 0xb + id = 0xB seq = 5 - data = b'\x0a' * 18 + data = b"\x0a" * 18 p = list() for dst in dsts: - p.append((Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IPv6(src=self.pg0.remote_ip6, dst=dst) / - ICMPv6EchoRequest(id=id, seq=seq, data=data))) + p.append( + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=self.pg0.remote_ip6, dst=dst) + / ICMPv6EchoRequest(id=id, seq=seq, data=data) + ) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) @@ -1248,7 +1308,7 @@ class TestICMPv6Echo(VppTestCase): class TestIPv6RD(TestIPv6ND): - """ IPv6 Router Discovery Test Case """ + """IPv6 Router Discovery Test Case""" @classmethod def setUpClass(cls): @@ -1278,51 +1338,52 @@ class TestIPv6RD(TestIPv6ND): super(TestIPv6RD, self).tearDown() def test_rd_send_router_solicitation(self): - """ Verify router solicitation packets """ + """Verify router solicitation packets""" count = 2 self.pg_enable_capture(self.pg_interfaces) self.pg_start() - self.vapi.ip6nd_send_router_solicitation(self.pg1.sw_if_index, - mrc=count) + self.vapi.ip6nd_send_router_solicitation(self.pg1.sw_if_index, mrc=count) rx_list = self.pg1.get_capture(count, timeout=3) self.assertEqual(len(rx_list), count) for packet in rx_list: self.assertEqual(packet.haslayer(IPv6), 1) - self.assertEqual(packet[IPv6].haslayer( - ICMPv6ND_RS), 1) + self.assertEqual(packet[IPv6].haslayer(ICMPv6ND_RS), 1) dst = ip6_normalize(packet[IPv6].dst) dst2 = ip6_normalize("ff02::2") self.assert_equal(dst, dst2) src = ip6_normalize(packet[IPv6].src) src2 = ip6_normalize(self.pg1.local_ip6_ll) self.assert_equal(src, src2) - self.assertTrue( - bool(packet[ICMPv6ND_RS].haslayer( - ICMPv6NDOptSrcLLAddr))) - self.assert_equal( - packet[ICMPv6NDOptSrcLLAddr].lladdr, - self.pg1.local_mac) + self.assertTrue(bool(packet[ICMPv6ND_RS].haslayer(ICMPv6NDOptSrcLLAddr))) + self.assert_equal(packet[ICMPv6NDOptSrcLLAddr].lladdr, self.pg1.local_mac) def verify_prefix_info(self, reported_prefix, prefix_option): prefix = IPv6Network( - text_type(prefix_option.getfieldval("prefix") + - "/" + - text_type(prefix_option.getfieldval("prefixlen"))), - strict=False) - self.assert_equal(reported_prefix.prefix.network_address, - prefix.network_address) + text_type( + prefix_option.getfieldval("prefix") + + "/" + + text_type(prefix_option.getfieldval("prefixlen")) + ), + strict=False, + ) + self.assert_equal( + reported_prefix.prefix.network_address, prefix.network_address + ) L = prefix_option.getfieldval("L") A = prefix_option.getfieldval("A") option_flags = (L << 7) | (A << 6) self.assert_equal(reported_prefix.flags, option_flags) - self.assert_equal(reported_prefix.valid_time, - prefix_option.getfieldval("validlifetime")) - self.assert_equal(reported_prefix.preferred_time, - prefix_option.getfieldval("preferredlifetime")) + self.assert_equal( + reported_prefix.valid_time, prefix_option.getfieldval("validlifetime") + ) + self.assert_equal( + reported_prefix.preferred_time, + prefix_option.getfieldval("preferredlifetime"), + ) def test_rd_receive_router_advertisement(self): - """ Verify events triggered by received RA packets """ + """Verify events triggered by received RA packets""" self.vapi.want_ip6_ra_events(enable=1) @@ -1344,12 +1405,13 @@ class TestIPv6RD(TestIPv6ND): A=0, ) - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IPv6(dst=self.pg1.local_ip6_ll, - src=mk_ll_addr(self.pg1.remote_mac)) / - ICMPv6ND_RA() / - prefix_info_1 / - prefix_info_2) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(dst=self.pg1.local_ip6_ll, src=mk_ll_addr(self.pg1.remote_mac)) + / ICMPv6ND_RA() + / prefix_info_1 + / prefix_info_2 + ) self.pg1.add_stream([p]) self.pg_start() @@ -1360,7 +1422,8 @@ class TestIPv6RD(TestIPv6ND): self.assert_equal(ev.router_lifetime_in_sec, 1800) self.assert_equal(ev.neighbor_reachable_time_in_msec, 0) self.assert_equal( - ev.time_in_msec_between_retransmitted_neighbor_solicitations, 0) + ev.time_in_msec_between_retransmitted_neighbor_solicitations, 0 + ) self.assert_equal(ev.n_prefixes, 2) @@ -1369,7 +1432,7 @@ class TestIPv6RD(TestIPv6ND): class TestIPv6RDControlPlane(TestIPv6ND): - """ IPv6 Router Discovery Control Plane Test Case """ + """IPv6 Router Discovery Control Plane Test Case""" @classmethod def setUpClass(cls): @@ -1403,8 +1466,11 @@ class TestIPv6RDControlPlane(TestIPv6ND): ra = ICMPv6ND_RA(routerlifetime=routerlifetime) else: ra = ICMPv6ND_RA() - p = (Ether(dst=pg.local_mac, src=pg.remote_mac) / - IPv6(dst=dst_ip, src=src_ip) / ra) + p = ( + Ether(dst=pg.local_mac, src=pg.remote_mac) + / IPv6(dst=dst_ip, src=src_ip) + / ra + ) return p @staticmethod @@ -1415,8 +1481,8 @@ class TestIPv6RDControlPlane(TestIPv6ND): for path in entry.route.paths: if path.sw_if_index != 0xFFFFFFFF: defaut_route = {} - defaut_route['sw_if_index'] = path.sw_if_index - defaut_route['next_hop'] = path.nh.address.ip6 + defaut_route["sw_if_index"] = path.sw_if_index + defaut_route["next_hop"] = path.nh.address.ip6 list.append(defaut_route) return list @@ -1431,7 +1497,7 @@ class TestIPv6RDControlPlane(TestIPv6ND): return list def wait_for_no_default_route(self, n_tries=50, s_time=1): - while (n_tries): + while n_tries: fib = self.vapi.ip_route_dump(0, True) default_routes = self.get_default_routes(fib) if 0 == len(default_routes): @@ -1442,7 +1508,7 @@ class TestIPv6RDControlPlane(TestIPv6ND): return False def test_all(self): - """ Test handling of SLAAC addresses and default routes """ + """Test handling of SLAAC addresses and default routes""" fib = self.vapi.ip_route_dump(0, True) default_routes = self.get_default_routes(fib) @@ -1455,22 +1521,25 @@ class TestIPv6RDControlPlane(TestIPv6ND): self.sleep(0.1) # send RA - packet = (self.create_ra_packet( - self.pg0) / ICMPv6NDOptPrefixInfo( - prefix="1::", - prefixlen=64, - validlifetime=2, - preferredlifetime=2, - L=1, - A=1, - ) / ICMPv6NDOptPrefixInfo( - prefix="7::", - prefixlen=20, - validlifetime=1500, - preferredlifetime=1000, - L=1, - A=0, - )) + packet = ( + self.create_ra_packet(self.pg0) + / ICMPv6NDOptPrefixInfo( + prefix="1::", + prefixlen=64, + validlifetime=2, + preferredlifetime=2, + L=1, + A=1, + ) + / ICMPv6NDOptPrefixInfo( + prefix="7::", + prefixlen=20, + validlifetime=1500, + preferredlifetime=1000, + L=1, + A=0, + ) + ) self.pg0.add_stream([packet]) self.pg_start() @@ -1482,16 +1551,17 @@ class TestIPv6RDControlPlane(TestIPv6ND): addresses = set(self.get_interface_addresses(fib, self.pg0)) new_addresses = addresses.difference(initial_addresses) self.assertEqual(len(new_addresses), 1) - prefix = IPv6Network(text_type("%s/%d" % (list(new_addresses)[0], 20)), - strict=False) - self.assertEqual(prefix, IPv6Network(text_type('1::/20'))) + prefix = IPv6Network( + text_type("%s/%d" % (list(new_addresses)[0], 20)), strict=False + ) + self.assertEqual(prefix, IPv6Network(text_type("1::/20"))) # check FIB for new default route default_routes = self.get_default_routes(fib) self.assertEqual(len(default_routes), 1) dr = default_routes[0] - self.assertEqual(dr['sw_if_index'], self.pg0.sw_if_index) - self.assertEqual(dr['next_hop'], router_address) + self.assertEqual(dr["sw_if_index"], self.pg0.sw_if_index) + self.assertEqual(dr["next_hop"], router_address) # send RA to delete default route packet = self.create_ra_packet(self.pg0, routerlifetime=0) @@ -1519,8 +1589,8 @@ class TestIPv6RDControlPlane(TestIPv6ND): default_routes = self.get_default_routes(fib) self.assertEqual(len(default_routes), 1) dr = default_routes[0] - self.assertEqual(dr['sw_if_index'], self.pg0.sw_if_index) - self.assertEqual(dr['next_hop'], router_address) + self.assertEqual(dr["sw_if_index"], self.pg0.sw_if_index) + self.assertEqual(dr["next_hop"], router_address) # send RA, updating router lifetime to 1s packet = self.create_ra_packet(self.pg0, 1) @@ -1534,8 +1604,8 @@ class TestIPv6RDControlPlane(TestIPv6ND): default_routes = self.get_default_routes(fib) self.assertEqual(len(default_routes), 1) dr = default_routes[0] - self.assertEqual(dr['sw_if_index'], self.pg0.sw_if_index) - self.assertEqual(dr['next_hop'], router_address) + self.assertEqual(dr["sw_if_index"], self.pg0.sw_if_index) + self.assertEqual(dr["next_hop"], router_address) self.sleep_on_vpp_time(1) @@ -1547,9 +1617,10 @@ class TestIPv6RDControlPlane(TestIPv6ND): new_addresses = addresses.difference(initial_addresses) self.assertEqual(len(new_addresses), 1) - prefix = IPv6Network(text_type("%s/%d" % (list(new_addresses)[0], 20)), - strict=False) - self.assertEqual(prefix, IPv6Network(text_type('1::/20'))) + prefix = IPv6Network( + text_type("%s/%d" % (list(new_addresses)[0], 20)), strict=False + ) + self.assertEqual(prefix, IPv6Network(text_type("1::/20"))) self.sleep_on_vpp_time(1) @@ -1561,7 +1632,7 @@ class TestIPv6RDControlPlane(TestIPv6ND): class IPv6NDProxyTest(TestIPv6ND): - """ IPv6 ND ProxyTest Case """ + """IPv6 ND ProxyTest Case""" @classmethod def setUpClass(cls): @@ -1589,7 +1660,7 @@ class IPv6NDProxyTest(TestIPv6ND): super(IPv6NDProxyTest, self).tearDown() def test_nd_proxy(self): - """ IPv6 Proxy ND """ + """IPv6 Proxy ND""" # # Generate some hosts in the subnet that we are proxying @@ -1604,12 +1675,12 @@ class IPv6NDProxyTest(TestIPv6ND): # expect no response since it's from an address that is not # on the link that has the prefix configured # - ns_pg1 = (Ether(dst=in6_getnsmac(nsma), src=self.pg1.remote_mac) / - IPv6(dst=d, - src=self.pg0._remote_hosts[2].ip6) / - ICMPv6ND_NS(tgt=self.pg0.local_ip6) / - ICMPv6NDOptSrcLLAddr( - lladdr=self.pg0._remote_hosts[2].mac)) + ns_pg1 = ( + Ether(dst=in6_getnsmac(nsma), src=self.pg1.remote_mac) + / IPv6(dst=d, src=self.pg0._remote_hosts[2].ip6) + / ICMPv6ND_NS(tgt=self.pg0.local_ip6) + / ICMPv6NDOptSrcLLAddr(lladdr=self.pg0._remote_hosts[2].mac) + ) self.send_and_assert_no_replies(self.pg1, ns_pg1, "Off link NS") @@ -1617,32 +1688,38 @@ class IPv6NDProxyTest(TestIPv6ND): # Add proxy support for the host # self.vapi.ip6nd_proxy_add_del( - is_add=1, ip=inet_pton(AF_INET6, self.pg0._remote_hosts[2].ip6), - sw_if_index=self.pg1.sw_if_index) + is_add=1, + ip=inet_pton(AF_INET6, self.pg0._remote_hosts[2].ip6), + sw_if_index=self.pg1.sw_if_index, + ) # # try that NS again. this time we expect an NA back # - self.send_and_expect_na(self.pg1, ns_pg1, - "NS to proxy entry", - dst_ip=self.pg0._remote_hosts[2].ip6, - tgt_ip=self.pg0.local_ip6) + self.send_and_expect_na( + self.pg1, + ns_pg1, + "NS to proxy entry", + dst_ip=self.pg0._remote_hosts[2].ip6, + tgt_ip=self.pg0.local_ip6, + ) # # ... and that we have an entry in the ND cache # - self.assertTrue(find_nbr(self, - self.pg1.sw_if_index, - self.pg0._remote_hosts[2].ip6)) + self.assertTrue( + find_nbr(self, self.pg1.sw_if_index, self.pg0._remote_hosts[2].ip6) + ) # # ... and we can route traffic to it # - t = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(dst=self.pg0._remote_hosts[2].ip6, - src=self.pg0.remote_ip6) / - inet6.UDP(sport=10000, dport=20000) / - Raw(b'\xa5' * 100)) + t = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(dst=self.pg0._remote_hosts[2].ip6, src=self.pg0.remote_ip6) + / inet6.UDP(sport=10000, dport=20000) + / Raw(b"\xa5" * 100) + ) self.pg0.add_stream(t) self.pg_enable_capture(self.pg_interfaces) @@ -1653,58 +1730,64 @@ class IPv6NDProxyTest(TestIPv6ND): self.assertEqual(rx[Ether].dst, self.pg0._remote_hosts[2].mac) self.assertEqual(rx[Ether].src, self.pg1.local_mac) - self.assertEqual(rx[IPv6].src, - t[IPv6].src) - self.assertEqual(rx[IPv6].dst, - t[IPv6].dst) + self.assertEqual(rx[IPv6].src, t[IPv6].src) + self.assertEqual(rx[IPv6].dst, t[IPv6].dst) # # Test we proxy for the host on the main interface # - ns_pg0 = (Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac) / - IPv6(dst=d, src=self.pg0.remote_ip6) / - ICMPv6ND_NS( - tgt=self.pg0._remote_hosts[2].ip6) / - ICMPv6NDOptSrcLLAddr( - lladdr=self.pg0.remote_mac)) + ns_pg0 = ( + Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac) + / IPv6(dst=d, src=self.pg0.remote_ip6) + / ICMPv6ND_NS(tgt=self.pg0._remote_hosts[2].ip6) + / ICMPv6NDOptSrcLLAddr(lladdr=self.pg0.remote_mac) + ) - self.send_and_expect_na(self.pg0, ns_pg0, - "NS to proxy entry on main", - tgt_ip=self.pg0._remote_hosts[2].ip6, - dst_ip=self.pg0.remote_ip6) + self.send_and_expect_na( + self.pg0, + ns_pg0, + "NS to proxy entry on main", + tgt_ip=self.pg0._remote_hosts[2].ip6, + dst_ip=self.pg0.remote_ip6, + ) # # Setup and resolve proxy for another host on another interface # - ns_pg2 = (Ether(dst=in6_getnsmac(nsma), src=self.pg2.remote_mac) / - IPv6(dst=d, - src=self.pg0._remote_hosts[3].ip6) / - ICMPv6ND_NS(tgt=self.pg0.local_ip6) / - ICMPv6NDOptSrcLLAddr( - lladdr=self.pg0._remote_hosts[2].mac)) + ns_pg2 = ( + Ether(dst=in6_getnsmac(nsma), src=self.pg2.remote_mac) + / IPv6(dst=d, src=self.pg0._remote_hosts[3].ip6) + / ICMPv6ND_NS(tgt=self.pg0.local_ip6) + / ICMPv6NDOptSrcLLAddr(lladdr=self.pg0._remote_hosts[2].mac) + ) self.vapi.ip6nd_proxy_add_del( - is_add=1, ip=inet_pton(AF_INET6, self.pg0._remote_hosts[3].ip6), - sw_if_index=self.pg2.sw_if_index) + is_add=1, + ip=inet_pton(AF_INET6, self.pg0._remote_hosts[3].ip6), + sw_if_index=self.pg2.sw_if_index, + ) - self.send_and_expect_na(self.pg2, ns_pg2, - "NS to proxy entry other interface", - dst_ip=self.pg0._remote_hosts[3].ip6, - tgt_ip=self.pg0.local_ip6) + self.send_and_expect_na( + self.pg2, + ns_pg2, + "NS to proxy entry other interface", + dst_ip=self.pg0._remote_hosts[3].ip6, + tgt_ip=self.pg0.local_ip6, + ) - self.assertTrue(find_nbr(self, - self.pg2.sw_if_index, - self.pg0._remote_hosts[3].ip6)) + self.assertTrue( + find_nbr(self, self.pg2.sw_if_index, self.pg0._remote_hosts[3].ip6) + ) # # hosts can communicate. pg2->pg1 # - t2 = (Ether(dst=self.pg2.local_mac, - src=self.pg0.remote_hosts[3].mac) / - IPv6(dst=self.pg0._remote_hosts[2].ip6, - src=self.pg0._remote_hosts[3].ip6) / - inet6.UDP(sport=10000, dport=20000) / - Raw(b'\xa5' * 100)) + t2 = ( + Ether(dst=self.pg2.local_mac, src=self.pg0.remote_hosts[3].mac) + / IPv6(dst=self.pg0._remote_hosts[2].ip6, src=self.pg0._remote_hosts[3].ip6) + / inet6.UDP(sport=10000, dport=20000) + / Raw(b"\xa5" * 100) + ) self.pg2.add_stream(t2) self.pg_enable_capture(self.pg_interfaces) @@ -1715,27 +1798,29 @@ class IPv6NDProxyTest(TestIPv6ND): self.assertEqual(rx[Ether].dst, self.pg0._remote_hosts[2].mac) self.assertEqual(rx[Ether].src, self.pg1.local_mac) - self.assertEqual(rx[IPv6].src, - t2[IPv6].src) - self.assertEqual(rx[IPv6].dst, - t2[IPv6].dst) + self.assertEqual(rx[IPv6].src, t2[IPv6].src) + self.assertEqual(rx[IPv6].dst, t2[IPv6].dst) # # remove the proxy configs # self.vapi.ip6nd_proxy_add_del( ip=inet_pton(AF_INET6, self.pg0._remote_hosts[2].ip6), - sw_if_index=self.pg1.sw_if_index, is_add=0) + sw_if_index=self.pg1.sw_if_index, + is_add=0, + ) self.vapi.ip6nd_proxy_add_del( ip=inet_pton(AF_INET6, self.pg0._remote_hosts[3].ip6), - sw_if_index=self.pg2.sw_if_index, is_add=0) + sw_if_index=self.pg2.sw_if_index, + is_add=0, + ) - self.assertFalse(find_nbr(self, - self.pg2.sw_if_index, - self.pg0._remote_hosts[3].ip6)) - self.assertFalse(find_nbr(self, - self.pg1.sw_if_index, - self.pg0._remote_hosts[2].ip6)) + self.assertFalse( + find_nbr(self, self.pg2.sw_if_index, self.pg0._remote_hosts[3].ip6) + ) + self.assertFalse( + find_nbr(self, self.pg1.sw_if_index, self.pg0._remote_hosts[2].ip6) + ) # # no longer proxy-ing... @@ -1758,7 +1843,7 @@ class IPv6NDProxyTest(TestIPv6ND): class TestIP6Null(VppTestCase): - """ IPv6 routes via NULL """ + """IPv6 routes via NULL""" @classmethod def setUpClass(cls): @@ -1786,21 +1871,28 @@ class TestIP6Null(VppTestCase): i.admin_down() def test_ip_null(self): - """ IP NULL route """ + """IP NULL route""" - p = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(src=self.pg0.remote_ip6, dst="2001::1") / - inet6.UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=self.pg0.remote_ip6, dst="2001::1") + / inet6.UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) # # A route via IP NULL that will reply with ICMP unreachables # ip_unreach = VppIpRoute( - self, "2001::", 64, - [VppRoutePath("::", 0xffffffff, - type=FibPathType.FIB_PATH_TYPE_ICMP_UNREACH)]) + self, + "2001::", + 64, + [ + VppRoutePath( + "::", 0xFFFFFFFF, type=FibPathType.FIB_PATH_TYPE_ICMP_UNREACH + ) + ], + ) ip_unreach.add_vpp_config() self.pg0.add_stream(p) @@ -1821,9 +1913,15 @@ class TestIP6Null(VppTestCase): # A route via IP NULL that will reply with ICMP prohibited # ip_prohibit = VppIpRoute( - self, "2001::1", 128, - [VppRoutePath("::", 0xffffffff, - type=FibPathType.FIB_PATH_TYPE_ICMP_PROHIBIT)]) + self, + "2001::1", + 128, + [ + VppRoutePath( + "::", 0xFFFFFFFF, type=FibPathType.FIB_PATH_TYPE_ICMP_PROHIBIT + ) + ], + ) ip_prohibit.add_vpp_config() self.pg0.add_stream(p) @@ -1839,7 +1937,7 @@ class TestIP6Null(VppTestCase): class TestIP6Disabled(VppTestCase): - """ IPv6 disabled """ + """IPv6 disabled""" @classmethod def setUpClass(cls): @@ -1870,7 +1968,7 @@ class TestIP6Disabled(VppTestCase): i.admin_down() def test_ip_disabled(self): - """ IP Disabled """ + """IP Disabled""" MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t @@ -1881,24 +1979,32 @@ class TestIP6Disabled(VppTestCase): route_ff_01 = VppIpMRoute( self, "::", - "ffef::1", 128, + "ffef::1", + 128, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - [VppMRoutePath(self.pg1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT), - VppMRoutePath(self.pg0.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)]) + [ + VppMRoutePath( + self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT + ), + VppMRoutePath( + self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ), + ], + ) route_ff_01.add_vpp_config() - pu = (Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) / - IPv6(src="2001::1", dst=self.pg0.remote_ip6) / - inet6.UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - pm = (Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) / - IPv6(src="2001::1", dst="ffef::1") / - inet6.UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + pu = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IPv6(src="2001::1", dst=self.pg0.remote_ip6) + / inet6.UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + pm = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IPv6(src="2001::1", dst="ffef::1") + / inet6.UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) # # PG1 does not forward IP traffic @@ -1937,7 +2043,7 @@ class TestIP6Disabled(VppTestCase): class TestIP6LoadBalance(VppTestCase): - """ IPv6 Load-Balancing """ + """IPv6 Load-Balancing""" @classmethod def setUpClass(cls): @@ -1969,7 +2075,7 @@ class TestIP6LoadBalance(VppTestCase): super(TestIP6LoadBalance, self).tearDown() def test_ip6_load_balance(self): - """ IPv6 Load-Balancing """ + """IPv6 Load-Balancing""" # # An array of packets that differ only in the destination port @@ -1991,47 +2097,65 @@ class TestIP6LoadBalance(VppTestCase): for ii in range(NUM_PKTS): port_ip_hdr = ( - IPv6(dst="3000::1", src="3000:1::1") / - inet6.UDP(sport=1234, dport=1234 + ii) / - Raw(b'\xa5' * 100)) - port_ip_pkts.append((Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - port_ip_hdr)) - port_mpls_pkts.append((Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - MPLS(label=66, ttl=2) / - port_ip_hdr)) - port_mpls_neos_pkts.append((Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - MPLS(label=67, ttl=2) / - MPLS(label=77, ttl=2) / - port_ip_hdr)) - port_ent_pkts.append((Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - MPLS(label=67, ttl=2) / - MPLS(label=14, ttl=2) / - MPLS(label=999, ttl=2) / - port_ip_hdr)) + IPv6(dst="3000::1", src="3000:1::1") + / inet6.UDP(sport=1234, dport=1234 + ii) + / Raw(b"\xa5" * 100) + ) + port_ip_pkts.append( + (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / port_ip_hdr) + ) + port_mpls_pkts.append( + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / MPLS(label=66, ttl=2) + / port_ip_hdr + ) + ) + port_mpls_neos_pkts.append( + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / MPLS(label=67, ttl=2) + / MPLS(label=77, ttl=2) + / port_ip_hdr + ) + ) + port_ent_pkts.append( + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / MPLS(label=67, ttl=2) + / MPLS(label=14, ttl=2) + / MPLS(label=999, ttl=2) + / port_ip_hdr + ) + ) src_ip_hdr = ( - IPv6(dst="3000::1", src="3000:1::%d" % ii) / - inet6.UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - src_ip_pkts.append((Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - src_ip_hdr)) - src_mpls_pkts.append((Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - MPLS(label=66, ttl=2) / - src_ip_hdr)) + IPv6(dst="3000::1", src="3000:1::%d" % ii) + / inet6.UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + src_ip_pkts.append( + (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / src_ip_hdr) + ) + src_mpls_pkts.append( + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / MPLS(label=66, ttl=2) + / src_ip_hdr + ) + ) # # A route for the IP packets # - route_3000_1 = VppIpRoute(self, "3000::1", 128, - [VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index), - VppRoutePath(self.pg2.remote_ip6, - self.pg2.sw_if_index)]) + route_3000_1 = VppIpRoute( + self, + "3000::1", + 128, + [ + VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index), + VppRoutePath(self.pg2.remote_ip6, self.pg2.sw_if_index), + ], + ) route_3000_1.add_vpp_config() # @@ -2043,13 +2167,15 @@ class TestIP6LoadBalance(VppTestCase): # # An MPLS route for the non-EOS packets # - route_67 = VppMplsRoute(self, 67, 0, - [VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index, - labels=[67]), - VppRoutePath(self.pg2.remote_ip6, - self.pg2.sw_if_index, - labels=[67])]) + route_67 = VppMplsRoute( + self, + 67, + 0, + [ + VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index, labels=[67]), + VppRoutePath(self.pg2.remote_ip6, self.pg2.sw_if_index, labels=[67]), + ], + ) route_67.add_vpp_config() # @@ -2061,17 +2187,20 @@ class TestIP6LoadBalance(VppTestCase): # be guaranteed. But with 64 different packets we do expect some # balancing. So instead just ensure there is traffic on each link. # - rx = self.send_and_expect_load_balancing(self.pg0, port_ip_pkts, - [self.pg1, self.pg2]) + rx = self.send_and_expect_load_balancing( + self.pg0, port_ip_pkts, [self.pg1, self.pg2] + ) n_ip_pg0 = len(rx[0]) - self.send_and_expect_load_balancing(self.pg0, src_ip_pkts, - [self.pg1, self.pg2]) - self.send_and_expect_load_balancing(self.pg0, port_mpls_pkts, - [self.pg1, self.pg2]) - self.send_and_expect_load_balancing(self.pg0, src_mpls_pkts, - [self.pg1, self.pg2]) - rx = self.send_and_expect_load_balancing(self.pg0, port_mpls_neos_pkts, - [self.pg1, self.pg2]) + self.send_and_expect_load_balancing(self.pg0, src_ip_pkts, [self.pg1, self.pg2]) + self.send_and_expect_load_balancing( + self.pg0, port_mpls_pkts, [self.pg1, self.pg2] + ) + self.send_and_expect_load_balancing( + self.pg0, src_mpls_pkts, [self.pg1, self.pg2] + ) + rx = self.send_and_expect_load_balancing( + self.pg0, port_mpls_neos_pkts, [self.pg1, self.pg2] + ) n_mpls_pg0 = len(rx[0]) # @@ -2079,12 +2208,14 @@ class TestIP6LoadBalance(VppTestCase): # self.vapi.set_ip_flow_hash_router_id(router_id=0x11111111) - rx = self.send_and_expect_load_balancing(self.pg0, port_ip_pkts, - [self.pg1, self.pg2]) + rx = self.send_and_expect_load_balancing( + self.pg0, port_ip_pkts, [self.pg1, self.pg2] + ) self.assertNotEqual(n_ip_pg0, len(rx[0])) - rx = self.send_and_expect_load_balancing(self.pg0, src_mpls_pkts, - [self.pg1, self.pg2]) + rx = self.send_and_expect_load_balancing( + self.pg0, src_mpls_pkts, [self.pg1, self.pg2] + ) self.assertNotEqual(n_mpls_pg0, len(rx[0])) # @@ -2098,20 +2229,22 @@ class TestIP6LoadBalance(VppTestCase): # - now only the stream with differing source address will # load-balance # - self.vapi.set_ip_flow_hash(vrf_id=0, src=1, dst=1, proto=1, - sport=0, dport=0, is_ipv6=1) + self.vapi.set_ip_flow_hash( + vrf_id=0, src=1, dst=1, proto=1, sport=0, dport=0, is_ipv6=1 + ) - self.send_and_expect_load_balancing(self.pg0, src_ip_pkts, - [self.pg1, self.pg2]) - self.send_and_expect_load_balancing(self.pg0, src_mpls_pkts, - [self.pg1, self.pg2]) + self.send_and_expect_load_balancing(self.pg0, src_ip_pkts, [self.pg1, self.pg2]) + self.send_and_expect_load_balancing( + self.pg0, src_mpls_pkts, [self.pg1, self.pg2] + ) self.send_and_expect_only(self.pg0, port_ip_pkts, self.pg2) # # change the flow hash config back to defaults # - self.vapi.set_ip_flow_hash(vrf_id=0, src=1, dst=1, sport=1, dport=1, - proto=1, is_ipv6=1) + self.vapi.set_ip_flow_hash( + vrf_id=0, src=1, dst=1, sport=1, dport=1, proto=1, is_ipv6=1 + ) # # Recursive prefixes @@ -2122,44 +2255,52 @@ class TestIP6LoadBalance(VppTestCase): src_pkts = [] for ii in range(257): - port_pkts.append((Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(dst="4000::1", - src="4000:1::1") / - inet6.UDP(sport=1234, - dport=1234 + ii) / - Raw(b'\xa5' * 100))) - src_pkts.append((Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(dst="4000::1", - src="4000:1::%d" % ii) / - inet6.UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100))) - - route_3000_2 = VppIpRoute(self, "3000::2", 128, - [VppRoutePath(self.pg3.remote_ip6, - self.pg3.sw_if_index), - VppRoutePath(self.pg4.remote_ip6, - self.pg4.sw_if_index)]) + port_pkts.append( + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(dst="4000::1", src="4000:1::1") + / inet6.UDP(sport=1234, dport=1234 + ii) + / Raw(b"\xa5" * 100) + ) + ) + src_pkts.append( + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(dst="4000::1", src="4000:1::%d" % ii) + / inet6.UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + ) + + route_3000_2 = VppIpRoute( + self, + "3000::2", + 128, + [ + VppRoutePath(self.pg3.remote_ip6, self.pg3.sw_if_index), + VppRoutePath(self.pg4.remote_ip6, self.pg4.sw_if_index), + ], + ) route_3000_2.add_vpp_config() - route_4000_1 = VppIpRoute(self, "4000::1", 128, - [VppRoutePath("3000::1", - 0xffffffff), - VppRoutePath("3000::2", - 0xffffffff)]) + route_4000_1 = VppIpRoute( + self, + "4000::1", + 128, + [VppRoutePath("3000::1", 0xFFFFFFFF), VppRoutePath("3000::2", 0xFFFFFFFF)], + ) route_4000_1.add_vpp_config() # # inject the packet on pg0 - expect load-balancing across all 4 paths # self.vapi.cli("clear trace") - self.send_and_expect_load_balancing(self.pg0, port_pkts, - [self.pg1, self.pg2, - self.pg3, self.pg4]) - self.send_and_expect_load_balancing(self.pg0, src_pkts, - [self.pg1, self.pg2, - self.pg3, self.pg4]) + self.send_and_expect_load_balancing( + self.pg0, port_pkts, [self.pg1, self.pg2, self.pg3, self.pg4] + ) + self.send_and_expect_load_balancing( + self.pg0, src_pkts, [self.pg1, self.pg2, self.pg3, self.pg4] + ) # # Recursive prefixes @@ -2168,22 +2309,26 @@ class TestIP6LoadBalance(VppTestCase): port_pkts = [] for ii in range(257): - port_pkts.append((Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(dst="6000::1", - src="6000:1::1") / - inet6.UDP(sport=1234, - dport=1234 + ii) / - Raw(b'\xa5' * 100))) - - route_5000_2 = VppIpRoute(self, "5000::2", 128, - [VppRoutePath(self.pg3.remote_ip6, - self.pg3.sw_if_index)]) + port_pkts.append( + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(dst="6000::1", src="6000:1::1") + / inet6.UDP(sport=1234, dport=1234 + ii) + / Raw(b"\xa5" * 100) + ) + ) + + route_5000_2 = VppIpRoute( + self, + "5000::2", + 128, + [VppRoutePath(self.pg3.remote_ip6, self.pg3.sw_if_index)], + ) route_5000_2.add_vpp_config() - route_6000_1 = VppIpRoute(self, "6000::1", 128, - [VppRoutePath("5000::2", - 0xffffffff)]) + route_6000_1 = VppIpRoute( + self, "6000::1", 128, [VppRoutePath("5000::2", 0xFFFFFFFF)] + ) route_6000_1.add_vpp_config() # @@ -2194,7 +2339,7 @@ class TestIP6LoadBalance(VppTestCase): class IP6PuntSetup(object): - """ Setup for IPv6 Punt Police/Redirect """ + """Setup for IPv6 Punt Police/Redirect""" def punt_setup(self): self.create_pg_interfaces(range(4)) @@ -2204,12 +2349,12 @@ class IP6PuntSetup(object): i.config_ip6() i.resolve_ndp() - self.pkt = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(src=self.pg0.remote_ip6, - dst=self.pg0.local_ip6) / - inet6.TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + self.pkt = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) + / inet6.TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) def punt_teardown(self): for i in self.pg_interfaces: @@ -2218,7 +2363,7 @@ class IP6PuntSetup(object): class TestIP6Punt(IP6PuntSetup, VppTestCase): - """ IPv6 Punt Police/Redirect """ + """IPv6 Punt Police/Redirect""" def setUp(self): super(TestIP6Punt, self).setUp() @@ -2229,7 +2374,7 @@ class TestIP6Punt(IP6PuntSetup, VppTestCase): super(TestIP6Punt, self).tearDown() def test_ip_punt(self): - """ IP6 punt police and redirect """ + """IP6 punt police and redirect""" pkts = self.pkt * 1025 @@ -2237,8 +2382,9 @@ class TestIP6Punt(IP6PuntSetup, VppTestCase): # Configure a punt redirect via pg1. # nh_addr = self.pg1.remote_ip6 - ip_punt_redirect = VppIpPuntRedirect(self, self.pg0.sw_if_index, - self.pg1.sw_if_index, nh_addr) + ip_punt_redirect = VppIpPuntRedirect( + self, self.pg0.sw_if_index, self.pg1.sw_if_index, nh_addr + ) ip_punt_redirect.add_vpp_config() self.send_and_expect(self.pg0, pkts, self.pg1) @@ -2248,8 +2394,7 @@ class TestIP6Punt(IP6PuntSetup, VppTestCase): # policer = VppPolicer(self, "ip6-punt", 400, 0, 10, 0, rate_type=1) policer.add_vpp_config() - ip_punt_policer = VppIpPuntPolicer(self, policer.policer_index, - is_ip6=True) + ip_punt_policer = VppIpPuntPolicer(self, policer.policer_index, is_ip6=True) ip_punt_policer.add_vpp_config() self.vapi.cli("clear trace") @@ -2265,9 +2410,9 @@ class TestIP6Punt(IP6PuntSetup, VppTestCase): stats = policer.get_stats() # Single rate policer - expect conform, violate but no exceed - self.assertGreater(stats['conform_packets'], 0) - self.assertEqual(stats['exceed_packets'], 0) - self.assertGreater(stats['violate_packets'], 0) + self.assertGreater(stats["conform_packets"], 0) + self.assertEqual(stats["exceed_packets"], 0) + self.assertGreater(stats["violate_packets"], 0) self.assertGreater(len(rx), 0) self.assertLess(len(rx), len(pkts)) @@ -2283,31 +2428,34 @@ class TestIP6Punt(IP6PuntSetup, VppTestCase): # remove the redirect. expect full drop. # ip_punt_redirect.remove_vpp_config() - self.send_and_assert_no_replies(self.pg0, pkts, - "IP no punt config") + self.send_and_assert_no_replies(self.pg0, pkts, "IP no punt config") # # Add a redirect that is not input port selective # - ip_punt_redirect = VppIpPuntRedirect(self, 0xffffffff, - self.pg1.sw_if_index, nh_addr) + ip_punt_redirect = VppIpPuntRedirect( + self, 0xFFFFFFFF, self.pg1.sw_if_index, nh_addr + ) ip_punt_redirect.add_vpp_config() self.send_and_expect(self.pg0, pkts, self.pg1) ip_punt_redirect.remove_vpp_config() def test_ip_punt_dump(self): - """ IP6 punt redirect dump""" + """IP6 punt redirect dump""" # # Configure a punt redirects # nh_address = self.pg3.remote_ip6 - ipr_03 = VppIpPuntRedirect(self, self.pg0.sw_if_index, - self.pg3.sw_if_index, nh_address) - ipr_13 = VppIpPuntRedirect(self, self.pg1.sw_if_index, - self.pg3.sw_if_index, nh_address) - ipr_23 = VppIpPuntRedirect(self, self.pg2.sw_if_index, - self.pg3.sw_if_index, '0::0') + ipr_03 = VppIpPuntRedirect( + self, self.pg0.sw_if_index, self.pg3.sw_if_index, nh_address + ) + ipr_13 = VppIpPuntRedirect( + self, self.pg1.sw_if_index, self.pg3.sw_if_index, nh_address + ) + ipr_23 = VppIpPuntRedirect( + self, self.pg2.sw_if_index, self.pg3.sw_if_index, "0::0" + ) ipr_03.add_vpp_config() ipr_13.add_vpp_config() ipr_23.add_vpp_config() @@ -2322,16 +2470,17 @@ class TestIP6Punt(IP6PuntSetup, VppTestCase): # # Dump punt redirects for all interfaces # - punts = self.vapi.ip_punt_redirect_dump(0xffffffff, is_ipv6=1) + punts = self.vapi.ip_punt_redirect_dump(0xFFFFFFFF, is_ipv6=1) self.assertEqual(len(punts), 3) for p in punts: self.assertEqual(p.punt.tx_sw_if_index, self.pg3.sw_if_index) self.assertNotEqual(punts[1].punt.nh, self.pg3.remote_ip6) - self.assertEqual(str(punts[2].punt.nh), '::') + self.assertEqual(str(punts[2].punt.nh), "::") class TestIP6PuntHandoff(IP6PuntSetup, VppTestCase): - """ IPv6 Punt Police/Redirect """ + """IPv6 Punt Police/Redirect""" + vpp_worker_count = 2 def setUp(self): @@ -2343,29 +2492,42 @@ class TestIP6PuntHandoff(IP6PuntSetup, VppTestCase): super(TestIP6PuntHandoff, self).tearDown() def test_ip_punt(self): - """ IP6 punt policer thread handoff """ + """IP6 punt policer thread handoff""" pkts = self.pkt * NUM_PKTS # # Configure a punt redirect via pg1. # nh_addr = self.pg1.remote_ip6 - ip_punt_redirect = VppIpPuntRedirect(self, self.pg0.sw_if_index, - self.pg1.sw_if_index, nh_addr) + ip_punt_redirect = VppIpPuntRedirect( + self, self.pg0.sw_if_index, self.pg1.sw_if_index, nh_addr + ) ip_punt_redirect.add_vpp_config() action_tx = PolicerAction( - VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT, - 0) + VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT, 0 + ) # # This policer drops no packets, we are just # testing that they get to the right thread. # - policer = VppPolicer(self, "ip6-punt", 400, 0, 10, 0, 1, - 0, 0, False, action_tx, action_tx, action_tx) + policer = VppPolicer( + self, + "ip6-punt", + 400, + 0, + 10, + 0, + 1, + 0, + 0, + False, + action_tx, + action_tx, + action_tx, + ) policer.add_vpp_config() - ip_punt_policer = VppIpPuntPolicer(self, policer.policer_index, - is_ip6=True) + ip_punt_policer = VppIpPuntPolicer(self, policer.policer_index, is_ip6=True) ip_punt_policer.add_vpp_config() for worker in [0, 1]: @@ -2377,9 +2539,9 @@ class TestIP6PuntHandoff(IP6PuntSetup, VppTestCase): stats = policer.get_stats() # Single rate policer - expect conform, violate but no exceed - self.assertGreater(stats['conform_packets'], 0) - self.assertEqual(stats['exceed_packets'], 0) - self.assertGreater(stats['violate_packets'], 0) + self.assertGreater(stats["conform_packets"], 0) + self.assertEqual(stats["exceed_packets"], 0) + self.assertGreater(stats["violate_packets"], 0) # Worker 0, should have done all the policing stats0 = policer.get_stats(worker=0) @@ -2387,9 +2549,9 @@ class TestIP6PuntHandoff(IP6PuntSetup, VppTestCase): # Worker 1, should have handed everything off stats1 = policer.get_stats(worker=1) - self.assertEqual(stats1['conform_packets'], 0) - self.assertEqual(stats1['exceed_packets'], 0) - self.assertEqual(stats1['violate_packets'], 0) + self.assertEqual(stats1["conform_packets"], 0) + self.assertEqual(stats1["exceed_packets"], 0) + self.assertEqual(stats1["violate_packets"], 0) # Bind the policer to worker 1 and repeat policer.bind_vpp_config(1, True) @@ -2402,19 +2564,23 @@ class TestIP6PuntHandoff(IP6PuntSetup, VppTestCase): stats0 = policer.get_stats(worker=0) stats1 = policer.get_stats(worker=1) - self.assertGreater(stats0['conform_packets'], 0) - self.assertEqual(stats0['exceed_packets'], 0) - self.assertGreater(stats0['violate_packets'], 0) + self.assertGreater(stats0["conform_packets"], 0) + self.assertEqual(stats0["exceed_packets"], 0) + self.assertGreater(stats0["violate_packets"], 0) - self.assertGreater(stats1['conform_packets'], 0) - self.assertEqual(stats1['exceed_packets'], 0) - self.assertGreater(stats1['violate_packets'], 0) + self.assertGreater(stats1["conform_packets"], 0) + self.assertEqual(stats1["exceed_packets"], 0) + self.assertGreater(stats1["violate_packets"], 0) - self.assertEqual(stats0['conform_packets'] + stats1['conform_packets'], - stats['conform_packets']) + self.assertEqual( + stats0["conform_packets"] + stats1["conform_packets"], + stats["conform_packets"], + ) - self.assertEqual(stats0['violate_packets'] + stats1['violate_packets'], - stats['violate_packets']) + self.assertEqual( + stats0["violate_packets"] + stats1["violate_packets"], + stats["violate_packets"], + ) # Unbind the policer and repeat policer.bind_vpp_config(1, False) @@ -2427,11 +2593,9 @@ class TestIP6PuntHandoff(IP6PuntSetup, VppTestCase): stats0new = policer.get_stats(worker=0) stats1new = policer.get_stats(worker=1) - self.assertGreater(stats0new['conform_packets'], - stats0['conform_packets']) - self.assertEqual(stats0new['exceed_packets'], 0) - self.assertGreater(stats0new['violate_packets'], - stats0['violate_packets']) + self.assertGreater(stats0new["conform_packets"], stats0["conform_packets"]) + self.assertEqual(stats0new["exceed_packets"], 0) + self.assertGreater(stats0new["violate_packets"], stats0["violate_packets"]) self.assertEqual(stats1, stats1new) @@ -2444,7 +2608,7 @@ class TestIP6PuntHandoff(IP6PuntSetup, VppTestCase): class TestIP6Deag(VppTestCase): - """ IPv6 Deaggregate Routes """ + """IPv6 Deaggregate Routes""" @classmethod def setUpClass(cls): @@ -2471,7 +2635,7 @@ class TestIP6Deag(VppTestCase): i.admin_down() def test_ip_deag(self): - """ IP Deag Routes """ + """IP Deag Routes""" # # Create a table to be used for: @@ -2487,16 +2651,22 @@ class TestIP6Deag(VppTestCase): # Add a route in the default table to point to a deag/ # second lookup in each of these tables # - route_to_dst = VppIpRoute(self, "1::1", 128, - [VppRoutePath("::", - 0xffffffff, - nh_table_id=1)]) + route_to_dst = VppIpRoute( + self, "1::1", 128, [VppRoutePath("::", 0xFFFFFFFF, nh_table_id=1)] + ) route_to_src = VppIpRoute( - self, "1::2", 128, - [VppRoutePath("::", - 0xffffffff, - nh_table_id=2, - type=FibPathType.FIB_PATH_TYPE_SOURCE_LOOKUP)]) + self, + "1::2", + 128, + [ + VppRoutePath( + "::", + 0xFFFFFFFF, + nh_table_id=2, + type=FibPathType.FIB_PATH_TYPE_SOURCE_LOOKUP, + ) + ], + ) route_to_dst.add_vpp_config() route_to_src.add_vpp_config() @@ -2505,31 +2675,34 @@ class TestIP6Deag(VppTestCase): # packets to these destination are dropped, since they'll # hit the respective default routes in the second table # - p_dst = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(src="5::5", dst="1::1") / - inet6.TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - p_src = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(src="2::2", dst="1::2") / - inet6.TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p_dst = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src="5::5", dst="1::1") + / inet6.TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + p_src = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src="2::2", dst="1::2") + / inet6.TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) pkts_dst = p_dst * 257 pkts_src = p_src * 257 - self.send_and_assert_no_replies(self.pg0, pkts_dst, - "IP in dst table") - self.send_and_assert_no_replies(self.pg0, pkts_src, - "IP in src table") + self.send_and_assert_no_replies(self.pg0, pkts_dst, "IP in dst table") + self.send_and_assert_no_replies(self.pg0, pkts_src, "IP in src table") # # add a route in the dst table to forward via pg1 # - route_in_dst = VppIpRoute(self, "1::1", 128, - [VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index)], - table_id=1) + route_in_dst = VppIpRoute( + self, + "1::1", + 128, + [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)], + table_id=1, + ) route_in_dst.add_vpp_config() self.send_and_expect(self.pg0, pkts_dst, self.pg1) @@ -2537,33 +2710,34 @@ class TestIP6Deag(VppTestCase): # # add a route in the src table to forward via pg2 # - route_in_src = VppIpRoute(self, "2::2", 128, - [VppRoutePath(self.pg2.remote_ip6, - self.pg2.sw_if_index)], - table_id=2) + route_in_src = VppIpRoute( + self, + "2::2", + 128, + [VppRoutePath(self.pg2.remote_ip6, self.pg2.sw_if_index)], + table_id=2, + ) route_in_src.add_vpp_config() self.send_and_expect(self.pg0, pkts_src, self.pg2) # # loop in the lookup DP # - route_loop = VppIpRoute(self, "3::3", 128, - [VppRoutePath("::", - 0xffffffff)]) + route_loop = VppIpRoute(self, "3::3", 128, [VppRoutePath("::", 0xFFFFFFFF)]) route_loop.add_vpp_config() - p_l = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(src="3::4", dst="3::3") / - inet6.TCP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p_l = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src="3::4", dst="3::3") + / inet6.TCP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) - self.send_and_assert_no_replies(self.pg0, p_l * 257, - "IP lookup loop") + self.send_and_assert_no_replies(self.pg0, p_l * 257, "IP lookup loop") class TestIP6Input(VppTestCase): - """ IPv6 Input Exception Test Cases """ + """IPv6 Input Exception Test Cases""" @classmethod def setUpClass(cls): @@ -2590,72 +2764,110 @@ class TestIP6Input(VppTestCase): i.admin_down() def test_ip_input_icmp_reply(self): - """ IP6 Input Exception - Return ICMP (3,0) """ + """IP6 Input Exception - Return ICMP (3,0)""" # # hop limit - ICMP replies # - p_version = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(src=self.pg0.remote_ip6, - dst=self.pg1.remote_ip6, - hlim=1) / - inet6.UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p_version = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6, hlim=1) + / inet6.UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) - rxs = self.send_and_expect_some(self.pg0, - p_version * NUM_PKTS, - self.pg0) + rxs = self.send_and_expect_some(self.pg0, p_version * NUM_PKTS, self.pg0) for rx in rxs: icmp = rx[ICMPv6TimeExceeded] # 0: "hop limit exceeded in transit", self.assertEqual((icmp.type, icmp.code), (3, 0)) - icmpv6_data = '\x0a' * 18 + icmpv6_data = "\x0a" * 18 all_0s = "::" all_1s = "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF" - @parameterized.expand([ - # Name, src, dst, l4proto, msg, timeout - ("src='iface', dst='iface'", None, None, - inet6.UDP(sport=1234, dport=1234), "funky version", None), - ("src='All 0's', dst='iface'", all_0s, None, - ICMPv6EchoRequest(id=0xb, seq=5, data=icmpv6_data), None, 0.1), - ("src='iface', dst='All 0's'", None, all_0s, - ICMPv6EchoRequest(id=0xb, seq=5, data=icmpv6_data), None, 0.1), - ("src='All 1's', dst='iface'", all_1s, None, - ICMPv6EchoRequest(id=0xb, seq=5, data=icmpv6_data), None, 0.1), - ("src='iface', dst='All 1's'", None, all_1s, - ICMPv6EchoRequest(id=0xb, seq=5, data=icmpv6_data), None, 0.1), - ("src='All 1's', dst='All 1's'", all_1s, all_1s, - ICMPv6EchoRequest(id=0xb, seq=5, data=icmpv6_data), None, 0.1), - - ]) + @parameterized.expand( + [ + # Name, src, dst, l4proto, msg, timeout + ( + "src='iface', dst='iface'", + None, + None, + inet6.UDP(sport=1234, dport=1234), + "funky version", + None, + ), + ( + "src='All 0's', dst='iface'", + all_0s, + None, + ICMPv6EchoRequest(id=0xB, seq=5, data=icmpv6_data), + None, + 0.1, + ), + ( + "src='iface', dst='All 0's'", + None, + all_0s, + ICMPv6EchoRequest(id=0xB, seq=5, data=icmpv6_data), + None, + 0.1, + ), + ( + "src='All 1's', dst='iface'", + all_1s, + None, + ICMPv6EchoRequest(id=0xB, seq=5, data=icmpv6_data), + None, + 0.1, + ), + ( + "src='iface', dst='All 1's'", + None, + all_1s, + ICMPv6EchoRequest(id=0xB, seq=5, data=icmpv6_data), + None, + 0.1, + ), + ( + "src='All 1's', dst='All 1's'", + all_1s, + all_1s, + ICMPv6EchoRequest(id=0xB, seq=5, data=icmpv6_data), + None, + 0.1, + ), + ] + ) def test_ip_input_no_replies(self, name, src, dst, l4, msg, timeout): - self._testMethodDoc = 'IPv6 Input Exception - %s' % name - - p_version = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(src=src or self.pg0.remote_ip6, - dst=dst or self.pg1.remote_ip6, - version=3) / - l4 / - Raw(b'\xa5' * 100)) + self._testMethodDoc = "IPv6 Input Exception - %s" % name + + p_version = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6( + src=src or self.pg0.remote_ip6, + dst=dst or self.pg1.remote_ip6, + version=3, + ) + / l4 + / Raw(b"\xa5" * 100) + ) - self.send_and_assert_no_replies(self.pg0, p_version * NUM_PKTS, - remark=msg or "", - timeout=timeout) + self.send_and_assert_no_replies( + self.pg0, p_version * NUM_PKTS, remark=msg or "", timeout=timeout + ) def test_hop_by_hop(self): - """ Hop-by-hop header test """ - - p = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) / - IPv6ExtHdrHopByHop() / - inet6.UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + """Hop-by-hop header test""" + + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) + / IPv6ExtHdrHopByHop() + / inet6.UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) @@ -2663,7 +2875,7 @@ class TestIP6Input(VppTestCase): class TestIP6Replace(VppTestCase): - """ IPv6 Table Replace """ + """IPv6 Table Replace""" @classmethod def setUpClass(cls): @@ -2685,8 +2897,7 @@ class TestIP6Replace(VppTestCase): i.admin_up() i.config_ip6() i.generate_remote_hosts(2) - self.tables.append(VppIpTable(self, table_id, - True).add_vpp_config()) + self.tables.append(VppIpTable(self, table_id, True).add_vpp_config()) table_id += 1 def tearDown(self): @@ -2696,7 +2907,7 @@ class TestIP6Replace(VppTestCase): i.unconfig_ip6() def test_replace(self): - """ IP Table Replace """ + """IP Table Replace""" MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t @@ -2713,31 +2924,50 @@ class TestIP6Replace(VppTestCase): for ii, t in enumerate(self.tables): for jj in range(1, N_ROUTES): uni = VppIpRoute( - self, "2001::%d" % jj if jj != 0 else "2001::", 128, - [VppRoutePath(links[ii].remote_hosts[0].ip6, - links[ii].sw_if_index), - VppRoutePath(links[ii].remote_hosts[1].ip6, - links[ii].sw_if_index)], - table_id=t.table_id).add_vpp_config() + self, + "2001::%d" % jj if jj != 0 else "2001::", + 128, + [ + VppRoutePath( + links[ii].remote_hosts[0].ip6, links[ii].sw_if_index + ), + VppRoutePath( + links[ii].remote_hosts[1].ip6, links[ii].sw_if_index + ), + ], + table_id=t.table_id, + ).add_vpp_config() multi = VppIpMRoute( - self, "::", - "ff:2001::%d" % jj, 128, + self, + "::", + "ff:2001::%d" % jj, + 128, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - [VppMRoutePath(self.pg0.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6), - VppMRoutePath(self.pg1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6), - VppMRoutePath(self.pg2.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6), - VppMRoutePath(self.pg3.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)], - table_id=t.table_id).add_vpp_config() - routes[ii].append({'uni': uni, - 'multi': multi}) + [ + VppMRoutePath( + self.pg0.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ), + VppMRoutePath( + self.pg1.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ), + VppMRoutePath( + self.pg2.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ), + VppMRoutePath( + self.pg3.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ), + ], + table_id=t.table_id, + ).add_vpp_config() + routes[ii].append({"uni": uni, "multi": multi}) # # replace the tables a few times @@ -2752,14 +2982,14 @@ class TestIP6Replace(VppTestCase): dump = t.dump() mdump = t.mdump() for r in routes[ii]: - self.assertTrue(find_route_in_dump(dump, r['uni'], t)) - self.assertTrue(find_mroute_in_dump(mdump, r['multi'], t)) + self.assertTrue(find_route_in_dump(dump, r["uni"], t)) + self.assertTrue(find_mroute_in_dump(mdump, r["multi"], t)) # redownload the even numbered routes for ii, t in enumerate(self.tables): for jj in range(0, N_ROUTES, 2): - routes[ii][jj]['uni'].add_vpp_config() - routes[ii][jj]['multi'].add_vpp_config() + routes[ii][jj]["uni"].add_vpp_config() + routes[ii][jj]["multi"].add_vpp_config() # signal each table converged for t in self.tables: @@ -2770,29 +3000,29 @@ class TestIP6Replace(VppTestCase): dump = t.dump() mdump = t.mdump() for jj in range(0, N_ROUTES, 2): - self.assertTrue(find_route_in_dump( - dump, routes[ii][jj]['uni'], t)) - self.assertTrue(find_mroute_in_dump( - mdump, routes[ii][jj]['multi'], t)) + self.assertTrue(find_route_in_dump(dump, routes[ii][jj]["uni"], t)) + self.assertTrue( + find_mroute_in_dump(mdump, routes[ii][jj]["multi"], t) + ) for jj in range(1, N_ROUTES - 1, 2): - self.assertFalse(find_route_in_dump( - dump, routes[ii][jj]['uni'], t)) - self.assertFalse(find_mroute_in_dump( - mdump, routes[ii][jj]['multi'], t)) + self.assertFalse(find_route_in_dump(dump, routes[ii][jj]["uni"], t)) + self.assertFalse( + find_mroute_in_dump(mdump, routes[ii][jj]["multi"], t) + ) # reload all the routes for ii, t in enumerate(self.tables): for r in routes[ii]: - r['uni'].add_vpp_config() - r['multi'].add_vpp_config() + r["uni"].add_vpp_config() + r["multi"].add_vpp_config() # all the routes are still there for ii, t in enumerate(self.tables): dump = t.dump() mdump = t.mdump() for r in routes[ii]: - self.assertTrue(find_route_in_dump(dump, r['uni'], t)) - self.assertTrue(find_mroute_in_dump(mdump, r['multi'], t)) + self.assertTrue(find_route_in_dump(dump, r["uni"], t)) + self.assertTrue(find_mroute_in_dump(mdump, r["multi"], t)) # # finally flush the tables for good measure @@ -2804,7 +3034,7 @@ class TestIP6Replace(VppTestCase): class TestIP6AddrReplace(VppTestCase): - """ IPv6 Interface Address Replace """ + """IPv6 Interface Address Replace""" @classmethod def setUpClass(cls): @@ -2831,7 +3061,7 @@ class TestIP6AddrReplace(VppTestCase): return len(self.vapi.ip_address_dump(intf.sw_if_index, True)) def test_replace(self): - """ IP interface address replace """ + """IP interface address replace""" intf_pfxs = [[], [], [], []] @@ -2915,8 +3145,7 @@ class TestIP6AddrReplace(VppTestCase): for intf in self.pg_interfaces: # 2001:18:x::1/64 addr = "2001:18:%d::1" % intf.sw_if_index - pfxs.append(VppIpInterfaceAddress(self, intf, addr, - 64).add_vpp_config()) + pfxs.append(VppIpInterfaceAddress(self, intf, addr, 64).add_vpp_config()) self.vapi.sw_interface_address_replace_end() @@ -2951,8 +3180,7 @@ class TestIP6AddrReplace(VppTestCase): for intf in self.pg_interfaces: # 2001:18:x::1/64 addr = "2001:18:%d::1" % (intf.sw_if_index + 1) - pfxs.append(VppIpInterfaceAddress(self, intf, - addr, 64).add_vpp_config()) + pfxs.append(VppIpInterfaceAddress(self, intf, addr, 64).add_vpp_config()) self.vapi.sw_interface_address_replace_end() @@ -2965,7 +3193,7 @@ class TestIP6AddrReplace(VppTestCase): class TestIP6LinkLocal(VppTestCase): - """ IPv6 Link Local """ + """IPv6 Link Local""" @classmethod def setUpClass(cls): @@ -2989,7 +3217,7 @@ class TestIP6LinkLocal(VppTestCase): i.admin_down() def test_ip6_ll(self): - """ IPv6 Link Local """ + """IPv6 Link Local""" # # two APIs to add a link local address. @@ -3004,35 +3232,33 @@ class TestIP6LinkLocal(VppTestCase): ll2 = "fe80:2::2" ll3 = "fe80:3::3" - VppNeighbor(self, - self.pg0.sw_if_index, - self.pg0.remote_mac, - ll2).add_vpp_config() + VppNeighbor( + self, self.pg0.sw_if_index, self.pg0.remote_mac, ll2 + ).add_vpp_config() VppIpInterfaceAddress(self, self.pg0, ll1, 128).add_vpp_config() # # should be able to ping the ll # - p_echo_request_1 = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(src=ll2, - dst=ll1) / - ICMPv6EchoRequest()) + p_echo_request_1 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=ll2, dst=ll1) + / ICMPv6EchoRequest() + ) self.send_and_expect(self.pg0, [p_echo_request_1], self.pg0) # # change the link-local on pg0 # - v_ll3 = VppIpInterfaceAddress(self, self.pg0, - ll3, 128).add_vpp_config() + v_ll3 = VppIpInterfaceAddress(self, self.pg0, ll3, 128).add_vpp_config() - p_echo_request_3 = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(src=ll2, - dst=ll3) / - ICMPv6EchoRequest()) + p_echo_request_3 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=ll2, dst=ll3) + / ICMPv6EchoRequest() + ) self.send_and_expect(self.pg0, [p_echo_request_3], self.pg0) @@ -3057,13 +3283,13 @@ class TestIP6LinkLocal(VppTestCase): self.send_and_expect(self.pg1, [p_echo_request_3], self.pg1) def test_ip6_ll_p2p(self): - """ IPv6 Link Local P2P (GRE)""" + """IPv6 Link Local P2P (GRE)""" self.pg0.config_ip4() self.pg0.resolve_arp() - gre_if = VppGreInterface(self, - self.pg0.local_ip4, - self.pg0.remote_ip4).add_vpp_config() + gre_if = VppGreInterface( + self, self.pg0.local_ip4, self.pg0.remote_ip4 + ).add_vpp_config() gre_if.admin_up() ll1 = "fe80:1::1" @@ -3073,20 +3299,20 @@ class TestIP6LinkLocal(VppTestCase): self.logger.info(self.vapi.cli("sh ip6-ll gre0 fe80:2::2")) - p_echo_request_1 = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, - dst=self.pg0.local_ip4) / - GRE() / - IPv6(src=ll2, dst=ll1) / - ICMPv6EchoRequest()) + p_echo_request_1 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / GRE() + / IPv6(src=ll2, dst=ll1) + / ICMPv6EchoRequest() + ) self.send_and_expect(self.pg0, [p_echo_request_1], self.pg0) self.pg0.unconfig_ip4() gre_if.remove_vpp_config() def test_ip6_ll_p2mp(self): - """ IPv6 Link Local P2MP (GRE)""" + """IPv6 Link Local P2MP (GRE)""" self.pg0.config_ip4() self.pg0.resolve_arp() @@ -3095,8 +3321,8 @@ class TestIP6LinkLocal(VppTestCase): self, self.pg0.local_ip4, "0.0.0.0", - mode=(VppEnum.vl_api_tunnel_mode_t. - TUNNEL_API_MODE_MP)).add_vpp_config() + mode=(VppEnum.vl_api_tunnel_mode_t.TUNNEL_API_MODE_MP), + ).add_vpp_config() gre_if.admin_up() ll1 = "fe80:1::1" @@ -3104,13 +3330,13 @@ class TestIP6LinkLocal(VppTestCase): VppIpInterfaceAddress(self, gre_if, ll1, 128).add_vpp_config() - p_echo_request_1 = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, - dst=self.pg0.local_ip4) / - GRE() / - IPv6(src=ll2, dst=ll1) / - ICMPv6EchoRequest()) + p_echo_request_1 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / GRE() + / IPv6(src=ll2, dst=ll1) + / ICMPv6EchoRequest() + ) # no route back at this point self.send_and_assert_no_replies(self.pg0, [p_echo_request_1]) @@ -3127,7 +3353,7 @@ class TestIP6LinkLocal(VppTestCase): class TestIPv6PathMTU(VppTestCase): - """ IPv6 Path MTU """ + """IPv6 Path MTU""" def setUp(self): super(TestIPv6PathMTU, self).setUp() @@ -3147,7 +3373,7 @@ class TestIPv6PathMTU(VppTestCase): i.admin_down() def test_path_mtu_local(self): - """ Path MTU for attached neighbour """ + """Path MTU for attached neighbour""" self.vapi.cli("set log class ip level debug") # @@ -3161,41 +3387,37 @@ class TestIPv6PathMTU(VppTestCase): # packets post encap # tun = VppIpIpTunInterface( - self, - self.pg1, - self.pg1.local_ip6, - self.pg1.remote_ip6) + self, self.pg1, self.pg1.local_ip6, self.pg1.remote_ip6 + ) tun.add_vpp_config() tun.admin_up() tun.config_ip6() # set the interface MTU to a reasonable value - self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, - [2800, 0, 0, 0]) - - p_6k = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, - dst=tun.remote_ip6) / - UDP(sport=1234, dport=5678) / - Raw(b'0xa' * 2000)) - p_2k = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, - dst=tun.remote_ip6) / - UDP(sport=1234, dport=5678) / - Raw(b'0xa' * 1000)) - p_1k = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, - dst=tun.remote_ip6) / - UDP(sport=1234, dport=5678) / - Raw(b'0xa' * 600)) - - nbr = VppNeighbor(self, - self.pg1.sw_if_index, - self.pg1.remote_mac, - self.pg1.remote_ip6).add_vpp_config() + self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [2800, 0, 0, 0]) + + p_6k = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=tun.remote_ip6) + / UDP(sport=1234, dport=5678) + / Raw(b"0xa" * 2000) + ) + p_2k = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=tun.remote_ip6) + / UDP(sport=1234, dport=5678) + / Raw(b"0xa" * 1000) + ) + p_1k = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=tun.remote_ip6) + / UDP(sport=1234, dport=5678) + / Raw(b"0xa" * 600) + ) + + nbr = VppNeighbor( + self, self.pg1.sw_if_index, self.pg1.remote_mac, self.pg1.remote_ip6 + ).add_vpp_config() # this is now the interface MTU frags self.send_and_expect(self.pg0, [p_6k], self.pg1, n_rx=4) @@ -3228,28 +3450,25 @@ class TestIPv6PathMTU(VppTestCase): # raise the interface's MTU # should still use that of the path - self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, - [2000, 0, 0, 0]) + self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [2000, 0, 0, 0]) self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3) self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2) # set path high and interface low pmtu.modify(2000) - self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, - [1300, 0, 0, 0]) + self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [1300, 0, 0, 0]) self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3) self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2) # remove the path MTU - self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, - [2800, 0, 0, 0]) + self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [2800, 0, 0, 0]) pmtu.modify(0) self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=2) self.send_and_expect(self.pg0, [p_1k], self.pg1) def test_path_mtu_remote(self): - """ Path MTU for remote neighbour """ + """Path MTU for remote neighbour""" self.vapi.cli("set log class ip level debug") # @@ -3260,44 +3479,37 @@ class TestIPv6PathMTU(VppTestCase): tun_dst = "2001::1" route = VppIpRoute( - self, tun_dst, 64, - [VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index)]).add_vpp_config() + self, tun_dst, 64, [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)] + ).add_vpp_config() # # IPv6 will only frag locally generated packets, so use tunnelled # packets post encap # - tun = VppIpIpTunInterface( - self, - self.pg1, - self.pg1.local_ip6, - tun_dst) + tun = VppIpIpTunInterface(self, self.pg1, self.pg1.local_ip6, tun_dst) tun.add_vpp_config() tun.admin_up() tun.config_ip6() # set the interface MTU to a reasonable value - self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, - [2800, 0, 0, 0]) - - p_2k = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, - dst=tun.remote_ip6) / - UDP(sport=1234, dport=5678) / - Raw(b'0xa' * 1000)) - p_1k = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, - dst=tun.remote_ip6) / - UDP(sport=1234, dport=5678) / - Raw(b'0xa' * 600)) - - nbr = VppNeighbor(self, - self.pg1.sw_if_index, - self.pg1.remote_mac, - self.pg1.remote_ip6).add_vpp_config() + self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [2800, 0, 0, 0]) + + p_2k = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=tun.remote_ip6) + / UDP(sport=1234, dport=5678) + / Raw(b"0xa" * 1000) + ) + p_1k = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=tun.remote_ip6) + / UDP(sport=1234, dport=5678) + / Raw(b"0xa" * 600) + ) + + nbr = VppNeighbor( + self, self.pg1.sw_if_index, self.pg1.remote_mac, self.pg1.remote_ip6 + ).add_vpp_config() # this is now the interface MTU frags self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=2) @@ -3328,44 +3540,38 @@ class TestIPv6PathMTU(VppTestCase): # raise the interface's MTU # should still use that of the path - self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, - [2000, 0, 0, 0]) + self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [2000, 0, 0, 0]) self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3) self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2) # turn the tun_dst into an attached neighbour - route.modify([VppRoutePath("::", - self.pg1.sw_if_index)]) - nbr2 = VppNeighbor(self, - self.pg1.sw_if_index, - self.pg1.remote_mac, - tun_dst).add_vpp_config() + route.modify([VppRoutePath("::", self.pg1.sw_if_index)]) + nbr2 = VppNeighbor( + self, self.pg1.sw_if_index, self.pg1.remote_mac, tun_dst + ).add_vpp_config() self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3) self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2) # add back to not attached nbr2.remove_vpp_config() - route.modify([VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index)]) + route.modify([VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)]) # set path high and interface low pmtu.modify(2000) - self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, - [1300, 0, 0, 0]) + self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [1300, 0, 0, 0]) self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3) self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2) # remove the path MTU - self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, - [2800, 0, 0, 0]) + self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [2800, 0, 0, 0]) pmtu.remove_vpp_config() self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=2) self.send_and_expect(self.pg0, [p_1k], self.pg1) class TestIPFibSource(VppTestCase): - """ IPv6 Table FibSource """ + """IPv6 Table FibSource""" @classmethod def setUpClass(cls): @@ -3394,7 +3600,7 @@ class TestIPFibSource(VppTestCase): i.unconfig_ip4() def test_fib_source(self): - """ IP Table FibSource """ + """IP Table FibSource""" routes = self.vapi.ip_route_v2_dump(0, True) @@ -3404,15 +3610,15 @@ class TestIPFibSource(VppTestCase): # dump all the sources in the FIB sources = self.vapi.fib_source_dump() for source in sources: - if (source.src.name == "API"): + if source.src.name == "API": api_source = source.src - if (source.src.name == "interface"): + if source.src.name == "interface": intf_source = source.src - if (source.src.name == "adjacency"): + if source.src.name == "adjacency": adj_source = source.src - if (source.src.name == "special"): + if source.src.name == "special": special_source = source.src - if (source.src.name == "default-route"): + if source.src.name == "default-route": dr_source = source.src # dump the individual route types @@ -3426,37 +3632,43 @@ class TestIPFibSource(VppTestCase): self.assertEqual(len(routes), 1) # add a new soure that'a better than the API - self.vapi.fib_source_add(src={'name': "bgp", - "priority": api_source.priority - 1}) + self.vapi.fib_source_add( + src={"name": "bgp", "priority": api_source.priority - 1} + ) # dump all the sources to check our new one is there sources = self.vapi.fib_source_dump() for source in sources: - if (source.src.name == "bgp"): + if source.src.name == "bgp": bgp_source = source.src self.assertTrue(bgp_source) - self.assertEqual(bgp_source.priority, - api_source.priority - 1) + self.assertEqual(bgp_source.priority, api_source.priority - 1) # add a route with the default API source r1 = VppIpRouteV2( - self, "2001::1", 128, - [VppRoutePath(self.pg0.remote_ip6, - self.pg0.sw_if_index)]).add_vpp_config() + self, + "2001::1", + 128, + [VppRoutePath(self.pg0.remote_ip6, self.pg0.sw_if_index)], + ).add_vpp_config() - r2 = VppIpRouteV2(self, "2001::1", 128, - [VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index)], - src=bgp_source.id).add_vpp_config() + r2 = VppIpRouteV2( + self, + "2001::1", + 128, + [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)], + src=bgp_source.id, + ).add_vpp_config() # ensure the BGP source takes priority - p = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(src=self.pg0.remote_ip6, dst="2001::1") / - inet6.UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=self.pg0.remote_ip6, dst="2001::1") + / inet6.UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) self.send_and_expect(self.pg0, [p], self.pg1) @@ -3467,7 +3679,7 @@ class TestIPFibSource(VppTestCase): class TestIPxAF(VppTestCase): - """ IP cross AF """ + """IP cross AF""" @classmethod def setUpClass(cls): @@ -3497,20 +3709,23 @@ class TestIPxAF(VppTestCase): i.unconfig_ip6() def test_x_af(self): - """ Cross AF routing """ + """Cross AF routing""" N_PKTS = 63 # a v4 route via a v6 attached next-hop VppIpRoute( - self, "1.1.1.1", 32, - [VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index)]).add_vpp_config() - - p = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst="1.1.1.1") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + self, + "1.1.1.1", + 32, + [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)], + ).add_vpp_config() + + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst="1.1.1.1") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) rxs = self.send_and_expect(self.pg0, p * N_PKTS, self.pg1) for rx in rxs: @@ -3518,15 +3733,18 @@ class TestIPxAF(VppTestCase): # a v6 route via a v4 attached next-hop VppIpRoute( - self, "2001::1", 128, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index)]).add_vpp_config() - - p = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(src=self.pg0.remote_ip6, dst="2001::1") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + self, + "2001::1", + 128, + [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)], + ).add_vpp_config() + + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=self.pg0.remote_ip6, dst="2001::1") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) rxs = self.send_and_expect(self.pg0, p * N_PKTS, self.pg1) for rx in rxs: @@ -3534,56 +3752,56 @@ class TestIPxAF(VppTestCase): # a recursive v4 route via a v6 next-hop (from above) VppIpRoute( - self, "2.2.2.2", 32, - [VppRoutePath("2001::1", - 0xffffffff)]).add_vpp_config() - - p = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst="2.2.2.2") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + self, "2.2.2.2", 32, [VppRoutePath("2001::1", 0xFFFFFFFF)] + ).add_vpp_config() + + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst="2.2.2.2") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) rxs = self.send_and_expect(self.pg0, p * N_PKTS, self.pg1) # a recursive v4 route via a v6 next-hop VppIpRoute( - self, "2.2.2.3", 32, - [VppRoutePath(self.pg1.remote_ip6, - 0xffffffff)]).add_vpp_config() - - p = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst="2.2.2.3") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + self, "2.2.2.3", 32, [VppRoutePath(self.pg1.remote_ip6, 0xFFFFFFFF)] + ).add_vpp_config() + + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst="2.2.2.3") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) rxs = self.send_and_expect(self.pg0, p * N_PKTS, self.pg1) # a recursive v6 route via a v4 next-hop VppIpRoute( - self, "3001::1", 128, - [VppRoutePath(self.pg1.remote_ip4, - 0xffffffff)]).add_vpp_config() - - p = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(src=self.pg0.remote_ip6, dst="3001::1") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + self, "3001::1", 128, [VppRoutePath(self.pg1.remote_ip4, 0xFFFFFFFF)] + ).add_vpp_config() + + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=self.pg0.remote_ip6, dst="3001::1") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) rxs = self.send_and_expect(self.pg0, p * N_PKTS, self.pg1) for rx in rxs: self.assertEqual(rx[IPv6].dst, "3001::1") VppIpRoute( - self, "3001::2", 128, - [VppRoutePath("1.1.1.1", - 0xffffffff)]).add_vpp_config() - - p = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(src=self.pg0.remote_ip6, dst="3001::2") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + self, "3001::2", 128, [VppRoutePath("1.1.1.1", 0xFFFFFFFF)] + ).add_vpp_config() + + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=self.pg0.remote_ip6, dst="3001::2") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) rxs = self.send_and_expect(self.pg0, p * N_PKTS, self.pg1) for rx in rxs: @@ -3591,7 +3809,7 @@ class TestIPxAF(VppTestCase): class TestIPv6Punt(VppTestCase): - """ IPv6 Punt Police/Redirect """ + """IPv6 Punt Police/Redirect""" def setUp(self): super(TestIPv6Punt, self).setUp() @@ -3609,7 +3827,7 @@ class TestIPv6Punt(VppTestCase): i.admin_down() def test_ip6_punt(self): - """ IPv6 punt police and redirect """ + """IPv6 punt police and redirect""" # use UDP packet that have a port we need to explicitly # register to get punted. @@ -3617,30 +3835,32 @@ class TestIPv6Punt(VppTestCase): af_ip6 = VppEnum.vl_api_address_family_t.ADDRESS_IP6 udp_proto = VppEnum.vl_api_ip_proto_t.IP_API_PROTO_UDP punt_udp = { - 'type': pt_l4, - 'punt': { - 'l4': { - 'af': af_ip6, - 'protocol': udp_proto, - 'port': 7654, + "type": pt_l4, + "punt": { + "l4": { + "af": af_ip6, + "protocol": udp_proto, + "port": 7654, } - } + }, } self.vapi.set_punt(is_add=1, punt=punt_udp) - pkts = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) / - UDP(sport=1234, dport=7654) / - Raw(b'\xa5' * 100)) * 1025 + pkts = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) + / UDP(sport=1234, dport=7654) + / Raw(b"\xa5" * 100) + ) * 1025 # # Configure a punt redirect via pg1. # nh_addr = self.pg1.remote_ip6 - ip_punt_redirect = VppIpPuntRedirect(self, self.pg0.sw_if_index, - self.pg1.sw_if_index, nh_addr) + ip_punt_redirect = VppIpPuntRedirect( + self, self.pg0.sw_if_index, self.pg1.sw_if_index, nh_addr + ) ip_punt_redirect.add_vpp_config() self.send_and_expect(self.pg0, pkts, self.pg1) @@ -3650,8 +3870,7 @@ class TestIPv6Punt(VppTestCase): # policer = VppPolicer(self, "ip6-punt", 400, 0, 10, 0, rate_type=1) policer.add_vpp_config() - ip_punt_policer = VppIpPuntPolicer(self, policer.policer_index, - is_ip6=True) + ip_punt_policer = VppIpPuntPolicer(self, policer.policer_index, is_ip6=True) ip_punt_policer.add_vpp_config() self.vapi.cli("clear trace") @@ -3668,9 +3887,9 @@ class TestIPv6Punt(VppTestCase): stats = policer.get_stats() # Single rate policer - expect conform, violate but no exceed - self.assertGreater(stats['conform_packets'], 0) - self.assertEqual(stats['exceed_packets'], 0) - self.assertGreater(stats['violate_packets'], 0) + self.assertGreater(stats["conform_packets"], 0) + self.assertEqual(stats["exceed_packets"], 0) + self.assertGreater(stats["violate_packets"], 0) self.assertGreater(len(rx), 0) self.assertLess(len(rx), len(pkts)) @@ -3686,31 +3905,34 @@ class TestIPv6Punt(VppTestCase): # remove the redirect. expect full drop. # ip_punt_redirect.remove_vpp_config() - self.send_and_assert_no_replies(self.pg0, pkts, - "IP no punt config") + self.send_and_assert_no_replies(self.pg0, pkts, "IP no punt config") # # Add a redirect that is not input port selective # - ip_punt_redirect = VppIpPuntRedirect(self, 0xffffffff, - self.pg1.sw_if_index, nh_addr) + ip_punt_redirect = VppIpPuntRedirect( + self, 0xFFFFFFFF, self.pg1.sw_if_index, nh_addr + ) ip_punt_redirect.add_vpp_config() self.send_and_expect(self.pg0, pkts, self.pg1) ip_punt_redirect.remove_vpp_config() def test_ip6_punt_dump(self): - """ IPv6 punt redirect dump""" + """IPv6 punt redirect dump""" # # Configure a punt redirects # nh_address = self.pg3.remote_ip6 - ipr_03 = VppIpPuntRedirect(self, self.pg0.sw_if_index, - self.pg3.sw_if_index, nh_address) - ipr_13 = VppIpPuntRedirect(self, self.pg1.sw_if_index, - self.pg3.sw_if_index, nh_address) - ipr_23 = VppIpPuntRedirect(self, self.pg2.sw_if_index, - self.pg3.sw_if_index, "::") + ipr_03 = VppIpPuntRedirect( + self, self.pg0.sw_if_index, self.pg3.sw_if_index, nh_address + ) + ipr_13 = VppIpPuntRedirect( + self, self.pg1.sw_if_index, self.pg3.sw_if_index, nh_address + ) + ipr_23 = VppIpPuntRedirect( + self, self.pg2.sw_if_index, self.pg3.sw_if_index, "::" + ) ipr_03.add_vpp_config() ipr_13.add_vpp_config() ipr_23.add_vpp_config() @@ -3725,14 +3947,13 @@ class TestIPv6Punt(VppTestCase): # # Dump punt redirects for all interfaces # - punts = self.vapi.ip_punt_redirect_dump(sw_if_index=0xffffffff, - is_ipv6=True) + punts = self.vapi.ip_punt_redirect_dump(sw_if_index=0xFFFFFFFF, is_ipv6=True) self.assertEqual(len(punts), 3) for p in punts: self.assertEqual(p.punt.tx_sw_if_index, self.pg3.sw_if_index) self.assertNotEqual(punts[1].punt.nh, self.pg3.remote_ip6) - self.assertEqual(str(punts[2].punt.nh), '::') + self.assertEqual(str(punts[2].punt.nh), "::") -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_ip6_nd_mirror_proxy.py b/test/test_ip6_nd_mirror_proxy.py index fa9880122fc..9214e32b447 100644 --- a/test/test_ip6_nd_mirror_proxy.py +++ b/test/test_ip6_nd_mirror_proxy.py @@ -7,8 +7,15 @@ from socket import AF_INET6, inet_pton, inet_ntop from framework import tag_fixme_vpp_workers from framework import VppTestCase, VppTestRunner from vpp_neighbor import VppNeighbor, find_nbr -from vpp_ip_route import VppIpRoute, VppRoutePath, find_route, \ - VppIpTable, DpoProto, FibPathType, VppIpInterfaceAddress +from vpp_ip_route import ( + VppIpRoute, + VppRoutePath, + find_route, + VppIpTable, + DpoProto, + FibPathType, + VppIpInterfaceAddress, +) from vpp_papi import VppEnum from vpp_ip import VppIpPuntRedirect @@ -16,14 +23,21 @@ import scapy.compat from scapy.packet import Raw from scapy.layers.l2 import Ether, ARP, Dot1Q from scapy.layers.inet import IP, UDP, TCP -from scapy.layers.inet6 import IPv6, ipv6nh, ICMPv6ND_NS, ICMPv6ND_NA, \ - ICMPv6NDOptSrcLLAddr, ICMPv6NDOptDstLLAddr, ICMPv6EchoRequest, \ - ICMPv6EchoReply +from scapy.layers.inet6 import ( + IPv6, + ipv6nh, + ICMPv6ND_NS, + ICMPv6ND_NA, + ICMPv6NDOptSrcLLAddr, + ICMPv6NDOptDstLLAddr, + ICMPv6EchoRequest, + ICMPv6EchoReply, +) from scapy.utils6 import in6_ptop, in6_getnsma, in6_getnsmac, in6_ismaddr class TestNDPROXY(VppTestCase): - """ IP6 ND (mirror) Proxy Test Case """ + """IP6 ND (mirror) Proxy Test Case""" @classmethod def setUpClass(self): @@ -49,7 +63,7 @@ class TestNDPROXY(VppTestCase): i.admin_down() def test_nd_mirror_proxy(self): - """ Interface (Mirror) Proxy ND """ + """Interface (Mirror) Proxy ND""" # # When VPP has an interface whose address is also applied to a TAP @@ -70,17 +84,19 @@ class TestNDPROXY(VppTestCase): # # Enable ND proxy on pg1 # - self.vapi.ip6nd_proxy_enable_disable(sw_if_index=self.pg1.sw_if_index, - is_enable=1) + self.vapi.ip6nd_proxy_enable_disable( + sw_if_index=self.pg1.sw_if_index, is_enable=1 + ) # # Send the ND request with an originating address that # is VPP's own address # - nd_req_from_host = (Ether(src=self.pg1.remote_mac, - dst=in6_getnsmac(nsma)) / - IPv6(dst=d, src=self.pg0.local_ip6) / - ICMPv6ND_NS(tgt=addr) / - ICMPv6NDOptSrcLLAddr(lladdr=self.pg1.remote_mac)) + nd_req_from_host = ( + Ether(src=self.pg1.remote_mac, dst=in6_getnsmac(nsma)) + / IPv6(dst=d, src=self.pg0.local_ip6) + / ICMPv6ND_NS(tgt=addr) + / ICMPv6NDOptSrcLLAddr(lladdr=self.pg1.remote_mac) + ) rx = self.send_and_expect(self.pg1, [nd_req_from_host], self.pg1) self.assertEqual(rx[0][Ether].src, self.pg1.local_mac) @@ -90,22 +106,19 @@ class TestNDPROXY(VppTestCase): self.assertEqual(ipv6nh[rx[0][IPv6].nh], "ICMPv6") self.assertEqual(rx[0][ICMPv6ND_NA].tgt, self.pg0.remote_ip6) self.assertTrue(rx[0].haslayer(ICMPv6NDOptDstLLAddr)) - self.assertEqual(rx[0][ICMPv6NDOptDstLLAddr].lladdr, - self.pg1.local_mac) + self.assertEqual(rx[0][ICMPv6NDOptDstLLAddr].lladdr, self.pg1.local_mac) # # Send the unicast ND request # - unicast_nd_req_from_host = (Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) / - IPv6(dst=self.pg0.remote_ip6, - src=self.pg1.remote_ip6_ll) / - ICMPv6ND_NS(tgt=self.pg0.remote_ip6) / - ICMPv6NDOptSrcLLAddr( - lladdr=self.pg1.remote_mac)) + unicast_nd_req_from_host = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IPv6(dst=self.pg0.remote_ip6, src=self.pg1.remote_ip6_ll) + / ICMPv6ND_NS(tgt=self.pg0.remote_ip6) + / ICMPv6NDOptSrcLLAddr(lladdr=self.pg1.remote_mac) + ) - rx = self.send_and_expect(self.pg1, [unicast_nd_req_from_host], - self.pg0) + rx = self.send_and_expect(self.pg1, [unicast_nd_req_from_host], self.pg0) self.assertEqual(rx[0][Ether].src, self.pg0.local_mac) self.assertEqual(rx[0][Ether].dst, in6_getnsmac(nsma)) self.assertEqual(rx[0][IPv6].src, self.pg0.local_ip6) @@ -113,8 +126,7 @@ class TestNDPROXY(VppTestCase): self.assertEqual(ipv6nh[rx[0][IPv6].nh], "ICMPv6") self.assertEqual(rx[0][ICMPv6ND_NS].tgt, self.pg0.remote_ip6) self.assertTrue(rx[0].haslayer(ICMPv6NDOptSrcLLAddr)) - self.assertEqual(rx[0][ICMPv6NDOptSrcLLAddr].lladdr, - self.pg0.local_mac) + self.assertEqual(rx[0][ICMPv6NDOptSrcLLAddr].lladdr, self.pg0.local_mac) # Resolve the NDs on the uplink self.pg0.resolve_ndp() @@ -123,28 +135,26 @@ class TestNDPROXY(VppTestCase): # Again send the unicast ND request, this time dst address should be # in local cache # - rx = self.send_and_expect(self.pg1, [unicast_nd_req_from_host], - self.pg1) + rx = self.send_and_expect(self.pg1, [unicast_nd_req_from_host], self.pg1) self.assertEqual(rx[0][Ether].src, self.pg1.local_mac) self.assertEqual(rx[0][Ether].dst, self.pg1.remote_mac) self.assertEqual(rx[0][IPv6].src, self.pg0.remote_ip6) - self.assertEqual(in6_ptop(rx[0][IPv6].dst), - in6_ptop(self.pg1.remote_ip6_ll)) + self.assertEqual(in6_ptop(rx[0][IPv6].dst), in6_ptop(self.pg1.remote_ip6_ll)) self.assertEqual(ipv6nh[rx[0][IPv6].nh], "ICMPv6") self.assertEqual(rx[0][ICMPv6ND_NA].tgt, self.pg0.remote_ip6) self.assertTrue(rx[0].haslayer(ICMPv6NDOptDstLLAddr)) - self.assertEqual(rx[0][ICMPv6NDOptDstLLAddr].lladdr, - self.pg1.local_mac) + self.assertEqual(rx[0][ICMPv6NDOptDstLLAddr].lladdr, self.pg1.local_mac) # # Send the Echo Request from host to remote (of uplink) # id = self.pg1.sw_if_index seq = 0x1 - echo_request = (Ether(dst=self.pg1.local_mac, - src=self.pg1.remote_mac) / - IPv6(dst=self.pg0.remote_ip6, src=self.pg0.local_ip6) / - ICMPv6EchoRequest(seq=seq, id=id)) + echo_request = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(dst=self.pg0.remote_ip6, src=self.pg0.local_ip6) + / ICMPv6EchoRequest(seq=seq, id=id) + ) rx = self.send_and_expect(self.pg1, [echo_request], self.pg0) self.assertEqual(rx[0][Ether].src, self.pg0.local_mac) @@ -159,13 +169,16 @@ class TestNDPROXY(VppTestCase): # # setup a punt redirect so packets from the uplink go to the tap # - redirect = VppIpPuntRedirect(self, self.pg0.sw_if_index, - self.pg1.sw_if_index, self.pg0.local_ip6) + redirect = VppIpPuntRedirect( + self, self.pg0.sw_if_index, self.pg1.sw_if_index, self.pg0.local_ip6 + ) redirect.add_vpp_config() - echo_reply = (Ether(dst=self.pg0.remote_mac, src=self.pg0.local_mac) / - IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) / - ICMPv6EchoReply(seq=1, id=id)) + echo_reply = ( + Ether(dst=self.pg0.remote_mac, src=self.pg0.local_mac) + / IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) + / ICMPv6EchoReply(seq=1, id=id) + ) rx = self.send_and_expect(self.pg0, [echo_reply], self.pg1) self.assertEqual(rx[0][Ether].src, self.pg1.local_mac) @@ -180,9 +193,11 @@ class TestNDPROXY(VppTestCase): # # cleanup # - self.vapi.ip6nd_proxy_enable_disable(sw_if_index=self.pg1.sw_if_index, - is_enable=0) + self.vapi.ip6nd_proxy_enable_disable( + sw_if_index=self.pg1.sw_if_index, is_enable=0 + ) redirect.remove_vpp_config() -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_ip6_vrf_multi_instance.py b/test/test_ip6_vrf_multi_instance.py index d95e7927f98..73df30d77f2 100644 --- a/test/test_ip6_vrf_multi_instance.py +++ b/test/test_ip6_vrf_multi_instance.py @@ -69,8 +69,14 @@ import socket from scapy.packet import Raw from scapy.layers.l2 import Ether -from scapy.layers.inet6 import UDP, IPv6, ICMPv6ND_NS, ICMPv6ND_RA, \ - RouterAlert, IPv6ExtHdrHopByHop +from scapy.layers.inet6 import ( + UDP, + IPv6, + ICMPv6ND_NS, + ICMPv6ND_RA, + RouterAlert, + IPv6ExtHdrHopByHop, +) from scapy.utils6 import in6_ismaddr, in6_isllsnmaddr, in6_getAddrType from scapy.pton_ntop import inet_ntop @@ -80,8 +86,8 @@ from vrf import VRFState def is_ipv6_misc_ext(p): - """ Is packet one of uninteresting IPv6 broadcasts (extended to filter out - ICMPv6 Neighbor Discovery - Neighbor Advertisement packets too)? """ + """Is packet one of uninteresting IPv6 broadcasts (extended to filter out + ICMPv6 Neighbor Discovery - Neighbor Advertisement packets too)?""" if p.haslayer(ICMPv6ND_RA): if in6_ismaddr(p[IPv6].dst): return True @@ -96,7 +102,7 @@ def is_ipv6_misc_ext(p): class TestIP6VrfMultiInst(VppTestCase): - """ IP6 VRF Multi-instance Test Case """ + """IP6 VRF Multi-instance Test Case""" @classmethod def setUpClass(cls): @@ -114,8 +120,7 @@ class TestIP6VrfMultiInst(VppTestCase): try: # Create pg interfaces - cls.create_pg_interfaces( - range(cls.nr_of_vrfs * cls.pg_ifs_per_vrf)) + cls.create_pg_interfaces(range(cls.nr_of_vrfs * cls.pg_ifs_per_vrf)) # Packet flows mapping pg0 -> pg1, pg2 etc. cls.flows = dict() @@ -124,7 +129,8 @@ class TestIP6VrfMultiInst(VppTestCase): pg_list = [ cls.pg_interfaces[multiplicand * cls.pg_ifs_per_vrf + j] for j in range(cls.pg_ifs_per_vrf) - if (multiplicand * cls.pg_ifs_per_vrf + j) != i] + if (multiplicand * cls.pg_ifs_per_vrf + j) != i + ] cls.flows[cls.pg_interfaces[i]] = pg_list # Packet sizes - jumbo packet (9018 bytes) skipped @@ -153,7 +159,8 @@ class TestIP6VrfMultiInst(VppTestCase): set_id = i + 1 pg_list = [ cls.pg_interfaces[i * cls.pg_ifs_per_vrf + j] - for j in range(cls.pg_ifs_per_vrf)] + for j in range(cls.pg_ifs_per_vrf) + ] cls.pg_if_sets[set_id] = pg_list except Exception: @@ -185,8 +192,9 @@ class TestIP6VrfMultiInst(VppTestCase): for i in range(self.pg_ifs_per_vrf): pg_if = self.pg_if_sets[if_set_id][i] pg_if.set_table_ip6(vrf_id) - self.logger.info("pg-interface %s added to IPv6 VRF ID %d" - % (pg_if.name, vrf_id)) + self.logger.info( + "pg-interface %s added to IPv6 VRF ID %d" % (pg_if.name, vrf_id) + ) if pg_if not in self.pg_in_vrf: self.pg_in_vrf.append(pg_if) if pg_if in self.pg_not_in_vrf: @@ -206,8 +214,9 @@ class TestIP6VrfMultiInst(VppTestCase): """ for i in range(count): vrf_id = i + start - self.vapi.ip_table_add_del(is_add=1, - table={'table_id': vrf_id, 'is_ip6': 1}) + self.vapi.ip_table_add_del( + is_add=1, table={"table_id": vrf_id, "is_ip6": 1} + ) self.logger.info("IPv6 VRF ID %d created" % vrf_id) if vrf_id not in self.vrf_list: self.vrf_list.append(vrf_id) @@ -217,8 +226,7 @@ class TestIP6VrfMultiInst(VppTestCase): self.logger.debug(self.vapi.ppcli("show ip6 fib")) self.logger.debug(self.vapi.ppcli("show ip6 neighbors")) - def create_vrf_by_id_and_assign_interfaces(self, set_id, - vrf_id=0xffffffff): + def create_vrf_by_id_and_assign_interfaces(self, set_id, vrf_id=0xFFFFFFFF): """ Create a FIB table / VRF by vrf_id, put 3 pg-ip6 interfaces to FIB table / VRF. @@ -226,8 +234,7 @@ class TestIP6VrfMultiInst(VppTestCase): :param int vrf_id: Required table ID / VRF ID. \ (Default value = 0xffffffff, ID will be selected automatically) """ - ret = self.vapi.ip_table_allocate(table={'table_id': vrf_id, - 'is_ip6': 1}) + ret = self.vapi.ip_table_allocate(table={"table_id": vrf_id, "is_ip6": 1}) vrf_id = ret.table.table_id self.logger.info("IPv6 VRF ID %d created" % vrf_id) if vrf_id not in self.vrf_list: @@ -248,7 +255,7 @@ class TestIP6VrfMultiInst(VppTestCase): """ if if_set_id is None: if_set_id = vrf_id - self.vapi.ip_table_flush(table={'table_id': vrf_id, 'is_ip6': 1}) + self.vapi.ip_table_flush(table={"table_id": vrf_id, "is_ip6": 1}) if vrf_id in self.vrf_list: self.vrf_list.remove(vrf_id) if vrf_id not in self.vrf_reset_list: @@ -270,8 +277,7 @@ class TestIP6VrfMultiInst(VppTestCase): self.vrf_list.remove(vrf_id) if vrf_id in self.vrf_reset_list: self.vrf_reset_list.remove(vrf_id) - self.vapi.ip_table_add_del(is_add=0, - table={'table_id': vrf_id, 'is_ip6': 1}) + self.vapi.ip_table_add_del(is_add=0, table={"table_id": vrf_id, "is_ip6": 1}) def create_stream(self, src_if, packet_sizes): """ @@ -288,16 +294,20 @@ class TestIP6VrfMultiInst(VppTestCase): src_host = random.choice(src_hosts) pkt_info = self.create_packet_info(src_if, dst_if) payload = self.info_to_payload(pkt_info) - p = (Ether(dst=src_if.local_mac, src=src_host.mac) / - IPv6(src=src_host.ip6, dst=dst_host.ip6) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=src_host.mac) + / IPv6(src=src_host.ip6, dst=dst_host.ip6) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) pkt_info.data = p.copy() size = random.choice(packet_sizes) self.extend_packet(p, size) pkts.append(p) - self.logger.debug("Input stream created for port %s. Length: %u pkt(s)" - % (src_if.name, len(pkts))) + self.logger.debug( + "Input stream created for port %s. Length: %u pkt(s)" + % (src_if.name, len(pkts)) + ) return pkts def create_stream_crosswise_vrf(self, src_if, vrf_id, packet_sizes): @@ -320,16 +330,20 @@ class TestIP6VrfMultiInst(VppTestCase): src_host = random.choice(src_hosts) pkt_info = self.create_packet_info(src_if, dst_if) payload = self.info_to_payload(pkt_info) - p = (Ether(dst=src_if.local_mac, src=src_host.mac) / - IPv6(src=src_host.ip6, dst=dst_host.ip6) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=src_host.mac) + / IPv6(src=src_host.ip6, dst=dst_host.ip6) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) pkt_info.data = p.copy() size = random.choice(packet_sizes) self.extend_packet(p, size) pkts.append(p) - self.logger.debug("Input stream created for port %s. Length: %u pkt(s)" - % (src_if.name, len(pkts))) + self.logger.debug( + "Input stream created for port %s. Length: %u pkt(s)" + % (src_if.name, len(pkts)) + ) return pkts def verify_capture(self, pg_if, capture): @@ -350,11 +364,13 @@ class TestIP6VrfMultiInst(VppTestCase): payload_info = self.payload_to_info(packet[Raw]) packet_index = payload_info.index self.assertEqual(payload_info.dst, dst_sw_if_index) - self.logger.debug("Got packet on port %s: src=%u (id=%u)" % - (pg_if.name, payload_info.src, packet_index)) + self.logger.debug( + "Got packet on port %s: src=%u (id=%u)" + % (pg_if.name, payload_info.src, packet_index) + ) next_info = self.get_next_packet_info_for_interface2( - payload_info.src, dst_sw_if_index, - last_info[payload_info.src]) + payload_info.src, dst_sw_if_index, last_info[payload_info.src] + ) last_info[payload_info.src] = next_info self.assertIsNotNone(next_info) self.assertEqual(packet_index, next_info.index) @@ -369,11 +385,13 @@ class TestIP6VrfMultiInst(VppTestCase): raise for i in self.pg_interfaces: remaining_packet = self.get_next_packet_info_for_interface2( - i, dst_sw_if_index, last_info[i.sw_if_index]) + i, dst_sw_if_index, last_info[i.sw_if_index] + ) self.assertIsNone( remaining_packet, - "Port %u: Packet expected from source %u didn't arrive" % - (dst_sw_if_index, i.sw_if_index)) + "Port %u: Packet expected from source %u didn't arrive" + % (dst_sw_if_index, i.sw_if_index), + ) def verify_vrf(self, vrf_id, if_set_id=None): """ @@ -437,8 +455,9 @@ class TestIP6VrfMultiInst(VppTestCase): capture = pg_if.get_capture(remark="interface is in VRF") self.verify_capture(pg_if, capture) elif pg_if in self.pg_not_in_vrf: - pg_if.assert_nothing_captured(remark="interface is not in VRF", - filter_out_fn=is_ipv6_misc_ext) + pg_if.assert_nothing_captured( + remark="interface is not in VRF", filter_out_fn=is_ipv6_misc_ext + ) self.logger.debug("No capture for interface %s" % pg_if.name) else: raise Exception("Unknown interface: %s" % pg_if.name) @@ -458,7 +477,8 @@ class TestIP6VrfMultiInst(VppTestCase): for vrf_id in self.vrf_list: for pg_if in self.pg_if_sets[vrf_id]: pkts = self.create_stream_crosswise_vrf( - pg_if, vrf_id, self.pg_if_packet_sizes) + pg_if, vrf_id, self.pg_if_packet_sizes + ) pg_if.add_stream(pkts) # Enable packet capture and start packet sending @@ -468,29 +488,27 @@ class TestIP6VrfMultiInst(VppTestCase): # Verify # Verify outgoing packet streams per packet-generator interface for pg_if in self.pg_interfaces: - pg_if.assert_nothing_captured(remark="interface is in other VRF", - filter_out_fn=is_ipv6_misc_ext) + pg_if.assert_nothing_captured( + remark="interface is in other VRF", filter_out_fn=is_ipv6_misc_ext + ) self.logger.debug("No capture for interface %s" % pg_if.name) def test_ip6_vrf_01(self): - """ IP6 VRF Multi-instance test 1 - create 4 VRFs - """ + """IP6 VRF Multi-instance test 1 - create 4 VRFs""" # Config 1 # Create 4 VRFs self.create_vrf_and_assign_interfaces(4) # Verify 1 for vrf_id in self.vrf_list: - self.assert_equal(self.verify_vrf(vrf_id), - VRFState.configured, VRFState) + self.assert_equal(self.verify_vrf(vrf_id), VRFState.configured, VRFState) # Test 1 self.run_verify_test() self.run_crosswise_vrf_test() def test_ip6_vrf_02(self): - """ IP6 VRF Multi-instance test 2 - reset 2 VRFs - """ + """IP6 VRF Multi-instance test 2 - reset 2 VRFs""" # Config 2 # Delete 2 VRFs self.reset_vrf_and_remove_from_vrf_list(1) @@ -498,11 +516,9 @@ class TestIP6VrfMultiInst(VppTestCase): # Verify 2 for vrf_id in self.vrf_reset_list: - self.assert_equal(self.verify_vrf(vrf_id), - VRFState.reset, VRFState) + self.assert_equal(self.verify_vrf(vrf_id), VRFState.reset, VRFState) for vrf_id in self.vrf_list: - self.assert_equal(self.verify_vrf(vrf_id), - VRFState.configured, VRFState) + self.assert_equal(self.verify_vrf(vrf_id), VRFState.configured, VRFState) # Test 2 self.run_verify_test() @@ -513,8 +529,7 @@ class TestIP6VrfMultiInst(VppTestCase): # self.reset_vrf_and_remove_from_vrf_list(vrf_id) def test_ip6_vrf_03(self): - """ IP6 VRF Multi-instance 3 - add 2 VRFs - """ + """IP6 VRF Multi-instance 3 - add 2 VRFs""" # Config 3 # Add 1 of reset VRFs and 1 new VRF self.create_vrf_and_assign_interfaces(1) @@ -522,11 +537,9 @@ class TestIP6VrfMultiInst(VppTestCase): # Verify 3 for vrf_id in self.vrf_reset_list: - self.assert_equal(self.verify_vrf(vrf_id), - VRFState.reset, VRFState) + self.assert_equal(self.verify_vrf(vrf_id), VRFState.reset, VRFState) for vrf_id in self.vrf_list: - self.assert_equal(self.verify_vrf(vrf_id), - VRFState.configured, VRFState) + self.assert_equal(self.verify_vrf(vrf_id), VRFState.configured, VRFState) # Test 3 self.run_verify_test() @@ -537,8 +550,7 @@ class TestIP6VrfMultiInst(VppTestCase): # self.reset_vrf_and_remove_from_vrf_list(vrf_id) def test_ip6_vrf_04(self): - """ IP6 VRF Multi-instance test 4 - reset 4 VRFs - """ + """IP6 VRF Multi-instance test 4 - reset 4 VRFs""" # Config 4 # Reset all VRFs (i.e. no VRF except VRF=0 configured) for i in range(len(self.vrf_list)): @@ -547,20 +559,20 @@ class TestIP6VrfMultiInst(VppTestCase): # Verify 4 for vrf_id in self.vrf_reset_list: - self.assert_equal(self.verify_vrf(vrf_id), - VRFState.reset, VRFState) + self.assert_equal(self.verify_vrf(vrf_id), VRFState.reset, VRFState) vrf_list_length = len(self.vrf_list) self.assertEqual( - vrf_list_length, 0, - "List of configured VRFs is not empty: %s != 0" % vrf_list_length) + vrf_list_length, + 0, + "List of configured VRFs is not empty: %s != 0" % vrf_list_length, + ) # Test 4 self.run_verify_test() self.run_crosswise_vrf_test() def test_ip6_vrf_05(self): - """ IP6 VRF Multi-instance test 5 - auto allocate vrf id - """ + """IP6 VRF Multi-instance test 5 - auto allocate vrf id""" # Config 5 # Create several VRFs # Set vrf_id manually first @@ -571,11 +583,11 @@ class TestIP6VrfMultiInst(VppTestCase): ] # Verify 5 - self.assert_equal(self.verify_vrf(10, 1), VRFState.configured, - VRFState) + self.assert_equal(self.verify_vrf(10, 1), VRFState.configured, VRFState) for i, vrf in enumerate(auto_vrf_id): - self.assert_equal(self.verify_vrf(vrf, i+2), - VRFState.configured, VRFState) + self.assert_equal( + self.verify_vrf(vrf, i + 2), VRFState.configured, VRFState + ) # Test 5 self.run_verify_test() @@ -584,18 +596,19 @@ class TestIP6VrfMultiInst(VppTestCase): # Reset VRFs self.reset_vrf_and_remove_from_vrf_list(10, 1) for i, vrf in enumerate(auto_vrf_id): - self.reset_vrf_and_remove_from_vrf_list(vrf, i+2) + self.reset_vrf_and_remove_from_vrf_list(vrf, i + 2) # Verify 5.1 self.assert_equal(self.verify_vrf(10, 1), VRFState.reset, VRFState) for i, vrf in enumerate(auto_vrf_id): - self.assert_equal(self.verify_vrf(vrf, i+2), - VRFState.reset, VRFState) + self.assert_equal(self.verify_vrf(vrf, i + 2), VRFState.reset, VRFState) vrf_list_length = len(self.vrf_list) self.assertEqual( - vrf_list_length, 0, - "List of configured VRFs is not empty: %s != 0" % vrf_list_length) + vrf_list_length, + 0, + "List of configured VRFs is not empty: %s != 0" % vrf_list_length, + ) # Cleanup our extra created VRFs for vrf in auto_vrf_id: @@ -604,14 +617,12 @@ class TestIP6VrfMultiInst(VppTestCase): self.delete_vrf(10) def test_ip6_vrf_06(self): - """ IP6 VRF Multi-instance test 6 - recreate 4 VRFs - """ + """IP6 VRF Multi-instance test 6 - recreate 4 VRFs""" # Reconfigure all the VRFs self.create_vrf_and_assign_interfaces(4) # Verify for vrf_id in self.vrf_list: - self.assert_equal(self.verify_vrf(vrf_id), - VRFState.configured, VRFState) + self.assert_equal(self.verify_vrf(vrf_id), VRFState.configured, VRFState) # Test self.run_verify_test() self.run_crosswise_vrf_test() @@ -620,16 +631,17 @@ class TestIP6VrfMultiInst(VppTestCase): self.reset_vrf_and_remove_from_vrf_list(self.vrf_list[0]) # Verify for vrf_id in self.vrf_reset_list: - self.assert_equal(self.verify_vrf(vrf_id), - VRFState.reset, VRFState) + self.assert_equal(self.verify_vrf(vrf_id), VRFState.reset, VRFState) vrf_list_length = len(self.vrf_list) self.assertEqual( - vrf_list_length, 0, - "List of configured VRFs is not empty: %s != 0" % vrf_list_length) + vrf_list_length, + 0, + "List of configured VRFs is not empty: %s != 0" % vrf_list_length, + ) # Test self.run_verify_test() self.run_crosswise_vrf_test() -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_ip_ecmp.py b/test/test_ip_ecmp.py index 1d3e872e45e..d5347db2530 100644 --- a/test/test_ip_ecmp.py +++ b/test/test_ip_ecmp.py @@ -26,7 +26,7 @@ N_PKTS_IN_STREAM = 300 class TestECMP(VppTestCase): - """ Equal-cost multi-path routing Test Case """ + """Equal-cost multi-path routing Test Case""" @classmethod def setUpClass(cls): @@ -92,11 +92,11 @@ class TestECMP(VppTestCase): ip_addr = IPv6Address(text_type(ip_addr_start)) ip_max_len = 128 - return str(ip_addr + - random.randint(0, 2 ** (ip_max_len - ip_prefix_len) - 2)) + return str(ip_addr + random.randint(0, 2 ** (ip_max_len - ip_prefix_len) - 2)) - def create_stream(self, src_if, src_ip_start, dst_ip_start, - ip_prefix_len, packet_sizes, ip_l=IP): + def create_stream( + self, src_if, src_ip_start, dst_ip_start, ip_prefix_len, packet_sizes, ip_l=IP + ): """Create input packet stream for defined interfaces. :param VppInterface src_if: Source Interface for packet stream. @@ -112,10 +112,12 @@ class TestECMP(VppTestCase): payload = self.info_to_payload(info) src_ip = self.get_ip_address(src_ip_start, ip_prefix_len) dst_ip = self.get_ip_address(dst_ip_start, ip_prefix_len) - p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - ip_l(src=src_ip, dst=dst_ip) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / ip_l(src=src_ip, dst=dst_ip) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) info.data = p.copy() size = random.choice(packet_sizes) self.extend_packet(p, size) @@ -142,12 +144,17 @@ class TestECMP(VppTestCase): payload_info = self.payload_to_info(packet[Raw]) packet_index = payload_info.index ip_sent = self._packet_infos[packet_index].data[ip_l] - self.logger.debug("Got packet on port %s: src=%u (id=%u)" % - (rx_if.name, payload_info.src, packet_index)) + self.logger.debug( + "Got packet on port %s: src=%u (id=%u)" + % (rx_if.name, payload_info.src, packet_index) + ) # Check standard fields - self.assertIn(packet.dst, rx_if._hosts_by_mac, - "Destination MAC address %s shouldn't be routed " - "via interface %s" % (packet.dst, rx_if.name)) + self.assertIn( + packet.dst, + rx_if._hosts_by_mac, + "Destination MAC address %s shouldn't be routed " + "via interface %s" % (packet.dst, rx_if.name), + ) self.assertEqual(packet.src, rx_if.local_mac) self.assertEqual(ip_received.src, ip_sent.src) self.assertEqual(ip_received.dst, ip_sent.dst) @@ -161,13 +168,15 @@ class TestECMP(VppTestCase): # We expect packet routed via all host of pg interface for host_mac in host_counters: nr = host_counters[host_mac] - self.assertNotEqual( - nr, 0, "No packet routed via host %s" % host_mac) - self.logger.info("%u packets routed via host %s of %s interface" % - (nr, host_mac, rx_if.name)) + self.assertNotEqual(nr, 0, "No packet routed via host %s" % host_mac) + self.logger.info( + "%u packets routed via host %s of %s interface" + % (nr, host_mac, rx_if.name) + ) count += nr - self.logger.info("Total amount of %u packets routed via %s interface" % - (count, rx_if.name)) + self.logger.info( + "Total amount of %u packets routed via %s interface" % (count, rx_if.name) + ) return count @@ -184,28 +193,27 @@ class TestECMP(VppTestCase): for pg_if in self.pg_interfaces[1:]: for nh_host in pg_if.remote_hosts: nh_host_ip = nh_host.ip4 if is_ipv6 == 0 else nh_host.ip6 - paths.append(VppRoutePath(nh_host_ip, - pg_if.sw_if_index)) + paths.append(VppRoutePath(nh_host_ip, pg_if.sw_if_index)) rip = VppIpRoute(self, dst_ip_net, dst_prefix_len, paths) rip.add_vpp_config() - self.logger.info("Route via %s on %s created" % - (nh_host_ip, pg_if.name)) + self.logger.info("Route via %s on %s created" % (nh_host_ip, pg_if.name)) self.logger.debug(self.vapi.ppcli("show ip fib")) self.logger.debug(self.vapi.ppcli("show ip6 fib")) def test_ip_ecmp(self): - """ IP equal-cost multi-path routing test """ + """IP equal-cost multi-path routing test""" - src_ip_net = '16.0.0.1' - dst_ip_net = '32.0.0.1' + src_ip_net = "16.0.0.1" + dst_ip_net = "32.0.0.1" ip_prefix_len = 24 self.create_ip_routes(dst_ip_net, ip_prefix_len) - pkts = self.create_stream(self.pg0, src_ip_net, dst_ip_net, - ip_prefix_len, self.pg_if_packet_sizes) + pkts = self.create_stream( + self.pg0, src_ip_net, dst_ip_net, ip_prefix_len, self.pg_if_packet_sizes + ) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) @@ -216,7 +224,8 @@ class TestECMP(VppTestCase): for pg_if in self.pg_interfaces[1:]: capture = pg_if._get_capture(timeout=1) self.assertNotEqual( - len(capture), 0, msg="No packets captured on %s" % pg_if.name) + len(capture), 0, msg="No packets captured on %s" % pg_if.name + ) rx_count += self.verify_capture(pg_if, capture) self.pg0.assert_nothing_captured(remark="IP packets forwarded on pg0") @@ -224,17 +233,22 @@ class TestECMP(VppTestCase): self.assertEqual(rx_count, len(pkts)) def test_ip6_ecmp(self): - """ IPv6 equal-cost multi-path routing test """ + """IPv6 equal-cost multi-path routing test""" - src_ip_net = '3ffe:51::1' - dst_ip_net = '3ffe:71::1' + src_ip_net = "3ffe:51::1" + dst_ip_net = "3ffe:71::1" ip_prefix_len = 64 self.create_ip_routes(dst_ip_net, ip_prefix_len, is_ipv6=1) pkts = self.create_stream( - self.pg0, src_ip_net, dst_ip_net, - ip_prefix_len, self.pg_if_packet_sizes, ip_l=IPv6) + self.pg0, + src_ip_net, + dst_ip_net, + ip_prefix_len, + self.pg_if_packet_sizes, + ip_l=IPv6, + ) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) @@ -245,7 +259,8 @@ class TestECMP(VppTestCase): for pg_if in self.pg_interfaces[1:]: capture = pg_if._get_capture(timeout=1) self.assertNotEqual( - len(capture), 0, msg="No packets captured on %s" % pg_if.name) + len(capture), 0, msg="No packets captured on %s" % pg_if.name + ) rx_count += self.verify_capture(pg_if, capture, ip_l=IPv6) self.pg0.assert_nothing_captured(remark="IP packets forwarded on pg0") @@ -253,5 +268,5 @@ class TestECMP(VppTestCase): self.assertEqual(rx_count, len(pkts)) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_ip_mcast.py b/test/test_ip_mcast.py index 50ac01b8844..c3ac16c6d85 100644 --- a/test/test_ip_mcast.py +++ b/test/test_ip_mcast.py @@ -5,8 +5,14 @@ import unittest from framework import tag_fixme_vpp_workers from framework import VppTestCase, VppTestRunner from vpp_ip import DpoProto -from vpp_ip_route import VppIpMRoute, VppMRoutePath, VppMFibSignal, \ - VppIpTable, FibPathProto, FibPathType +from vpp_ip_route import ( + VppIpMRoute, + VppMRoutePath, + VppMFibSignal, + VppIpTable, + FibPathProto, + FibPathType, +) from vpp_gre_interface import VppGreInterface from vpp_papi import VppEnum @@ -26,7 +32,7 @@ N_PKTS_IN_STREAM = 91 class TestMFIB(VppTestCase): - """ MFIB Test Case """ + """MFIB Test Case""" @classmethod def setUpClass(cls): @@ -40,7 +46,7 @@ class TestMFIB(VppTestCase): super(TestMFIB, self).setUp() def test_mfib(self): - """ MFIB Unit Tests """ + """MFIB Unit Tests""" error = self.vapi.cli("test mfib") if error: @@ -50,7 +56,7 @@ class TestMFIB(VppTestCase): @tag_fixme_vpp_workers class TestIPMcast(VppTestCase): - """ IP Multicast Test Case """ + """IP Multicast Test Case""" @classmethod def setUpClass(cls): @@ -98,12 +104,14 @@ class TestIPMcast(VppTestCase): def create_stream_ip4(self, src_if, src_ip, dst_ip, payload_size=0): pkts = [] # default to small packet sizes - p = (Ether(dst=getmacbyip(dst_ip), src=src_if.remote_mac) / - IP(src=src_ip, dst=dst_ip) / - UDP(sport=1234, dport=1234)) + p = ( + Ether(dst=getmacbyip(dst_ip), src=src_if.remote_mac) + / IP(src=src_ip, dst=dst_ip) + / UDP(sport=1234, dport=1234) + ) if not payload_size: payload_size = 64 - len(p) - p = p / Raw(b'\xa5' * payload_size) + p = p / Raw(b"\xa5" * payload_size) for i in range(0, N_PKTS_IN_STREAM): pkts.append(p) @@ -114,10 +122,12 @@ class TestIPMcast(VppTestCase): for i in range(0, N_PKTS_IN_STREAM): info = self.create_packet_info(src_if, src_if) payload = self.info_to_payload(info) - p = (Ether(dst=getmacbyip6(dst_ip), src=src_if.remote_mac) / - IPv6(src=src_ip, dst=dst_ip) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + Ether(dst=getmacbyip6(dst_ip), src=src_if.remote_mac) + / IPv6(src=src_ip, dst=dst_ip) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) info.data = p.copy() pkts.append(p) return pkts @@ -126,7 +136,7 @@ class TestIPMcast(VppTestCase): if not len(capture) == len(sent): # filter out any IPv6 RAs from the capture for p in capture: - if (p.haslayer(IPv6)): + if p.haslayer(IPv6): capture.remove(p) return capture @@ -186,7 +196,7 @@ class TestIPMcast(VppTestCase): self.assertEqual(rx_ip.hlim + 1, tx_ip.hlim) def test_ip_mcast(self): - """ IP Multicast Replication """ + """IP Multicast Replication""" MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t @@ -210,9 +220,11 @@ class TestIPMcast(VppTestCase): self.pg_start() self.pg0.assert_nothing_captured( - remark="IP multicast packets forwarded on default route") + remark="IP multicast packets forwarded on default route" + ) count = self.statistics.get_err_counter( - "/err/ip4-input/Multicast RPF check failed") + "/err/ip4-input/Multicast RPF check failed" + ) self.assertEqual(count, len(tx)) # @@ -224,24 +236,36 @@ class TestIPMcast(VppTestCase): route_232_1_1_1 = VppIpMRoute( self, "0.0.0.0", - "232.1.1.1", 32, + "232.1.1.1", + 32, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - [VppMRoutePath(self.pg0.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT), - VppMRoutePath(self.pg1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD), - VppMRoutePath(self.pg2.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD), - VppMRoutePath(self.pg3.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD), - VppMRoutePath(self.pg4.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD), - VppMRoutePath(self.pg5.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD), - VppMRoutePath(self.pg6.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD), - VppMRoutePath(self.pg7.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)]) + [ + VppMRoutePath( + self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT + ), + VppMRoutePath( + self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ), + VppMRoutePath( + self.pg2.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ), + VppMRoutePath( + self.pg3.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ), + VppMRoutePath( + self.pg4.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ), + VppMRoutePath( + self.pg5.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ), + VppMRoutePath( + self.pg6.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ), + VppMRoutePath( + self.pg7.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ), + ], + ) route_232_1_1_1.add_vpp_config() # @@ -251,14 +275,21 @@ class TestIPMcast(VppTestCase): route_1_1_1_1_232_1_1_1 = VppIpMRoute( self, "1.1.1.1", - "232.1.1.1", 27, # any grp-len is ok when src is set + "232.1.1.1", + 27, # any grp-len is ok when src is set MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - [VppMRoutePath(self.pg0.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT), - VppMRoutePath(self.pg1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD), - VppMRoutePath(self.pg2.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)]) + [ + VppMRoutePath( + self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT + ), + VppMRoutePath( + self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ), + VppMRoutePath( + self.pg2.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ), + ], + ) route_1_1_1_1_232_1_1_1.add_vpp_config() # @@ -269,16 +300,25 @@ class TestIPMcast(VppTestCase): route_1_1_1_1_232_1_1_2 = VppIpMRoute( self, "1.1.1.1", - "232.1.1.2", 64, + "232.1.1.2", + 64, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - [VppMRoutePath(self.pg0.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT), - VppMRoutePath(self.pg1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, - nh=self.pg1.remote_ip4), - VppMRoutePath(self.pg2.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, - nh=self.pg2.remote_ip4)]) + [ + VppMRoutePath( + self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT + ), + VppMRoutePath( + self.pg1.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + nh=self.pg1.remote_ip4, + ), + VppMRoutePath( + self.pg2.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + nh=self.pg2.remote_ip4, + ), + ], + ) route_1_1_1_1_232_1_1_2.add_vpp_config() # @@ -288,12 +328,18 @@ class TestIPMcast(VppTestCase): route_232 = VppIpMRoute( self, "0.0.0.0", - "232.0.0.0", 8, + "232.0.0.0", + 8, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - [VppMRoutePath(self.pg0.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT), - VppMRoutePath(self.pg1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)]) + [ + VppMRoutePath( + self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT + ), + VppMRoutePath( + self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ), + ], + ) route_232.add_vpp_config() # @@ -307,26 +353,22 @@ class TestIPMcast(VppTestCase): self.pg_enable_capture(self.pg_interfaces) self.pg_start() - self.assertEqual(route_1_1_1_1_232_1_1_1.get_stats()['packets'], - len(tx)) + self.assertEqual(route_1_1_1_1_232_1_1_1.get_stats()["packets"], len(tx)) # We expect replications on Pg1->7 self.verify_capture_ip4(self.pg1, tx) self.verify_capture_ip4(self.pg2, tx) # no replications on Pg0 - self.pg0.assert_nothing_captured( - remark="IP multicast packets forwarded on PG0") - self.pg3.assert_nothing_captured( - remark="IP multicast packets forwarded on PG3") + self.pg0.assert_nothing_captured(remark="IP multicast packets forwarded on PG0") + self.pg3.assert_nothing_captured(remark="IP multicast packets forwarded on PG3") # # a stream that matches the route for (1.1.1.1,232.1.1.1) # large packets # self.vapi.cli("clear trace") - tx = self.create_stream_ip4(self.pg0, "1.1.1.1", "232.1.1.1", - payload_size=1024) + tx = self.create_stream_ip4(self.pg0, "1.1.1.1", "232.1.1.1", payload_size=1024) self.pg0.add_stream(tx) self.pg_enable_capture(self.pg_interfaces) @@ -336,14 +378,11 @@ class TestIPMcast(VppTestCase): self.verify_capture_ip4(self.pg1, tx) self.verify_capture_ip4(self.pg2, tx) - self.assertEqual(route_1_1_1_1_232_1_1_1.get_stats()['packets'], - 2*len(tx)) + self.assertEqual(route_1_1_1_1_232_1_1_1.get_stats()["packets"], 2 * len(tx)) # no replications on Pg0 - self.pg0.assert_nothing_captured( - remark="IP multicast packets forwarded on PG0") - self.pg3.assert_nothing_captured( - remark="IP multicast packets forwarded on PG3") + self.pg0.assert_nothing_captured(remark="IP multicast packets forwarded on PG0") + self.pg3.assert_nothing_captured(remark="IP multicast packets forwarded on PG3") # # a stream to the unicast next-hops @@ -360,10 +399,8 @@ class TestIPMcast(VppTestCase): self.verify_capture_ip4(self.pg2, tx, dst_mac=self.pg2.remote_mac) # no replications on Pg0 nor pg3 - self.pg0.assert_nothing_captured( - remark="IP multicast packets forwarded on PG0") - self.pg3.assert_nothing_captured( - remark="IP multicast packets forwarded on PG3") + self.pg0.assert_nothing_captured(remark="IP multicast packets forwarded on PG0") + self.pg3.assert_nothing_captured(remark="IP multicast packets forwarded on PG3") # # a stream that matches the route for (*,232.0.0.0/8) @@ -379,15 +416,12 @@ class TestIPMcast(VppTestCase): # We expect replications on Pg1 only self.verify_capture_ip4(self.pg1, tx) - self.assertEqual(route_232.get_stats()['packets'], len(tx)) + self.assertEqual(route_232.get_stats()["packets"], len(tx)) # no replications on Pg0, Pg2 not Pg3 - self.pg0.assert_nothing_captured( - remark="IP multicast packets forwarded on PG0") - self.pg2.assert_nothing_captured( - remark="IP multicast packets forwarded on PG2") - self.pg3.assert_nothing_captured( - remark="IP multicast packets forwarded on PG3") + self.pg0.assert_nothing_captured(remark="IP multicast packets forwarded on PG0") + self.pg2.assert_nothing_captured(remark="IP multicast packets forwarded on PG2") + self.pg3.assert_nothing_captured(remark="IP multicast packets forwarded on PG3") # # a stream that matches the route for (*,232.1.1.1) @@ -409,8 +443,7 @@ class TestIPMcast(VppTestCase): self.verify_capture_ip4(self.pg7, tx) # no replications on Pg0 - self.pg0.assert_nothing_captured( - remark="IP multicast packets forwarded on PG0") + self.pg0.assert_nothing_captured(remark="IP multicast packets forwarded on PG0") self.vapi.cli("packet mac-filter pg0 off") self.vapi.cli("packet mac-filter pg1 off") @@ -421,7 +454,7 @@ class TestIPMcast(VppTestCase): self.vapi.cli("packet mac-filter pg7 off") def test_ip6_mcast(self): - """ IPv6 Multicast Replication """ + """IPv6 Multicast Replication""" MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t @@ -444,7 +477,8 @@ class TestIPMcast(VppTestCase): self.pg_start() self.pg0.assert_nothing_captured( - remark="IPv6 multicast packets forwarded on default route") + remark="IPv6 multicast packets forwarded on default route" + ) # # A (*,G). @@ -453,20 +487,32 @@ class TestIPMcast(VppTestCase): route_ff01_1 = VppIpMRoute( self, "::", - "ff01::1", 128, + "ff01::1", + 128, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - [VppMRoutePath(self.pg0.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6), - VppMRoutePath(self.pg1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6), - VppMRoutePath(self.pg2.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6), - VppMRoutePath(self.pg3.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)]) + [ + VppMRoutePath( + self.pg0.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ), + VppMRoutePath( + self.pg1.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ), + VppMRoutePath( + self.pg2.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ), + VppMRoutePath( + self.pg3.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ), + ], + ) route_ff01_1.add_vpp_config() # @@ -476,17 +522,27 @@ class TestIPMcast(VppTestCase): route_2001_ff01_1 = VppIpMRoute( self, "2001::1", - "ff01::1", 0, # any grp-len is ok when src is set + "ff01::1", + 0, # any grp-len is ok when src is set MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - [VppMRoutePath(self.pg0.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6), - VppMRoutePath(self.pg1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6), - VppMRoutePath(self.pg2.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)]) + [ + VppMRoutePath( + self.pg0.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ), + VppMRoutePath( + self.pg1.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ), + VppMRoutePath( + self.pg2.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ), + ], + ) route_2001_ff01_1.add_vpp_config() # @@ -496,14 +552,22 @@ class TestIPMcast(VppTestCase): route_ff01 = VppIpMRoute( self, "::", - "ff01::", 16, + "ff01::", + 16, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - [VppMRoutePath(self.pg0.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6), - VppMRoutePath(self.pg1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)]) + [ + VppMRoutePath( + self.pg0.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ), + VppMRoutePath( + self.pg1.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ), + ], + ) route_ff01.add_vpp_config() # @@ -514,7 +578,8 @@ class TestIPMcast(VppTestCase): tx = self.create_stream_ip6(self.pg1, "2002::1", "ff01:2::255") self.send_and_assert_no_replies(self.pg1, tx, "RPF miss") count = self.statistics.get_err_counter( - "/err/ip6-input/Multicast RPF check failed") + "/err/ip6-input/Multicast RPF check failed" + ) self.assertEqual(count, 2 * len(tx)) # @@ -532,12 +597,9 @@ class TestIPMcast(VppTestCase): self.verify_capture_ip6(self.pg1, tx) # no replications on Pg0, Pg3 - self.pg0.assert_nothing_captured( - remark="IP multicast packets forwarded on PG0") - self.pg2.assert_nothing_captured( - remark="IP multicast packets forwarded on PG2") - self.pg3.assert_nothing_captured( - remark="IP multicast packets forwarded on PG3") + self.pg0.assert_nothing_captured(remark="IP multicast packets forwarded on PG0") + self.pg2.assert_nothing_captured(remark="IP multicast packets forwarded on PG2") + self.pg3.assert_nothing_captured(remark="IP multicast packets forwarded on PG3") # # Bounce the interface and it should still work @@ -547,7 +609,8 @@ class TestIPMcast(VppTestCase): self.pg_enable_capture(self.pg_interfaces) self.pg_start() self.pg1.assert_nothing_captured( - remark="IP multicast packets forwarded on down PG1") + remark="IP multicast packets forwarded on down PG1" + ) self.pg1.admin_up() self.pg0.add_stream(tx) @@ -572,7 +635,8 @@ class TestIPMcast(VppTestCase): # no replications on Pg0 self.pg0.assert_nothing_captured( - remark="IPv6 multicast packets forwarded on PG0") + remark="IPv6 multicast packets forwarded on PG0" + ) # # a stream that matches the route for (2001::1, ff00::1) @@ -589,10 +653,8 @@ class TestIPMcast(VppTestCase): self.verify_capture_ip6(self.pg2, tx) # no replications on Pg0, Pg3 - self.pg0.assert_nothing_captured( - remark="IP multicast packets forwarded on PG0") - self.pg3.assert_nothing_captured( - remark="IP multicast packets forwarded on PG3") + self.pg0.assert_nothing_captured(remark="IP multicast packets forwarded on PG0") + self.pg3.assert_nothing_captured(remark="IP multicast packets forwarded on PG3") self.vapi.cli("packet mac-filter pg0 off") self.vapi.cli("packet mac-filter pg1 off") @@ -604,9 +666,7 @@ class TestIPMcast(VppTestCase): def _mcast_connected_send_stream(self, dst_ip): self.vapi.cli("clear trace") - tx = self.create_stream_ip4(self.pg0, - self.pg0.remote_ip4, - dst_ip) + tx = self.create_stream_ip4(self.pg0, self.pg0.remote_ip4, dst_ip) self.pg0.add_stream(tx) self.pg_enable_capture(self.pg_interfaces) @@ -618,7 +678,7 @@ class TestIPMcast(VppTestCase): return tx def test_ip_mcast_connected(self): - """ IP Multicast Connected Source check """ + """IP Multicast Connected Source check""" MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t @@ -630,16 +690,23 @@ class TestIPMcast(VppTestCase): route_232_1_1_1 = VppIpMRoute( self, "0.0.0.0", - "232.1.1.1", 32, + "232.1.1.1", + 32, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - [VppMRoutePath(self.pg0.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT), - VppMRoutePath(self.pg1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)]) + [ + VppMRoutePath( + self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT + ), + VppMRoutePath( + self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ), + ], + ) route_232_1_1_1.add_vpp_config() route_232_1_1_1.update_entry_flags( - MRouteEntryFlags.MFIB_API_ENTRY_FLAG_CONNECTED) + MRouteEntryFlags.MFIB_API_ENTRY_FLAG_CONNECTED + ) # # Now the (*,G) is present, send from connected source @@ -649,10 +716,9 @@ class TestIPMcast(VppTestCase): # # Constrct a representation of the signal we expect on pg0 # - signal_232_1_1_1_itf_0 = VppMFibSignal(self, - route_232_1_1_1, - self.pg0.sw_if_index, - tx[0]) + signal_232_1_1_1_itf_0 = VppMFibSignal( + self, route_232_1_1_1, self.pg0.sw_if_index, tx[0] + ) # # read the only expected signal @@ -680,24 +746,30 @@ class TestIPMcast(VppTestCase): route_232_1_1_2 = VppIpMRoute( self, "0.0.0.0", - "232.1.1.2", 32, + "232.1.1.2", + 32, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - [VppMRoutePath(self.pg0.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT), - VppMRoutePath(self.pg1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)]) + [ + VppMRoutePath( + self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT + ), + VppMRoutePath( + self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ), + ], + ) route_232_1_1_2.add_vpp_config() route_232_1_1_2.update_entry_flags( - MRouteEntryFlags.MFIB_API_ENTRY_FLAG_CONNECTED) + MRouteEntryFlags.MFIB_API_ENTRY_FLAG_CONNECTED + ) # # Send traffic to both entries. One read should net us two signals # - signal_232_1_1_2_itf_0 = VppMFibSignal(self, - route_232_1_1_2, - self.pg0.sw_if_index, - tx[0]) + signal_232_1_1_2_itf_0 = VppMFibSignal( + self, route_232_1_1_2, self.pg0.sw_if_index, tx[0] + ) tx = self._mcast_connected_send_stream("232.1.1.1") tx2 = self._mcast_connected_send_stream("232.1.1.2") @@ -711,13 +783,11 @@ class TestIPMcast(VppTestCase): signal_232_1_1_1_itf_0.compare(signals[1]) signal_232_1_1_2_itf_0.compare(signals[0]) - route_232_1_1_1.update_entry_flags( - MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE) - route_232_1_1_2.update_entry_flags( - MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE) + route_232_1_1_1.update_entry_flags(MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE) + route_232_1_1_2.update_entry_flags(MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE) def test_ip_mcast_signal(self): - """ IP Multicast Signal """ + """IP Multicast Signal""" MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t @@ -729,17 +799,22 @@ class TestIPMcast(VppTestCase): route_232_1_1_1 = VppIpMRoute( self, "0.0.0.0", - "232.1.1.1", 32, + "232.1.1.1", + 32, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - [VppMRoutePath(self.pg0.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT), - VppMRoutePath(self.pg1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)]) + [ + VppMRoutePath( + self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT + ), + VppMRoutePath( + self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ), + ], + ) route_232_1_1_1.add_vpp_config() - route_232_1_1_1.update_entry_flags( - MRouteEntryFlags.MFIB_API_ENTRY_FLAG_SIGNAL) + route_232_1_1_1.update_entry_flags(MRouteEntryFlags.MFIB_API_ENTRY_FLAG_SIGNAL) # # Now the (*,G) is present, send from connected source @@ -749,10 +824,9 @@ class TestIPMcast(VppTestCase): # # Constrct a representation of the signal we expect on pg0 # - signal_232_1_1_1_itf_0 = VppMFibSignal(self, - route_232_1_1_1, - self.pg0.sw_if_index, - tx[0]) + signal_232_1_1_1_itf_0 = VppMFibSignal( + self, route_232_1_1_1, self.pg0.sw_if_index, tx[0] + ) # # read the only expected signal @@ -779,8 +853,11 @@ class TestIPMcast(VppTestCase): # route_232_1_1_1.update_path_flags( self.pg0.sw_if_index, - (MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT | - MRouteItfFlags.MFIB_API_ITF_FLAG_NEGATE_SIGNAL)) + ( + MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT + | MRouteItfFlags.MFIB_API_ITF_FLAG_NEGATE_SIGNAL + ), + ) self.vapi.cli("clear trace") tx = self._mcast_connected_send_stream("232.1.1.1") @@ -792,8 +869,7 @@ class TestIPMcast(VppTestCase): # Clear the SIGNAL flag on the entry and the signals should # come back since the interface is still NEGATE-SIGNAL # - route_232_1_1_1.update_entry_flags( - MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE) + route_232_1_1_1.update_entry_flags(MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE) tx = self._mcast_connected_send_stream("232.1.1.1") @@ -806,15 +882,15 @@ class TestIPMcast(VppTestCase): # signals should stop # route_232_1_1_1.update_path_flags( - self.pg0.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT) + self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT + ) tx = self._mcast_connected_send_stream("232.1.1.1") signals = self.vapi.mfib_signal_dump() self.assertEqual(0, len(signals)) def test_ip_mcast_vrf(self): - """ IP Multicast Replication in non-default table""" + """IP Multicast Replication in non-default table""" MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t @@ -826,15 +902,22 @@ class TestIPMcast(VppTestCase): route_1_1_1_1_232_1_1_1 = VppIpMRoute( self, "1.1.1.1", - "232.1.1.1", 64, + "232.1.1.1", + 64, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - [VppMRoutePath(self.pg8.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT), - VppMRoutePath(self.pg1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD), - VppMRoutePath(self.pg2.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)], - table_id=10) + [ + VppMRoutePath( + self.pg8.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT + ), + VppMRoutePath( + self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ), + VppMRoutePath( + self.pg2.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ), + ], + table_id=10, + ) route_1_1_1_1_232_1_1_1.add_vpp_config() # @@ -858,14 +941,21 @@ class TestIPMcast(VppTestCase): route_0_0_0_0_224_0_0_5 = VppIpMRoute( self, "0.0.0.0", - "224.0.0.5", 32, + "224.0.0.5", + 32, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - [VppMRoutePath(self.pg8.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT), - VppMRoutePath(0xffffffff, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, - type=FibPathType.FIB_PATH_TYPE_LOCAL)], - table_id=10) + [ + VppMRoutePath( + self.pg8.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT + ), + VppMRoutePath( + 0xFFFFFFFF, + MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + type=FibPathType.FIB_PATH_TYPE_LOCAL, + ), + ], + table_id=10, + ) route_0_0_0_0_224_0_0_5.add_vpp_config() # @@ -879,34 +969,33 @@ class TestIPMcast(VppTestCase): # send a ping to mcast address from peer on pg8 # expect a response # - icmp_id = 0xb + icmp_id = 0xB icmp_seq = 5 - icmp_load = b'\x0a' * 18 - tx = (Ether(dst=getmacbyip("224.0.0.5"), src=self.pg8.remote_mac) / - IP(src=self.pg8.remote_ip4, dst="224.0.0.5") / - ICMP(id=icmp_id, seq=icmp_seq) / - Raw(load=icmp_load)) * 2 + icmp_load = b"\x0a" * 18 + tx = ( + Ether(dst=getmacbyip("224.0.0.5"), src=self.pg8.remote_mac) + / IP(src=self.pg8.remote_ip4, dst="224.0.0.5") + / ICMP(id=icmp_id, seq=icmp_seq) + / Raw(load=icmp_load) + ) * 2 self.send_and_expect(self.pg8, tx, self.pg8) def test_ip_mcast_gre(self): - """ IP Multicast Replication over GRE""" + """IP Multicast Replication over GRE""" MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t gre_if_1 = VppGreInterface( - self, - self.pg1.local_ip4, - self.pg1.remote_ip4).add_vpp_config() + self, self.pg1.local_ip4, self.pg1.remote_ip4 + ).add_vpp_config() gre_if_2 = VppGreInterface( - self, - self.pg2.local_ip4, - self.pg2.remote_ip4).add_vpp_config() + self, self.pg2.local_ip4, self.pg2.remote_ip4 + ).add_vpp_config() gre_if_3 = VppGreInterface( - self, - self.pg3.local_ip4, - self.pg3.remote_ip4).add_vpp_config() + self, self.pg3.local_ip4, self.pg3.remote_ip4 + ).add_vpp_config() gre_if_1.admin_up() gre_if_1.config_ip4() @@ -922,28 +1011,35 @@ class TestIPMcast(VppTestCase): route_1_1_1_1_232_1_1_1 = VppIpMRoute( self, "1.1.1.1", - "232.2.2.2", 64, + "232.2.2.2", + 64, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - [VppMRoutePath(gre_if_1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT), - VppMRoutePath(gre_if_2.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD), - VppMRoutePath(gre_if_3.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)]) + [ + VppMRoutePath( + gre_if_1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT + ), + VppMRoutePath( + gre_if_2.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ), + VppMRoutePath( + gre_if_3.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ), + ], + ) route_1_1_1_1_232_1_1_1.add_vpp_config() # # a stream that matches the route for (1.1.1.1,232.2.2.2) # small packets # - tx = (Ether(dst=self.pg1.local_mac, - src=self.pg1.remote_mac) / - IP(src=self.pg1.remote_ip4, - dst=self.pg1.local_ip4) / - GRE() / - IP(src="1.1.1.1", dst="232.2.2.2") / - UDP(sport=1234, dport=1234) / - Raw(b'\a5' * 64)) * 63 + tx = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src=self.pg1.remote_ip4, dst=self.pg1.local_ip4) + / GRE() + / IP(src="1.1.1.1", dst="232.2.2.2") + / UDP(sport=1234, dport=1234) + / Raw(b"\a5" * 64) + ) * 63 self.vapi.cli("clear trace") self.pg1.add_stream(tx) @@ -966,23 +1062,20 @@ class TestIPMcast(VppTestCase): self.assert_packet_checksums_valid(rx) def test_ip6_mcast_gre(self): - """ IP6 Multicast Replication over GRE""" + """IP6 Multicast Replication over GRE""" MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t gre_if_1 = VppGreInterface( - self, - self.pg1.local_ip4, - self.pg1.remote_ip4).add_vpp_config() + self, self.pg1.local_ip4, self.pg1.remote_ip4 + ).add_vpp_config() gre_if_2 = VppGreInterface( - self, - self.pg2.local_ip4, - self.pg2.remote_ip4).add_vpp_config() + self, self.pg2.local_ip4, self.pg2.remote_ip4 + ).add_vpp_config() gre_if_3 = VppGreInterface( - self, - self.pg3.local_ip4, - self.pg3.remote_ip4).add_vpp_config() + self, self.pg3.local_ip4, self.pg3.remote_ip4 + ).add_vpp_config() gre_if_1.admin_up() gre_if_1.config_ip6() @@ -998,28 +1091,35 @@ class TestIPMcast(VppTestCase): route_1_1_FF_1 = VppIpMRoute( self, "1::1", - "FF00::1", 256, + "FF00::1", + 256, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - [VppMRoutePath(gre_if_1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT), - VppMRoutePath(gre_if_2.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD), - VppMRoutePath(gre_if_3.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)]) + [ + VppMRoutePath( + gre_if_1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT + ), + VppMRoutePath( + gre_if_2.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ), + VppMRoutePath( + gre_if_3.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ), + ], + ) route_1_1_FF_1.add_vpp_config() # # a stream that matches the route for (1::1, FF::1) # small packets # - tx = (Ether(dst=self.pg1.local_mac, - src=self.pg1.remote_mac) / - IP(src=self.pg1.remote_ip4, - dst=self.pg1.local_ip4) / - GRE() / - IPv6(src="1::1", dst="FF00::1") / - UDP(sport=1234, dport=1234) / - Raw(b'\a5' * 64)) * 63 + tx = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src=self.pg1.remote_ip4, dst=self.pg1.local_ip4) + / GRE() + / IPv6(src="1::1", dst="FF00::1") + / UDP(sport=1234, dport=1234) + / Raw(b"\a5" * 64) + ) * 63 self.vapi.cli("clear trace") self.pg1.add_stream(tx) @@ -1042,7 +1142,7 @@ class TestIPMcast(VppTestCase): self.assert_packet_checksums_valid(rx) def test_ip6_mcast_vrf(self): - """ IPv6 Multicast Replication in non-default table""" + """IPv6 Multicast Replication in non-default table""" MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t @@ -1054,18 +1154,28 @@ class TestIPMcast(VppTestCase): route_2001_ff01_1 = VppIpMRoute( self, "2001::1", - "ff01::1", 256, + "ff01::1", + 256, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - [VppMRoutePath(self.pg8.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6), - VppMRoutePath(self.pg1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6), - VppMRoutePath(self.pg2.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)], - table_id=10) + [ + VppMRoutePath( + self.pg8.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ), + VppMRoutePath( + self.pg1.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ), + VppMRoutePath( + self.pg2.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ), + ], + table_id=10, + ) route_2001_ff01_1.add_vpp_config() # @@ -1083,7 +1193,7 @@ class TestIPMcast(VppTestCase): self.verify_capture_ip6(self.pg2, tx) def test_bidir(self): - """ IP Multicast Bi-directional """ + """IP Multicast Bi-directional""" MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t @@ -1094,20 +1204,32 @@ class TestIPMcast(VppTestCase): route_232_1_1_1 = VppIpMRoute( self, "0.0.0.0", - "232.1.1.1", 32, + "232.1.1.1", + 32, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - [VppMRoutePath(self.pg0.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT | - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD), - VppMRoutePath(self.pg1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT | - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD), - VppMRoutePath(self.pg2.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT | - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD), - VppMRoutePath(self.pg3.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT | - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)]) + [ + VppMRoutePath( + self.pg0.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT + | MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + ), + VppMRoutePath( + self.pg1.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT + | MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + ), + VppMRoutePath( + self.pg2.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT + | MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + ), + VppMRoutePath( + self.pg3.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT + | MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + ), + ], + ) route_232_1_1_1.add_vpp_config() tx = self.create_stream_ip4(self.pg0, "1.1.1.1", "232.1.1.1") @@ -1120,9 +1242,8 @@ class TestIPMcast(VppTestCase): self.verify_capture_ip4(self.pg1, tx) self.verify_capture_ip4(self.pg2, tx) self.verify_capture_ip4(self.pg3, tx) - self.pg0.assert_nothing_captured( - remark="IP multicast packets forwarded on PG0") + self.pg0.assert_nothing_captured(remark="IP multicast packets forwarded on PG0") -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_ipfix_export.py b/test/test_ipfix_export.py index be7476e67cf..f7b8be7e4d8 100644 --- a/test/test_ipfix_export.py +++ b/test/test_ipfix_export.py @@ -16,7 +16,7 @@ from socket import AF_INET, AF_INET6 class TestIpfixExporter(VppTestCase): - """ Ipfix Exporter Tests """ + """Ipfix Exporter Tests""" def setUp(self): super(TestIpfixExporter, self).setUp() @@ -37,15 +37,16 @@ class TestIpfixExporter(VppTestCase): i.admin_down() def find_exp_by_collector_addr(self, exporters, addr): - """ Find the exporter in the list of exportes with the given addr """ + """Find the exporter in the list of exportes with the given addr""" for exp in exporters: if exp.collector_address == IPv4Address(addr): return exp return None - def verify_exporter_detail(self, exp, collector_addr, src_addr, - collector_port=4739, mtu=1400, interval=20): + def verify_exporter_detail( + self, exp, collector_addr, src_addr, collector_port=4739, mtu=1400, interval=20 + ): self.assertTrue(exp is not None) self.assert_equal(exp.collector_address, collector_addr) self.assert_equal(exp.src_address, src_addr) @@ -54,7 +55,7 @@ class TestIpfixExporter(VppTestCase): self.assert_equal(exp.template_interval, interval) def test_create_multipe_exporters(self): - """ test that we can create and dump multiple exporters """ + """test that we can create and dump multiple exporters""" mtu = 1400 interval = 20 @@ -66,20 +67,20 @@ class TestIpfixExporter(VppTestCase): src_address=self.pg0.local_ip4, collector_port=4739, path_mtu=mtu, - template_interval=interval) + template_interval=interval, + ) exporters = self.vapi.ipfix_exporter_dump() exp = self.find_exp_by_collector_addr(exporters, self.pg1.remote_ip4) - self.verify_exporter_detail(exp, - IPv4Address(self.pg1.remote_ip4), - IPv4Address(self.pg0.local_ip4)) + self.verify_exporter_detail( + exp, IPv4Address(self.pg1.remote_ip4), IPv4Address(self.pg0.local_ip4) + ) - exporters = list(self.vapi.vpp.details_iter( - self.vapi.ipfix_all_exporter_get)) + exporters = list(self.vapi.vpp.details_iter(self.vapi.ipfix_all_exporter_get)) exp = self.find_exp_by_collector_addr(exporters, self.pg1.remote_ip4) - self.verify_exporter_detail(exp, - IPv4Address(self.pg1.remote_ip4), - IPv4Address(self.pg0.local_ip4)) + self.verify_exporter_detail( + exp, IPv4Address(self.pg1.remote_ip4), IPv4Address(self.pg0.local_ip4) + ) # create a 2nd exporter self.vapi.ipfix_exporter_create_delete( @@ -88,19 +89,19 @@ class TestIpfixExporter(VppTestCase): collector_port=4739, path_mtu=mtu, template_interval=interval, - is_create=True) + is_create=True, + ) - exporters = list(self.vapi.vpp.details_iter( - self.vapi.ipfix_all_exporter_get)) + exporters = list(self.vapi.vpp.details_iter(self.vapi.ipfix_all_exporter_get)) self.assertTrue(len(exporters) == 2) exp = self.find_exp_by_collector_addr(exporters, self.pg1.remote_ip4) - self.verify_exporter_detail(exp, - IPv4Address(self.pg1.remote_ip4), - IPv4Address(self.pg0.local_ip4)) + self.verify_exporter_detail( + exp, IPv4Address(self.pg1.remote_ip4), IPv4Address(self.pg0.local_ip4) + ) exp = self.find_exp_by_collector_addr(exporters, self.pg2.remote_ip4) - self.verify_exporter_detail(exp, - IPv4Address(self.pg2.remote_ip4), - IPv4Address(self.pg0.local_ip4)) + self.verify_exporter_detail( + exp, IPv4Address(self.pg2.remote_ip4), IPv4Address(self.pg0.local_ip4) + ) # Create a 3rd exporter self.vapi.ipfix_exporter_create_delete( @@ -109,49 +110,52 @@ class TestIpfixExporter(VppTestCase): collector_port=4739, path_mtu=mtu, template_interval=interval, - is_create=True) + is_create=True, + ) - exporters = list(self.vapi.vpp.details_iter( - self.vapi.ipfix_all_exporter_get)) + exporters = list(self.vapi.vpp.details_iter(self.vapi.ipfix_all_exporter_get)) self.assertTrue(len(exporters) == 3) exp = self.find_exp_by_collector_addr(exporters, self.pg1.remote_ip4) - self.verify_exporter_detail(exp, - IPv4Address(self.pg1.remote_ip4), - IPv4Address(self.pg0.local_ip4)) + self.verify_exporter_detail( + exp, IPv4Address(self.pg1.remote_ip4), IPv4Address(self.pg0.local_ip4) + ) exp = self.find_exp_by_collector_addr(exporters, self.pg2.remote_ip4) - self.verify_exporter_detail(exp, - IPv4Address(self.pg2.remote_ip4), - IPv4Address(self.pg0.local_ip4)) + self.verify_exporter_detail( + exp, IPv4Address(self.pg2.remote_ip4), IPv4Address(self.pg0.local_ip4) + ) exp = self.find_exp_by_collector_addr(exporters, self.pg3.remote_ip4) - self.verify_exporter_detail(exp, - IPv4Address(self.pg3.remote_ip4), - IPv4Address(self.pg0.local_ip4)) + self.verify_exporter_detail( + exp, IPv4Address(self.pg3.remote_ip4), IPv4Address(self.pg0.local_ip4) + ) # Modify the 2nd exporter. self.vapi.ipfix_exporter_create_delete( collector_address=self.pg2.remote_ip4, src_address=self.pg0.local_ip4, collector_port=4739, - path_mtu=mtu+1, - template_interval=interval+1, - is_create=True) + path_mtu=mtu + 1, + template_interval=interval + 1, + is_create=True, + ) - exporters = list(self.vapi.vpp.details_iter( - self.vapi.ipfix_all_exporter_get)) + exporters = list(self.vapi.vpp.details_iter(self.vapi.ipfix_all_exporter_get)) self.assertTrue(len(exporters) == 3) exp = self.find_exp_by_collector_addr(exporters, self.pg1.remote_ip4) - self.verify_exporter_detail(exp, - IPv4Address(self.pg1.remote_ip4), - IPv4Address(self.pg0.local_ip4)) + self.verify_exporter_detail( + exp, IPv4Address(self.pg1.remote_ip4), IPv4Address(self.pg0.local_ip4) + ) exp = self.find_exp_by_collector_addr(exporters, self.pg2.remote_ip4) - self.verify_exporter_detail(exp, - IPv4Address(self.pg2.remote_ip4), - IPv4Address(self.pg0.local_ip4), - mtu=mtu+1, interval=interval+1) + self.verify_exporter_detail( + exp, + IPv4Address(self.pg2.remote_ip4), + IPv4Address(self.pg0.local_ip4), + mtu=mtu + 1, + interval=interval + 1, + ) exp = self.find_exp_by_collector_addr(exporters, self.pg3.remote_ip4) - self.verify_exporter_detail(exp, - IPv4Address(self.pg3.remote_ip4), - IPv4Address(self.pg0.local_ip4)) + self.verify_exporter_detail( + exp, IPv4Address(self.pg3.remote_ip4), IPv4Address(self.pg0.local_ip4) + ) # Delete 2nd exporter self.vapi.ipfix_exporter_create_delete( @@ -160,19 +164,19 @@ class TestIpfixExporter(VppTestCase): collector_port=4739, path_mtu=mtu, template_interval=interval, - is_create=False) + is_create=False, + ) - exporters = list(self.vapi.vpp.details_iter( - self.vapi.ipfix_all_exporter_get)) + exporters = list(self.vapi.vpp.details_iter(self.vapi.ipfix_all_exporter_get)) self.assertTrue(len(exporters) == 2) exp = self.find_exp_by_collector_addr(exporters, self.pg1.remote_ip4) - self.verify_exporter_detail(exp, - IPv4Address(self.pg1.remote_ip4), - IPv4Address(self.pg0.local_ip4)) + self.verify_exporter_detail( + exp, IPv4Address(self.pg1.remote_ip4), IPv4Address(self.pg0.local_ip4) + ) exp = self.find_exp_by_collector_addr(exporters, self.pg3.remote_ip4) - self.verify_exporter_detail(exp, - IPv4Address(self.pg3.remote_ip4), - IPv4Address(self.pg0.local_ip4)) + self.verify_exporter_detail( + exp, IPv4Address(self.pg3.remote_ip4), IPv4Address(self.pg0.local_ip4) + ) # Delete final exporter (exporter in slot 0 can not be deleted) self.vapi.ipfix_exporter_create_delete( @@ -181,12 +185,12 @@ class TestIpfixExporter(VppTestCase): collector_port=4739, path_mtu=mtu, template_interval=interval, - is_create=False) + is_create=False, + ) - exporters = list(self.vapi.vpp.details_iter( - self.vapi.ipfix_all_exporter_get)) + exporters = list(self.vapi.vpp.details_iter(self.vapi.ipfix_all_exporter_get)) self.assertTrue(len(exporters) == 1) exp = self.find_exp_by_collector_addr(exporters, self.pg1.remote_ip4) - self.verify_exporter_detail(exp, - IPv4Address(self.pg1.remote_ip4), - IPv4Address(self.pg0.local_ip4)) + self.verify_exporter_detail( + exp, IPv4Address(self.pg1.remote_ip4), IPv4Address(self.pg0.local_ip4) + ) diff --git a/test/test_ipip.py b/test/test_ipip.py index b1ea57d7e12..cbaedd51273 100644 --- a/test/test_ipip.py +++ b/test/test_ipip.py @@ -7,8 +7,15 @@ from scapy.contrib.mpls import MPLS from scapy.all import fragment, fragment6, RandShort, defragment6 from framework import VppTestCase, VppTestRunner from vpp_ip import DpoProto -from vpp_ip_route import VppIpRoute, VppRoutePath, VppIpTable, FibPathProto, \ - VppMplsLabel, VppMplsRoute, VppMplsTable +from vpp_ip_route import ( + VppIpRoute, + VppRoutePath, + VppIpTable, + FibPathProto, + VppMplsLabel, + VppMplsRoute, + VppMplsTable, +) from vpp_ipip_tun_interface import VppIpIpTunInterface from vpp_teib import VppTeib from vpp_papi import VppEnum @@ -22,27 +29,27 @@ IPIP tests. """ -def ipip_add_tunnel(test, src, dst, table_id=0, dscp=0x0, - flags=0): - """ Add a IPIP tunnel """ +def ipip_add_tunnel(test, src, dst, table_id=0, dscp=0x0, flags=0): + """Add a IPIP tunnel""" return test.vapi.ipip_add_tunnel( tunnel={ - 'src': src, - 'dst': dst, - 'table_id': table_id, - 'instance': 0xffffffff, - 'dscp': dscp, - 'flags': flags + "src": src, + "dst": dst, + "table_id": table_id, + "instance": 0xFFFFFFFF, + "dscp": dscp, + "flags": flags, } ) + # the number of packets to send when injecting traffic. # a multiple of 8 minus one, so we test all by 8/4/2/1 loops N_PACKETS = 64 - 1 class TestIPIP(VppTestCase): - """ IPIP Test Case """ + """IPIP Test Case""" @classmethod def setUpClass(cls): @@ -88,21 +95,24 @@ class TestIPIP(VppTestCase): p_ether = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) p_payload = UDP(sport=1234, dport=1234) / self.payload(payload_length) p_ip4 = IP(src="1.2.3.4", dst=self.pg0.remote_ip4) - outer_ip4 = (p_ether / IP(src=self.pg1.remote_ip4, - id=RandShort(), - dst=self.pg0.local_ip4) / p_ip4 / p_payload) + outer_ip4 = ( + p_ether + / IP(src=self.pg1.remote_ip4, id=RandShort(), dst=self.pg0.local_ip4) + / p_ip4 + / p_payload + ) frags = fragment(outer_ip4, fragment_size) - p4_reply = (p_ip4 / p_payload) + p4_reply = p_ip4 / p_payload p4_reply.ttl -= 1 return frags, p4_reply def verify_ip4ip4_encaps(self, a, p_ip4s, p_ip4_encaps): for i, p_ip4 in enumerate(p_ip4s): p_ip4.dst = a - p4 = (self.p_ether / p_ip4 / self.p_payload) + p4 = self.p_ether / p_ip4 / self.p_payload p_ip4_inner = p_ip4 p_ip4_inner.ttl -= 1 - p4_reply = (p_ip4_encaps[i] / p_ip4_inner / self.p_payload) + p4_reply = p_ip4_encaps[i] / p_ip4_inner / self.p_payload p4_reply.ttl -= 1 p4_reply.id = 0 rx = self.send_and_expect(self.pg0, p4 * N_PACKETS, self.pg1) @@ -113,10 +123,10 @@ class TestIPIP(VppTestCase): def verify_ip6ip4_encaps(self, a, p_ip6s, p_ip4_encaps): for i, p_ip6 in enumerate(p_ip6s): p_ip6.dst = a - p6 = (self.p_ether / p_ip6 / self.p_payload) + p6 = self.p_ether / p_ip6 / self.p_payload p_inner_ip6 = p_ip6 p_inner_ip6.hlim -= 1 - p6_reply = (p_ip4_encaps[i] / p_inner_ip6 / self.p_payload) + p6_reply = p_ip4_encaps[i] / p_inner_ip6 / self.p_payload p6_reply.ttl -= 1 rx = self.send_and_expect(self.pg0, p6 * N_PACKETS, self.pg1) for p in rx: @@ -124,14 +134,14 @@ class TestIPIP(VppTestCase): self.assert_packet_checksums_valid(p) def test_ipip4(self): - """ ip{v4,v6} over ip4 test """ + """ip{v4,v6} over ip4 test""" self.pg1.generate_remote_hosts(5) self.pg1.configure_ipv4_neighbors() e = VppEnum.vl_api_tunnel_encap_decap_flags_t d = VppEnum.vl_api_ip_dscp_t self.p_ether = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) - self.p_payload = UDP(sport=1234, dport=1234) / Raw(b'X' * 100) + self.p_payload = UDP(sport=1234, dport=1234) / Raw(b"X" * 100) # create a TOS byte by shifting a DSCP code point 2 bits. those 2 bits # are for the ECN. @@ -145,7 +155,8 @@ class TestIPIP(VppTestCase): self.pg0, self.pg0.local_ip4, self.pg1.remote_hosts[0].ip4, - flags=e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP) + flags=e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP, + ) tun_dscp.add_vpp_config() # IPv4 transport that copies the DCSP and ECN from the payload tun_dscp_ecn = VppIpIpTunInterface( @@ -153,8 +164,11 @@ class TestIPIP(VppTestCase): self.pg0, self.pg0.local_ip4, self.pg1.remote_hosts[1].ip4, - flags=(e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP | - e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN)) + flags=( + e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP + | e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN + ), + ) tun_dscp_ecn.add_vpp_config() # IPv4 transport that copies the ECN from the payload and sets the # DF bit on encap. copies the ECN on decap @@ -163,9 +177,12 @@ class TestIPIP(VppTestCase): self.pg0, self.pg0.local_ip4, self.pg1.remote_hosts[2].ip4, - flags=(e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN | - e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_SET_DF | - e.TUNNEL_API_ENCAP_DECAP_FLAG_DECAP_COPY_ECN)) + flags=( + e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN + | e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_SET_DF + | e.TUNNEL_API_ENCAP_DECAP_FLAG_DECAP_COPY_ECN + ), + ) tun_ecn.add_vpp_config() # IPv4 transport that sets a fixed DSCP in the encap and copies # the DF bit @@ -175,7 +192,8 @@ class TestIPIP(VppTestCase): self.pg0.local_ip4, self.pg1.remote_hosts[3].ip4, dscp=d.IP_API_DSCP_AF11, - flags=e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DF) + flags=e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DF, + ) tun.add_vpp_config() # array of all the tunnels @@ -186,22 +204,26 @@ class TestIPIP(VppTestCase): a6s = ["" for i in range(len(tuns))] # IP headers with each combination of DSCp/ECN tested - p_ip6s = [IPv6(src="1::1", dst="DEAD::1", nh='UDP', tc=dscp), - IPv6(src="1::1", dst="DEAD::1", nh='UDP', tc=dscp_ecn), - IPv6(src="1::1", dst="DEAD::1", nh='UDP', tc=ecn), - IPv6(src="1::1", dst="DEAD::1", nh='UDP', tc=0xff)] - p_ip4s = [IP(src="1.2.3.4", dst="130.67.0.1", tos=dscp, flags='DF'), - IP(src="1.2.3.4", dst="130.67.0.1", tos=dscp_ecn), - IP(src="1.2.3.4", dst="130.67.0.1", tos=ecn), - IP(src="1.2.3.4", dst="130.67.0.1", tos=0xff)] + p_ip6s = [ + IPv6(src="1::1", dst="DEAD::1", nh="UDP", tc=dscp), + IPv6(src="1::1", dst="DEAD::1", nh="UDP", tc=dscp_ecn), + IPv6(src="1::1", dst="DEAD::1", nh="UDP", tc=ecn), + IPv6(src="1::1", dst="DEAD::1", nh="UDP", tc=0xFF), + ] + p_ip4s = [ + IP(src="1.2.3.4", dst="130.67.0.1", tos=dscp, flags="DF"), + IP(src="1.2.3.4", dst="130.67.0.1", tos=dscp_ecn), + IP(src="1.2.3.4", dst="130.67.0.1", tos=ecn), + IP(src="1.2.3.4", dst="130.67.0.1", tos=0xFF), + ] # Configure each tunnel for i, t in enumerate(tuns): # Set interface up and enable IP on it self.vapi.sw_interface_set_flags(t.sw_if_index, 1) self.vapi.sw_interface_set_unnumbered( - sw_if_index=self.pg0.sw_if_index, - unnumbered_sw_if_index=t.sw_if_index) + sw_if_index=self.pg0.sw_if_index, unnumbered_sw_if_index=t.sw_if_index + ) # prefix for route / destination address for packets a4s[i] = "130.67.%d.0" % i @@ -209,17 +231,29 @@ class TestIPIP(VppTestCase): # Add IPv4 and IPv6 routes via tunnel interface ip4_via_tunnel = VppIpRoute( - self, a4s[i], 24, - [VppRoutePath("0.0.0.0", - t.sw_if_index, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP4)]) + self, + a4s[i], + 24, + [ + VppRoutePath( + "0.0.0.0", + t.sw_if_index, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP4, + ) + ], + ) ip4_via_tunnel.add_vpp_config() ip6_via_tunnel = VppIpRoute( - self, a6s[i], 64, - [VppRoutePath("::", - t.sw_if_index, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)]) + self, + a6s[i], + 64, + [ + VppRoutePath( + "::", t.sw_if_index, proto=FibPathProto.FIB_PATH_NH_PROTO_IP6 + ) + ], + ) ip6_via_tunnel.add_vpp_config() # @@ -229,13 +263,14 @@ class TestIPIP(VppTestCase): # tun_dscp copies only the dscp # expected TC values are thus only the DCSP value is present from the # inner - exp_tcs = [dscp, dscp, 0, 0xfc] - p_ip44_encaps = [IP(src=self.pg0.local_ip4, - dst=tun_dscp.dst, - tos=tc) for tc in exp_tcs] - p_ip64_encaps = [IP(src=self.pg0.local_ip4, - dst=tun_dscp.dst, - proto='ipv6', id=0, tos=tc) for tc in exp_tcs] + exp_tcs = [dscp, dscp, 0, 0xFC] + p_ip44_encaps = [ + IP(src=self.pg0.local_ip4, dst=tun_dscp.dst, tos=tc) for tc in exp_tcs + ] + p_ip64_encaps = [ + IP(src=self.pg0.local_ip4, dst=tun_dscp.dst, proto="ipv6", id=0, tos=tc) + for tc in exp_tcs + ] # IPv4 in to IPv4 tunnel self.verify_ip4ip4_encaps(a4s[0], p_ip4s, p_ip44_encaps) @@ -243,41 +278,50 @@ class TestIPIP(VppTestCase): self.verify_ip6ip4_encaps(a6s[0], p_ip6s, p_ip64_encaps) # tun_dscp_ecn copies the dscp and the ecn - exp_tcs = [dscp, dscp_ecn, ecn, 0xff] - p_ip44_encaps = [IP(src=self.pg0.local_ip4, - dst=tun_dscp_ecn.dst, - tos=tc) for tc in exp_tcs] - p_ip64_encaps = [IP(src=self.pg0.local_ip4, - dst=tun_dscp_ecn.dst, - proto='ipv6', id=0, tos=tc) for tc in exp_tcs] + exp_tcs = [dscp, dscp_ecn, ecn, 0xFF] + p_ip44_encaps = [ + IP(src=self.pg0.local_ip4, dst=tun_dscp_ecn.dst, tos=tc) for tc in exp_tcs + ] + p_ip64_encaps = [ + IP(src=self.pg0.local_ip4, dst=tun_dscp_ecn.dst, proto="ipv6", id=0, tos=tc) + for tc in exp_tcs + ] self.verify_ip4ip4_encaps(a4s[1], p_ip4s, p_ip44_encaps) self.verify_ip6ip4_encaps(a6s[1], p_ip6s, p_ip64_encaps) # tun_ecn copies only the ecn and always sets DF exp_tcs = [0, ecn, ecn, ecn] - p_ip44_encaps = [IP(src=self.pg0.local_ip4, - dst=tun_ecn.dst, - flags='DF', tos=tc) for tc in exp_tcs] - p_ip64_encaps = [IP(src=self.pg0.local_ip4, - dst=tun_ecn.dst, - flags='DF', proto='ipv6', id=0, tos=tc) - for tc in exp_tcs] + p_ip44_encaps = [ + IP(src=self.pg0.local_ip4, dst=tun_ecn.dst, flags="DF", tos=tc) + for tc in exp_tcs + ] + p_ip64_encaps = [ + IP( + src=self.pg0.local_ip4, + dst=tun_ecn.dst, + flags="DF", + proto="ipv6", + id=0, + tos=tc, + ) + for tc in exp_tcs + ] self.verify_ip4ip4_encaps(a4s[2], p_ip4s, p_ip44_encaps) self.verify_ip6ip4_encaps(a6s[2], p_ip6s, p_ip64_encaps) # tun sets a fixed dscp and copies DF fixed_dscp = tun.dscp << 2 - flags = ['DF', 0, 0, 0] - p_ip44_encaps = [IP(src=self.pg0.local_ip4, - dst=tun.dst, - flags=f, - tos=fixed_dscp) for f in flags] - p_ip64_encaps = [IP(src=self.pg0.local_ip4, - dst=tun.dst, - proto='ipv6', id=0, - tos=fixed_dscp) for i in range(len(p_ip4s))] + flags = ["DF", 0, 0, 0] + p_ip44_encaps = [ + IP(src=self.pg0.local_ip4, dst=tun.dst, flags=f, tos=fixed_dscp) + for f in flags + ] + p_ip64_encaps = [ + IP(src=self.pg0.local_ip4, dst=tun.dst, proto="ipv6", id=0, tos=fixed_dscp) + for i in range(len(p_ip4s)) + ] self.verify_ip4ip4_encaps(a4s[3], p_ip4s, p_ip44_encaps) self.verify_ip6ip4_encaps(a6s[3], p_ip6s, p_ip64_encaps) @@ -293,15 +337,13 @@ class TestIPIP(VppTestCase): # one overlay packet and all combinations of its encap p_ip4 = IP(src="1.2.3.4", dst=self.pg0.remote_ip4) - p_ip4_encaps = [IP(src=tun.dst, - dst=self.pg0.local_ip4, - tos=tc) for tc in tcs] + p_ip4_encaps = [IP(src=tun.dst, dst=self.pg0.local_ip4, tos=tc) for tc in tcs] # for each encap tun will produce the same inner packet because it does # not copy up fields from the payload for p_ip4_encap in p_ip4_encaps: - p4 = (self.p_ether / p_ip4_encap / p_ip4 / self.p_payload) - p4_reply = (p_ip4 / self.p_payload) + p4 = self.p_ether / p_ip4_encap / p_ip4 / self.p_payload + p4_reply = p_ip4 / self.p_payload p4_reply.ttl -= 1 rx = self.send_and_expect(self.pg1, p4 * N_PACKETS, self.pg0) n_packets_decapped += N_PACKETS @@ -309,20 +351,19 @@ class TestIPIP(VppTestCase): self.validate(p[1], p4_reply) self.assert_packet_checksums_valid(p) - err = self.statistics.get_err_counter( - '/err/ipip4-input/packets decapsulated') + err = self.statistics.get_err_counter("/err/ipip4-input/packets decapsulated") self.assertEqual(err, n_packets_decapped) # tun_ecn copies the ECN bits from the encap to the inner - p_ip4_encaps = [IP(src=tun_ecn.dst, - dst=self.pg0.local_ip4, - tos=tc) for tc in tcs] + p_ip4_encaps = [ + IP(src=tun_ecn.dst, dst=self.pg0.local_ip4, tos=tc) for tc in tcs + ] p_ip4_replys = [p_ip4.copy() for i in range(len(p_ip4_encaps))] p_ip4_replys[2].tos = ecn p_ip4_replys[3].tos = ecn for i, p_ip4_encap in enumerate(p_ip4_encaps): - p4 = (self.p_ether / p_ip4_encap / p_ip4 / self.p_payload) - p4_reply = (p_ip4_replys[i] / self.p_payload) + p4 = self.p_ether / p_ip4_encap / p_ip4 / self.p_payload + p4_reply = p_ip4_replys[i] / self.p_payload p4_reply.ttl -= 1 rx = self.send_and_expect(self.pg1, p4 * N_PACKETS, self.pg0) n_packets_decapped += N_PACKETS @@ -330,22 +371,17 @@ class TestIPIP(VppTestCase): self.validate(p[1], p4_reply) self.assert_packet_checksums_valid(p) - err = self.statistics.get_err_counter( - '/err/ipip4-input/packets decapsulated') + err = self.statistics.get_err_counter("/err/ipip4-input/packets decapsulated") self.assertEqual(err, n_packets_decapped) # IPv4 tunnel to IPv6 # for each encap tun will produce the same inner packet because it does # not copy up fields from the payload - p_ip4_encaps = [IP(src=tun.dst, - dst=self.pg0.local_ip4, - tos=tc) for tc in tcs] + p_ip4_encaps = [IP(src=tun.dst, dst=self.pg0.local_ip4, tos=tc) for tc in tcs] p_ip6 = IPv6(src="1:2:3::4", dst=self.pg0.remote_ip6) for p_ip4_encap in p_ip4_encaps: - p6 = (self.p_ether / - p_ip4_encap / p_ip6 / - self.p_payload) - p6_reply = (p_ip6 / self.p_payload) + p6 = self.p_ether / p_ip4_encap / p_ip6 / self.p_payload + p6_reply = p_ip6 / self.p_payload p6_reply.hlim = 63 rx = self.send_and_expect(self.pg1, p6 * N_PACKETS, self.pg0) n_packets_decapped += N_PACKETS @@ -353,22 +389,21 @@ class TestIPIP(VppTestCase): self.validate(p[1], p6_reply) self.assert_packet_checksums_valid(p) - err = self.statistics.get_err_counter( - '/err/ipip4-input/packets decapsulated') + err = self.statistics.get_err_counter("/err/ipip4-input/packets decapsulated") self.assertEqual(err, n_packets_decapped) # IPv4 tunnel to IPv6 # tun_ecn copies the ECN bits from the encap to the inner - p_ip4_encaps = [IP(src=tun_ecn.dst, - dst=self.pg0.local_ip4, - tos=tc) for tc in tcs] + p_ip4_encaps = [ + IP(src=tun_ecn.dst, dst=self.pg0.local_ip4, tos=tc) for tc in tcs + ] p_ip6 = IPv6(src="1:2:3::4", dst=self.pg0.remote_ip6) p_ip6_replys = [p_ip6.copy() for i in range(len(p_ip4_encaps))] p_ip6_replys[2].tc = ecn p_ip6_replys[3].tc = ecn for i, p_ip4_encap in enumerate(p_ip4_encaps): - p6 = (self.p_ether / p_ip4_encap / p_ip6 / self.p_payload) - p6_reply = (p_ip6_replys[i] / self.p_payload) + p6 = self.p_ether / p_ip4_encap / p_ip6 / self.p_payload + p6_reply = p_ip6_replys[i] / self.p_payload p6_reply.hlim = 63 rx = self.send_and_expect(self.pg1, p6 * N_PACKETS, self.pg0) n_packets_decapped += N_PACKETS @@ -376,21 +411,23 @@ class TestIPIP(VppTestCase): self.validate(p[1], p6_reply) self.assert_packet_checksums_valid(p) - err = self.statistics.get_err_counter( - '/err/ipip4-input/packets decapsulated') + err = self.statistics.get_err_counter("/err/ipip4-input/packets decapsulated") self.assertEqual(err, n_packets_decapped) # # Fragmentation / Reassembly and Re-fragmentation # rv = self.vapi.ip_reassembly_enable_disable( - sw_if_index=self.pg1.sw_if_index, - enable_ip4=1) + sw_if_index=self.pg1.sw_if_index, enable_ip4=1 + ) - self.vapi.ip_reassembly_set(timeout_ms=1000, max_reassemblies=1000, - max_reassembly_length=1000, - expire_walk_interval_ms=10000, - is_ip6=0) + self.vapi.ip_reassembly_set( + timeout_ms=1000, + max_reassemblies=1000, + max_reassembly_length=1000, + expire_walk_interval_ms=10000, + is_ip6=0, + ) # Send lots of fragments, verify reassembled packet frags, p4_reply = self.generate_ip4_frags(3131, 1400) @@ -406,8 +443,7 @@ class TestIPIP(VppTestCase): for p in rx: self.validate(p[1], p4_reply) - err = self.statistics.get_err_counter( - '/err/ipip4-input/packets decapsulated') + err = self.statistics.get_err_counter("/err/ipip4-input/packets decapsulated") self.assertEqual(err, n_packets_decapped) f = [] @@ -453,9 +489,12 @@ class TestIPIP(VppTestCase): # send large packets through the tunnel, expect them to be fragmented self.vapi.sw_interface_set_mtu(tun_dscp.sw_if_index, [600, 0, 0, 0]) - p4 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src="1.2.3.4", dst="130.67.0.1", tos=42) / - UDP(sport=1234, dport=1234) / Raw(b'Q' * 1000)) + p4 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src="1.2.3.4", dst="130.67.0.1", tos=42) + / UDP(sport=1234, dport=1234) + / Raw(b"Q" * 1000) + ) rx = self.send_and_expect(self.pg0, p4 * 15, self.pg1, 30) inners = [] for p in rx: @@ -466,25 +505,25 @@ class TestIPIP(VppTestCase): self.assertEqual(p[IP].ttl, 63) def test_ipip_create(self): - """ ipip create / delete interface test """ - rv = ipip_add_tunnel(self, '1.2.3.4', '2.3.4.5') + """ipip create / delete interface test""" + rv = ipip_add_tunnel(self, "1.2.3.4", "2.3.4.5") sw_if_index = rv.sw_if_index self.vapi.ipip_del_tunnel(sw_if_index) def test_ipip_vrf_create(self): - """ ipip create / delete interface VRF test """ + """ipip create / delete interface VRF test""" t = VppIpTable(self, 20) t.add_vpp_config() - rv = ipip_add_tunnel(self, '1.2.3.4', '2.3.4.5', table_id=20) + rv = ipip_add_tunnel(self, "1.2.3.4", "2.3.4.5", table_id=20) sw_if_index = rv.sw_if_index self.vapi.ipip_del_tunnel(sw_if_index) def payload(self, len): - return 'x' * len + return "x" * len def test_mipip4(self): - """ p2mp IPv4 tunnel Tests """ + """p2mp IPv4 tunnel Tests""" for itf in self.pg_interfaces[:2]: # @@ -499,11 +538,13 @@ class TestIPIP(VppTestCase): # - assign an IP Addres # - Add a route via the tunnel # - ipip_if = VppIpIpTunInterface(self, itf, - itf.local_ip4, - "0.0.0.0", - mode=(VppEnum.vl_api_tunnel_mode_t. - TUNNEL_API_MODE_MP)) + ipip_if = VppIpIpTunInterface( + self, + itf, + itf.local_ip4, + "0.0.0.0", + mode=(VppEnum.vl_api_tunnel_mode_t.TUNNEL_API_MODE_MP), + ) ipip_if.add_vpp_config() ipip_if.admin_up() ipip_if.config_ip4() @@ -533,31 +574,40 @@ class TestIPIP(VppTestCase): # route traffic via the peer # route_via_tun = VppIpRoute( - self, route_addr, 32, - [VppRoutePath(ipip_if._remote_hosts[ii].ip4, - ipip_if.sw_if_index)]) + self, + route_addr, + 32, + [VppRoutePath(ipip_if._remote_hosts[ii].ip4, ipip_if.sw_if_index)], + ) route_via_tun.add_vpp_config() # # Add a TEIB entry resolves the peer # - teib = VppTeib(self, ipip_if, - ipip_if._remote_hosts[ii].ip4, - itf._remote_hosts[ii].ip4) + teib = VppTeib( + self, + ipip_if, + ipip_if._remote_hosts[ii].ip4, + itf._remote_hosts[ii].ip4, + ) teib.add_vpp_config() - self.logger.info(self.vapi.cli("sh adj nbr ipip0 %s" % - ipip_if._remote_hosts[ii].ip4)) + self.logger.info( + self.vapi.cli("sh adj nbr ipip0 %s" % ipip_if._remote_hosts[ii].ip4) + ) # # Send a packet stream that is routed into the tunnel # - packets are IPIP encapped # - inner = (IP(dst=route_addr, src="5.5.5.5") / - UDP(sport=1234, dport=1234) / - Raw(b'0x44' * 100)) - tx_e = [(Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - inner) for x in range(63)] + inner = ( + IP(dst=route_addr, src="5.5.5.5") + / UDP(sport=1234, dport=1234) + / Raw(b"0x44" * 100) + ) + tx_e = [ + (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / inner) + for x in range(63) + ] rxs = self.send_and_expect(self.pg0, tx_e, itf) @@ -565,13 +615,16 @@ class TestIPIP(VppTestCase): self.assertEqual(rx[IP].src, itf.local_ip4) self.assertEqual(rx[IP].dst, itf._remote_hosts[ii].ip4) - tx_i = [(Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IP(src=itf._remote_hosts[ii].ip4, - dst=itf.local_ip4) / - IP(src=self.pg0.local_ip4, dst=self.pg0.remote_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'0x44' * 100)) for x in range(63)] + tx_i = [ + ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=itf._remote_hosts[ii].ip4, dst=itf.local_ip4) + / IP(src=self.pg0.local_ip4, dst=self.pg0.remote_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"0x44" * 100) + ) + for x in range(63) + ] self.logger.info(self.vapi.cli("sh ipip tunnel-hash")) rx = self.send_and_expect(self.pg0, tx_i, self.pg0) @@ -593,12 +646,15 @@ class TestIPIP(VppTestCase): # # we can also send to the peer's address # - inner = (IP(dst=teib.peer, src="5.5.5.5") / - UDP(sport=1234, dport=1234) / - Raw(b'0x44' * 100)) - tx_e = [(Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - inner) for x in range(63)] + inner = ( + IP(dst=teib.peer, src="5.5.5.5") + / UDP(sport=1234, dport=1234) + / Raw(b"0x44" * 100) + ) + tx_e = [ + (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / inner) + for x in range(63) + ] rxs = self.send_and_expect(self.pg0, tx_e, itf) @@ -616,12 +672,15 @@ class TestIPIP(VppTestCase): # # we should still be able to reach the peers from the new table # - inner = (IP(dst=teib.peer, src="5.5.5.5") / - UDP(sport=1234, dport=1234) / - Raw(b'0x44' * 100)) - tx_e = [(Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - inner) for x in range(63)] + inner = ( + IP(dst=teib.peer, src="5.5.5.5") + / UDP(sport=1234, dport=1234) + / Raw(b"0x44" * 100) + ) + tx_e = [ + (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / inner) + for x in range(63) + ] rxs = self.send_and_expect(self.pg2, tx_e, itf) @@ -631,7 +690,7 @@ class TestIPIP(VppTestCase): class TestIPIP6(VppTestCase): - """ IPIP6 Test Case """ + """IPIP6 Test Case""" @classmethod def setUpClass(cls): @@ -665,30 +724,34 @@ class TestIPIP6(VppTestCase): def setup_tunnel(self): # IPv6 transport - rv = ipip_add_tunnel(self, - self.pg0.local_ip6, - self.pg1.remote_ip6) + rv = ipip_add_tunnel(self, self.pg0.local_ip6, self.pg1.remote_ip6) sw_if_index = rv.sw_if_index self.tunnel_if_index = sw_if_index self.vapi.sw_interface_set_flags(sw_if_index, 1) self.vapi.sw_interface_set_unnumbered( - sw_if_index=self.pg0.sw_if_index, - unnumbered_sw_if_index=sw_if_index) + sw_if_index=self.pg0.sw_if_index, unnumbered_sw_if_index=sw_if_index + ) # Add IPv4 and IPv6 routes via tunnel interface ip4_via_tunnel = VppIpRoute( - self, "130.67.0.0", 16, - [VppRoutePath("0.0.0.0", - sw_if_index, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP4)]) + self, + "130.67.0.0", + 16, + [ + VppRoutePath( + "0.0.0.0", sw_if_index, proto=FibPathProto.FIB_PATH_NH_PROTO_IP4 + ) + ], + ) ip4_via_tunnel.add_vpp_config() ip6_via_tunnel = VppIpRoute( - self, "dead::", 16, - [VppRoutePath("::", - sw_if_index, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)]) + self, + "dead::", + 16, + [VppRoutePath("::", sw_if_index, proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)], + ) ip6_via_tunnel.add_vpp_config() self.tunnel_ip6_via_tunnel = ip6_via_tunnel @@ -708,11 +771,15 @@ class TestIPIP6(VppTestCase): p_ether = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) p_payload = UDP(sport=1234, dport=1234) / self.payload(payload_length) p_ip6 = IPv6(src="1::1", dst=self.pg0.remote_ip6) - outer_ip6 = (p_ether / IPv6(src=self.pg1.remote_ip6, - dst=self.pg0.local_ip6) / - IPv6ExtHdrFragment() / p_ip6 / p_payload) + outer_ip6 = ( + p_ether + / IPv6(src=self.pg1.remote_ip6, dst=self.pg0.local_ip6) + / IPv6ExtHdrFragment() + / p_ip6 + / p_payload + ) frags = fragment6(outer_ip6, fragment_size) - p6_reply = (p_ip6 / p_payload) + p6_reply = p_ip6 / p_payload p6_reply.hlim -= 1 return frags, p6_reply @@ -720,58 +787,73 @@ class TestIPIP6(VppTestCase): p_ether = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) p_payload = UDP(sport=1234, dport=1234) / self.payload(payload_length) p_ip6 = IPv6(src="1::1", dst="dead::1") - outer_ip6 = (p_ether / IPv6(src=self.pg1.remote_ip6, - dst=self.pg0.local_ip6) / - IPv6ExtHdrFragment() / p_ip6 / p_payload) + outer_ip6 = ( + p_ether + / IPv6(src=self.pg1.remote_ip6, dst=self.pg0.local_ip6) + / IPv6ExtHdrFragment() + / p_ip6 + / p_payload + ) frags = fragment6(outer_ip6, fragment_size) p_ip6.hlim -= 1 - p6_reply = (IPv6(src=self.pg0.local_ip6, dst=self.pg1.remote_ip6, - hlim=63) / p_ip6 / p_payload) + p6_reply = ( + IPv6(src=self.pg0.local_ip6, dst=self.pg1.remote_ip6, hlim=63) + / p_ip6 + / p_payload + ) return frags, p6_reply def test_encap(self): - """ ip{v4,v6} over ip6 test encap """ + """ip{v4,v6} over ip6 test encap""" p_ether = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) - p_ip6 = IPv6(src="1::1", dst="DEAD::1", tc=42, nh='UDP') + p_ip6 = IPv6(src="1::1", dst="DEAD::1", tc=42, nh="UDP") p_ip4 = IP(src="1.2.3.4", dst="130.67.0.1", tos=42) p_payload = UDP(sport=1234, dport=1234) # Encapsulation # IPv6 in to IPv6 tunnel - p6 = (p_ether / p_ip6 / p_payload) - p6_reply = (IPv6(src=self.pg0.local_ip6, dst=self.pg1.remote_ip6, - hlim=64) / - p_ip6 / p_payload) + p6 = p_ether / p_ip6 / p_payload + p6_reply = ( + IPv6(src=self.pg0.local_ip6, dst=self.pg1.remote_ip6, hlim=64) + / p_ip6 + / p_payload + ) p6_reply[1].hlim -= 1 rx = self.send_and_expect(self.pg0, p6 * 11, self.pg1) for p in rx: self.validate(p[1], p6_reply) # IPv4 in to IPv6 tunnel - p4 = (p_ether / p_ip4 / p_payload) - p4_reply = (IPv6(src=self.pg0.local_ip6, - dst=self.pg1.remote_ip6, hlim=64) / - p_ip4 / p_payload) + p4 = p_ether / p_ip4 / p_payload + p4_reply = ( + IPv6(src=self.pg0.local_ip6, dst=self.pg1.remote_ip6, hlim=64) + / p_ip4 + / p_payload + ) p4_reply[1].ttl -= 1 rx = self.send_and_expect(self.pg0, p4 * 11, self.pg1) for p in rx: self.validate(p[1], p4_reply) def test_decap(self): - """ ip{v4,v6} over ip6 test decap """ + """ip{v4,v6} over ip6 test decap""" p_ether = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) - p_ip6 = IPv6(src="1::1", dst="DEAD::1", tc=42, nh='UDP') + p_ip6 = IPv6(src="1::1", dst="DEAD::1", tc=42, nh="UDP") p_ip4 = IP(src="1.2.3.4", dst=self.pg0.remote_ip4) p_payload = UDP(sport=1234, dport=1234) # Decapsulation # IPv6 tunnel to IPv4 - p4 = (p_ether / IPv6(src=self.pg1.remote_ip6, - dst=self.pg0.local_ip6) / p_ip4 / p_payload) - p4_reply = (p_ip4 / p_payload) + p4 = ( + p_ether + / IPv6(src=self.pg1.remote_ip6, dst=self.pg0.local_ip6) + / p_ip4 + / p_payload + ) + p4_reply = p_ip4 / p_payload p4_reply.ttl -= 1 rx = self.send_and_expect(self.pg1, p4 * 11, self.pg0) for p in rx: @@ -779,9 +861,13 @@ class TestIPIP6(VppTestCase): # IPv6 tunnel to IPv6 p_ip6 = IPv6(src="1:2:3::4", dst=self.pg0.remote_ip6) - p6 = (p_ether / IPv6(src=self.pg1.remote_ip6, - dst=self.pg0.local_ip6) / p_ip6 / p_payload) - p6_reply = (p_ip6 / p_payload) + p6 = ( + p_ether + / IPv6(src=self.pg1.remote_ip6, dst=self.pg0.local_ip6) + / p_ip6 + / p_payload + ) + p6_reply = p_ip6 / p_payload p6_reply.hlim = 63 rx = self.send_and_expect(self.pg1, p6 * 11, self.pg0) for p in rx: @@ -790,10 +876,10 @@ class TestIPIP6(VppTestCase): def verify_ip4ip6_encaps(self, a, p_ip4s, p_ip6_encaps): for i, p_ip4 in enumerate(p_ip4s): p_ip4.dst = a - p4 = (self.p_ether / p_ip4 / self.p_payload) + p4 = self.p_ether / p_ip4 / self.p_payload p_ip4_inner = p_ip4 p_ip4_inner.ttl -= 1 - p6_reply = (p_ip6_encaps[i] / p_ip4_inner / self.p_payload) + p6_reply = p_ip6_encaps[i] / p_ip4_inner / self.p_payload rx = self.send_and_expect(self.pg0, p4 * N_PACKETS, self.pg1) for p in rx: self.validate(p[1], p6_reply) @@ -802,17 +888,17 @@ class TestIPIP6(VppTestCase): def verify_ip6ip6_encaps(self, a, p_ip6s, p_ip6_encaps): for i, p_ip6 in enumerate(p_ip6s): p_ip6.dst = a - p6 = (self.p_ether / p_ip6 / self.p_payload) + p6 = self.p_ether / p_ip6 / self.p_payload p_inner_ip6 = p_ip6 p_inner_ip6.hlim -= 1 - p6_reply = (p_ip6_encaps[i] / p_inner_ip6 / self.p_payload) + p6_reply = p_ip6_encaps[i] / p_inner_ip6 / self.p_payload rx = self.send_and_expect(self.pg0, p6 * N_PACKETS, self.pg1) for p in rx: self.validate(p[1], p6_reply) self.assert_packet_checksums_valid(p) def test_ipip6(self): - """ ip{v4,v6} over ip6 test """ + """ip{v4,v6} over ip6 test""" # that's annoying self.destroy_tunnel() @@ -822,7 +908,7 @@ class TestIPIP6(VppTestCase): e = VppEnum.vl_api_tunnel_encap_decap_flags_t d = VppEnum.vl_api_ip_dscp_t self.p_ether = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) - self.p_payload = UDP(sport=1234, dport=1234) / Raw(b'X' * 100) + self.p_payload = UDP(sport=1234, dport=1234) / Raw(b"X" * 100) # create a TOS byte by shifting a DSCP code point 2 bits. those 2 bits # are for the ECN. @@ -836,7 +922,8 @@ class TestIPIP6(VppTestCase): self.pg0, self.pg0.local_ip6, self.pg1.remote_hosts[0].ip6, - flags=e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP) + flags=e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP, + ) tun_dscp.add_vpp_config() # IPv4 transport that copies the DCSP and ECN from the payload tun_dscp_ecn = VppIpIpTunInterface( @@ -844,8 +931,11 @@ class TestIPIP6(VppTestCase): self.pg0, self.pg0.local_ip6, self.pg1.remote_hosts[1].ip6, - flags=(e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP | - e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN)) + flags=( + e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP + | e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN + ), + ) tun_dscp_ecn.add_vpp_config() # IPv4 transport that copies the ECN from the payload and sets the # DF bit on encap. copies the ECN on decap @@ -854,9 +944,12 @@ class TestIPIP6(VppTestCase): self.pg0, self.pg0.local_ip6, self.pg1.remote_hosts[2].ip6, - flags=(e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN | - e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_SET_DF | - e.TUNNEL_API_ENCAP_DECAP_FLAG_DECAP_COPY_ECN)) + flags=( + e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN + | e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_SET_DF + | e.TUNNEL_API_ENCAP_DECAP_FLAG_DECAP_COPY_ECN + ), + ) tun_ecn.add_vpp_config() # IPv4 transport that sets a fixed DSCP in the encap and copies # the DF bit @@ -866,7 +959,8 @@ class TestIPIP6(VppTestCase): self.pg0.local_ip6, self.pg1.remote_hosts[3].ip6, dscp=d.IP_API_DSCP_AF11, - flags=e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DF) + flags=e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DF, + ) tun.add_vpp_config() # array of all the tunnels @@ -877,22 +971,26 @@ class TestIPIP6(VppTestCase): a6s = ["" for i in range(len(tuns))] # IP headers for inner packets with each combination of DSCp/ECN tested - p_ip6s = [IPv6(src="1::1", dst="DEAD::1", nh='UDP', tc=dscp), - IPv6(src="1::1", dst="DEAD::1", nh='UDP', tc=dscp_ecn), - IPv6(src="1::1", dst="DEAD::1", nh='UDP', tc=ecn), - IPv6(src="1::1", dst="DEAD::1", nh='UDP', tc=0xff)] - p_ip4s = [IP(src="1.2.3.4", dst="130.67.0.1", tos=dscp, flags='DF'), - IP(src="1.2.3.4", dst="130.67.0.1", tos=dscp_ecn), - IP(src="1.2.3.4", dst="130.67.0.1", tos=ecn), - IP(src="1.2.3.4", dst="130.67.0.1", tos=0xff)] + p_ip6s = [ + IPv6(src="1::1", dst="DEAD::1", nh="UDP", tc=dscp), + IPv6(src="1::1", dst="DEAD::1", nh="UDP", tc=dscp_ecn), + IPv6(src="1::1", dst="DEAD::1", nh="UDP", tc=ecn), + IPv6(src="1::1", dst="DEAD::1", nh="UDP", tc=0xFF), + ] + p_ip4s = [ + IP(src="1.2.3.4", dst="130.67.0.1", tos=dscp, flags="DF"), + IP(src="1.2.3.4", dst="130.67.0.1", tos=dscp_ecn), + IP(src="1.2.3.4", dst="130.67.0.1", tos=ecn), + IP(src="1.2.3.4", dst="130.67.0.1", tos=0xFF), + ] # Configure each tunnel for i, t in enumerate(tuns): # Set interface up and enable IP on it self.vapi.sw_interface_set_flags(t.sw_if_index, 1) self.vapi.sw_interface_set_unnumbered( - sw_if_index=self.pg0.sw_if_index, - unnumbered_sw_if_index=t.sw_if_index) + sw_if_index=self.pg0.sw_if_index, unnumbered_sw_if_index=t.sw_if_index + ) # prefix for route / destination address for packets a4s[i] = "130.67.%d.0" % i @@ -900,17 +998,29 @@ class TestIPIP6(VppTestCase): # Add IPv4 and IPv6 routes via tunnel interface ip4_via_tunnel = VppIpRoute( - self, a4s[i], 24, - [VppRoutePath("0.0.0.0", - t.sw_if_index, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP4)]) + self, + a4s[i], + 24, + [ + VppRoutePath( + "0.0.0.0", + t.sw_if_index, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP4, + ) + ], + ) ip4_via_tunnel.add_vpp_config() ip6_via_tunnel = VppIpRoute( - self, a6s[i], 64, - [VppRoutePath("::", - t.sw_if_index, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)]) + self, + a6s[i], + 64, + [ + VppRoutePath( + "::", t.sw_if_index, proto=FibPathProto.FIB_PATH_NH_PROTO_IP6 + ) + ], + ) ip6_via_tunnel.add_vpp_config() # @@ -920,10 +1030,10 @@ class TestIPIP6(VppTestCase): # tun_dscp copies only the dscp # expected TC values are thus only the DCSP value is present from the # inner - exp_tcs = [dscp, dscp, 0, 0xfc] - p_ip6_encaps = [IPv6(src=self.pg0.local_ip6, - dst=tun_dscp.dst, - tc=tc) for tc in exp_tcs] + exp_tcs = [dscp, dscp, 0, 0xFC] + p_ip6_encaps = [ + IPv6(src=self.pg0.local_ip6, dst=tun_dscp.dst, tc=tc) for tc in exp_tcs + ] # IPv4 in to IPv4 tunnel self.verify_ip4ip6_encaps(a4s[0], p_ip4s, p_ip6_encaps) @@ -931,28 +1041,29 @@ class TestIPIP6(VppTestCase): self.verify_ip6ip6_encaps(a6s[0], p_ip6s, p_ip6_encaps) # tun_dscp_ecn copies the dscp and the ecn - exp_tcs = [dscp, dscp_ecn, ecn, 0xff] - p_ip6_encaps = [IPv6(src=self.pg0.local_ip6, - dst=tun_dscp_ecn.dst, - tc=tc) for tc in exp_tcs] + exp_tcs = [dscp, dscp_ecn, ecn, 0xFF] + p_ip6_encaps = [ + IPv6(src=self.pg0.local_ip6, dst=tun_dscp_ecn.dst, tc=tc) for tc in exp_tcs + ] self.verify_ip4ip6_encaps(a4s[1], p_ip4s, p_ip6_encaps) self.verify_ip6ip6_encaps(a6s[1], p_ip6s, p_ip6_encaps) # tun_ecn copies only the ecn and always sets DF exp_tcs = [0, ecn, ecn, ecn] - p_ip6_encaps = [IPv6(src=self.pg0.local_ip6, - dst=tun_ecn.dst, - tc=tc) for tc in exp_tcs] + p_ip6_encaps = [ + IPv6(src=self.pg0.local_ip6, dst=tun_ecn.dst, tc=tc) for tc in exp_tcs + ] self.verify_ip4ip6_encaps(a4s[2], p_ip4s, p_ip6_encaps) self.verify_ip6ip6_encaps(a6s[2], p_ip6s, p_ip6_encaps) # tun sets a fixed dscp fixed_dscp = tun.dscp << 2 - p_ip6_encaps = [IPv6(src=self.pg0.local_ip6, - dst=tun.dst, - tc=fixed_dscp) for i in range(len(p_ip4s))] + p_ip6_encaps = [ + IPv6(src=self.pg0.local_ip6, dst=tun.dst, tc=fixed_dscp) + for i in range(len(p_ip4s)) + ] self.verify_ip4ip6_encaps(a4s[3], p_ip4s, p_ip6_encaps) self.verify_ip6ip6_encaps(a6s[3], p_ip6s, p_ip6_encaps) @@ -961,7 +1072,8 @@ class TestIPIP6(VppTestCase): # Decapsulation # n_packets_decapped = self.statistics.get_err_counter( - '/err/ipip6-input/packets decapsulated') + "/err/ipip6-input/packets decapsulated" + ) self.p_ether = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) @@ -970,15 +1082,13 @@ class TestIPIP6(VppTestCase): # one overlay packet and all combinations of its encap p_ip4 = IP(src="1.2.3.4", dst=self.pg0.remote_ip4) - p_ip6_encaps = [IPv6(src=tun.dst, - dst=self.pg0.local_ip6, - tc=tc) for tc in tcs] + p_ip6_encaps = [IPv6(src=tun.dst, dst=self.pg0.local_ip6, tc=tc) for tc in tcs] # for each encap tun will produce the same inner packet because it does # not copy up fields from the payload for p_ip6_encap in p_ip6_encaps: - p6 = (self.p_ether / p_ip6_encap / p_ip4 / self.p_payload) - p4_reply = (p_ip4 / self.p_payload) + p6 = self.p_ether / p_ip6_encap / p_ip4 / self.p_payload + p4_reply = p_ip4 / self.p_payload p4_reply.ttl -= 1 rx = self.send_and_expect(self.pg1, p6 * N_PACKETS, self.pg0) n_packets_decapped += N_PACKETS @@ -986,20 +1096,19 @@ class TestIPIP6(VppTestCase): self.validate(p[1], p4_reply) self.assert_packet_checksums_valid(p) - err = self.statistics.get_err_counter( - '/err/ipip6-input/packets decapsulated') + err = self.statistics.get_err_counter("/err/ipip6-input/packets decapsulated") self.assertEqual(err, n_packets_decapped) # tun_ecn copies the ECN bits from the encap to the inner - p_ip6_encaps = [IPv6(src=tun_ecn.dst, - dst=self.pg0.local_ip6, - tc=tc) for tc in tcs] + p_ip6_encaps = [ + IPv6(src=tun_ecn.dst, dst=self.pg0.local_ip6, tc=tc) for tc in tcs + ] p_ip4_replys = [p_ip4.copy() for i in range(len(p_ip6_encaps))] p_ip4_replys[2].tos = ecn p_ip4_replys[3].tos = ecn for i, p_ip6_encap in enumerate(p_ip6_encaps): - p6 = (self.p_ether / p_ip6_encap / p_ip4 / self.p_payload) - p4_reply = (p_ip4_replys[i] / self.p_payload) + p6 = self.p_ether / p_ip6_encap / p_ip4 / self.p_payload + p4_reply = p_ip4_replys[i] / self.p_payload p4_reply.ttl -= 1 rx = self.send_and_expect(self.pg1, p6 * N_PACKETS, self.pg0) n_packets_decapped += N_PACKETS @@ -1007,20 +1116,17 @@ class TestIPIP6(VppTestCase): self.validate(p[1], p4_reply) self.assert_packet_checksums_valid(p) - err = self.statistics.get_err_counter( - '/err/ipip6-input/packets decapsulated') + err = self.statistics.get_err_counter("/err/ipip6-input/packets decapsulated") self.assertEqual(err, n_packets_decapped) # IPv6 tunnel to IPv6 # for each encap tun will produce the same inner packet because it does # not copy up fields from the payload - p_ip6_encaps = [IPv6(src=tun.dst, - dst=self.pg0.local_ip6, - tc=tc) for tc in tcs] + p_ip6_encaps = [IPv6(src=tun.dst, dst=self.pg0.local_ip6, tc=tc) for tc in tcs] p_ip6 = IPv6(src="1:2:3::4", dst=self.pg0.remote_ip6) for p_ip6_encap in p_ip6_encaps: - p6 = (self.p_ether / p_ip6_encap / p_ip6 / self.p_payload) - p6_reply = (p_ip6 / self.p_payload) + p6 = self.p_ether / p_ip6_encap / p_ip6 / self.p_payload + p6_reply = p_ip6 / self.p_payload p6_reply.hlim = 63 rx = self.send_and_expect(self.pg1, p6 * N_PACKETS, self.pg0) n_packets_decapped += N_PACKETS @@ -1028,22 +1134,21 @@ class TestIPIP6(VppTestCase): self.validate(p[1], p6_reply) self.assert_packet_checksums_valid(p) - err = self.statistics.get_err_counter( - '/err/ipip6-input/packets decapsulated') + err = self.statistics.get_err_counter("/err/ipip6-input/packets decapsulated") self.assertEqual(err, n_packets_decapped) # IPv6 tunnel to IPv6 # tun_ecn copies the ECN bits from the encap to the inner - p_ip6_encaps = [IPv6(src=tun_ecn.dst, - dst=self.pg0.local_ip6, - tc=tc) for tc in tcs] + p_ip6_encaps = [ + IPv6(src=tun_ecn.dst, dst=self.pg0.local_ip6, tc=tc) for tc in tcs + ] p_ip6 = IPv6(src="1:2:3::4", dst=self.pg0.remote_ip6) p_ip6_replys = [p_ip6.copy() for i in range(len(p_ip6_encaps))] p_ip6_replys[2].tc = ecn p_ip6_replys[3].tc = ecn for i, p_ip6_encap in enumerate(p_ip6_encaps): - p6 = (self.p_ether / p_ip6_encap / p_ip6 / self.p_payload) - p6_reply = (p_ip6_replys[i] / self.p_payload) + p6 = self.p_ether / p_ip6_encap / p_ip6 / self.p_payload + p6_reply = p_ip6_replys[i] / self.p_payload p6_reply.hlim = 63 rx = self.send_and_expect(self.pg1, p6 * N_PACKETS, self.pg0) n_packets_decapped += N_PACKETS @@ -1051,15 +1156,14 @@ class TestIPIP6(VppTestCase): self.validate(p[1], p6_reply) self.assert_packet_checksums_valid(p) - err = self.statistics.get_err_counter( - '/err/ipip6-input/packets decapsulated') + err = self.statistics.get_err_counter("/err/ipip6-input/packets decapsulated") self.assertEqual(err, n_packets_decapped) def test_frag(self): - """ ip{v4,v6} over ip6 test frag """ + """ip{v4,v6} over ip6 test frag""" p_ether = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) - p_ip6 = IPv6(src="1::1", dst="DEAD::1", tc=42, nh='UDP') + p_ip6 = IPv6(src="1::1", dst="DEAD::1", tc=42, nh="UDP") p_ip4 = IP(src="1.2.3.4", dst=self.pg0.remote_ip4) p_payload = UDP(sport=1234, dport=1234) @@ -1067,17 +1171,21 @@ class TestIPIP6(VppTestCase): # Fragmentation / Reassembly and Re-fragmentation # rv = self.vapi.ip_reassembly_enable_disable( - sw_if_index=self.pg1.sw_if_index, - enable_ip6=1) + sw_if_index=self.pg1.sw_if_index, enable_ip6=1 + ) - self.vapi.ip_reassembly_set(timeout_ms=1000, max_reassemblies=1000, - max_reassembly_length=1000, - expire_walk_interval_ms=10000, - is_ip6=1) + self.vapi.ip_reassembly_set( + timeout_ms=1000, + max_reassemblies=1000, + max_reassembly_length=1000, + expire_walk_interval_ms=10000, + is_ip6=1, + ) # Send lots of fragments, verify reassembled packet before_cnt = self.statistics.get_err_counter( - '/err/ipip6-input/packets decapsulated') + "/err/ipip6-input/packets decapsulated" + ) frags, p6_reply = self.generate_ip6_frags(3131, 1400) f = [] for i in range(0, 1000): @@ -1090,8 +1198,7 @@ class TestIPIP6(VppTestCase): for p in rx: self.validate(p[1], p6_reply) - cnt = self.statistics.get_err_counter( - '/err/ipip6-input/packets decapsulated') + cnt = self.statistics.get_err_counter("/err/ipip6-input/packets decapsulated") self.assertEqual(cnt, before_cnt + 1000) f = [] @@ -1117,10 +1224,12 @@ class TestIPIP6(VppTestCase): # IPv6 in to IPv6 tunnel p_payload = UDP(sport=1234, dport=1234) / self.payload(1300) - p6 = (p_ether / p_ip6 / p_payload) - p6_reply = (IPv6(src=self.pg0.local_ip6, dst=self.pg1.remote_ip6, - hlim=63) / - p_ip6 / p_payload) + p6 = p_ether / p_ip6 / p_payload + p6_reply = ( + IPv6(src=self.pg0.local_ip6, dst=self.pg1.remote_ip6, hlim=63) + / p_ip6 + / p_payload + ) p6_reply[1].hlim -= 1 self.pg_enable_capture() self.pg0.add_stream(p6) @@ -1151,47 +1260,49 @@ class TestIPIP6(VppTestCase): self.validate(reass_pkt, p6_reply) def test_ip6_mpls_frag(self): - """ Test fragmenting IPv6 over MPLS """ + """Test fragmenting IPv6 over MPLS""" # IPv6 packets must be locally generated to be fragmented # the use of tunnel encaps tun_dst = VppIpRoute( - self, "1000::1", 128, - [VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index, - labels=[VppMplsLabel(32)])]).add_vpp_config() + self, + "1000::1", + 128, + [ + VppRoutePath( + self.pg1.remote_ip6, self.pg1.sw_if_index, labels=[VppMplsLabel(32)] + ) + ], + ).add_vpp_config() tun = VppIpIpTunInterface( - self, - self.pg0, - self.pg0.local_ip6, - "1000::1").add_vpp_config() + self, self.pg0, self.pg0.local_ip6, "1000::1" + ).add_vpp_config() tun.admin_up() tun.config_ip6() tun.config_ip4() - self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, - [2000, 0, 0, 0]) - - p_6k = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, - dst=tun.remote_ip6) / - UDP(sport=1234, dport=5678) / - Raw(b'0xa' * 2000)) - p_2k = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, - dst=tun.remote_ip6) / - UDP(sport=1234, dport=5678) / - Raw(b'0xa' * 1000)) - p_1k = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, - dst=tun.remote_ip6) / - UDP(sport=1234, dport=5678) / - Raw(b'0xa' * 600)) + self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [2000, 0, 0, 0]) + + p_6k = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=tun.remote_ip6) + / UDP(sport=1234, dport=5678) + / Raw(b"0xa" * 2000) + ) + p_2k = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=tun.remote_ip6) + / UDP(sport=1234, dport=5678) + / Raw(b"0xa" * 1000) + ) + p_1k = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=tun.remote_ip6) + / UDP(sport=1234, dport=5678) + / Raw(b"0xa" * 600) + ) # this is now the interface MTU frags rxs = self.send_and_expect(self.pg0, [p_6k], self.pg1, n_rx=4) @@ -1204,26 +1315,26 @@ class TestIPIP6(VppTestCase): self.send_and_expect(self.pg0, [p_1k], self.pg1) def test_ipip_create(self): - """ ipip create / delete interface test """ - rv = ipip_add_tunnel(self, '1.2.3.4', '2.3.4.5') + """ipip create / delete interface test""" + rv = ipip_add_tunnel(self, "1.2.3.4", "2.3.4.5") sw_if_index = rv.sw_if_index self.vapi.ipip_del_tunnel(sw_if_index) def test_ipip_vrf_create(self): - """ ipip create / delete interface VRF test """ + """ipip create / delete interface VRF test""" t = VppIpTable(self, 20) t.add_vpp_config() - rv = ipip_add_tunnel(self, '1.2.3.4', '2.3.4.5', table_id=20) + rv = ipip_add_tunnel(self, "1.2.3.4", "2.3.4.5", table_id=20) sw_if_index = rv.sw_if_index self.vapi.ipip_del_tunnel(sw_if_index) def payload(self, len): - return 'x' * len + return "x" * len class TestIPIPMPLS(VppTestCase): - """ MPLS Test Case """ + """MPLS Test Case""" @classmethod def setUpClass(cls): @@ -1254,62 +1365,69 @@ class TestIPIPMPLS(VppTestCase): i.admin_down() def test_mpls(self): - """ MPLS over ip{6,4} test """ + """MPLS over ip{6,4} test""" tbl = VppMplsTable(self, 0) tbl.add_vpp_config() self.p_ether = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) - self.p_payload = UDP(sport=1234, dport=1234) / Raw(b'X' * 100) + self.p_payload = UDP(sport=1234, dport=1234) / Raw(b"X" * 100) f = FibPathProto # IPv4 transport tun4 = VppIpIpTunInterface( - self, - self.pg1, - self.pg1.local_ip4, - self.pg1.remote_ip4).add_vpp_config() + self, self.pg1, self.pg1.local_ip4, self.pg1.remote_ip4 + ).add_vpp_config() tun4.admin_up() tun4.config_ip4() tun4.enable_mpls() # IPv6 transport tun6 = VppIpIpTunInterface( - self, - self.pg1, - self.pg1.local_ip6, - self.pg1.remote_ip6).add_vpp_config() + self, self.pg1, self.pg1.local_ip6, self.pg1.remote_ip6 + ).add_vpp_config() tun6.admin_up() tun6.config_ip6() tun6.enable_mpls() # ip routes into the tunnels with output labels - r4 = VppIpRoute(self, "1.1.1.1", 32, - [VppRoutePath( - tun4.remote_ip4, - tun4.sw_if_index, - labels=[VppMplsLabel(44)])]).add_vpp_config() - r6 = VppIpRoute(self, "1::1", 128, - [VppRoutePath( - tun6.remote_ip6, - tun6.sw_if_index, - labels=[VppMplsLabel(66)])]).add_vpp_config() + r4 = VppIpRoute( + self, + "1.1.1.1", + 32, + [ + VppRoutePath( + tun4.remote_ip4, tun4.sw_if_index, labels=[VppMplsLabel(44)] + ) + ], + ).add_vpp_config() + r6 = VppIpRoute( + self, + "1::1", + 128, + [ + VppRoutePath( + tun6.remote_ip6, tun6.sw_if_index, labels=[VppMplsLabel(66)] + ) + ], + ).add_vpp_config() # deag MPLS routes from the tunnel - r4 = VppMplsRoute(self, 44, 1, - [VppRoutePath( - self.pg0.remote_ip4, - self.pg0.sw_if_index)]).add_vpp_config() - r6 = VppMplsRoute(self, 66, 1, - [VppRoutePath( - self.pg0.remote_ip6, - self.pg0.sw_if_index)], - eos_proto=f.FIB_PATH_NH_PROTO_IP6).add_vpp_config() + r4 = VppMplsRoute( + self, 44, 1, [VppRoutePath(self.pg0.remote_ip4, self.pg0.sw_if_index)] + ).add_vpp_config() + r6 = VppMplsRoute( + self, + 66, + 1, + [VppRoutePath(self.pg0.remote_ip6, self.pg0.sw_if_index)], + eos_proto=f.FIB_PATH_NH_PROTO_IP6, + ).add_vpp_config() # # Tunnel Encap # - p4 = (self.p_ether / IP(src="2.2.2.2", dst="1.1.1.1") / self.p_payload) + p4 = self.p_ether / IP(src="2.2.2.2", dst="1.1.1.1") / self.p_payload rxs = self.send_and_expect(self.pg0, p4 * N_PACKETS, self.pg1) @@ -1321,7 +1439,7 @@ class TestIPIPMPLS(VppTestCase): self.assertEqual(inner.src, "2.2.2.2") self.assertEqual(inner.dst, "1.1.1.1") - p6 = (self.p_ether / IPv6(src="2::2", dst="1::1") / self.p_payload) + p6 = self.p_ether / IPv6(src="2::2", dst="1::1") / self.p_payload rxs = self.send_and_expect(self.pg0, p6 * N_PACKETS, self.pg1) @@ -1336,13 +1454,13 @@ class TestIPIPMPLS(VppTestCase): # # Tunnel Decap # - p4 = (self.p_ether / - IP(src=self.pg1.remote_ip4, - dst=self.pg1.local_ip4) / - MPLS(label=44, ttl=4) / - IP(src="1.1.1.1", - dst="2.2.2.2") / - self.p_payload) + p4 = ( + self.p_ether + / IP(src=self.pg1.remote_ip4, dst=self.pg1.local_ip4) + / MPLS(label=44, ttl=4) + / IP(src="1.1.1.1", dst="2.2.2.2") + / self.p_payload + ) rxs = self.send_and_expect(self.pg1, p4 * N_PACKETS, self.pg0) @@ -1350,13 +1468,13 @@ class TestIPIPMPLS(VppTestCase): self.assertEqual(rx[IP].src, "1.1.1.1") self.assertEqual(rx[IP].dst, "2.2.2.2") - p6 = (self.p_ether / - IPv6(src=self.pg1.remote_ip6, - dst=self.pg1.local_ip6) / - MPLS(label=66, ttl=4) / - IPv6(src="1::1", - dst="2::2") / - self.p_payload) + p6 = ( + self.p_ether + / IPv6(src=self.pg1.remote_ip6, dst=self.pg1.local_ip6) + / MPLS(label=66, ttl=4) + / IPv6(src="1::1", dst="2::2") + / self.p_payload + ) rxs = self.send_and_expect(self.pg1, p6 * N_PACKETS, self.pg0) @@ -1368,5 +1486,5 @@ class TestIPIPMPLS(VppTestCase): tun6.disable_mpls() -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_ipsec_ah.py b/test/test_ipsec_ah.py index 8f8b2bf1550..190bde78f56 100644 --- a/test/test_ipsec_ah.py +++ b/test/test_ipsec_ah.py @@ -8,13 +8,23 @@ from scapy.layers.l2 import Ether from scapy.packet import Raw from framework import VppTestRunner -from template_ipsec import TemplateIpsec, IpsecTra46Tests, IpsecTun46Tests, \ - config_tun_params, config_tra_params, IPsecIPv4Params, IPsecIPv6Params, \ - IpsecTra4, IpsecTun4, IpsecTra6, IpsecTun6, \ - IpsecTun6HandoffTests, IpsecTun4HandoffTests +from template_ipsec import ( + TemplateIpsec, + IpsecTra46Tests, + IpsecTun46Tests, + config_tun_params, + config_tra_params, + IPsecIPv4Params, + IPsecIPv6Params, + IpsecTra4, + IpsecTun4, + IpsecTra6, + IpsecTun6, + IpsecTun6HandoffTests, + IpsecTun4HandoffTests, +) from template_ipsec import IpsecTcpTests -from vpp_ipsec import VppIpsecSA, VppIpsecSpd, VppIpsecSpdEntry,\ - VppIpsecSpdItfBinding +from vpp_ipsec import VppIpsecSA, VppIpsecSpd, VppIpsecSpdEntry, VppIpsecSpdItfBinding from vpp_ip_route import VppIpRoute, VppRoutePath from vpp_ip import DpoProto from vpp_papi import VppEnum @@ -41,6 +51,7 @@ class ConfigIpsecAH(TemplateIpsec): --- --- --- """ + encryption_type = AH net_objs = [] tra4_encrypt_node_name = "ah4-encrypt" @@ -79,13 +90,11 @@ class ConfigIpsecAH(TemplateIpsec): self.tun_spd.add_vpp_config() self.net_objs.append(self.tun_spd) - b = VppIpsecSpdItfBinding(self, self.tra_spd, - self.tra_if) + b = VppIpsecSpdItfBinding(self, self.tra_spd, self.tra_if) b.add_vpp_config() self.net_objs.append(b) - b = VppIpsecSpdItfBinding(self, self.tun_spd, - self.tun_if) + b = VppIpsecSpdItfBinding(self, self.tun_spd, self.tun_if) b.add_vpp_config() self.net_objs.append(b) @@ -97,10 +106,16 @@ class ConfigIpsecAH(TemplateIpsec): config_tun_params(p, self.encryption_type, self.tun_if) for p in params: d = DpoProto.DPO_PROTO_IP6 if p.is_ipv6 else DpoProto.DPO_PROTO_IP4 - r = VppIpRoute(self, p.remote_tun_if_host, p.addr_len, - [VppRoutePath(self.tun_if.remote_addr[p.addr_type], - 0xffffffff, - proto=d)]) + r = VppIpRoute( + self, + p.remote_tun_if_host, + p.addr_len, + [ + VppRoutePath( + self.tun_if.remote_addr[p.addr_type], 0xFFFFFFFF, proto=d + ) + ], + ) r.add_vpp_config() self.net_objs.append(r) self.logger.info(self.vapi.ppcli("show ipsec all")) @@ -130,74 +145,116 @@ class ConfigIpsecAH(TemplateIpsec): params.outer_hop_limit = 253 params.outer_flow_label = 0x12345 - params.tun_sa_in = VppIpsecSA(self, scapy_tun_sa_id, scapy_tun_spi, - auth_algo_vpp_id, auth_key, - crypt_algo_vpp_id, crypt_key, - self.vpp_ah_protocol, - self.tun_if.local_addr[addr_type], - self.tun_if.remote_addr[addr_type], - tun_flags=tun_flags, - flags=flags, - dscp=params.dscp) - - params.tun_sa_out = VppIpsecSA(self, vpp_tun_sa_id, vpp_tun_spi, - auth_algo_vpp_id, auth_key, - crypt_algo_vpp_id, crypt_key, - self.vpp_ah_protocol, - self.tun_if.remote_addr[addr_type], - self.tun_if.local_addr[addr_type], - tun_flags=tun_flags, - flags=flags, - dscp=params.dscp) + params.tun_sa_in = VppIpsecSA( + self, + scapy_tun_sa_id, + scapy_tun_spi, + auth_algo_vpp_id, + auth_key, + crypt_algo_vpp_id, + crypt_key, + self.vpp_ah_protocol, + self.tun_if.local_addr[addr_type], + self.tun_if.remote_addr[addr_type], + tun_flags=tun_flags, + flags=flags, + dscp=params.dscp, + ) + + params.tun_sa_out = VppIpsecSA( + self, + vpp_tun_sa_id, + vpp_tun_spi, + auth_algo_vpp_id, + auth_key, + crypt_algo_vpp_id, + crypt_key, + self.vpp_ah_protocol, + self.tun_if.remote_addr[addr_type], + self.tun_if.local_addr[addr_type], + tun_flags=tun_flags, + flags=flags, + dscp=params.dscp, + ) objs.append(params.tun_sa_in) objs.append(params.tun_sa_out) - params.spd_policy_in_any = VppIpsecSpdEntry(self, self.tun_spd, - vpp_tun_sa_id, - addr_any, addr_bcast, - addr_any, addr_bcast, - socket.IPPROTO_AH) - params.spd_policy_out_any = VppIpsecSpdEntry(self, self.tun_spd, - vpp_tun_sa_id, - addr_any, addr_bcast, - addr_any, addr_bcast, - socket.IPPROTO_AH, - is_outbound=0) + params.spd_policy_in_any = VppIpsecSpdEntry( + self, + self.tun_spd, + vpp_tun_sa_id, + addr_any, + addr_bcast, + addr_any, + addr_bcast, + socket.IPPROTO_AH, + ) + params.spd_policy_out_any = VppIpsecSpdEntry( + self, + self.tun_spd, + vpp_tun_sa_id, + addr_any, + addr_bcast, + addr_any, + addr_bcast, + socket.IPPROTO_AH, + is_outbound=0, + ) objs.append(params.spd_policy_out_any) objs.append(params.spd_policy_in_any) - e1 = VppIpsecSpdEntry(self, self.tun_spd, vpp_tun_sa_id, - remote_tun_if_host, - remote_tun_if_host, - self.pg1.remote_addr[addr_type], - self.pg1.remote_addr[addr_type], - 0, priority=10, - policy=e.IPSEC_API_SPD_ACTION_PROTECT, - is_outbound=0) - e2 = VppIpsecSpdEntry(self, self.tun_spd, scapy_tun_sa_id, - self.pg1.remote_addr[addr_type], - self.pg1.remote_addr[addr_type], - remote_tun_if_host, - remote_tun_if_host, - 0, policy=e.IPSEC_API_SPD_ACTION_PROTECT, - priority=10) - e3 = VppIpsecSpdEntry(self, self.tun_spd, vpp_tun_sa_id, - remote_tun_if_host, - remote_tun_if_host, - self.pg0.local_addr[addr_type], - self.pg0.local_addr[addr_type], - 0, priority=20, - policy=e.IPSEC_API_SPD_ACTION_PROTECT, - is_outbound=0) - e4 = VppIpsecSpdEntry(self, self.tun_spd, scapy_tun_sa_id, - self.pg0.local_addr[addr_type], - self.pg0.local_addr[addr_type], - remote_tun_if_host, - remote_tun_if_host, - 0, policy=e.IPSEC_API_SPD_ACTION_PROTECT, - priority=20) + e1 = VppIpsecSpdEntry( + self, + self.tun_spd, + vpp_tun_sa_id, + remote_tun_if_host, + remote_tun_if_host, + self.pg1.remote_addr[addr_type], + self.pg1.remote_addr[addr_type], + 0, + priority=10, + policy=e.IPSEC_API_SPD_ACTION_PROTECT, + is_outbound=0, + ) + e2 = VppIpsecSpdEntry( + self, + self.tun_spd, + scapy_tun_sa_id, + self.pg1.remote_addr[addr_type], + self.pg1.remote_addr[addr_type], + remote_tun_if_host, + remote_tun_if_host, + 0, + policy=e.IPSEC_API_SPD_ACTION_PROTECT, + priority=10, + ) + e3 = VppIpsecSpdEntry( + self, + self.tun_spd, + vpp_tun_sa_id, + remote_tun_if_host, + remote_tun_if_host, + self.pg0.local_addr[addr_type], + self.pg0.local_addr[addr_type], + 0, + priority=20, + policy=e.IPSEC_API_SPD_ACTION_PROTECT, + is_outbound=0, + ) + e4 = VppIpsecSpdEntry( + self, + self.tun_spd, + scapy_tun_sa_id, + self.pg0.local_addr[addr_type], + self.pg0.local_addr[addr_type], + remote_tun_if_host, + remote_tun_if_host, + 0, + policy=e.IPSEC_API_SPD_ACTION_PROTECT, + priority=20, + ) objs = objs + [e1, e2, e3, e4] @@ -218,49 +275,92 @@ class ConfigIpsecAH(TemplateIpsec): crypt_key = params.crypt_key addr_any = params.addr_any addr_bcast = params.addr_bcast - flags = params.flags | (VppEnum.vl_api_ipsec_sad_flags_t. - IPSEC_API_SAD_FLAG_USE_ANTI_REPLAY) + flags = params.flags | ( + VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_USE_ANTI_REPLAY + ) e = VppEnum.vl_api_ipsec_spd_action_t objs = [] - params.tra_sa_in = VppIpsecSA(self, scapy_tra_sa_id, scapy_tra_spi, - auth_algo_vpp_id, auth_key, - crypt_algo_vpp_id, crypt_key, - self.vpp_ah_protocol, - flags=flags) - params.tra_sa_out = VppIpsecSA(self, vpp_tra_sa_id, vpp_tra_spi, - auth_algo_vpp_id, auth_key, - crypt_algo_vpp_id, crypt_key, - self.vpp_ah_protocol, - flags=flags) + params.tra_sa_in = VppIpsecSA( + self, + scapy_tra_sa_id, + scapy_tra_spi, + auth_algo_vpp_id, + auth_key, + crypt_algo_vpp_id, + crypt_key, + self.vpp_ah_protocol, + flags=flags, + ) + params.tra_sa_out = VppIpsecSA( + self, + vpp_tra_sa_id, + vpp_tra_spi, + auth_algo_vpp_id, + auth_key, + crypt_algo_vpp_id, + crypt_key, + self.vpp_ah_protocol, + flags=flags, + ) objs.append(params.tra_sa_in) objs.append(params.tra_sa_out) - objs.append(VppIpsecSpdEntry(self, self.tra_spd, vpp_tra_sa_id, - addr_any, addr_bcast, - addr_any, addr_bcast, - socket.IPPROTO_AH)) - objs.append(VppIpsecSpdEntry(self, self.tra_spd, scapy_tra_sa_id, - addr_any, addr_bcast, - addr_any, addr_bcast, - socket.IPPROTO_AH, - is_outbound=0)) - objs.append(VppIpsecSpdEntry(self, self.tra_spd, vpp_tra_sa_id, - self.tra_if.local_addr[addr_type], - self.tra_if.local_addr[addr_type], - self.tra_if.remote_addr[addr_type], - self.tra_if.remote_addr[addr_type], - 0, priority=10, - policy=e.IPSEC_API_SPD_ACTION_PROTECT, - is_outbound=0)) - objs.append(VppIpsecSpdEntry(self, self.tra_spd, scapy_tra_sa_id, - self.tra_if.local_addr[addr_type], - self.tra_if.local_addr[addr_type], - self.tra_if.remote_addr[addr_type], - self.tra_if.remote_addr[addr_type], - 0, policy=e.IPSEC_API_SPD_ACTION_PROTECT, - priority=10)) + objs.append( + VppIpsecSpdEntry( + self, + self.tra_spd, + vpp_tra_sa_id, + addr_any, + addr_bcast, + addr_any, + addr_bcast, + socket.IPPROTO_AH, + ) + ) + objs.append( + VppIpsecSpdEntry( + self, + self.tra_spd, + scapy_tra_sa_id, + addr_any, + addr_bcast, + addr_any, + addr_bcast, + socket.IPPROTO_AH, + is_outbound=0, + ) + ) + objs.append( + VppIpsecSpdEntry( + self, + self.tra_spd, + vpp_tra_sa_id, + self.tra_if.local_addr[addr_type], + self.tra_if.local_addr[addr_type], + self.tra_if.remote_addr[addr_type], + self.tra_if.remote_addr[addr_type], + 0, + priority=10, + policy=e.IPSEC_API_SPD_ACTION_PROTECT, + is_outbound=0, + ) + ) + objs.append( + VppIpsecSpdEntry( + self, + self.tra_spd, + scapy_tra_sa_id, + self.tra_if.local_addr[addr_type], + self.tra_if.local_addr[addr_type], + self.tra_if.remote_addr[addr_type], + self.tra_if.remote_addr[addr_type], + 0, + policy=e.IPSEC_API_SPD_ACTION_PROTECT, + priority=10, + ) + ) for o in objs: o.add_vpp_config() @@ -288,6 +388,7 @@ class TemplateIpsecAh(ConfigIpsecAH): --- --- --- """ + @classmethod def setUpClass(cls): super(TemplateIpsecAh, cls).setUpClass() @@ -306,26 +407,30 @@ class TemplateIpsecAh(ConfigIpsecAH): class TestIpsecAh1(TemplateIpsecAh, IpsecTcpTests): - """ Ipsec AH - TCP tests """ + """Ipsec AH - TCP tests""" + pass class TestIpsecAh2(TemplateIpsecAh, IpsecTra46Tests, IpsecTun46Tests): - """ Ipsec AH w/ SHA1 """ + """Ipsec AH w/ SHA1""" + pass class TestIpsecAhTun(TemplateIpsecAh, IpsecTun46Tests): - """ Ipsec AH - TUN encap tests """ + """Ipsec AH - TUN encap tests""" def setUp(self): self.ipv4_params = IPsecIPv4Params() self.ipv6_params = IPsecIPv6Params() - c = (VppEnum.vl_api_tunnel_encap_decap_flags_t. - TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP) - c1 = c | (VppEnum.vl_api_tunnel_encap_decap_flags_t. - TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN) + c = ( + VppEnum.vl_api_tunnel_encap_decap_flags_t.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP + ) + c1 = c | ( + VppEnum.vl_api_tunnel_encap_decap_flags_t.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN + ) self.ipv4_params.tun_flags = c self.ipv6_params.tun_flags = c1 @@ -334,19 +439,23 @@ class TestIpsecAhTun(TemplateIpsecAh, IpsecTun46Tests): def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=54): # set the DSCP + ECN - flags are set to copy only DSCP - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - IP(src=src, dst=dst, tos=5) / - UDP(sport=4444, dport=4444) / - Raw(b'X' * payload_size) - for i in range(count)] + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / IP(src=src, dst=dst, tos=5) + / UDP(sport=4444, dport=4444) + / Raw(b"X" * payload_size) + for i in range(count) + ] def gen_pkts6(self, p, sw_intf, src, dst, count=1, payload_size=54): # set the DSCP + ECN - flags are set to copy both - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - IPv6(src=src, dst=dst, tc=5) / - UDP(sport=4444, dport=4444) / - Raw(b'X' * payload_size) - for i in range(count)] + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / IPv6(src=src, dst=dst, tc=5) + / UDP(sport=4444, dport=4444) + / Raw(b"X" * payload_size) + for i in range(count) + ] def verify_encrypted(self, p, sa, rxs): # just check that only the DSCP is copied @@ -360,7 +469,7 @@ class TestIpsecAhTun(TemplateIpsecAh, IpsecTun46Tests): class TestIpsecAhTun2(TemplateIpsecAh, IpsecTun46Tests): - """ Ipsec AH - TUN encap tests """ + """Ipsec AH - TUN encap tests""" def setUp(self): self.ipv4_params = IPsecIPv4Params() @@ -373,24 +482,28 @@ class TestIpsecAhTun2(TemplateIpsecAh, IpsecTun46Tests): def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=54): # set the DSCP + ECN - flags are set to copy only DSCP - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - IP(src=src, dst=dst, tos=0) / - UDP(sport=4444, dport=4444) / - Raw(b'X' * payload_size) - for i in range(count)] + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / IP(src=src, dst=dst, tos=0) + / UDP(sport=4444, dport=4444) + / Raw(b"X" * payload_size) + for i in range(count) + ] def gen_pkts6(self, p, sw_intf, src, dst, count=1, payload_size=54): # set the DSCP + ECN - flags are set to copy both - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - IPv6(src=src, dst=dst, tc=0) / - UDP(sport=4444, dport=4444) / - Raw(b'X' * payload_size) - for i in range(count)] + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / IPv6(src=src, dst=dst, tc=0) + / UDP(sport=4444, dport=4444) + / Raw(b"X" * payload_size) + for i in range(count) + ] def verify_encrypted(self, p, sa, rxs): # just check that only the DSCP is copied for rx in rxs: - self.assertEqual(rx[IP].tos, 0xc) + self.assertEqual(rx[IP].tos, 0xC) def verify_encrypted6(self, p, sa, rxs): # just check that the DSCP & ECN are copied @@ -398,17 +511,14 @@ class TestIpsecAhTun2(TemplateIpsecAh, IpsecTun46Tests): self.assertEqual(rx[IPv6].tc, 0x10) -class TestIpsecAhHandoff(TemplateIpsecAh, - IpsecTun6HandoffTests, - IpsecTun4HandoffTests): - """ Ipsec AH Handoff """ +class TestIpsecAhHandoff(TemplateIpsecAh, IpsecTun6HandoffTests, IpsecTun4HandoffTests): + """Ipsec AH Handoff""" + pass -class TestIpsecAhAll(ConfigIpsecAH, - IpsecTra4, IpsecTra6, - IpsecTun4, IpsecTun6): - """ Ipsec AH all Algos """ +class TestIpsecAhAll(ConfigIpsecAH, IpsecTra4, IpsecTra6, IpsecTun4, IpsecTun6): + """Ipsec AH all Algos""" def setUp(self): super(TestIpsecAhAll, self).setUp() @@ -421,21 +531,26 @@ class TestIpsecAhAll(ConfigIpsecAH, # foreach VPP crypto engine engines = ["ia32", "ipsecmb", "openssl"] - algos = [{'vpp': VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_SHA1_96, - 'scapy': "HMAC-SHA1-96"}, - {'vpp': VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_SHA_256_128, - 'scapy': "SHA2-256-128"}, - {'vpp': VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_SHA_384_192, - 'scapy': "SHA2-384-192"}, - {'vpp': VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_SHA_512_256, - 'scapy': "SHA2-512-256"}] - - flags = [0, (VppEnum.vl_api_ipsec_sad_flags_t. - IPSEC_API_SAD_FLAG_USE_ESN)] + algos = [ + { + "vpp": VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96, + "scapy": "HMAC-SHA1-96", + }, + { + "vpp": VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA_256_128, + "scapy": "SHA2-256-128", + }, + { + "vpp": VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA_384_192, + "scapy": "SHA2-384-192", + }, + { + "vpp": VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA_512_256, + "scapy": "SHA2-512-256", + }, + ] + + flags = [0, (VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_USE_ESN)] # # loop through the VPP engines @@ -454,14 +569,14 @@ class TestIpsecAhAll(ConfigIpsecAH, self.ipv4_params = IPsecIPv4Params() self.ipv6_params = IPsecIPv6Params() - self.params = {self.ipv4_params.addr_type: - self.ipv4_params, - self.ipv6_params.addr_type: - self.ipv6_params} + self.params = { + self.ipv4_params.addr_type: self.ipv4_params, + self.ipv6_params.addr_type: self.ipv6_params, + } for _, p in self.params.items(): - p.auth_algo_vpp_id = algo['vpp'] - p.auth_algo = algo['scapy'] + p.auth_algo_vpp_id = algo["vpp"] + p.auth_algo = algo["scapy"] p.flags = p.flags | flag # @@ -484,5 +599,5 @@ class TestIpsecAhAll(ConfigIpsecAH, self.unconfig_network() -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_ipsec_api.py b/test/test_ipsec_api.py index b5b4adac66b..9c62c87e16d 100644 --- a/test/test_ipsec_api.py +++ b/test/test_ipsec_api.py @@ -6,7 +6,7 @@ from vpp_papi import VppEnum class IpsecApiTestCase(VppTestCase): - """ IPSec API tests """ + """IPSec API tests""" @classmethod def setUpClass(cls): @@ -22,10 +22,8 @@ class IpsecApiTestCase(VppTestCase): self.pg0.config_ip4() self.pg0.admin_up() - self.vpp_esp_protocol = (VppEnum.vl_api_ipsec_proto_t. - IPSEC_API_PROTO_ESP) - self.vpp_ah_protocol = (VppEnum.vl_api_ipsec_proto_t. - IPSEC_API_PROTO_AH) + self.vpp_esp_protocol = VppEnum.vl_api_ipsec_proto_t.IPSEC_API_PROTO_ESP + self.vpp_ah_protocol = VppEnum.vl_api_ipsec_proto_t.IPSEC_API_PROTO_AH self.ipv4_params = IPsecIPv4Params() def tearDown(self): @@ -34,32 +32,34 @@ class IpsecApiTestCase(VppTestCase): super(IpsecApiTestCase, self).tearDown() def test_backend_dump(self): - """ backend dump """ + """backend dump""" d = self.vapi.ipsec_backend_dump() self.assert_equal(len(d), 2, "number of ipsec backends in dump") - self.assert_equal(d[0].protocol, self.vpp_ah_protocol, - "ipsec protocol in dump entry") + self.assert_equal( + d[0].protocol, self.vpp_ah_protocol, "ipsec protocol in dump entry" + ) self.assert_equal(d[0].index, 0, "index in dump entry") self.assert_equal(d[0].active, 1, "active flag in dump entry") - self.assert_equal(d[1].protocol, self.vpp_esp_protocol, - "ipsec protocol in dump entry") + self.assert_equal( + d[1].protocol, self.vpp_esp_protocol, "ipsec protocol in dump entry" + ) self.assert_equal(d[1].index, 0, "index in dump entry") self.assert_equal(d[1].active, 1, "active flag in dump entry") def test_select_valid_backend(self): - """ select valid backend """ + """select valid backend""" self.vapi.ipsec_select_backend(self.vpp_ah_protocol, 0) self.vapi.ipsec_select_backend(self.vpp_esp_protocol, 0) def test_select_invalid_backend(self): - """ select invalid backend """ + """select invalid backend""" with self.vapi.assert_negative_api_retval(): self.vapi.ipsec_select_backend(self.vpp_ah_protocol, 200) with self.vapi.assert_negative_api_retval(): self.vapi.ipsec_select_backend(self.vpp_esp_protocol, 200) def test_select_backend_in_use(self): - """ attempt to change backend while sad configured """ + """attempt to change backend while sad configured""" params = self.ipv4_params addr_type = params.addr_type is_ipv6 = params.is_ipv6 @@ -73,48 +73,48 @@ class IpsecApiTestCase(VppTestCase): self.vapi.ipsec_sad_entry_add_del( is_add=1, entry={ - 'sad_id': scapy_tun_sa_id, - 'spi': scapy_tun_spi, - 'integrity_algorithm': auth_algo_vpp_id, - 'integrity_key': { - 'data': auth_key, - 'length': len(auth_key), + "sad_id": scapy_tun_sa_id, + "spi": scapy_tun_spi, + "integrity_algorithm": auth_algo_vpp_id, + "integrity_key": { + "data": auth_key, + "length": len(auth_key), }, - 'crypto_algorithm': crypt_algo_vpp_id, - 'crypto_key': { - 'data': crypt_key, - 'length': len(crypt_key), + "crypto_algorithm": crypt_algo_vpp_id, + "crypto_key": { + "data": crypt_key, + "length": len(crypt_key), }, - 'protocol': self.vpp_ah_protocol, - 'tunnel_src': self.pg0.local_addr[addr_type], - 'tunnel_dst': self.pg0.remote_addr[addr_type] - }) + "protocol": self.vpp_ah_protocol, + "tunnel_src": self.pg0.local_addr[addr_type], + "tunnel_dst": self.pg0.remote_addr[addr_type], + }, + ) with self.vapi.assert_negative_api_retval(): - self.vapi.ipsec_select_backend( - protocol=self.vpp_ah_protocol, index=0) + self.vapi.ipsec_select_backend(protocol=self.vpp_ah_protocol, index=0) self.vapi.ipsec_sad_entry_add_del( is_add=0, entry={ - 'sad_id': scapy_tun_sa_id, - 'spi': scapy_tun_spi, - 'integrity_algorithm': auth_algo_vpp_id, - 'integrity_key': { - 'data': auth_key, - 'length': len(auth_key), + "sad_id": scapy_tun_sa_id, + "spi": scapy_tun_spi, + "integrity_algorithm": auth_algo_vpp_id, + "integrity_key": { + "data": auth_key, + "length": len(auth_key), }, - 'crypto_algorithm': crypt_algo_vpp_id, - 'crypto_key': { - 'data': crypt_key, - 'length': len(crypt_key), + "crypto_algorithm": crypt_algo_vpp_id, + "crypto_key": { + "data": crypt_key, + "length": len(crypt_key), }, - 'protocol': self.vpp_ah_protocol, - 'tunnel_src': self.pg0.local_addr[addr_type], - 'tunnel_dst': self.pg0.remote_addr[addr_type] - }) - self.vapi.ipsec_select_backend( - protocol=self.vpp_ah_protocol, index=0) + "protocol": self.vpp_ah_protocol, + "tunnel_src": self.pg0.local_addr[addr_type], + "tunnel_dst": self.pg0.remote_addr[addr_type], + }, + ) + self.vapi.ipsec_select_backend(protocol=self.vpp_ah_protocol, index=0) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_ipsec_default.py b/test/test_ipsec_default.py index 6ee6f7822a2..f9de210e6dc 100644 --- a/test/test_ipsec_default.py +++ b/test/test_ipsec_default.py @@ -33,7 +33,7 @@ packets are dropped as expected. class IPSecInboundDefaultDrop(IPSecIPv4Fwd): - """ IPSec: inbound packets drop by default with no matching rule """ + """IPSec: inbound packets drop by default with no matching rule""" def test_ipsec_inbound_default_drop(self): # configure two interfaces and bind the same SPD to both @@ -43,13 +43,26 @@ class IPSecInboundDefaultDrop(IPSecIPv4Fwd): # catch-all inbound BYPASS policy, all interfaces inbound_policy = self.spd_add_rem_policy( - 1, None, None, socket.IPPROTO_UDP, is_out=0, priority=10, - policy_type="bypass", all_ips=True) + 1, + None, + None, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="bypass", + all_ips=True, + ) # outbound BYPASS policy allowing traffic from pg0->pg1 outbound_policy = self.spd_add_rem_policy( - 1, self.pg0, self.pg1, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="bypass") + 1, + self.pg0, + self.pg1, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="bypass", + ) # create a packet stream pg0->pg1 + add to pg0 packets0 = self.create_stream(self.pg0, self.pg1, pkt_count) @@ -64,8 +77,7 @@ class IPSecInboundDefaultDrop(IPSecIPv4Fwd): try: self.logger.debug(ppp("SPD - Got packet:", packet)) except Exception: - self.logger.error( - ppp("Unexpected or invalid packet:", packet)) + self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise self.logger.debug("SPD: Num packets: %s", len(cap1.res)) # verify captures on pg1 @@ -76,8 +88,16 @@ class IPSecInboundDefaultDrop(IPSecIPv4Fwd): # remove inbound catch-all BYPASS rule, traffic should now be dropped self.spd_add_rem_policy( # inbound, all interfaces - 1, None, None, socket.IPPROTO_UDP, is_out=0, priority=10, - policy_type="bypass", all_ips=True, remove=True) + 1, + None, + None, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="bypass", + all_ips=True, + remove=True, + ) # create another packet stream pg0->pg1 + add to pg0 packets1 = self.create_stream(self.pg0, self.pg1, pkt_count) @@ -85,8 +105,9 @@ class IPSecInboundDefaultDrop(IPSecIPv4Fwd): self.pg_interfaces[1].enable_capture() self.pg_start() # confirm traffic has now been dropped - self.pg1.assert_nothing_captured(remark="inbound pkts with no matching" - "rules NOT dropped by default") + self.pg1.assert_nothing_captured( + remark="inbound pkts with no matching" "rules NOT dropped by default" + ) # both policies should not have matched any further packets # since we've dropped at input stage self.verify_policy_match(pkt_count, outbound_policy) @@ -94,7 +115,7 @@ class IPSecInboundDefaultDrop(IPSecIPv4Fwd): class IPSecOutboundDefaultDrop(IPSecIPv4Fwd): - """ IPSec: outbound packets drop by default with no matching rule """ + """IPSec: outbound packets drop by default with no matching rule""" def test_ipsec_inbound_default_drop(self): # configure two interfaces and bind the same SPD to both @@ -104,13 +125,26 @@ class IPSecOutboundDefaultDrop(IPSecIPv4Fwd): # catch-all inbound BYPASS policy, all interfaces inbound_policy = self.spd_add_rem_policy( - 1, None, None, socket.IPPROTO_UDP, is_out=0, priority=10, - policy_type="bypass", all_ips=True) + 1, + None, + None, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="bypass", + all_ips=True, + ) # outbound BYPASS policy allowing traffic from pg0->pg1 outbound_policy = self.spd_add_rem_policy( - 1, self.pg0, self.pg1, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="bypass") + 1, + self.pg0, + self.pg1, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="bypass", + ) # create a packet stream pg0->pg1 + add to pg0 packets0 = self.create_stream(self.pg0, self.pg1, pkt_count) @@ -125,8 +159,7 @@ class IPSecOutboundDefaultDrop(IPSecIPv4Fwd): try: self.logger.debug(ppp("SPD - Got packet:", packet)) except Exception: - self.logger.error( - ppp("Unexpected or invalid packet:", packet)) + self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise self.logger.debug("SPD: Num packets: %s", len(cap1.res)) # verify captures on pg1 @@ -137,9 +170,15 @@ class IPSecOutboundDefaultDrop(IPSecIPv4Fwd): # remove outbound rule self.spd_add_rem_policy( - 1, self.pg0, self.pg1, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="bypass", - remove=True) + 1, + self.pg0, + self.pg1, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="bypass", + remove=True, + ) # create another packet stream pg0->pg1 + add to pg0 packets1 = self.create_stream(self.pg0, self.pg1, pkt_count) @@ -148,13 +187,13 @@ class IPSecOutboundDefaultDrop(IPSecIPv4Fwd): self.pg_start() # confirm traffic was dropped and not forwarded self.pg1.assert_nothing_captured( - remark="outbound pkts with no matching rules NOT dropped " - "by default") + remark="outbound pkts with no matching rules NOT dropped " "by default" + ) # inbound rule should have matched twice the # of pkts now - self.verify_policy_match(pkt_count*2, inbound_policy) + self.verify_policy_match(pkt_count * 2, inbound_policy) # as dropped at outbound, outbound policy is the same self.verify_policy_match(pkt_count, outbound_policy) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_ipsec_esp.py b/test/test_ipsec_esp.py index 74d01cd5568..54b877112e9 100644 --- a/test/test_ipsec_esp.py +++ b/test/test_ipsec_esp.py @@ -8,14 +8,26 @@ from scapy.packet import Raw from parameterized import parameterized from framework import VppTestRunner -from template_ipsec import IpsecTra46Tests, IpsecTun46Tests, TemplateIpsec, \ - IpsecTcpTests, IpsecTun4Tests, IpsecTra4Tests, config_tra_params, \ - config_tun_params, IPsecIPv4Params, IPsecIPv6Params, \ - IpsecTra4, IpsecTun4, IpsecTra6, IpsecTun6, \ - IpsecTun6HandoffTests, IpsecTun4HandoffTests, \ - IpsecTra6ExtTests -from vpp_ipsec import VppIpsecSpd, VppIpsecSpdEntry, VppIpsecSA,\ - VppIpsecSpdItfBinding +from template_ipsec import ( + IpsecTra46Tests, + IpsecTun46Tests, + TemplateIpsec, + IpsecTcpTests, + IpsecTun4Tests, + IpsecTra4Tests, + config_tra_params, + config_tun_params, + IPsecIPv4Params, + IPsecIPv6Params, + IpsecTra4, + IpsecTun4, + IpsecTra6, + IpsecTun6, + IpsecTun6HandoffTests, + IpsecTun4HandoffTests, + IpsecTra6ExtTests, +) +from vpp_ipsec import VppIpsecSpd, VppIpsecSpdEntry, VppIpsecSA, VppIpsecSpdItfBinding from vpp_ip_route import VppIpRoute, VppRoutePath from vpp_ip import DpoProto from vpp_papi import VppEnum @@ -68,13 +80,11 @@ class ConfigIpsecESP(TemplateIpsec): self.tun_spd.add_vpp_config() self.net_objs.append(self.tun_spd) - b = VppIpsecSpdItfBinding(self, self.tun_spd, - self.tun_if) + b = VppIpsecSpdItfBinding(self, self.tun_spd, self.tun_if) b.add_vpp_config() self.net_objs.append(b) - b = VppIpsecSpdItfBinding(self, self.tra_spd, - self.tra_if) + b = VppIpsecSpdItfBinding(self, self.tra_spd, self.tra_if) b.add_vpp_config() self.net_objs.append(b) @@ -87,10 +97,16 @@ class ConfigIpsecESP(TemplateIpsec): for p in params: d = DpoProto.DPO_PROTO_IP6 if p.is_ipv6 else DpoProto.DPO_PROTO_IP4 - r = VppIpRoute(self, p.remote_tun_if_host, p.addr_len, - [VppRoutePath(self.tun_if.remote_addr[p.addr_type], - 0xffffffff, - proto=d)]) + r = VppIpRoute( + self, + p.remote_tun_if_host, + p.addr_len, + [ + VppRoutePath( + self.tun_if.remote_addr[p.addr_type], 0xFFFFFFFF, proto=d + ) + ], + ) r.add_vpp_config() self.net_objs.append(r) @@ -120,75 +136,125 @@ class ConfigIpsecESP(TemplateIpsec): salt = params.salt objs = [] - params.tun_sa_in = VppIpsecSA(self, scapy_tun_sa_id, scapy_tun_spi, - auth_algo_vpp_id, auth_key, - crypt_algo_vpp_id, crypt_key, - self.vpp_esp_protocol, - self.tun_if.local_addr[addr_type], - self.tun_if.remote_addr[addr_type], - tun_flags=tun_flags, - dscp=params.dscp, - flags=flags, - salt=salt, - hop_limit=params.outer_hop_limit) - params.tun_sa_out = VppIpsecSA(self, vpp_tun_sa_id, vpp_tun_spi, - auth_algo_vpp_id, auth_key, - crypt_algo_vpp_id, crypt_key, - self.vpp_esp_protocol, - self.tun_if.remote_addr[addr_type], - self.tun_if.local_addr[addr_type], - tun_flags=tun_flags, - dscp=params.dscp, - flags=flags, - salt=salt, - hop_limit=params.outer_hop_limit) + params.tun_sa_in = VppIpsecSA( + self, + scapy_tun_sa_id, + scapy_tun_spi, + auth_algo_vpp_id, + auth_key, + crypt_algo_vpp_id, + crypt_key, + self.vpp_esp_protocol, + self.tun_if.local_addr[addr_type], + self.tun_if.remote_addr[addr_type], + tun_flags=tun_flags, + dscp=params.dscp, + flags=flags, + salt=salt, + hop_limit=params.outer_hop_limit, + ) + params.tun_sa_out = VppIpsecSA( + self, + vpp_tun_sa_id, + vpp_tun_spi, + auth_algo_vpp_id, + auth_key, + crypt_algo_vpp_id, + crypt_key, + self.vpp_esp_protocol, + self.tun_if.remote_addr[addr_type], + self.tun_if.local_addr[addr_type], + tun_flags=tun_flags, + dscp=params.dscp, + flags=flags, + salt=salt, + hop_limit=params.outer_hop_limit, + ) objs.append(params.tun_sa_in) objs.append(params.tun_sa_out) - params.spd_policy_in_any = VppIpsecSpdEntry(self, self.tun_spd, - scapy_tun_sa_id, - addr_any, addr_bcast, - addr_any, addr_bcast, - socket.IPPROTO_ESP) - params.spd_policy_out_any = VppIpsecSpdEntry(self, self.tun_spd, - scapy_tun_sa_id, - addr_any, addr_bcast, - addr_any, addr_bcast, - socket.IPPROTO_ESP, - is_outbound=0) + params.spd_policy_in_any = VppIpsecSpdEntry( + self, + self.tun_spd, + scapy_tun_sa_id, + addr_any, + addr_bcast, + addr_any, + addr_bcast, + socket.IPPROTO_ESP, + ) + params.spd_policy_out_any = VppIpsecSpdEntry( + self, + self.tun_spd, + scapy_tun_sa_id, + addr_any, + addr_bcast, + addr_any, + addr_bcast, + socket.IPPROTO_ESP, + is_outbound=0, + ) objs.append(params.spd_policy_out_any) objs.append(params.spd_policy_in_any) - objs.append(VppIpsecSpdEntry(self, self.tun_spd, vpp_tun_sa_id, - remote_tun_if_host, remote_tun_if_host, - self.pg1.remote_addr[addr_type], - self.pg1.remote_addr[addr_type], - 0, - priority=10, - policy=e.IPSEC_API_SPD_ACTION_PROTECT, - is_outbound=0)) - objs.append(VppIpsecSpdEntry(self, self.tun_spd, scapy_tun_sa_id, - self.pg1.remote_addr[addr_type], - self.pg1.remote_addr[addr_type], - remote_tun_if_host, remote_tun_if_host, - 0, - policy=e.IPSEC_API_SPD_ACTION_PROTECT, - priority=10)) - objs.append(VppIpsecSpdEntry(self, self.tun_spd, vpp_tun_sa_id, - remote_tun_if_host, remote_tun_if_host, - self.pg0.local_addr[addr_type], - self.pg0.local_addr[addr_type], - 0, - priority=20, - policy=e.IPSEC_API_SPD_ACTION_PROTECT, - is_outbound=0)) - objs.append(VppIpsecSpdEntry(self, self.tun_spd, scapy_tun_sa_id, - self.pg0.local_addr[addr_type], - self.pg0.local_addr[addr_type], - remote_tun_if_host, remote_tun_if_host, - 0, - policy=e.IPSEC_API_SPD_ACTION_PROTECT, - priority=20)) + objs.append( + VppIpsecSpdEntry( + self, + self.tun_spd, + vpp_tun_sa_id, + remote_tun_if_host, + remote_tun_if_host, + self.pg1.remote_addr[addr_type], + self.pg1.remote_addr[addr_type], + 0, + priority=10, + policy=e.IPSEC_API_SPD_ACTION_PROTECT, + is_outbound=0, + ) + ) + objs.append( + VppIpsecSpdEntry( + self, + self.tun_spd, + scapy_tun_sa_id, + self.pg1.remote_addr[addr_type], + self.pg1.remote_addr[addr_type], + remote_tun_if_host, + remote_tun_if_host, + 0, + policy=e.IPSEC_API_SPD_ACTION_PROTECT, + priority=10, + ) + ) + objs.append( + VppIpsecSpdEntry( + self, + self.tun_spd, + vpp_tun_sa_id, + remote_tun_if_host, + remote_tun_if_host, + self.pg0.local_addr[addr_type], + self.pg0.local_addr[addr_type], + 0, + priority=20, + policy=e.IPSEC_API_SPD_ACTION_PROTECT, + is_outbound=0, + ) + ) + objs.append( + VppIpsecSpdEntry( + self, + self.tun_spd, + scapy_tun_sa_id, + self.pg0.local_addr[addr_type], + self.pg0.local_addr[addr_type], + remote_tun_if_host, + remote_tun_if_host, + 0, + policy=e.IPSEC_API_SPD_ACTION_PROTECT, + priority=20, + ) + ) for o in objs: o.add_vpp_config() self.net_objs = self.net_objs + objs @@ -210,45 +276,87 @@ class ConfigIpsecESP(TemplateIpsec): salt = params.salt objs = [] - params.tra_sa_in = VppIpsecSA(self, scapy_tra_sa_id, scapy_tra_spi, - auth_algo_vpp_id, auth_key, - crypt_algo_vpp_id, crypt_key, - self.vpp_esp_protocol, - flags=flags, - salt=salt) - params.tra_sa_out = VppIpsecSA(self, vpp_tra_sa_id, vpp_tra_spi, - auth_algo_vpp_id, auth_key, - crypt_algo_vpp_id, crypt_key, - self.vpp_esp_protocol, - flags=flags, - salt=salt) + params.tra_sa_in = VppIpsecSA( + self, + scapy_tra_sa_id, + scapy_tra_spi, + auth_algo_vpp_id, + auth_key, + crypt_algo_vpp_id, + crypt_key, + self.vpp_esp_protocol, + flags=flags, + salt=salt, + ) + params.tra_sa_out = VppIpsecSA( + self, + vpp_tra_sa_id, + vpp_tra_spi, + auth_algo_vpp_id, + auth_key, + crypt_algo_vpp_id, + crypt_key, + self.vpp_esp_protocol, + flags=flags, + salt=salt, + ) objs.append(params.tra_sa_in) objs.append(params.tra_sa_out) - objs.append(VppIpsecSpdEntry(self, self.tra_spd, vpp_tra_sa_id, - addr_any, addr_bcast, - addr_any, addr_bcast, - socket.IPPROTO_ESP)) - objs.append(VppIpsecSpdEntry(self, self.tra_spd, vpp_tra_sa_id, - addr_any, addr_bcast, - addr_any, addr_bcast, - socket.IPPROTO_ESP, - is_outbound=0)) - objs.append(VppIpsecSpdEntry(self, self.tra_spd, vpp_tra_sa_id, - self.tra_if.local_addr[addr_type], - self.tra_if.local_addr[addr_type], - self.tra_if.remote_addr[addr_type], - self.tra_if.remote_addr[addr_type], - 0, priority=10, - policy=e.IPSEC_API_SPD_ACTION_PROTECT, - is_outbound=0)) - objs.append(VppIpsecSpdEntry(self, self.tra_spd, scapy_tra_sa_id, - self.tra_if.local_addr[addr_type], - self.tra_if.local_addr[addr_type], - self.tra_if.remote_addr[addr_type], - self.tra_if.remote_addr[addr_type], - 0, policy=e.IPSEC_API_SPD_ACTION_PROTECT, - priority=10)) + objs.append( + VppIpsecSpdEntry( + self, + self.tra_spd, + vpp_tra_sa_id, + addr_any, + addr_bcast, + addr_any, + addr_bcast, + socket.IPPROTO_ESP, + ) + ) + objs.append( + VppIpsecSpdEntry( + self, + self.tra_spd, + vpp_tra_sa_id, + addr_any, + addr_bcast, + addr_any, + addr_bcast, + socket.IPPROTO_ESP, + is_outbound=0, + ) + ) + objs.append( + VppIpsecSpdEntry( + self, + self.tra_spd, + vpp_tra_sa_id, + self.tra_if.local_addr[addr_type], + self.tra_if.local_addr[addr_type], + self.tra_if.remote_addr[addr_type], + self.tra_if.remote_addr[addr_type], + 0, + priority=10, + policy=e.IPSEC_API_SPD_ACTION_PROTECT, + is_outbound=0, + ) + ) + objs.append( + VppIpsecSpdEntry( + self, + self.tra_spd, + scapy_tra_sa_id, + self.tra_if.local_addr[addr_type], + self.tra_if.local_addr[addr_type], + self.tra_if.remote_addr[addr_type], + self.tra_if.remote_addr[addr_type], + 0, + policy=e.IPSEC_API_SPD_ACTION_PROTECT, + priority=10, + ) + ) for o in objs: o.add_vpp_config() self.net_objs = self.net_objs + objs @@ -308,9 +416,10 @@ class TemplateIpsecEsp(ConfigIpsecESP): super(TemplateIpsecEsp, self).tearDown() -class TestIpsecEsp1(TemplateIpsecEsp, IpsecTra46Tests, - IpsecTun46Tests, IpsecTra6ExtTests): - """ Ipsec ESP - TUN & TRA tests """ +class TestIpsecEsp1( + TemplateIpsecEsp, IpsecTra46Tests, IpsecTun46Tests, IpsecTra6ExtTests +): + """Ipsec ESP - TUN & TRA tests""" @classmethod def setUpClass(cls): @@ -327,7 +436,7 @@ class TestIpsecEsp1(TemplateIpsecEsp, IpsecTra46Tests, super(TestIpsecEsp1, self).tearDown() def test_tun_46(self): - """ ipsec 4o6 tunnel """ + """ipsec 4o6 tunnel""" # add an SPD entry to direct 2.2.2.2 to the v6 tunnel SA p6 = self.ipv6_params p4 = self.ipv4_params @@ -335,20 +444,25 @@ class TestIpsecEsp1(TemplateIpsecEsp, IpsecTra46Tests, p6.remote_tun_if_host4 = "2.2.2.2" e = VppEnum.vl_api_ipsec_spd_action_t - VppIpsecSpdEntry(self, - self.tun_spd, - p6.scapy_tun_sa_id, - self.pg1.remote_addr[p4.addr_type], - self.pg1.remote_addr[p4.addr_type], - p6.remote_tun_if_host4, - p6.remote_tun_if_host4, - 0, - priority=10, - policy=e.IPSEC_API_SPD_ACTION_PROTECT, - is_outbound=1).add_vpp_config() - VppIpRoute(self, p6.remote_tun_if_host4, p4.addr_len, - [VppRoutePath(self.tun_if.remote_addr[p4.addr_type], - 0xffffffff)]).add_vpp_config() + VppIpsecSpdEntry( + self, + self.tun_spd, + p6.scapy_tun_sa_id, + self.pg1.remote_addr[p4.addr_type], + self.pg1.remote_addr[p4.addr_type], + p6.remote_tun_if_host4, + p6.remote_tun_if_host4, + 0, + priority=10, + policy=e.IPSEC_API_SPD_ACTION_PROTECT, + is_outbound=1, + ).add_vpp_config() + VppIpRoute( + self, + p6.remote_tun_if_host4, + p4.addr_len, + [VppRoutePath(self.tun_if.remote_addr[p4.addr_type], 0xFFFFFFFF)], + ).add_vpp_config() old_name = self.tun6_encrypt_node_name self.tun6_encrypt_node_name = "esp4-encrypt" @@ -357,7 +471,7 @@ class TestIpsecEsp1(TemplateIpsecEsp, IpsecTra46Tests, self.tun6_encrypt_node_name = old_name def test_tun_64(self): - """ ipsec 6o4 tunnel """ + """ipsec 6o4 tunnel""" # add an SPD entry to direct 4444::4 to the v4 tunnel SA p6 = self.ipv6_params p4 = self.ipv4_params @@ -365,22 +479,26 @@ class TestIpsecEsp1(TemplateIpsecEsp, IpsecTra46Tests, p4.remote_tun_if_host6 = "4444::4" e = VppEnum.vl_api_ipsec_spd_action_t - VppIpsecSpdEntry(self, - self.tun_spd, - p4.scapy_tun_sa_id, - self.pg1.remote_addr[p6.addr_type], - self.pg1.remote_addr[p6.addr_type], - p4.remote_tun_if_host6, - p4.remote_tun_if_host6, - 0, - priority=10, - policy=e.IPSEC_API_SPD_ACTION_PROTECT, - is_outbound=1).add_vpp_config() + VppIpsecSpdEntry( + self, + self.tun_spd, + p4.scapy_tun_sa_id, + self.pg1.remote_addr[p6.addr_type], + self.pg1.remote_addr[p6.addr_type], + p4.remote_tun_if_host6, + p4.remote_tun_if_host6, + 0, + priority=10, + policy=e.IPSEC_API_SPD_ACTION_PROTECT, + is_outbound=1, + ).add_vpp_config() d = DpoProto.DPO_PROTO_IP6 - VppIpRoute(self, p4.remote_tun_if_host6, p6.addr_len, - [VppRoutePath(self.tun_if.remote_addr[p6.addr_type], - 0xffffffff, - proto=d)]).add_vpp_config() + VppIpRoute( + self, + p4.remote_tun_if_host6, + p6.addr_len, + [VppRoutePath(self.tun_if.remote_addr[p6.addr_type], 0xFFFFFFFF, proto=d)], + ).add_vpp_config() old_name = self.tun4_encrypt_node_name self.tun4_encrypt_node_name = "esp6-encrypt" @@ -389,16 +507,18 @@ class TestIpsecEsp1(TemplateIpsecEsp, IpsecTra46Tests, class TestIpsecEspTun(TemplateIpsecEsp, IpsecTun46Tests): - """ Ipsec ESP - TUN encap tests """ + """Ipsec ESP - TUN encap tests""" def setUp(self): self.ipv4_params = IPsecIPv4Params() self.ipv6_params = IPsecIPv6Params() - c = (VppEnum.vl_api_tunnel_encap_decap_flags_t. - TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP) - c1 = c | (VppEnum.vl_api_tunnel_encap_decap_flags_t. - TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN) + c = ( + VppEnum.vl_api_tunnel_encap_decap_flags_t.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP + ) + c1 = c | ( + VppEnum.vl_api_tunnel_encap_decap_flags_t.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN + ) self.ipv4_params.tun_flags = c self.ipv6_params.tun_flags = c1 @@ -407,19 +527,23 @@ class TestIpsecEspTun(TemplateIpsecEsp, IpsecTun46Tests): def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=54): # set the DSCP + ECN - flags are set to copy only DSCP - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - IP(src=src, dst=dst, tos=5) / - UDP(sport=4444, dport=4444) / - Raw(b'X' * payload_size) - for i in range(count)] + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / IP(src=src, dst=dst, tos=5) + / UDP(sport=4444, dport=4444) + / Raw(b"X" * payload_size) + for i in range(count) + ] def gen_pkts6(self, p, sw_intf, src, dst, count=1, payload_size=54): # set the DSCP + ECN - flags are set to copy both - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - IPv6(src=src, dst=dst, tc=5) / - UDP(sport=4444, dport=4444) / - Raw(b'X' * payload_size) - for i in range(count)] + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / IPv6(src=src, dst=dst, tc=5) + / UDP(sport=4444, dport=4444) + / Raw(b"X" * payload_size) + for i in range(count) + ] def verify_encrypted(self, p, sa, rxs): # just check that only the DSCP is copied @@ -433,7 +557,7 @@ class TestIpsecEspTun(TemplateIpsecEsp, IpsecTun46Tests): class TestIpsecEspTun2(TemplateIpsecEsp, IpsecTun46Tests): - """ Ipsec ESP - TUN DSCP tests """ + """Ipsec ESP - TUN DSCP tests""" def setUp(self): self.ipv4_params = IPsecIPv4Params() @@ -445,39 +569,44 @@ class TestIpsecEspTun2(TemplateIpsecEsp, IpsecTun46Tests): super(TestIpsecEspTun2, self).setUp() def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=54): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - IP(src=src, dst=dst) / - UDP(sport=4444, dport=4444) / - Raw(b'X' * payload_size) - for i in range(count)] + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / IP(src=src, dst=dst) + / UDP(sport=4444, dport=4444) + / Raw(b"X" * payload_size) + for i in range(count) + ] def gen_pkts6(self, p, sw_intf, src, dst, count=1, payload_size=54): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - IPv6(src=src, dst=dst) / - UDP(sport=4444, dport=4444) / - Raw(b'X' * payload_size) - for i in range(count)] + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / IPv6(src=src, dst=dst) + / UDP(sport=4444, dport=4444) + / Raw(b"X" * payload_size) + for i in range(count) + ] def verify_encrypted(self, p, sa, rxs): # just check that only the DSCP is set for rx in rxs: - self.assertEqual(rx[IP].tos, - VppEnum.vl_api_ip_dscp_t.IP_API_DSCP_EF << 2) + self.assertEqual(rx[IP].tos, VppEnum.vl_api_ip_dscp_t.IP_API_DSCP_EF << 2) def verify_encrypted6(self, p, sa, rxs): # just check that the DSCP is set for rx in rxs: - self.assertEqual(rx[IPv6].tc, - VppEnum.vl_api_ip_dscp_t.IP_API_DSCP_AF11 << 2) + self.assertEqual( + rx[IPv6].tc, VppEnum.vl_api_ip_dscp_t.IP_API_DSCP_AF11 << 2 + ) class TestIpsecEsp2(TemplateIpsecEsp, IpsecTcpTests): - """ Ipsec ESP - TCP tests """ + """Ipsec ESP - TCP tests""" + pass class TestIpsecEspAsync(TemplateIpsecEsp): - """ Ipsec ESP - Aysnc tests """ + """Ipsec ESP - Aysnc tests""" vpp_worker_count = 2 @@ -486,15 +615,16 @@ class TestIpsecEspAsync(TemplateIpsecEsp): self.p_sync = IPsecIPv4Params() - self.p_sync.crypt_algo_vpp_id = (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_AES_CBC_256) - self.p_sync.crypt_algo = 'AES-CBC' # scapy name - self.p_sync.crypt_key = b'JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h' + self.p_sync.crypt_algo_vpp_id = ( + VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CBC_256 + ) + self.p_sync.crypt_algo = "AES-CBC" # scapy name + self.p_sync.crypt_key = b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h" - self.p_sync.scapy_tun_sa_id += 0xf0000 - self.p_sync.scapy_tun_spi += 0xf0000 - self.p_sync.vpp_tun_sa_id += 0xf0000 - self.p_sync.vpp_tun_spi += 0xf0000 + self.p_sync.scapy_tun_sa_id += 0xF0000 + self.p_sync.scapy_tun_spi += 0xF0000 + self.p_sync.vpp_tun_sa_id += 0xF0000 + self.p_sync.vpp_tun_spi += 0xF0000 self.p_sync.remote_tun_if_host = "2.2.2.2" e = VppEnum.vl_api_ipsec_spd_action_t @@ -508,7 +638,8 @@ class TestIpsecEspAsync(TemplateIpsecEsp): self.p_sync.crypt_key, self.vpp_esp_protocol, self.tun_if.local_addr[self.p_sync.addr_type], - self.tun_if.remote_addr[self.p_sync.addr_type]).add_vpp_config() + self.tun_if.remote_addr[self.p_sync.addr_type], + ).add_vpp_config() self.p_sync.spd = VppIpsecSpdEntry( self, self.tun_spd, @@ -520,35 +651,40 @@ class TestIpsecEspAsync(TemplateIpsecEsp): 0, priority=1, policy=e.IPSEC_API_SPD_ACTION_PROTECT, - is_outbound=1).add_vpp_config() - VppIpRoute(self, - self.p_sync.remote_tun_if_host, - self.p_sync.addr_len, - [VppRoutePath( - self.tun_if.remote_addr[self.p_sync.addr_type], - 0xffffffff)]).add_vpp_config() + is_outbound=1, + ).add_vpp_config() + VppIpRoute( + self, + self.p_sync.remote_tun_if_host, + self.p_sync.addr_len, + [VppRoutePath(self.tun_if.remote_addr[self.p_sync.addr_type], 0xFFFFFFFF)], + ).add_vpp_config() config_tun_params(self.p_sync, self.encryption_type, self.tun_if) self.p_async = IPsecIPv4Params() - self.p_async.crypt_algo_vpp_id = (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_AES_GCM_256) - self.p_async.auth_algo_vpp_id = (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_NONE) - self.p_async.crypt_algo = 'AES-GCM' # scapy name - self.p_async.crypt_key = b'JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h' - self.p_async.auth_algo = 'NULL' - - self.p_async.scapy_tun_sa_id += 0xe0000 - self.p_async.scapy_tun_spi += 0xe0000 - self.p_async.vpp_tun_sa_id += 0xe0000 - self.p_async.vpp_tun_spi += 0xe0000 + self.p_async.crypt_algo_vpp_id = ( + VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_GCM_256 + ) + self.p_async.auth_algo_vpp_id = ( + VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_NONE + ) + self.p_async.crypt_algo = "AES-GCM" # scapy name + self.p_async.crypt_key = b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h" + self.p_async.auth_algo = "NULL" + + self.p_async.scapy_tun_sa_id += 0xE0000 + self.p_async.scapy_tun_spi += 0xE0000 + self.p_async.vpp_tun_sa_id += 0xE0000 + self.p_async.vpp_tun_spi += 0xE0000 self.p_async.remote_tun_if_host = "2.2.2.3" iflags = VppEnum.vl_api_ipsec_sad_flags_t - self.p_async.flags = (iflags.IPSEC_API_SAD_FLAG_USE_ESN | - iflags.IPSEC_API_SAD_FLAG_USE_ANTI_REPLAY | - iflags.IPSEC_API_SAD_FLAG_ASYNC) + self.p_async.flags = ( + iflags.IPSEC_API_SAD_FLAG_USE_ESN + | iflags.IPSEC_API_SAD_FLAG_USE_ANTI_REPLAY + | iflags.IPSEC_API_SAD_FLAG_ASYNC + ) self.p_async.sa = VppIpsecSA( self, @@ -561,7 +697,8 @@ class TestIpsecEspAsync(TemplateIpsecEsp): self.vpp_esp_protocol, self.tun_if.local_addr[self.p_async.addr_type], self.tun_if.remote_addr[self.p_async.addr_type], - flags=self.p_async.flags).add_vpp_config() + flags=self.p_async.flags, + ).add_vpp_config() self.p_async.spd = VppIpsecSpdEntry( self, self.tun_spd, @@ -573,30 +710,35 @@ class TestIpsecEspAsync(TemplateIpsecEsp): 0, priority=2, policy=e.IPSEC_API_SPD_ACTION_PROTECT, - is_outbound=1).add_vpp_config() - VppIpRoute(self, - self.p_async.remote_tun_if_host, - self.p_async.addr_len, - [VppRoutePath( - self.tun_if.remote_addr[self.p_async.addr_type], - 0xffffffff)]).add_vpp_config() + is_outbound=1, + ).add_vpp_config() + VppIpRoute( + self, + self.p_async.remote_tun_if_host, + self.p_async.addr_len, + [VppRoutePath(self.tun_if.remote_addr[self.p_async.addr_type], 0xFFFFFFFF)], + ).add_vpp_config() config_tun_params(self.p_async, self.encryption_type, self.tun_if) def test_dual_stream(self): - """ Alternating SAs """ + """Alternating SAs""" p = self.params[self.p_sync.addr_type] self.vapi.ipsec_set_async_mode(async_enable=True) - pkts = [(Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, - dst=self.p_sync.remote_tun_if_host) / - UDP(sport=4444, dport=4444) / - Raw(b'0x0' * 200)), - (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, - dst=p.remote_tun_if_host) / - UDP(sport=4444, dport=4444) / - Raw(b'0x0' * 200))] + pkts = [ + ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.p_sync.remote_tun_if_host) + / UDP(sport=4444, dport=4444) + / Raw(b"0x0" * 200) + ), + ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=p.remote_tun_if_host) + / UDP(sport=4444, dport=4444) + / Raw(b"0x0" * 200) + ), + ] pkts *= 1023 rxs = self.send_and_expect(self.pg1, pkts, self.pg0) @@ -619,15 +761,18 @@ class TestIpsecEspAsync(TemplateIpsecEsp): self.vapi.ipsec_set_async_mode(async_enable=False) def test_sync_async_noop_stream(self): - """ Alternating SAs sync/async/noop """ + """Alternating SAs sync/async/noop""" p = self.params[self.p_sync.addr_type] # first pin the default/noop SA to worker 0 - pkts = [(Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, - dst=p.remote_tun_if_host) / - UDP(sport=4444, dport=4444) / - Raw(b'0x0' * 200))] + pkts = [ + ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=p.remote_tun_if_host) + / UDP(sport=4444, dport=4444) + / Raw(b"0x0" * 200) + ) + ] rxs = self.send_and_expect(self.pg1, pkts, self.pg0, worker=0) self.logger.info(self.vapi.cli("sh ipsec sa")) @@ -635,21 +780,26 @@ class TestIpsecEspAsync(TemplateIpsecEsp): # then use all the other SAs on worker 1. # some will handoff, other take the sync and async paths - pkts = [(Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, - dst=self.p_sync.remote_tun_if_host) / - UDP(sport=4444, dport=4444) / - Raw(b'0x0' * 200)), - (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, - dst=p.remote_tun_if_host) / - UDP(sport=4444, dport=4444) / - Raw(b'0x0' * 200)), - (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, - dst=self.p_async.remote_tun_if_host) / - UDP(sport=4444, dport=4444) / - Raw(b'0x0' * 200))] + pkts = [ + ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.p_sync.remote_tun_if_host) + / UDP(sport=4444, dport=4444) + / Raw(b"0x0" * 200) + ), + ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=p.remote_tun_if_host) + / UDP(sport=4444, dport=4444) + / Raw(b"0x0" * 200) + ), + ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.p_async.remote_tun_if_host) + / UDP(sport=4444, dport=4444) + / Raw(b"0x0" * 200) + ), + ] pkts *= 1023 rxs = self.send_and_expect(self.pg1, pkts, self.pg0, worker=1) @@ -678,10 +828,11 @@ class TestIpsecEspAsync(TemplateIpsecEsp): self.assertTrue("DISABLED" in self.vapi.cli("sh crypto async status")) -class TestIpsecEspHandoff(TemplateIpsecEsp, - IpsecTun6HandoffTests, - IpsecTun4HandoffTests): - """ Ipsec ESP - handoff tests """ +class TestIpsecEspHandoff( + TemplateIpsecEsp, IpsecTun6HandoffTests, IpsecTun4HandoffTests +): + """Ipsec ESP - handoff tests""" + pass @@ -706,33 +857,33 @@ class TemplateIpsecEspUdp(ConfigIpsecESP): self.logger.info(self.vapi.ppcli("show int addr")) p = self.ipv4_params - p.flags = (VppEnum.vl_api_ipsec_sad_flags_t. - IPSEC_API_SAD_FLAG_UDP_ENCAP | - VppEnum.vl_api_ipsec_sad_flags_t. - IPSEC_API_SAD_FLAG_USE_ANTI_REPLAY) + p.flags = ( + VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_UDP_ENCAP + | VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_USE_ANTI_REPLAY + ) p.nat_header = UDP(sport=5454, dport=4500) self.tra_spd = VppIpsecSpd(self, self.tra_spd_id) self.tra_spd.add_vpp_config() - VppIpsecSpdItfBinding(self, self.tra_spd, - self.tra_if).add_vpp_config() + VppIpsecSpdItfBinding(self, self.tra_spd, self.tra_if).add_vpp_config() self.config_esp_tra(p) config_tra_params(p, self.encryption_type) self.tun_spd = VppIpsecSpd(self, self.tun_spd_id) self.tun_spd.add_vpp_config() - VppIpsecSpdItfBinding(self, self.tun_spd, - self.tun_if).add_vpp_config() + VppIpsecSpdItfBinding(self, self.tun_spd, self.tun_if).add_vpp_config() self.config_esp_tun(p) self.logger.info(self.vapi.ppcli("show ipsec all")) d = DpoProto.DPO_PROTO_IP4 - VppIpRoute(self, p.remote_tun_if_host, p.addr_len, - [VppRoutePath(self.tun_if.remote_addr[p.addr_type], - 0xffffffff, - proto=d)]).add_vpp_config() + VppIpRoute( + self, + p.remote_tun_if_host, + p.addr_len, + [VppRoutePath(self.tun_if.remote_addr[p.addr_type], 0xFFFFFFFF, proto=d)], + ).add_vpp_config() def tearDown(self): super(TemplateIpsecEspUdp, self).tearDown() @@ -742,11 +893,12 @@ class TemplateIpsecEspUdp(ConfigIpsecESP): class TestIpsecEspUdp(TemplateIpsecEspUdp, IpsecTra4Tests): - """ Ipsec NAT-T ESP UDP tests """ + """Ipsec NAT-T ESP UDP tests""" + pass -class MyParameters(): +class MyParameters: def __init__(self): saf = VppEnum.vl_api_ipsec_sad_flags_t flag_esn = saf.IPSEC_API_SAD_FLAG_USE_ESN @@ -754,111 +906,143 @@ class MyParameters(): self.flags = [0, flag_esn, flag_ar] # foreach crypto algorithm self.algos = { - 'AES-GCM-128/NONE': { - 'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_AES_GCM_128), - 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_NONE), - 'scapy-crypto': "AES-GCM", - 'scapy-integ': "NULL", - 'key': b"JPjyOWBeVEQiMe7h", - 'salt': 0}, - 'AES-GCM-192/NONE': { - 'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_AES_GCM_192), - 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_NONE), - 'scapy-crypto': "AES-GCM", - 'scapy-integ': "NULL", - 'key': b"JPjyOWBeVEQiMe7h01234567", - 'salt': 1010}, - 'AES-GCM-256/NONE': { - 'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_AES_GCM_256), - 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_NONE), - 'scapy-crypto': "AES-GCM", - 'scapy-integ': "NULL", - 'key': b"JPjyOWBeVEQiMe7h0123456787654321", - 'salt': 2020}, - 'AES-CBC-128/MD5-96': { - 'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_AES_CBC_128), - 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_MD5_96), - 'scapy-crypto': "AES-CBC", - 'scapy-integ': "HMAC-MD5-96", - 'salt': 0, - 'key': b"JPjyOWBeVEQiMe7h"}, - 'AES-CBC-192/SHA1-96': { - 'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_AES_CBC_192), - 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_SHA1_96), - 'scapy-crypto': "AES-CBC", - 'scapy-integ': "HMAC-SHA1-96", - 'salt': 0, - 'key': b"JPjyOWBeVEQiMe7hJPjyOWBe"}, - 'AES-CBC-256/SHA1-96': { - 'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_AES_CBC_256), - 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_SHA1_96), - 'scapy-crypto': "AES-CBC", - 'scapy-integ': "HMAC-SHA1-96", - 'salt': 0, - 'key': b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h"}, - '3DES-CBC/SHA1-96': { - 'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_3DES_CBC), - 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_SHA1_96), - 'scapy-crypto': "3DES", - 'scapy-integ': "HMAC-SHA1-96", - 'salt': 0, - 'key': b"JPjyOWBeVEQiMe7h00112233"}, - 'NONE/SHA1-96': { - 'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_NONE), - 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_SHA1_96), - 'scapy-crypto': "NULL", - 'scapy-integ': "HMAC-SHA1-96", - 'salt': 0, - 'key': b"JPjyOWBeVEQiMe7h00112233"}, - 'AES-CTR-128/SHA1-96': { - 'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_AES_CTR_128), - 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_SHA1_96), - 'scapy-crypto': "AES-CTR", - 'scapy-integ': "HMAC-SHA1-96", - 'salt': 0, - 'key': b"JPjyOWBeVEQiMe7h"}, - 'AES-CTR-192/SHA1-96': { - 'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_AES_CTR_192), - 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_SHA1_96), - 'scapy-crypto': "AES-CTR", - 'scapy-integ': "HMAC-SHA1-96", - 'salt': 1010, - 'key': b"JPjyOWBeVEQiMe7hJPjyOWBe"}, - 'AES-CTR-256/SHA1-96': { - 'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_AES_CTR_256), - 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_SHA1_96), - 'scapy-crypto': "AES-CTR", - 'scapy-integ': "HMAC-SHA1-96", - 'salt': 2020, - 'key': b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h"}} - - -class RunTestIpsecEspAll(ConfigIpsecESP, - IpsecTra4, IpsecTra6, - IpsecTun4, IpsecTun6): - """ Ipsec ESP all Algos """ + "AES-GCM-128/NONE": { + "vpp-crypto": ( + VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_GCM_128 + ), + "vpp-integ": ( + VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_NONE + ), + "scapy-crypto": "AES-GCM", + "scapy-integ": "NULL", + "key": b"JPjyOWBeVEQiMe7h", + "salt": 0, + }, + "AES-GCM-192/NONE": { + "vpp-crypto": ( + VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_GCM_192 + ), + "vpp-integ": ( + VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_NONE + ), + "scapy-crypto": "AES-GCM", + "scapy-integ": "NULL", + "key": b"JPjyOWBeVEQiMe7h01234567", + "salt": 1010, + }, + "AES-GCM-256/NONE": { + "vpp-crypto": ( + VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_GCM_256 + ), + "vpp-integ": ( + VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_NONE + ), + "scapy-crypto": "AES-GCM", + "scapy-integ": "NULL", + "key": b"JPjyOWBeVEQiMe7h0123456787654321", + "salt": 2020, + }, + "AES-CBC-128/MD5-96": { + "vpp-crypto": ( + VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CBC_128 + ), + "vpp-integ": ( + VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_MD5_96 + ), + "scapy-crypto": "AES-CBC", + "scapy-integ": "HMAC-MD5-96", + "salt": 0, + "key": b"JPjyOWBeVEQiMe7h", + }, + "AES-CBC-192/SHA1-96": { + "vpp-crypto": ( + VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CBC_192 + ), + "vpp-integ": ( + VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96 + ), + "scapy-crypto": "AES-CBC", + "scapy-integ": "HMAC-SHA1-96", + "salt": 0, + "key": b"JPjyOWBeVEQiMe7hJPjyOWBe", + }, + "AES-CBC-256/SHA1-96": { + "vpp-crypto": ( + VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CBC_256 + ), + "vpp-integ": ( + VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96 + ), + "scapy-crypto": "AES-CBC", + "scapy-integ": "HMAC-SHA1-96", + "salt": 0, + "key": b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h", + }, + "3DES-CBC/SHA1-96": { + "vpp-crypto": ( + VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_3DES_CBC + ), + "vpp-integ": ( + VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96 + ), + "scapy-crypto": "3DES", + "scapy-integ": "HMAC-SHA1-96", + "salt": 0, + "key": b"JPjyOWBeVEQiMe7h00112233", + }, + "NONE/SHA1-96": { + "vpp-crypto": ( + VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_NONE + ), + "vpp-integ": ( + VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96 + ), + "scapy-crypto": "NULL", + "scapy-integ": "HMAC-SHA1-96", + "salt": 0, + "key": b"JPjyOWBeVEQiMe7h00112233", + }, + "AES-CTR-128/SHA1-96": { + "vpp-crypto": ( + VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CTR_128 + ), + "vpp-integ": ( + VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96 + ), + "scapy-crypto": "AES-CTR", + "scapy-integ": "HMAC-SHA1-96", + "salt": 0, + "key": b"JPjyOWBeVEQiMe7h", + }, + "AES-CTR-192/SHA1-96": { + "vpp-crypto": ( + VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CTR_192 + ), + "vpp-integ": ( + VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96 + ), + "scapy-crypto": "AES-CTR", + "scapy-integ": "HMAC-SHA1-96", + "salt": 1010, + "key": b"JPjyOWBeVEQiMe7hJPjyOWBe", + }, + "AES-CTR-256/SHA1-96": { + "vpp-crypto": ( + VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CTR_256 + ), + "vpp-integ": ( + VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96 + ), + "scapy-crypto": "AES-CTR", + "scapy-integ": "HMAC-SHA1-96", + "salt": 2020, + "key": b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h", + }, + } + + +class RunTestIpsecEspAll(ConfigIpsecESP, IpsecTra4, IpsecTra6, IpsecTun4, IpsecTun6): + """Ipsec ESP all Algos""" @classmethod def setUpConstants(cls): @@ -875,9 +1059,9 @@ class RunTestIpsecEspAll(ConfigIpsecESP, params = MyParameters() self.engine = test_args[0] self.flag = params.flags[0] - if test_args[1] == 'ESNon': + if test_args[1] == "ESNon": self.flag |= params.flags[1] - if test_args[2] == 'ARon': + if test_args[2] == "ARon": self.flag |= params.flags[2] self.algo = params.algos[test_args[3]] @@ -901,18 +1085,18 @@ class RunTestIpsecEspAll(ConfigIpsecESP, self.ipv4_params = IPsecIPv4Params() self.ipv6_params = IPsecIPv6Params() - self.params = {self.ipv4_params.addr_type: - self.ipv4_params, - self.ipv6_params.addr_type: - self.ipv6_params} + self.params = { + self.ipv4_params.addr_type: self.ipv4_params, + self.ipv6_params.addr_type: self.ipv6_params, + } for _, p in self.params.items(): - p.auth_algo_vpp_id = algo['vpp-integ'] - p.crypt_algo_vpp_id = algo['vpp-crypto'] - p.crypt_algo = algo['scapy-crypto'] - p.auth_algo = algo['scapy-integ'] - p.crypt_key = algo['key'] - p.salt = algo['salt'] + p.auth_algo_vpp_id = algo["vpp-integ"] + p.crypt_algo_vpp_id = algo["vpp-crypto"] + p.crypt_algo = algo["scapy-crypto"] + p.auth_algo = algo["scapy-integ"] + p.crypt_key = algo["key"] + p.salt = algo["salt"] p.flags = flag p.outer_flow_label = 243224 p.async_mode = self.async_mode @@ -931,8 +1115,7 @@ class RunTestIpsecEspAll(ConfigIpsecESP, # self.verify_tra_basic6(count=NUM_PKTS) self.verify_tra_basic4(count=NUM_PKTS) - self.verify_tun_66(self.params[socket.AF_INET6], - count=NUM_PKTS) + self.verify_tun_66(self.params[socket.AF_INET6], count=NUM_PKTS) # # Use an odd-byte payload size to check for correct padding. # @@ -940,26 +1123,29 @@ class RunTestIpsecEspAll(ConfigIpsecESP, # to 56 for 8 byte alignment, and +13 to 64 for 64 byte alignment. # This should catch bugs where the code is incorrectly over-padding # for algorithms that don't require it - psz = 49 - len(IP()/ICMP()) if payload_size is None else payload_size - self.verify_tun_44(self.params[socket.AF_INET], - count=NUM_PKTS, payload_size=psz) + psz = 49 - len(IP() / ICMP()) if payload_size is None else payload_size + self.verify_tun_44( + self.params[socket.AF_INET], count=NUM_PKTS, payload_size=psz + ) LARGE_PKT_SZ = [ 1970, # results in 2 chained buffers entering decrypt node - # but leaving as simple buffer due to ICV removal (tra4) + # but leaving as simple buffer due to ICV removal (tra4) 2004, # footer+ICV will be added to 2nd buffer (tun4) 4010, # ICV ends up splitted across 2 buffers in esp_decrypt - # for transport4; transport6 takes normal path + # for transport4; transport6 takes normal path 4020, # same as above but tra4 and tra6 are switched ] if self.engine in engines_supporting_chain_bufs: for sz in LARGE_PKT_SZ: self.verify_tra_basic4(count=NUM_PKTS, payload_size=sz) self.verify_tra_basic6(count=NUM_PKTS, payload_size=sz) - self.verify_tun_66(self.params[socket.AF_INET6], - count=NUM_PKTS, payload_size=sz) - self.verify_tun_44(self.params[socket.AF_INET], - count=NUM_PKTS, payload_size=sz) + self.verify_tun_66( + self.params[socket.AF_INET6], count=NUM_PKTS, payload_size=sz + ) + self.verify_tun_44( + self.params[socket.AF_INET], count=NUM_PKTS, payload_size=sz + ) # # reconfigure the network and SA to run the @@ -990,6 +1176,7 @@ class RunTestIpsecEspAll(ConfigIpsecESP, self.unconfig_network() + # # To generate test classes, do: # grep '# GEN' test_ipsec_esp.py | sed -e 's/# GEN //g' | bash @@ -1026,6 +1213,7 @@ class RunTestIpsecEspAll(ConfigIpsecESP, class Test_native_ESNon_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll): """native ESNon ARon AES-GCM-128/NONE IPSec test""" + def test_ipsec(self): """native ESNon ARon AES-GCM-128/NONE IPSec test""" self.run_test() @@ -1033,6 +1221,7 @@ class Test_native_ESNon_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll): class Test_native_ESNon_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll): """native ESNon ARon AES-GCM-192/NONE IPSec test""" + def test_ipsec(self): """native ESNon ARon AES-GCM-192/NONE IPSec test""" self.run_test() @@ -1040,6 +1229,7 @@ class Test_native_ESNon_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll): class Test_native_ESNon_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll): """native ESNon ARon AES-GCM-256/NONE IPSec test""" + def test_ipsec(self): """native ESNon ARon AES-GCM-256/NONE IPSec test""" self.run_test() @@ -1047,6 +1237,7 @@ class Test_native_ESNon_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll): class Test_native_ESNon_ARon_AES_CBC_128_MD5_96(RunTestIpsecEspAll): """native ESNon ARon AES-CBC-128/MD5-96 IPSec test""" + def test_ipsec(self): """native ESNon ARon AES-CBC-128/MD5-96 IPSec test""" self.run_test() @@ -1054,6 +1245,7 @@ class Test_native_ESNon_ARon_AES_CBC_128_MD5_96(RunTestIpsecEspAll): class Test_native_ESNon_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): """native ESNon ARon AES-CBC-192/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNon ARon AES-CBC-192/SHA1-96 IPSec test""" self.run_test() @@ -1061,6 +1253,7 @@ class Test_native_ESNon_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNon_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): """native ESNon ARon AES-CBC-256/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNon ARon AES-CBC-256/SHA1-96 IPSec test""" self.run_test() @@ -1068,6 +1261,7 @@ class Test_native_ESNon_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNon_ARon_3DES_CBC_SHA1_96(RunTestIpsecEspAll): """native ESNon ARon 3DES-CBC/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNon ARon 3DES-CBC/SHA1-96 IPSec test""" self.run_test() @@ -1075,6 +1269,7 @@ class Test_native_ESNon_ARon_3DES_CBC_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNon_ARon_NONE_SHA1_96(RunTestIpsecEspAll): """native ESNon ARon NONE/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNon ARon NONE/SHA1-96 IPSec test""" self.run_test() @@ -1082,6 +1277,7 @@ class Test_native_ESNon_ARon_NONE_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNon_ARon_AES_CTR_128_SHA1_96(RunTestIpsecEspAll): """native ESNon ARon AES-CTR-128/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNon ARon AES-CTR-128/SHA1-96 IPSec test""" self.run_test() @@ -1089,6 +1285,7 @@ class Test_native_ESNon_ARon_AES_CTR_128_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNon_ARon_AES_CTR_192_SHA1_96(RunTestIpsecEspAll): """native ESNon ARon AES-CTR-192/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNon ARon AES-CTR-192/SHA1-96 IPSec test""" self.run_test() @@ -1096,6 +1293,7 @@ class Test_native_ESNon_ARon_AES_CTR_192_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNon_ARon_AES_CTR_256_SHA1_96(RunTestIpsecEspAll): """native ESNon ARon AES-CTR-256/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNon ARon AES-CTR-256/SHA1-96 IPSec test""" self.run_test() @@ -1103,6 +1301,7 @@ class Test_native_ESNon_ARon_AES_CTR_256_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNon_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll): """native ESNon ARoff AES-GCM-128/NONE IPSec test""" + def test_ipsec(self): """native ESNon ARoff AES-GCM-128/NONE IPSec test""" self.run_test() @@ -1110,6 +1309,7 @@ class Test_native_ESNon_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll): class Test_native_ESNon_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll): """native ESNon ARoff AES-GCM-192/NONE IPSec test""" + def test_ipsec(self): """native ESNon ARoff AES-GCM-192/NONE IPSec test""" self.run_test() @@ -1117,6 +1317,7 @@ class Test_native_ESNon_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll): class Test_native_ESNon_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll): """native ESNon ARoff AES-GCM-256/NONE IPSec test""" + def test_ipsec(self): """native ESNon ARoff AES-GCM-256/NONE IPSec test""" self.run_test() @@ -1124,6 +1325,7 @@ class Test_native_ESNon_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll): class Test_native_ESNon_ARoff_AES_CBC_128_MD5_96(RunTestIpsecEspAll): """native ESNon ARoff AES-CBC-128/MD5-96 IPSec test""" + def test_ipsec(self): """native ESNon ARoff AES-CBC-128/MD5-96 IPSec test""" self.run_test() @@ -1131,6 +1333,7 @@ class Test_native_ESNon_ARoff_AES_CBC_128_MD5_96(RunTestIpsecEspAll): class Test_native_ESNon_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): """native ESNon ARoff AES-CBC-192/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNon ARoff AES-CBC-192/SHA1-96 IPSec test""" self.run_test() @@ -1138,6 +1341,7 @@ class Test_native_ESNon_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNon_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): """native ESNon ARoff AES-CBC-256/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNon ARoff AES-CBC-256/SHA1-96 IPSec test""" self.run_test() @@ -1145,6 +1349,7 @@ class Test_native_ESNon_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNon_ARoff_3DES_CBC_SHA1_96(RunTestIpsecEspAll): """native ESNon ARoff 3DES-CBC/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNon ARoff 3DES-CBC/SHA1-96 IPSec test""" self.run_test() @@ -1152,6 +1357,7 @@ class Test_native_ESNon_ARoff_3DES_CBC_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNon_ARoff_NONE_SHA1_96(RunTestIpsecEspAll): """native ESNon ARoff NONE/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNon ARoff NONE/SHA1-96 IPSec test""" self.run_test() @@ -1159,6 +1365,7 @@ class Test_native_ESNon_ARoff_NONE_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNon_ARoff_AES_CTR_128_SHA1_96(RunTestIpsecEspAll): """native ESNon ARoff AES-CTR-128/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNon ARoff AES-CTR-128/SHA1-96 IPSec test""" self.run_test() @@ -1166,6 +1373,7 @@ class Test_native_ESNon_ARoff_AES_CTR_128_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNon_ARoff_AES_CTR_192_SHA1_96(RunTestIpsecEspAll): """native ESNon ARoff AES-CTR-192/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNon ARoff AES-CTR-192/SHA1-96 IPSec test""" self.run_test() @@ -1173,6 +1381,7 @@ class Test_native_ESNon_ARoff_AES_CTR_192_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNon_ARoff_AES_CTR_256_SHA1_96(RunTestIpsecEspAll): """native ESNon ARoff AES-CTR-256/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNon ARoff AES-CTR-256/SHA1-96 IPSec test""" self.run_test() @@ -1180,6 +1389,7 @@ class Test_native_ESNon_ARoff_AES_CTR_256_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNoff_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll): """native ESNoff ARon AES-GCM-128/NONE IPSec test""" + def test_ipsec(self): """native ESNoff ARon AES-GCM-128/NONE IPSec test""" self.run_test() @@ -1187,6 +1397,7 @@ class Test_native_ESNoff_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll): class Test_native_ESNoff_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll): """native ESNoff ARon AES-GCM-192/NONE IPSec test""" + def test_ipsec(self): """native ESNoff ARon AES-GCM-192/NONE IPSec test""" self.run_test() @@ -1194,6 +1405,7 @@ class Test_native_ESNoff_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll): class Test_native_ESNoff_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll): """native ESNoff ARon AES-GCM-256/NONE IPSec test""" + def test_ipsec(self): """native ESNoff ARon AES-GCM-256/NONE IPSec test""" self.run_test() @@ -1201,6 +1413,7 @@ class Test_native_ESNoff_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll): class Test_native_ESNoff_ARon_AES_CBC_128_MD5_96(RunTestIpsecEspAll): """native ESNoff ARon AES-CBC-128/MD5-96 IPSec test""" + def test_ipsec(self): """native ESNoff ARon AES-CBC-128/MD5-96 IPSec test""" self.run_test() @@ -1208,6 +1421,7 @@ class Test_native_ESNoff_ARon_AES_CBC_128_MD5_96(RunTestIpsecEspAll): class Test_native_ESNoff_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): """native ESNoff ARon AES-CBC-192/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNoff ARon AES-CBC-192/SHA1-96 IPSec test""" self.run_test() @@ -1215,6 +1429,7 @@ class Test_native_ESNoff_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNoff_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): """native ESNoff ARon AES-CBC-256/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNoff ARon AES-CBC-256/SHA1-96 IPSec test""" self.run_test() @@ -1222,6 +1437,7 @@ class Test_native_ESNoff_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNoff_ARon_3DES_CBC_SHA1_96(RunTestIpsecEspAll): """native ESNoff ARon 3DES-CBC/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNoff ARon 3DES-CBC/SHA1-96 IPSec test""" self.run_test() @@ -1229,6 +1445,7 @@ class Test_native_ESNoff_ARon_3DES_CBC_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNoff_ARon_NONE_SHA1_96(RunTestIpsecEspAll): """native ESNoff ARon NONE/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNoff ARon NONE/SHA1-96 IPSec test""" self.run_test() @@ -1236,6 +1453,7 @@ class Test_native_ESNoff_ARon_NONE_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNoff_ARon_AES_CTR_128_SHA1_96(RunTestIpsecEspAll): """native ESNoff ARon AES-CTR-128/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNoff ARon AES-CTR-128/SHA1-96 IPSec test""" self.run_test() @@ -1243,6 +1461,7 @@ class Test_native_ESNoff_ARon_AES_CTR_128_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNoff_ARon_AES_CTR_192_SHA1_96(RunTestIpsecEspAll): """native ESNoff ARon AES-CTR-192/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNoff ARon AES-CTR-192/SHA1-96 IPSec test""" self.run_test() @@ -1250,6 +1469,7 @@ class Test_native_ESNoff_ARon_AES_CTR_192_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNoff_ARon_AES_CTR_256_SHA1_96(RunTestIpsecEspAll): """native ESNoff ARon AES-CTR-256/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNoff ARon AES-CTR-256/SHA1-96 IPSec test""" self.run_test() @@ -1257,6 +1477,7 @@ class Test_native_ESNoff_ARon_AES_CTR_256_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNoff_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll): """native ESNoff ARoff AES-GCM-128/NONE IPSec test""" + def test_ipsec(self): """native ESNoff ARoff AES-GCM-128/NONE IPSec test""" self.run_test() @@ -1264,6 +1485,7 @@ class Test_native_ESNoff_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll): class Test_native_ESNoff_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll): """native ESNoff ARoff AES-GCM-192/NONE IPSec test""" + def test_ipsec(self): """native ESNoff ARoff AES-GCM-192/NONE IPSec test""" self.run_test() @@ -1271,6 +1493,7 @@ class Test_native_ESNoff_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll): class Test_native_ESNoff_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll): """native ESNoff ARoff AES-GCM-256/NONE IPSec test""" + def test_ipsec(self): """native ESNoff ARoff AES-GCM-256/NONE IPSec test""" self.run_test() @@ -1278,6 +1501,7 @@ class Test_native_ESNoff_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll): class Test_native_ESNoff_ARoff_AES_CBC_128_MD5_96(RunTestIpsecEspAll): """native ESNoff ARoff AES-CBC-128/MD5-96 IPSec test""" + def test_ipsec(self): """native ESNoff ARoff AES-CBC-128/MD5-96 IPSec test""" self.run_test() @@ -1285,6 +1509,7 @@ class Test_native_ESNoff_ARoff_AES_CBC_128_MD5_96(RunTestIpsecEspAll): class Test_native_ESNoff_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): """native ESNoff ARoff AES-CBC-192/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNoff ARoff AES-CBC-192/SHA1-96 IPSec test""" self.run_test() @@ -1292,6 +1517,7 @@ class Test_native_ESNoff_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNoff_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): """native ESNoff ARoff AES-CBC-256/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNoff ARoff AES-CBC-256/SHA1-96 IPSec test""" self.run_test() @@ -1299,6 +1525,7 @@ class Test_native_ESNoff_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNoff_ARoff_3DES_CBC_SHA1_96(RunTestIpsecEspAll): """native ESNoff ARoff 3DES-CBC/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNoff ARoff 3DES-CBC/SHA1-96 IPSec test""" self.run_test() @@ -1306,6 +1533,7 @@ class Test_native_ESNoff_ARoff_3DES_CBC_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNoff_ARoff_NONE_SHA1_96(RunTestIpsecEspAll): """native ESNoff ARoff NONE/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNoff ARoff NONE/SHA1-96 IPSec test""" self.run_test() @@ -1313,6 +1541,7 @@ class Test_native_ESNoff_ARoff_NONE_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNoff_ARoff_AES_CTR_128_SHA1_96(RunTestIpsecEspAll): """native ESNoff ARoff AES-CTR-128/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNoff ARoff AES-CTR-128/SHA1-96 IPSec test""" self.run_test() @@ -1320,6 +1549,7 @@ class Test_native_ESNoff_ARoff_AES_CTR_128_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNoff_ARoff_AES_CTR_192_SHA1_96(RunTestIpsecEspAll): """native ESNoff ARoff AES-CTR-192/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNoff ARoff AES-CTR-192/SHA1-96 IPSec test""" self.run_test() @@ -1327,6 +1557,7 @@ class Test_native_ESNoff_ARoff_AES_CTR_192_SHA1_96(RunTestIpsecEspAll): class Test_native_ESNoff_ARoff_AES_CTR_256_SHA1_96(RunTestIpsecEspAll): """native ESNoff ARoff AES-CTR-256/SHA1-96 IPSec test""" + def test_ipsec(self): """native ESNoff ARoff AES-CTR-256/SHA1-96 IPSec test""" self.run_test() @@ -1334,6 +1565,7 @@ class Test_native_ESNoff_ARoff_AES_CTR_256_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNon_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll): """ipsecmb ESNon ARon AES-GCM-128/NONE IPSec test""" + def test_ipsec(self): """ipsecmb ESNon ARon AES-GCM-128/NONE IPSec test""" self.run_test() @@ -1341,6 +1573,7 @@ class Test_ipsecmb_ESNon_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll): class Test_ipsecmb_ESNon_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll): """ipsecmb ESNon ARon AES-GCM-192/NONE IPSec test""" + def test_ipsec(self): """ipsecmb ESNon ARon AES-GCM-192/NONE IPSec test""" self.run_test() @@ -1348,6 +1581,7 @@ class Test_ipsecmb_ESNon_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll): class Test_ipsecmb_ESNon_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll): """ipsecmb ESNon ARon AES-GCM-256/NONE IPSec test""" + def test_ipsec(self): """ipsecmb ESNon ARon AES-GCM-256/NONE IPSec test""" self.run_test() @@ -1355,6 +1589,7 @@ class Test_ipsecmb_ESNon_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll): class Test_ipsecmb_ESNon_ARon_AES_CBC_128_MD5_96(RunTestIpsecEspAll): """ipsecmb ESNon ARon AES-CBC-128/MD5-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNon ARon AES-CBC-128/MD5-96 IPSec test""" self.run_test() @@ -1362,6 +1597,7 @@ class Test_ipsecmb_ESNon_ARon_AES_CBC_128_MD5_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNon_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNon ARon AES-CBC-192/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNon ARon AES-CBC-192/SHA1-96 IPSec test""" self.run_test() @@ -1369,6 +1605,7 @@ class Test_ipsecmb_ESNon_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNon_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNon ARon AES-CBC-256/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNon ARon AES-CBC-256/SHA1-96 IPSec test""" self.run_test() @@ -1376,6 +1613,7 @@ class Test_ipsecmb_ESNon_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNon_ARon_3DES_CBC_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNon ARon 3DES-CBC/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNon ARon 3DES-CBC/SHA1-96 IPSec test""" self.run_test() @@ -1383,6 +1621,7 @@ class Test_ipsecmb_ESNon_ARon_3DES_CBC_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNon_ARon_NONE_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNon ARon NONE/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNon ARon NONE/SHA1-96 IPSec test""" self.run_test() @@ -1390,6 +1629,7 @@ class Test_ipsecmb_ESNon_ARon_NONE_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNon_ARon_AES_CTR_128_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNon ARon AES-CTR-128/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNon ARon AES-CTR-128/SHA1-96 IPSec test""" self.run_test() @@ -1397,6 +1637,7 @@ class Test_ipsecmb_ESNon_ARon_AES_CTR_128_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNon_ARon_AES_CTR_192_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNon ARon AES-CTR-192/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNon ARon AES-CTR-192/SHA1-96 IPSec test""" self.run_test() @@ -1404,6 +1645,7 @@ class Test_ipsecmb_ESNon_ARon_AES_CTR_192_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNon_ARon_AES_CTR_256_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNon ARon AES-CTR-256/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNon ARon AES-CTR-256/SHA1-96 IPSec test""" self.run_test() @@ -1411,6 +1653,7 @@ class Test_ipsecmb_ESNon_ARon_AES_CTR_256_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNon_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll): """ipsecmb ESNon ARoff AES-GCM-128/NONE IPSec test""" + def test_ipsec(self): """ipsecmb ESNon ARoff AES-GCM-128/NONE IPSec test""" self.run_test() @@ -1418,6 +1661,7 @@ class Test_ipsecmb_ESNon_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll): class Test_ipsecmb_ESNon_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll): """ipsecmb ESNon ARoff AES-GCM-192/NONE IPSec test""" + def test_ipsec(self): """ipsecmb ESNon ARoff AES-GCM-192/NONE IPSec test""" self.run_test() @@ -1425,6 +1669,7 @@ class Test_ipsecmb_ESNon_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll): class Test_ipsecmb_ESNon_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll): """ipsecmb ESNon ARoff AES-GCM-256/NONE IPSec test""" + def test_ipsec(self): """ipsecmb ESNon ARoff AES-GCM-256/NONE IPSec test""" self.run_test() @@ -1432,6 +1677,7 @@ class Test_ipsecmb_ESNon_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll): class Test_ipsecmb_ESNon_ARoff_AES_CBC_128_MD5_96(RunTestIpsecEspAll): """ipsecmb ESNon ARoff AES-CBC-128/MD5-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNon ARoff AES-CBC-128/MD5-96 IPSec test""" self.run_test() @@ -1439,6 +1685,7 @@ class Test_ipsecmb_ESNon_ARoff_AES_CBC_128_MD5_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNon_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNon ARoff AES-CBC-192/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNon ARoff AES-CBC-192/SHA1-96 IPSec test""" self.run_test() @@ -1446,6 +1693,7 @@ class Test_ipsecmb_ESNon_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNon_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNon ARoff AES-CBC-256/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNon ARoff AES-CBC-256/SHA1-96 IPSec test""" self.run_test() @@ -1453,6 +1701,7 @@ class Test_ipsecmb_ESNon_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNon_ARoff_3DES_CBC_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNon ARoff 3DES-CBC/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNon ARoff 3DES-CBC/SHA1-96 IPSec test""" self.run_test() @@ -1460,6 +1709,7 @@ class Test_ipsecmb_ESNon_ARoff_3DES_CBC_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNon_ARoff_NONE_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNon ARoff NONE/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNon ARoff NONE/SHA1-96 IPSec test""" self.run_test() @@ -1467,6 +1717,7 @@ class Test_ipsecmb_ESNon_ARoff_NONE_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNon_ARoff_AES_CTR_128_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNon ARoff AES-CTR-128/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNon ARoff AES-CTR-128/SHA1-96 IPSec test""" self.run_test() @@ -1474,6 +1725,7 @@ class Test_ipsecmb_ESNon_ARoff_AES_CTR_128_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNon_ARoff_AES_CTR_192_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNon ARoff AES-CTR-192/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNon ARoff AES-CTR-192/SHA1-96 IPSec test""" self.run_test() @@ -1481,6 +1733,7 @@ class Test_ipsecmb_ESNon_ARoff_AES_CTR_192_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNon_ARoff_AES_CTR_256_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNon ARoff AES-CTR-256/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNon ARoff AES-CTR-256/SHA1-96 IPSec test""" self.run_test() @@ -1488,6 +1741,7 @@ class Test_ipsecmb_ESNon_ARoff_AES_CTR_256_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNoff_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll): """ipsecmb ESNoff ARon AES-GCM-128/NONE IPSec test""" + def test_ipsec(self): """ipsecmb ESNoff ARon AES-GCM-128/NONE IPSec test""" self.run_test() @@ -1495,6 +1749,7 @@ class Test_ipsecmb_ESNoff_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll): class Test_ipsecmb_ESNoff_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll): """ipsecmb ESNoff ARon AES-GCM-192/NONE IPSec test""" + def test_ipsec(self): """ipsecmb ESNoff ARon AES-GCM-192/NONE IPSec test""" self.run_test() @@ -1502,6 +1757,7 @@ class Test_ipsecmb_ESNoff_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll): class Test_ipsecmb_ESNoff_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll): """ipsecmb ESNoff ARon AES-GCM-256/NONE IPSec test""" + def test_ipsec(self): """ipsecmb ESNoff ARon AES-GCM-256/NONE IPSec test""" self.run_test() @@ -1509,6 +1765,7 @@ class Test_ipsecmb_ESNoff_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll): class Test_ipsecmb_ESNoff_ARon_AES_CBC_128_MD5_96(RunTestIpsecEspAll): """ipsecmb ESNoff ARon AES-CBC-128/MD5-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNoff ARon AES-CBC-128/MD5-96 IPSec test""" self.run_test() @@ -1516,6 +1773,7 @@ class Test_ipsecmb_ESNoff_ARon_AES_CBC_128_MD5_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNoff_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNoff ARon AES-CBC-192/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNoff ARon AES-CBC-192/SHA1-96 IPSec test""" self.run_test() @@ -1523,6 +1781,7 @@ class Test_ipsecmb_ESNoff_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNoff_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNoff ARon AES-CBC-256/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNoff ARon AES-CBC-256/SHA1-96 IPSec test""" self.run_test() @@ -1530,6 +1789,7 @@ class Test_ipsecmb_ESNoff_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNoff_ARon_3DES_CBC_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNoff ARon 3DES-CBC/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNoff ARon 3DES-CBC/SHA1-96 IPSec test""" self.run_test() @@ -1537,6 +1797,7 @@ class Test_ipsecmb_ESNoff_ARon_3DES_CBC_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNoff_ARon_NONE_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNoff ARon NONE/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNoff ARon NONE/SHA1-96 IPSec test""" self.run_test() @@ -1544,6 +1805,7 @@ class Test_ipsecmb_ESNoff_ARon_NONE_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNoff_ARon_AES_CTR_128_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNoff ARon AES-CTR-128/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNoff ARon AES-CTR-128/SHA1-96 IPSec test""" self.run_test() @@ -1551,6 +1813,7 @@ class Test_ipsecmb_ESNoff_ARon_AES_CTR_128_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNoff_ARon_AES_CTR_192_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNoff ARon AES-CTR-192/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNoff ARon AES-CTR-192/SHA1-96 IPSec test""" self.run_test() @@ -1558,6 +1821,7 @@ class Test_ipsecmb_ESNoff_ARon_AES_CTR_192_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNoff_ARon_AES_CTR_256_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNoff ARon AES-CTR-256/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNoff ARon AES-CTR-256/SHA1-96 IPSec test""" self.run_test() @@ -1565,6 +1829,7 @@ class Test_ipsecmb_ESNoff_ARon_AES_CTR_256_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNoff_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll): """ipsecmb ESNoff ARoff AES-GCM-128/NONE IPSec test""" + def test_ipsec(self): """ipsecmb ESNoff ARoff AES-GCM-128/NONE IPSec test""" self.run_test() @@ -1572,6 +1837,7 @@ class Test_ipsecmb_ESNoff_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll): class Test_ipsecmb_ESNoff_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll): """ipsecmb ESNoff ARoff AES-GCM-192/NONE IPSec test""" + def test_ipsec(self): """ipsecmb ESNoff ARoff AES-GCM-192/NONE IPSec test""" self.run_test() @@ -1579,6 +1845,7 @@ class Test_ipsecmb_ESNoff_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll): class Test_ipsecmb_ESNoff_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll): """ipsecmb ESNoff ARoff AES-GCM-256/NONE IPSec test""" + def test_ipsec(self): """ipsecmb ESNoff ARoff AES-GCM-256/NONE IPSec test""" self.run_test() @@ -1586,6 +1853,7 @@ class Test_ipsecmb_ESNoff_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll): class Test_ipsecmb_ESNoff_ARoff_AES_CBC_128_MD5_96(RunTestIpsecEspAll): """ipsecmb ESNoff ARoff AES-CBC-128/MD5-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNoff ARoff AES-CBC-128/MD5-96 IPSec test""" self.run_test() @@ -1593,6 +1861,7 @@ class Test_ipsecmb_ESNoff_ARoff_AES_CBC_128_MD5_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNoff_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNoff ARoff AES-CBC-192/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNoff ARoff AES-CBC-192/SHA1-96 IPSec test""" self.run_test() @@ -1600,6 +1869,7 @@ class Test_ipsecmb_ESNoff_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNoff_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNoff ARoff AES-CBC-256/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNoff ARoff AES-CBC-256/SHA1-96 IPSec test""" self.run_test() @@ -1607,6 +1877,7 @@ class Test_ipsecmb_ESNoff_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNoff_ARoff_3DES_CBC_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNoff ARoff 3DES-CBC/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNoff ARoff 3DES-CBC/SHA1-96 IPSec test""" self.run_test() @@ -1614,6 +1885,7 @@ class Test_ipsecmb_ESNoff_ARoff_3DES_CBC_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNoff_ARoff_NONE_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNoff ARoff NONE/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNoff ARoff NONE/SHA1-96 IPSec test""" self.run_test() @@ -1621,6 +1893,7 @@ class Test_ipsecmb_ESNoff_ARoff_NONE_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNoff_ARoff_AES_CTR_128_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNoff ARoff AES-CTR-128/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNoff ARoff AES-CTR-128/SHA1-96 IPSec test""" self.run_test() @@ -1628,6 +1901,7 @@ class Test_ipsecmb_ESNoff_ARoff_AES_CTR_128_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNoff_ARoff_AES_CTR_192_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNoff ARoff AES-CTR-192/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNoff ARoff AES-CTR-192/SHA1-96 IPSec test""" self.run_test() @@ -1635,6 +1909,7 @@ class Test_ipsecmb_ESNoff_ARoff_AES_CTR_192_SHA1_96(RunTestIpsecEspAll): class Test_ipsecmb_ESNoff_ARoff_AES_CTR_256_SHA1_96(RunTestIpsecEspAll): """ipsecmb ESNoff ARoff AES-CTR-256/SHA1-96 IPSec test""" + def test_ipsec(self): """ipsecmb ESNoff ARoff AES-CTR-256/SHA1-96 IPSec test""" self.run_test() @@ -1642,6 +1917,7 @@ class Test_ipsecmb_ESNoff_ARoff_AES_CTR_256_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNon_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll): """openssl ESNon ARon AES-GCM-128/NONE IPSec test""" + def test_ipsec(self): """openssl ESNon ARon AES-GCM-128/NONE IPSec test""" self.run_test() @@ -1649,6 +1925,7 @@ class Test_openssl_ESNon_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll): class Test_openssl_ESNon_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll): """openssl ESNon ARon AES-GCM-192/NONE IPSec test""" + def test_ipsec(self): """openssl ESNon ARon AES-GCM-192/NONE IPSec test""" self.run_test() @@ -1656,6 +1933,7 @@ class Test_openssl_ESNon_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll): class Test_openssl_ESNon_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll): """openssl ESNon ARon AES-GCM-256/NONE IPSec test""" + def test_ipsec(self): """openssl ESNon ARon AES-GCM-256/NONE IPSec test""" self.run_test() @@ -1663,6 +1941,7 @@ class Test_openssl_ESNon_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll): class Test_openssl_ESNon_ARon_AES_CBC_128_MD5_96(RunTestIpsecEspAll): """openssl ESNon ARon AES-CBC-128/MD5-96 IPSec test""" + def test_ipsec(self): """openssl ESNon ARon AES-CBC-128/MD5-96 IPSec test""" self.run_test() @@ -1670,6 +1949,7 @@ class Test_openssl_ESNon_ARon_AES_CBC_128_MD5_96(RunTestIpsecEspAll): class Test_openssl_ESNon_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): """openssl ESNon ARon AES-CBC-192/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNon ARon AES-CBC-192/SHA1-96 IPSec test""" self.run_test() @@ -1677,6 +1957,7 @@ class Test_openssl_ESNon_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNon_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): """openssl ESNon ARon AES-CBC-256/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNon ARon AES-CBC-256/SHA1-96 IPSec test""" self.run_test() @@ -1684,6 +1965,7 @@ class Test_openssl_ESNon_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNon_ARon_3DES_CBC_SHA1_96(RunTestIpsecEspAll): """openssl ESNon ARon 3DES-CBC/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNon ARon 3DES-CBC/SHA1-96 IPSec test""" self.run_test() @@ -1691,6 +1973,7 @@ class Test_openssl_ESNon_ARon_3DES_CBC_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNon_ARon_NONE_SHA1_96(RunTestIpsecEspAll): """openssl ESNon ARon NONE/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNon ARon NONE/SHA1-96 IPSec test""" self.run_test() @@ -1698,6 +1981,7 @@ class Test_openssl_ESNon_ARon_NONE_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNon_ARon_AES_CTR_128_SHA1_96(RunTestIpsecEspAll): """openssl ESNon ARon AES-CTR-128/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNon ARon AES-CTR-128/SHA1-96 IPSec test""" self.run_test() @@ -1705,6 +1989,7 @@ class Test_openssl_ESNon_ARon_AES_CTR_128_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNon_ARon_AES_CTR_192_SHA1_96(RunTestIpsecEspAll): """openssl ESNon ARon AES-CTR-192/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNon ARon AES-CTR-192/SHA1-96 IPSec test""" self.run_test() @@ -1712,6 +1997,7 @@ class Test_openssl_ESNon_ARon_AES_CTR_192_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNon_ARon_AES_CTR_256_SHA1_96(RunTestIpsecEspAll): """openssl ESNon ARon AES-CTR-256/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNon ARon AES-CTR-256/SHA1-96 IPSec test""" self.run_test() @@ -1719,6 +2005,7 @@ class Test_openssl_ESNon_ARon_AES_CTR_256_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNon_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll): """openssl ESNon ARoff AES-GCM-128/NONE IPSec test""" + def test_ipsec(self): """openssl ESNon ARoff AES-GCM-128/NONE IPSec test""" self.run_test() @@ -1726,6 +2013,7 @@ class Test_openssl_ESNon_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll): class Test_openssl_ESNon_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll): """openssl ESNon ARoff AES-GCM-192/NONE IPSec test""" + def test_ipsec(self): """openssl ESNon ARoff AES-GCM-192/NONE IPSec test""" self.run_test() @@ -1733,6 +2021,7 @@ class Test_openssl_ESNon_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll): class Test_openssl_ESNon_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll): """openssl ESNon ARoff AES-GCM-256/NONE IPSec test""" + def test_ipsec(self): """openssl ESNon ARoff AES-GCM-256/NONE IPSec test""" self.run_test() @@ -1740,6 +2029,7 @@ class Test_openssl_ESNon_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll): class Test_openssl_ESNon_ARoff_AES_CBC_128_MD5_96(RunTestIpsecEspAll): """openssl ESNon ARoff AES-CBC-128/MD5-96 IPSec test""" + def test_ipsec(self): """openssl ESNon ARoff AES-CBC-128/MD5-96 IPSec test""" self.run_test() @@ -1747,6 +2037,7 @@ class Test_openssl_ESNon_ARoff_AES_CBC_128_MD5_96(RunTestIpsecEspAll): class Test_openssl_ESNon_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): """openssl ESNon ARoff AES-CBC-192/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNon ARoff AES-CBC-192/SHA1-96 IPSec test""" self.run_test() @@ -1754,6 +2045,7 @@ class Test_openssl_ESNon_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNon_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): """openssl ESNon ARoff AES-CBC-256/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNon ARoff AES-CBC-256/SHA1-96 IPSec test""" self.run_test() @@ -1761,6 +2053,7 @@ class Test_openssl_ESNon_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNon_ARoff_3DES_CBC_SHA1_96(RunTestIpsecEspAll): """openssl ESNon ARoff 3DES-CBC/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNon ARoff 3DES-CBC/SHA1-96 IPSec test""" self.run_test() @@ -1768,6 +2061,7 @@ class Test_openssl_ESNon_ARoff_3DES_CBC_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNon_ARoff_NONE_SHA1_96(RunTestIpsecEspAll): """openssl ESNon ARoff NONE/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNon ARoff NONE/SHA1-96 IPSec test""" self.run_test() @@ -1775,6 +2069,7 @@ class Test_openssl_ESNon_ARoff_NONE_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNon_ARoff_AES_CTR_128_SHA1_96(RunTestIpsecEspAll): """openssl ESNon ARoff AES-CTR-128/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNon ARoff AES-CTR-128/SHA1-96 IPSec test""" self.run_test() @@ -1782,6 +2077,7 @@ class Test_openssl_ESNon_ARoff_AES_CTR_128_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNon_ARoff_AES_CTR_192_SHA1_96(RunTestIpsecEspAll): """openssl ESNon ARoff AES-CTR-192/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNon ARoff AES-CTR-192/SHA1-96 IPSec test""" self.run_test() @@ -1789,6 +2085,7 @@ class Test_openssl_ESNon_ARoff_AES_CTR_192_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNon_ARoff_AES_CTR_256_SHA1_96(RunTestIpsecEspAll): """openssl ESNon ARoff AES-CTR-256/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNon ARoff AES-CTR-256/SHA1-96 IPSec test""" self.run_test() @@ -1796,6 +2093,7 @@ class Test_openssl_ESNon_ARoff_AES_CTR_256_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNoff_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll): """openssl ESNoff ARon AES-GCM-128/NONE IPSec test""" + def test_ipsec(self): """openssl ESNoff ARon AES-GCM-128/NONE IPSec test""" self.run_test() @@ -1803,6 +2101,7 @@ class Test_openssl_ESNoff_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll): class Test_openssl_ESNoff_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll): """openssl ESNoff ARon AES-GCM-192/NONE IPSec test""" + def test_ipsec(self): """openssl ESNoff ARon AES-GCM-192/NONE IPSec test""" self.run_test() @@ -1810,6 +2109,7 @@ class Test_openssl_ESNoff_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll): class Test_openssl_ESNoff_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll): """openssl ESNoff ARon AES-GCM-256/NONE IPSec test""" + def test_ipsec(self): """openssl ESNoff ARon AES-GCM-256/NONE IPSec test""" self.run_test() @@ -1817,6 +2117,7 @@ class Test_openssl_ESNoff_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll): class Test_openssl_ESNoff_ARon_AES_CBC_128_MD5_96(RunTestIpsecEspAll): """openssl ESNoff ARon AES-CBC-128/MD5-96 IPSec test""" + def test_ipsec(self): """openssl ESNoff ARon AES-CBC-128/MD5-96 IPSec test""" self.run_test() @@ -1824,6 +2125,7 @@ class Test_openssl_ESNoff_ARon_AES_CBC_128_MD5_96(RunTestIpsecEspAll): class Test_openssl_ESNoff_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): """openssl ESNoff ARon AES-CBC-192/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNoff ARon AES-CBC-192/SHA1-96 IPSec test""" self.run_test() @@ -1831,6 +2133,7 @@ class Test_openssl_ESNoff_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNoff_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): """openssl ESNoff ARon AES-CBC-256/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNoff ARon AES-CBC-256/SHA1-96 IPSec test""" self.run_test() @@ -1838,6 +2141,7 @@ class Test_openssl_ESNoff_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNoff_ARon_3DES_CBC_SHA1_96(RunTestIpsecEspAll): """openssl ESNoff ARon 3DES-CBC/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNoff ARon 3DES-CBC/SHA1-96 IPSec test""" self.run_test() @@ -1845,6 +2149,7 @@ class Test_openssl_ESNoff_ARon_3DES_CBC_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNoff_ARon_NONE_SHA1_96(RunTestIpsecEspAll): """openssl ESNoff ARon NONE/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNoff ARon NONE/SHA1-96 IPSec test""" self.run_test() @@ -1852,6 +2157,7 @@ class Test_openssl_ESNoff_ARon_NONE_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNoff_ARon_AES_CTR_128_SHA1_96(RunTestIpsecEspAll): """openssl ESNoff ARon AES-CTR-128/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNoff ARon AES-CTR-128/SHA1-96 IPSec test""" self.run_test() @@ -1859,6 +2165,7 @@ class Test_openssl_ESNoff_ARon_AES_CTR_128_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNoff_ARon_AES_CTR_192_SHA1_96(RunTestIpsecEspAll): """openssl ESNoff ARon AES-CTR-192/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNoff ARon AES-CTR-192/SHA1-96 IPSec test""" self.run_test() @@ -1866,6 +2173,7 @@ class Test_openssl_ESNoff_ARon_AES_CTR_192_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNoff_ARon_AES_CTR_256_SHA1_96(RunTestIpsecEspAll): """openssl ESNoff ARon AES-CTR-256/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNoff ARon AES-CTR-256/SHA1-96 IPSec test""" self.run_test() @@ -1873,6 +2181,7 @@ class Test_openssl_ESNoff_ARon_AES_CTR_256_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNoff_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll): """openssl ESNoff ARoff AES-GCM-128/NONE IPSec test""" + def test_ipsec(self): """openssl ESNoff ARoff AES-GCM-128/NONE IPSec test""" self.run_test() @@ -1880,6 +2189,7 @@ class Test_openssl_ESNoff_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll): class Test_openssl_ESNoff_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll): """openssl ESNoff ARoff AES-GCM-192/NONE IPSec test""" + def test_ipsec(self): """openssl ESNoff ARoff AES-GCM-192/NONE IPSec test""" self.run_test() @@ -1887,6 +2197,7 @@ class Test_openssl_ESNoff_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll): class Test_openssl_ESNoff_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll): """openssl ESNoff ARoff AES-GCM-256/NONE IPSec test""" + def test_ipsec(self): """openssl ESNoff ARoff AES-GCM-256/NONE IPSec test""" self.run_test() @@ -1894,6 +2205,7 @@ class Test_openssl_ESNoff_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll): class Test_openssl_ESNoff_ARoff_AES_CBC_128_MD5_96(RunTestIpsecEspAll): """openssl ESNoff ARoff AES-CBC-128/MD5-96 IPSec test""" + def test_ipsec(self): """openssl ESNoff ARoff AES-CBC-128/MD5-96 IPSec test""" self.run_test() @@ -1901,6 +2213,7 @@ class Test_openssl_ESNoff_ARoff_AES_CBC_128_MD5_96(RunTestIpsecEspAll): class Test_openssl_ESNoff_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): """openssl ESNoff ARoff AES-CBC-192/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNoff ARoff AES-CBC-192/SHA1-96 IPSec test""" self.run_test() @@ -1908,6 +2221,7 @@ class Test_openssl_ESNoff_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNoff_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): """openssl ESNoff ARoff AES-CBC-256/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNoff ARoff AES-CBC-256/SHA1-96 IPSec test""" self.run_test() @@ -1915,6 +2229,7 @@ class Test_openssl_ESNoff_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNoff_ARoff_3DES_CBC_SHA1_96(RunTestIpsecEspAll): """openssl ESNoff ARoff 3DES-CBC/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNoff ARoff 3DES-CBC/SHA1-96 IPSec test""" self.run_test() @@ -1922,6 +2237,7 @@ class Test_openssl_ESNoff_ARoff_3DES_CBC_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNoff_ARoff_NONE_SHA1_96(RunTestIpsecEspAll): """openssl ESNoff ARoff NONE/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNoff ARoff NONE/SHA1-96 IPSec test""" self.run_test() @@ -1929,6 +2245,7 @@ class Test_openssl_ESNoff_ARoff_NONE_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNoff_ARoff_AES_CTR_128_SHA1_96(RunTestIpsecEspAll): """openssl ESNoff ARoff AES-CTR-128/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNoff ARoff AES-CTR-128/SHA1-96 IPSec test""" self.run_test() @@ -1936,6 +2253,7 @@ class Test_openssl_ESNoff_ARoff_AES_CTR_128_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNoff_ARoff_AES_CTR_192_SHA1_96(RunTestIpsecEspAll): """openssl ESNoff ARoff AES-CTR-192/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNoff ARoff AES-CTR-192/SHA1-96 IPSec test""" self.run_test() @@ -1943,6 +2261,7 @@ class Test_openssl_ESNoff_ARoff_AES_CTR_192_SHA1_96(RunTestIpsecEspAll): class Test_openssl_ESNoff_ARoff_AES_CTR_256_SHA1_96(RunTestIpsecEspAll): """openssl ESNoff ARoff AES-CTR-256/SHA1-96 IPSec test""" + def test_ipsec(self): """openssl ESNoff ARoff AES-CTR-256/SHA1-96 IPSec test""" self.run_test() @@ -1950,6 +2269,7 @@ class Test_openssl_ESNoff_ARoff_AES_CTR_256_SHA1_96(RunTestIpsecEspAll): class Test_async_ESNon_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll): """async ESNon ARon AES-GCM-128/NONE IPSec test""" + def test_ipsec(self): """async ESNon ARon AES-GCM-128/NONE IPSec test""" self.run_test() @@ -1957,6 +2277,7 @@ class Test_async_ESNon_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll): class Test_async_ESNon_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll): """async ESNon ARon AES-GCM-192/NONE IPSec test""" + def test_ipsec(self): """async ESNon ARon AES-GCM-192/NONE IPSec test""" self.run_test() @@ -1964,6 +2285,7 @@ class Test_async_ESNon_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll): class Test_async_ESNon_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll): """async ESNon ARon AES-GCM-256/NONE IPSec test""" + def test_ipsec(self): """async ESNon ARon AES-GCM-256/NONE IPSec test""" self.run_test() @@ -1971,6 +2293,7 @@ class Test_async_ESNon_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll): class Test_async_ESNon_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): """async ESNon ARon AES-CBC-192/SHA1-96 IPSec test""" + def test_ipsec(self): """async ESNon ARon AES-CBC-192/SHA1-96 IPSec test""" self.run_test() @@ -1978,6 +2301,7 @@ class Test_async_ESNon_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): class Test_async_ESNon_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): """async ESNon ARon AES-CBC-256/SHA1-96 IPSec test""" + def test_ipsec(self): """async ESNon ARon AES-CBC-256/SHA1-96 IPSec test""" self.run_test() @@ -1985,6 +2309,7 @@ class Test_async_ESNon_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): class Test_async_ESNon_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll): """async ESNon ARoff AES-GCM-128/NONE IPSec test""" + def test_ipsec(self): """async ESNon ARoff AES-GCM-128/NONE IPSec test""" self.run_test() @@ -1992,6 +2317,7 @@ class Test_async_ESNon_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll): class Test_async_ESNon_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll): """async ESNon ARoff AES-GCM-192/NONE IPSec test""" + def test_ipsec(self): """async ESNon ARoff AES-GCM-192/NONE IPSec test""" self.run_test() @@ -1999,6 +2325,7 @@ class Test_async_ESNon_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll): class Test_async_ESNon_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll): """async ESNon ARoff AES-GCM-256/NONE IPSec test""" + def test_ipsec(self): """async ESNon ARoff AES-GCM-256/NONE IPSec test""" self.run_test() @@ -2006,6 +2333,7 @@ class Test_async_ESNon_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll): class Test_async_ESNon_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): """async ESNon ARoff AES-CBC-192/SHA1-96 IPSec test""" + def test_ipsec(self): """async ESNon ARoff AES-CBC-192/SHA1-96 IPSec test""" self.run_test() @@ -2013,6 +2341,7 @@ class Test_async_ESNon_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): class Test_async_ESNon_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): """async ESNon ARoff AES-CBC-256/SHA1-96 IPSec test""" + def test_ipsec(self): """async ESNon ARoff AES-CBC-256/SHA1-96 IPSec test""" self.run_test() @@ -2020,6 +2349,7 @@ class Test_async_ESNon_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): class Test_async_ESNoff_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll): """async ESNoff ARon AES-GCM-128/NONE IPSec test""" + def test_ipsec(self): """async ESNoff ARon AES-GCM-128/NONE IPSec test""" self.run_test() @@ -2027,6 +2357,7 @@ class Test_async_ESNoff_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll): class Test_async_ESNoff_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll): """async ESNoff ARon AES-GCM-192/NONE IPSec test""" + def test_ipsec(self): """async ESNoff ARon AES-GCM-192/NONE IPSec test""" self.run_test() @@ -2034,6 +2365,7 @@ class Test_async_ESNoff_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll): class Test_async_ESNoff_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll): """async ESNoff ARon AES-GCM-256/NONE IPSec test""" + def test_ipsec(self): """async ESNoff ARon AES-GCM-256/NONE IPSec test""" self.run_test() @@ -2041,6 +2373,7 @@ class Test_async_ESNoff_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll): class Test_async_ESNoff_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): """async ESNoff ARon AES-CBC-192/SHA1-96 IPSec test""" + def test_ipsec(self): """async ESNoff ARon AES-CBC-192/SHA1-96 IPSec test""" self.run_test() @@ -2048,6 +2381,7 @@ class Test_async_ESNoff_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): class Test_async_ESNoff_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): """async ESNoff ARon AES-CBC-256/SHA1-96 IPSec test""" + def test_ipsec(self): """async ESNoff ARon AES-CBC-256/SHA1-96 IPSec test""" self.run_test() @@ -2055,6 +2389,7 @@ class Test_async_ESNoff_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): class Test_async_ESNoff_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll): """async ESNoff ARoff AES-GCM-128/NONE IPSec test""" + def test_ipsec(self): """async ESNoff ARoff AES-GCM-128/NONE IPSec test""" self.run_test() @@ -2062,6 +2397,7 @@ class Test_async_ESNoff_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll): class Test_async_ESNoff_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll): """async ESNoff ARoff AES-GCM-192/NONE IPSec test""" + def test_ipsec(self): """async ESNoff ARoff AES-GCM-192/NONE IPSec test""" self.run_test() @@ -2069,6 +2405,7 @@ class Test_async_ESNoff_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll): class Test_async_ESNoff_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll): """async ESNoff ARoff AES-GCM-256/NONE IPSec test""" + def test_ipsec(self): """async ESNoff ARoff AES-GCM-256/NONE IPSec test""" self.run_test() @@ -2076,6 +2413,7 @@ class Test_async_ESNoff_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll): class Test_async_ESNoff_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): """async ESNoff ARoff AES-CBC-192/SHA1-96 IPSec test""" + def test_ipsec(self): """async ESNoff ARoff AES-CBC-192/SHA1-96 IPSec test""" self.run_test() @@ -2083,6 +2421,7 @@ class Test_async_ESNoff_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll): class Test_async_ESNoff_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll): """async ESNoff ARoff AES-CBC-256/SHA1-96 IPSec test""" + def test_ipsec(self): """async ESNoff ARoff AES-CBC-256/SHA1-96 IPSec test""" self.run_test() diff --git a/test/test_ipsec_nat.py b/test/test_ipsec_nat.py index b7ccb2befdc..64a2725dda6 100644 --- a/test/test_ipsec_nat.py +++ b/test/test_ipsec_nat.py @@ -9,15 +9,14 @@ from scapy.layers.ipsec import SecurityAssociation, ESP from util import ppp, ppc from template_ipsec import TemplateIpsec -from vpp_ipsec import VppIpsecSA, VppIpsecSpd, VppIpsecSpdEntry,\ - VppIpsecSpdItfBinding +from vpp_ipsec import VppIpsecSA, VppIpsecSpd, VppIpsecSpdEntry, VppIpsecSpdItfBinding from vpp_ip_route import VppIpRoute, VppRoutePath from vpp_ip import DpoProto from vpp_papi import VppEnum class IPSecNATTestCase(TemplateIpsec): - """ IPSec/NAT + """IPSec/NAT TUNNEL MODE:: @@ -53,18 +52,19 @@ class IPSecNATTestCase(TemplateIpsec): self.tun_spd = VppIpsecSpd(self, self.tun_spd_id) self.tun_spd.add_vpp_config() - VppIpsecSpdItfBinding(self, self.tun_spd, - self.tun_if).add_vpp_config() + VppIpsecSpdItfBinding(self, self.tun_spd, self.tun_if).add_vpp_config() p = self.ipv4_params self.config_esp_tun(p) self.logger.info(self.vapi.ppcli("show ipsec all")) d = DpoProto.DPO_PROTO_IP6 if p.is_ipv6 else DpoProto.DPO_PROTO_IP4 - VppIpRoute(self, p.remote_tun_if_host, p.addr_len, - [VppRoutePath(self.tun_if.remote_addr[p.addr_type], - 0xffffffff, - proto=d)]).add_vpp_config() + VppIpRoute( + self, + p.remote_tun_if_host, + p.addr_len, + [VppRoutePath(self.tun_if.remote_addr[p.addr_type], 0xFFFFFFFF, proto=d)], + ).add_vpp_config() def tearDown(self): super(IPSecNATTestCase, self).tearDown() @@ -72,65 +72,84 @@ class IPSecNATTestCase(TemplateIpsec): def create_stream_plain(self, src_mac, dst_mac, src_ip, dst_ip): return [ # TCP - Ether(src=src_mac, dst=dst_mac) / - IP(src=src_ip, dst=dst_ip) / - TCP(sport=self.tcp_port_in, dport=20), + Ether(src=src_mac, dst=dst_mac) + / IP(src=src_ip, dst=dst_ip) + / TCP(sport=self.tcp_port_in, dport=20), # UDP - Ether(src=src_mac, dst=dst_mac) / - IP(src=src_ip, dst=dst_ip) / - UDP(sport=self.udp_port_in, dport=20), + Ether(src=src_mac, dst=dst_mac) + / IP(src=src_ip, dst=dst_ip) + / UDP(sport=self.udp_port_in, dport=20), # ICMP - Ether(src=src_mac, dst=dst_mac) / - IP(src=src_ip, dst=dst_ip) / - ICMP(id=self.icmp_id_in, type='echo-request') + Ether(src=src_mac, dst=dst_mac) + / IP(src=src_ip, dst=dst_ip) + / ICMP(id=self.icmp_id_in, type="echo-request"), ] def create_stream_encrypted(self, src_mac, dst_mac, src_ip, dst_ip, sa): return [ # TCP - Ether(src=src_mac, dst=dst_mac) / - sa.encrypt(IP(src=src_ip, dst=dst_ip) / - TCP(dport=self.tcp_port_out, sport=20)), + Ether(src=src_mac, dst=dst_mac) + / sa.encrypt( + IP(src=src_ip, dst=dst_ip) / TCP(dport=self.tcp_port_out, sport=20) + ), # UDP - Ether(src=src_mac, dst=dst_mac) / - sa.encrypt(IP(src=src_ip, dst=dst_ip) / - UDP(dport=self.udp_port_out, sport=20)), + Ether(src=src_mac, dst=dst_mac) + / sa.encrypt( + IP(src=src_ip, dst=dst_ip) / UDP(dport=self.udp_port_out, sport=20) + ), # ICMP - Ether(src=src_mac, dst=dst_mac) / - sa.encrypt(IP(src=src_ip, dst=dst_ip) / - ICMP(id=self.icmp_id_out, type='echo-request')) + Ether(src=src_mac, dst=dst_mac) + / sa.encrypt( + IP(src=src_ip, dst=dst_ip) + / ICMP(id=self.icmp_id_out, type="echo-request") + ), ] def verify_capture_plain(self, capture): for packet in capture: try: self.assert_packet_checksums_valid(packet) - self.assert_equal(packet[IP].src, self.tun_if.remote_ip4, - "decrypted packet source address") - self.assert_equal(packet[IP].dst, self.pg1.remote_ip4, - "decrypted packet destination address") + self.assert_equal( + packet[IP].src, + self.tun_if.remote_ip4, + "decrypted packet source address", + ) + self.assert_equal( + packet[IP].dst, + self.pg1.remote_ip4, + "decrypted packet destination address", + ) if packet.haslayer(TCP): self.assertFalse( packet.haslayer(UDP), - "unexpected UDP header in decrypted packet") - self.assert_equal(packet[TCP].dport, self.tcp_port_in, - "decrypted packet TCP destination port") + "unexpected UDP header in decrypted packet", + ) + self.assert_equal( + packet[TCP].dport, + self.tcp_port_in, + "decrypted packet TCP destination port", + ) elif packet.haslayer(UDP): if packet[UDP].payload: self.assertFalse( packet[UDP][1].haslayer(UDP), - "unexpected UDP header in decrypted packet") - self.assert_equal(packet[UDP].dport, self.udp_port_in, - "decrypted packet UDP destination port") + "unexpected UDP header in decrypted packet", + ) + self.assert_equal( + packet[UDP].dport, + self.udp_port_in, + "decrypted packet UDP destination port", + ) else: self.assertFalse( packet.haslayer(UDP), - "unexpected UDP header in decrypted packet") - self.assert_equal(packet[ICMP].id, self.icmp_id_in, - "decrypted packet ICMP ID") + "unexpected UDP header in decrypted packet", + ) + self.assert_equal( + packet[ICMP].id, self.icmp_id_in, "decrypted packet ICMP ID" + ) except Exception: - self.logger.error( - ppp("Unexpected or invalid plain packet:", packet)) + self.logger.error(ppp("Unexpected or invalid plain packet:", packet)) raise def verify_capture_encrypted(self, capture, sa): @@ -139,19 +158,25 @@ class IPSecNATTestCase(TemplateIpsec): copy = packet.__class__(scapy.compat.raw(packet)) del copy[UDP].len copy = packet.__class__(scapy.compat.raw(copy)) - self.assert_equal(packet[UDP].len, copy[UDP].len, - "UDP header length") + self.assert_equal(packet[UDP].len, copy[UDP].len, "UDP header length") self.assert_packet_checksums_valid(packet) self.assertIn(ESP, packet[IP]) decrypt_pkt = sa.decrypt(packet[IP]) self.assert_packet_checksums_valid(decrypt_pkt) - self.assert_equal(decrypt_pkt[IP].src, self.pg1.remote_ip4, - "encrypted packet source address") - self.assert_equal(decrypt_pkt[IP].dst, self.tun_if.remote_ip4, - "encrypted packet destination address") + self.assert_equal( + decrypt_pkt[IP].src, + self.pg1.remote_ip4, + "encrypted packet source address", + ) + self.assert_equal( + decrypt_pkt[IP].dst, + self.tun_if.remote_ip4, + "encrypted packet destination address", + ) except Exception: self.logger.error( - ppp("Unexpected or invalid encrypted packet:", packet)) + ppp("Unexpected or invalid encrypted packet:", packet) + ) raise def config_esp_tun(self, params): @@ -166,104 +191,153 @@ class IPSecNATTestCase(TemplateIpsec): crypt_key = params.crypt_key addr_any = params.addr_any addr_bcast = params.addr_bcast - flags = (VppEnum.vl_api_ipsec_sad_flags_t. - IPSEC_API_SAD_FLAG_UDP_ENCAP) + flags = VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_UDP_ENCAP e = VppEnum.vl_api_ipsec_spd_action_t - VppIpsecSA(self, scapy_tun_sa_id, scapy_tun_spi, - auth_algo_vpp_id, auth_key, - crypt_algo_vpp_id, crypt_key, - self.vpp_esp_protocol, - self.pg1.remote_addr[addr_type], - self.tun_if.remote_addr[addr_type], - flags=flags).add_vpp_config() - VppIpsecSA(self, vpp_tun_sa_id, vpp_tun_spi, - auth_algo_vpp_id, auth_key, - crypt_algo_vpp_id, crypt_key, - self.vpp_esp_protocol, - self.tun_if.remote_addr[addr_type], - self.pg1.remote_addr[addr_type], - flags=flags).add_vpp_config() + VppIpsecSA( + self, + scapy_tun_sa_id, + scapy_tun_spi, + auth_algo_vpp_id, + auth_key, + crypt_algo_vpp_id, + crypt_key, + self.vpp_esp_protocol, + self.pg1.remote_addr[addr_type], + self.tun_if.remote_addr[addr_type], + flags=flags, + ).add_vpp_config() + VppIpsecSA( + self, + vpp_tun_sa_id, + vpp_tun_spi, + auth_algo_vpp_id, + auth_key, + crypt_algo_vpp_id, + crypt_key, + self.vpp_esp_protocol, + self.tun_if.remote_addr[addr_type], + self.pg1.remote_addr[addr_type], + flags=flags, + ).add_vpp_config() - VppIpsecSpdEntry(self, self.tun_spd, scapy_tun_sa_id, - addr_any, addr_bcast, - addr_any, addr_bcast, - socket.IPPROTO_ESP).add_vpp_config() - VppIpsecSpdEntry(self, self.tun_spd, scapy_tun_sa_id, - addr_any, addr_bcast, - addr_any, addr_bcast, - socket.IPPROTO_ESP, - is_outbound=0).add_vpp_config() - VppIpsecSpdEntry(self, self.tun_spd, scapy_tun_sa_id, - addr_any, addr_bcast, - addr_any, addr_bcast, - socket.IPPROTO_UDP, - remote_port_start=4500, - remote_port_stop=4500).add_vpp_config() - VppIpsecSpdEntry(self, self.tun_spd, scapy_tun_sa_id, - addr_any, addr_bcast, - addr_any, addr_bcast, - socket.IPPROTO_UDP, - remote_port_start=4500, - remote_port_stop=4500, - is_outbound=0).add_vpp_config() - VppIpsecSpdEntry(self, self.tun_spd, vpp_tun_sa_id, - self.tun_if.remote_addr[addr_type], - self.tun_if.remote_addr[addr_type], - self.pg1.remote_addr[addr_type], - self.pg1.remote_addr[addr_type], - 0, priority=10, - policy=e.IPSEC_API_SPD_ACTION_PROTECT, - is_outbound=0).add_vpp_config() - VppIpsecSpdEntry(self, self.tun_spd, scapy_tun_sa_id, - self.pg1.remote_addr[addr_type], - self.pg1.remote_addr[addr_type], - self.tun_if.remote_addr[addr_type], - self.tun_if.remote_addr[addr_type], - 0, policy=e.IPSEC_API_SPD_ACTION_PROTECT, - priority=10).add_vpp_config() + VppIpsecSpdEntry( + self, + self.tun_spd, + scapy_tun_sa_id, + addr_any, + addr_bcast, + addr_any, + addr_bcast, + socket.IPPROTO_ESP, + ).add_vpp_config() + VppIpsecSpdEntry( + self, + self.tun_spd, + scapy_tun_sa_id, + addr_any, + addr_bcast, + addr_any, + addr_bcast, + socket.IPPROTO_ESP, + is_outbound=0, + ).add_vpp_config() + VppIpsecSpdEntry( + self, + self.tun_spd, + scapy_tun_sa_id, + addr_any, + addr_bcast, + addr_any, + addr_bcast, + socket.IPPROTO_UDP, + remote_port_start=4500, + remote_port_stop=4500, + ).add_vpp_config() + VppIpsecSpdEntry( + self, + self.tun_spd, + scapy_tun_sa_id, + addr_any, + addr_bcast, + addr_any, + addr_bcast, + socket.IPPROTO_UDP, + remote_port_start=4500, + remote_port_stop=4500, + is_outbound=0, + ).add_vpp_config() + VppIpsecSpdEntry( + self, + self.tun_spd, + vpp_tun_sa_id, + self.tun_if.remote_addr[addr_type], + self.tun_if.remote_addr[addr_type], + self.pg1.remote_addr[addr_type], + self.pg1.remote_addr[addr_type], + 0, + priority=10, + policy=e.IPSEC_API_SPD_ACTION_PROTECT, + is_outbound=0, + ).add_vpp_config() + VppIpsecSpdEntry( + self, + self.tun_spd, + scapy_tun_sa_id, + self.pg1.remote_addr[addr_type], + self.pg1.remote_addr[addr_type], + self.tun_if.remote_addr[addr_type], + self.tun_if.remote_addr[addr_type], + 0, + policy=e.IPSEC_API_SPD_ACTION_PROTECT, + priority=10, + ).add_vpp_config() def test_ipsec_nat_tun(self): - """ IPSec/NAT tunnel test case """ + """IPSec/NAT tunnel test case""" p = self.ipv4_params - scapy_tun_sa = SecurityAssociation(ESP, spi=p.scapy_tun_spi, - crypt_algo=p.crypt_algo, - crypt_key=p.crypt_key, - auth_algo=p.auth_algo, - auth_key=p.auth_key, - tunnel_header=IP( - src=self.pg1.remote_ip4, - dst=self.tun_if.remote_ip4), - nat_t_header=UDP( - sport=4500, - dport=4500)) + scapy_tun_sa = SecurityAssociation( + ESP, + spi=p.scapy_tun_spi, + crypt_algo=p.crypt_algo, + crypt_key=p.crypt_key, + auth_algo=p.auth_algo, + auth_key=p.auth_key, + tunnel_header=IP(src=self.pg1.remote_ip4, dst=self.tun_if.remote_ip4), + nat_t_header=UDP(sport=4500, dport=4500), + ) # in2out - from private network to public pkts = self.create_stream_plain( - self.pg1.remote_mac, self.pg1.local_mac, - self.pg1.remote_ip4, self.tun_if.remote_ip4) + self.pg1.remote_mac, + self.pg1.local_mac, + self.pg1.remote_ip4, + self.tun_if.remote_ip4, + ) self.pg1.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() capture = self.tun_if.get_capture(len(pkts)) self.verify_capture_encrypted(capture, scapy_tun_sa) - vpp_tun_sa = SecurityAssociation(ESP, - spi=p.vpp_tun_spi, - crypt_algo=p.crypt_algo, - crypt_key=p.crypt_key, - auth_algo=p.auth_algo, - auth_key=p.auth_key, - tunnel_header=IP( - src=self.tun_if.remote_ip4, - dst=self.pg1.remote_ip4), - nat_t_header=UDP( - sport=4500, - dport=4500)) + vpp_tun_sa = SecurityAssociation( + ESP, + spi=p.vpp_tun_spi, + crypt_algo=p.crypt_algo, + crypt_key=p.crypt_key, + auth_algo=p.auth_algo, + auth_key=p.auth_key, + tunnel_header=IP(src=self.tun_if.remote_ip4, dst=self.pg1.remote_ip4), + nat_t_header=UDP(sport=4500, dport=4500), + ) # out2in - from public network to private pkts = self.create_stream_encrypted( - self.tun_if.remote_mac, self.tun_if.local_mac, - self.tun_if.remote_ip4, self.pg1.remote_ip4, vpp_tun_sa) + self.tun_if.remote_mac, + self.tun_if.local_mac, + self.tun_if.remote_ip4, + self.pg1.remote_ip4, + vpp_tun_sa, + ) self.logger.info(ppc("Sending packets:", pkts)) self.tun_if.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) diff --git a/test/test_ipsec_spd_flow_cache_input.py b/test/test_ipsec_spd_flow_cache_input.py index 2d70d1540b8..02ecb5625ce 100644 --- a/test/test_ipsec_spd_flow_cache_input.py +++ b/test/test_ipsec_spd_flow_cache_input.py @@ -12,16 +12,14 @@ class SpdFlowCacheInbound(SpdFlowCacheTemplate): @classmethod def setUpConstants(cls): super(SpdFlowCacheInbound, cls).setUpConstants() - cls.vpp_cmdline.extend(["ipsec", "{", - "ipv4-inbound-spd-flow-cache on", - "}"]) - cls.logger.info("VPP modified cmdline is %s" % " " - .join(cls.vpp_cmdline)) + cls.vpp_cmdline.extend(["ipsec", "{", "ipv4-inbound-spd-flow-cache on", "}"]) + cls.logger.info("VPP modified cmdline is %s" % " ".join(cls.vpp_cmdline)) class IPSec4SpdTestCaseBypass(SpdFlowCacheInbound): """ IPSec/IPv4 inbound: Policy mode test case with flow cache \ (add bypass)""" + def test_ipsec_spd_inbound_bypass(self): # In this test case, packets in IPv4 FWD path are configured # to go through IPSec inbound SPD policy lookup. @@ -42,16 +40,34 @@ class IPSec4SpdTestCaseBypass(SpdFlowCacheInbound): # bypass rule should take precedence over discard rule, # even though it's lower priority policy_0 = self.spd_add_rem_policy( # inbound, priority 10 - 1, self.pg1, self.pg0, socket.IPPROTO_UDP, - is_out=0, priority=10, policy_type="bypass") + 1, + self.pg1, + self.pg0, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="bypass", + ) policy_1 = self.spd_add_rem_policy( # inbound, priority 15 - 1, self.pg1, self.pg0, socket.IPPROTO_UDP, - is_out=0, priority=15, policy_type="discard") + 1, + self.pg1, + self.pg0, + socket.IPPROTO_UDP, + is_out=0, + priority=15, + policy_type="discard", + ) # create output rule so we can capture forwarded packets policy_2 = self.spd_add_rem_policy( # outbound, priority 10 - 1, self.pg0, self.pg1, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="bypass") + 1, + self.pg0, + self.pg1, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="bypass", + ) # check flow cache is empty before sending traffic self.verify_num_inbound_flow_cache_entries(0) @@ -85,6 +101,7 @@ class IPSec4SpdTestCaseBypass(SpdFlowCacheInbound): class IPSec4SpdTestCaseDiscard(SpdFlowCacheInbound): """ IPSec/IPv4 inbound: Policy mode test case with flow cache \ (add discard)""" + def test_ipsec_spd_inbound_discard(self): # In this test case, packets in IPv4 FWD path are configured # to go through IPSec inbound SPD policy lookup. @@ -96,13 +113,25 @@ class IPSec4SpdTestCaseDiscard(SpdFlowCacheInbound): # create input rule policy_0 = self.spd_add_rem_policy( # inbound, priority 10 - 1, self.pg1, self.pg0, socket.IPPROTO_UDP, - is_out=0, priority=10, policy_type="discard") + 1, + self.pg1, + self.pg0, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="discard", + ) # create output rule so we can capture forwarded packets policy_1 = self.spd_add_rem_policy( # outbound, priority 10 - 1, self.pg0, self.pg1, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="bypass") + 1, + self.pg0, + self.pg1, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="bypass", + ) # check flow cache is empty before sending traffic self.verify_num_inbound_flow_cache_entries(0) @@ -124,6 +153,7 @@ class IPSec4SpdTestCaseDiscard(SpdFlowCacheInbound): class IPSec4SpdTestCaseRemove(SpdFlowCacheInbound): """ IPSec/IPv4 inbound: Policy mode test case with flow cache \ (remove bypass)""" + def test_ipsec_spd_inbound_remove(self): # In this test case, packets in IPv4 FWD path are configured # to go through IPSec inbound SPD policy lookup. @@ -147,16 +177,34 @@ class IPSec4SpdTestCaseRemove(SpdFlowCacheInbound): # bypass rule should take precedence over discard rule, # even though it's lower priority policy_0 = self.spd_add_rem_policy( # inbound, priority 10 - 1, self.pg1, self.pg0, socket.IPPROTO_UDP, - is_out=0, priority=10, policy_type="bypass") + 1, + self.pg1, + self.pg0, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="bypass", + ) policy_1 = self.spd_add_rem_policy( # inbound, priority 15 - 1, self.pg1, self.pg0, socket.IPPROTO_UDP, - is_out=0, priority=15, policy_type="discard") + 1, + self.pg1, + self.pg0, + socket.IPPROTO_UDP, + is_out=0, + priority=15, + policy_type="discard", + ) # create output rule so we can capture forwarded packets policy_2 = self.spd_add_rem_policy( # outbound, priority 10 - 1, self.pg0, self.pg1, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="bypass") + 1, + self.pg0, + self.pg1, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="bypass", + ) # check flow cache is empty before sending traffic self.verify_num_inbound_flow_cache_entries(0) @@ -188,9 +236,15 @@ class IPSec4SpdTestCaseRemove(SpdFlowCacheInbound): # remove the input bypass rule self.spd_add_rem_policy( # inbound, priority 10 - 1, self.pg1, self.pg0, socket.IPPROTO_UDP, - is_out=0, priority=10, policy_type="bypass", - remove=True) + 1, + self.pg1, + self.pg0, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="bypass", + remove=True, + ) # verify flow cache counter has been reset by rule removal self.verify_num_inbound_flow_cache_entries(0) @@ -213,6 +267,7 @@ class IPSec4SpdTestCaseRemove(SpdFlowCacheInbound): class IPSec4SpdTestCaseReadd(SpdFlowCacheInbound): """ IPSec/IPv4 inbound: Policy mode test case with flow cache \ (add, remove, re-add bypass)""" + def test_ipsec_spd_inbound_readd(self): # In this test case, packets in IPv4 FWD path are configured # to go through IPSec inbound SPD policy lookup. @@ -239,16 +294,34 @@ class IPSec4SpdTestCaseReadd(SpdFlowCacheInbound): # bypass rule should take precedence over discard rule, # even though it's lower priority policy_0 = self.spd_add_rem_policy( # inbound, priority 10 - 1, self.pg1, self.pg0, socket.IPPROTO_UDP, - is_out=0, priority=10, policy_type="bypass") + 1, + self.pg1, + self.pg0, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="bypass", + ) policy_1 = self.spd_add_rem_policy( # inbound, priority 15 - 1, self.pg1, self.pg0, socket.IPPROTO_UDP, - is_out=0, priority=15, policy_type="discard") + 1, + self.pg1, + self.pg0, + socket.IPPROTO_UDP, + is_out=0, + priority=15, + policy_type="discard", + ) # create output rule so we can capture forwarded packets policy_2 = self.spd_add_rem_policy( # outbound, priority 10 - 1, self.pg0, self.pg1, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="bypass") + 1, + self.pg0, + self.pg1, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="bypass", + ) # check flow cache is empty before sending traffic self.verify_num_inbound_flow_cache_entries(0) @@ -280,9 +353,15 @@ class IPSec4SpdTestCaseReadd(SpdFlowCacheInbound): # remove the input bypass rule self.spd_add_rem_policy( # inbound, priority 10 - 1, self.pg1, self.pg0, socket.IPPROTO_UDP, - is_out=0, priority=10, policy_type="bypass", - remove=True) + 1, + self.pg1, + self.pg0, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="bypass", + remove=True, + ) # verify flow cache counter has been reset by rule removal self.verify_num_inbound_flow_cache_entries(0) @@ -303,8 +382,14 @@ class IPSec4SpdTestCaseReadd(SpdFlowCacheInbound): # readd the input bypass rule policy_0 = self.spd_add_rem_policy( # inbound, priority 10 - 1, self.pg1, self.pg0, socket.IPPROTO_UDP, - is_out=0, priority=10, policy_type="bypass") + 1, + self.pg1, + self.pg0, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="bypass", + ) # verify flow cache counter has been reset by rule addition self.verify_num_inbound_flow_cache_entries(0) @@ -327,7 +412,7 @@ class IPSec4SpdTestCaseReadd(SpdFlowCacheInbound): # verify all policies matched the expected number of times self.verify_policy_match(pkt_count, policy_0) self.verify_policy_match(pkt_count, policy_1) - self.verify_policy_match(pkt_count*2, policy_2) + self.verify_policy_match(pkt_count * 2, policy_2) # by readding the bypass rule, we reset the flow cache # we only expect the bypass rule to now be in the flow cache self.verify_num_inbound_flow_cache_entries(1) @@ -336,6 +421,7 @@ class IPSec4SpdTestCaseReadd(SpdFlowCacheInbound): class IPSec4SpdTestCaseMultiple(SpdFlowCacheInbound): """ IPSec/IPv4 inbound: Policy mode test case with flow cache \ (multiple interfaces, multiple rules)""" + def test_ipsec_spd_inbound_multiple(self): # In this test case, packets in IPv4 FWD path are configured to go # through IPSec outbound SPD policy lookup. @@ -353,23 +439,47 @@ class IPSec4SpdTestCaseMultiple(SpdFlowCacheInbound): # add input rules on all interfaces # pg0 -> pg1 policy_0 = self.spd_add_rem_policy( # inbound, priority 10 - 1, self.pg1, self.pg0, socket.IPPROTO_UDP, - is_out=0, priority=10, policy_type="bypass") + 1, + self.pg1, + self.pg0, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="bypass", + ) # pg1 -> pg2 policy_1 = self.spd_add_rem_policy( # inbound, priority 10 - 1, self.pg2, self.pg1, socket.IPPROTO_UDP, - is_out=0, priority=10, policy_type="bypass") + 1, + self.pg2, + self.pg1, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="bypass", + ) # pg2 -> pg0 policy_2 = self.spd_add_rem_policy( # inbound, priority 10 - 1, self.pg0, self.pg2, socket.IPPROTO_UDP, - is_out=0, priority=10, policy_type="discard") + 1, + self.pg0, + self.pg2, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="discard", + ) # create output rules covering the the full ip range # 0.0.0.0 -> 255.255.255.255, so we can capture forwarded packets policy_3 = self.spd_add_rem_policy( # outbound, priority 10 - 1, self.pg0, self.pg0, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="bypass", - all_ips=True) + 1, + self.pg0, + self.pg0, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="bypass", + all_ips=True, + ) # check flow cache is empty (0 active elements) before sending traffic self.verify_num_inbound_flow_cache_entries(0) @@ -396,8 +506,7 @@ class IPSec4SpdTestCaseMultiple(SpdFlowCacheInbound): try: self.logger.debug(ppp("SPD Add - Got packet:", packet)) except Exception: - self.logger.error( - ppp("Unexpected or invalid packet:", packet)) + self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise # verify captures that matched BYPASS rules @@ -416,6 +525,7 @@ class IPSec4SpdTestCaseMultiple(SpdFlowCacheInbound): class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheInbound): """ IPSec/IPv4 inbound: Policy mode test case with flow cache \ (overwrite stale entries)""" + def test_ipsec_spd_inbound_overwrite(self): # The operation of the flow cache is setup so that the entire cache # is invalidated when adding or removing an SPD policy rule. @@ -436,23 +546,47 @@ class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheInbound): # add input rules on all interfaces # pg0 -> pg1 policy_0 = self.spd_add_rem_policy( # inbound - 1, self.pg1, self.pg0, socket.IPPROTO_UDP, - is_out=0, priority=10, policy_type="bypass") + 1, + self.pg1, + self.pg0, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="bypass", + ) # pg1 -> pg2 policy_1 = self.spd_add_rem_policy( # inbound - 1, self.pg2, self.pg1, socket.IPPROTO_UDP, - is_out=0, priority=10, policy_type="bypass") + 1, + self.pg2, + self.pg1, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="bypass", + ) # pg2 -> pg0 policy_2 = self.spd_add_rem_policy( # inbound - 1, self.pg0, self.pg2, socket.IPPROTO_UDP, - is_out=0, priority=10, policy_type="discard") + 1, + self.pg0, + self.pg2, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="discard", + ) # create output rules covering the the full ip range # 0.0.0.0 -> 255.255.255.255, so we can capture forwarded packets policy_3 = self.spd_add_rem_policy( # outbound - 1, self.pg0, self.pg0, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="bypass", - all_ips=True) + 1, + self.pg0, + self.pg0, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="bypass", + all_ips=True, + ) # check flow cache is empty (0 active elements) before sending traffic self.verify_num_inbound_flow_cache_entries(0) @@ -479,8 +613,7 @@ class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheInbound): try: self.logger.debug(ppp("SPD Add - Got packet:", packet)) except Exception: - self.logger.error( - ppp("Unexpected or invalid packet:", packet)) + self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise # verify captures that matched BYPASS rules @@ -497,22 +630,40 @@ class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheInbound): # adding an outbound policy should not invalidate output flow cache self.spd_add_rem_policy( # outbound - 1, self.pg0, self.pg0, socket.IPPROTO_UDP, - is_out=1, priority=1, policy_type="bypass", - all_ips=True) + 1, + self.pg0, + self.pg0, + socket.IPPROTO_UDP, + is_out=1, + priority=1, + policy_type="bypass", + all_ips=True, + ) # check inbound flow cache counter has not been reset self.verify_num_inbound_flow_cache_entries(3) # remove + readd bypass policy - flow cache counter will be reset, # and there will be 3x stale entries in flow cache self.spd_add_rem_policy( # inbound, priority 10 - 1, self.pg1, self.pg0, socket.IPPROTO_UDP, - is_out=0, priority=10, policy_type="bypass", - remove=True) + 1, + self.pg1, + self.pg0, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="bypass", + remove=True, + ) # readd policy policy_0 = self.spd_add_rem_policy( # inbound, priority 10 - 1, self.pg1, self.pg0, socket.IPPROTO_UDP, - is_out=0, priority=10, policy_type="bypass") + 1, + self.pg1, + self.pg0, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="bypass", + ) # check counter was reset self.verify_num_inbound_flow_cache_entries(0) @@ -532,8 +683,7 @@ class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheInbound): try: self.logger.debug(ppp("SPD Add - Got packet:", packet)) except Exception: - self.logger.error( - ppp("Unexpected or invalid packet:", packet)) + self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise # verify captures that matched BYPASS rules @@ -543,8 +693,8 @@ class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheInbound): self.pg0.assert_nothing_captured() # verify all policies matched the expected number of times self.verify_policy_match(pkt_count, policy_0) - self.verify_policy_match(pkt_count*2, policy_1) - self.verify_policy_match(pkt_count*2, policy_2) + self.verify_policy_match(pkt_count * 2, policy_1) + self.verify_policy_match(pkt_count * 2, policy_2) # we are overwriting 3x stale entries - check flow cache counter # is correct self.verify_num_inbound_flow_cache_entries(3) @@ -553,18 +703,23 @@ class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheInbound): class IPSec4SpdTestCaseCollision(SpdFlowCacheInbound): """ IPSec/IPv4 inbound: Policy mode test case with flow cache \ (hash collision)""" + # Override class setup to restrict hash table size to 16 buckets. # This forces using only the lower 4 bits of the hash as a key, # making hash collisions easy to find. @classmethod def setUpConstants(cls): super(SpdFlowCacheInbound, cls).setUpConstants() - cls.vpp_cmdline.extend(["ipsec", "{", - "ipv4-inbound-spd-flow-cache on", - "ipv4-inbound-spd-hash-buckets 16", - "}"]) - cls.logger.info("VPP modified cmdline is %s" % " " - .join(cls.vpp_cmdline)) + cls.vpp_cmdline.extend( + [ + "ipsec", + "{", + "ipv4-inbound-spd-flow-cache on", + "ipv4-inbound-spd-hash-buckets 16", + "}", + ] + ) + cls.logger.info("VPP modified cmdline is %s" % " ".join(cls.vpp_cmdline)) def test_ipsec_spd_inbound_collision(self): # The flow cache operation is setup to overwrite an entry @@ -588,20 +743,38 @@ class IPSec4SpdTestCaseCollision(SpdFlowCacheInbound): # create output rules covering the the full ip range # 0.0.0.0 -> 255.255.255.255, so we can capture forwarded packets policy_0 = self.spd_add_rem_policy( # outbound - 1, self.pg0, self.pg0, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="bypass", - all_ips=True) + 1, + self.pg0, + self.pg0, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="bypass", + all_ips=True, + ) capture_intfs = [] if self.crc32_supported(): # create crc32 collision on last 4 bits hashed_with_crc32 = True # add matching rules policy_1 = self.spd_add_rem_policy( # inbound, priority 10 - 1, self.pg1, self.pg2, socket.IPPROTO_UDP, - is_out=0, priority=10, policy_type="bypass") + 1, + self.pg1, + self.pg2, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="bypass", + ) policy_2 = self.spd_add_rem_policy( # inbound, priority 10 - 1, self.pg3, self.pg0, socket.IPPROTO_UDP, - is_out=0, priority=10, policy_type="bypass") + 1, + self.pg3, + self.pg0, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="bypass", + ) # we expect to get captures on pg1 + pg3 capture_intfs.append(self.pg1) @@ -623,11 +796,23 @@ class IPSec4SpdTestCaseCollision(SpdFlowCacheInbound): hashed_with_crc32 = False # add matching rules policy_1 = self.spd_add_rem_policy( # inbound, priority 10 - 1, self.pg1, self.pg2, socket.IPPROTO_UDP, - is_out=0, priority=10, policy_type="bypass") + 1, + self.pg1, + self.pg2, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="bypass", + ) policy_2 = self.spd_add_rem_policy( # inbound, priority 10 - 1, self.pg2, self.pg3, socket.IPPROTO_UDP, - is_out=0, priority=10, policy_type="bypass") + 1, + self.pg2, + self.pg3, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="bypass", + ) capture_intfs.append(self.pg1) capture_intfs.append(self.pg2) @@ -655,15 +840,13 @@ class IPSec4SpdTestCaseCollision(SpdFlowCacheInbound): if_caps.append(pg.get_capture()) for packet in if_caps[-1]: try: - self.logger.debug(ppp( - "SPD Add - Got packet:", packet)) + self.logger.debug(ppp("SPD Add - Got packet:", packet)) except Exception: - self.logger.error(ppp( - "Unexpected or invalid packet:", packet)) + self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise # verify captures that matched BYPASS rule - if(hashed_with_crc32): + if hashed_with_crc32: self.verify_capture(self.pg2, self.pg1, if_caps[0]) self.verify_capture(self.pg0, self.pg3, if_caps[1]) else: # hashed with xxhash @@ -673,11 +856,11 @@ class IPSec4SpdTestCaseCollision(SpdFlowCacheInbound): # verify all policies matched the expected number of times self.verify_policy_match(pkt_count, policy_1) self.verify_policy_match(pkt_count, policy_2) - self.verify_policy_match(pkt_count*2, policy_0) # output policy + self.verify_policy_match(pkt_count * 2, policy_0) # output policy # we have matched 2 policies, but due to the hash collision # one active entry is expected self.verify_num_inbound_flow_cache_entries(1) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_ipsec_spd_flow_cache_output.py b/test/test_ipsec_spd_flow_cache_output.py index 54571c6741a..9852b375a82 100644 --- a/test/test_ipsec_spd_flow_cache_output.py +++ b/test/test_ipsec_spd_flow_cache_output.py @@ -11,16 +11,14 @@ class SpdFlowCacheOutbound(SpdFlowCacheTemplate): @classmethod def setUpConstants(cls): super(SpdFlowCacheOutbound, cls).setUpConstants() - cls.vpp_cmdline.extend(["ipsec", "{", - "ipv4-outbound-spd-flow-cache on", - "}"]) - cls.logger.info("VPP modified cmdline is %s" % " " - .join(cls.vpp_cmdline)) + cls.vpp_cmdline.extend(["ipsec", "{", "ipv4-outbound-spd-flow-cache on", "}"]) + cls.logger.info("VPP modified cmdline is %s" % " ".join(cls.vpp_cmdline)) class IPSec4SpdTestCaseAdd(SpdFlowCacheOutbound): """ IPSec/IPv4 outbound: Policy mode test case with flow cache \ (add rule)""" + def test_ipsec_spd_outbound_add(self): # In this test case, packets in IPv4 FWD path are configured # to go through IPSec outbound SPD policy lookup. @@ -33,11 +31,23 @@ class IPSec4SpdTestCaseAdd(SpdFlowCacheOutbound): pkt_count = 5 self.spd_create_and_intf_add(1, [self.pg1]) policy_0 = self.spd_add_rem_policy( # outbound, priority 10 - 1, self.pg0, self.pg1, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="bypass") + 1, + self.pg0, + self.pg1, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="bypass", + ) policy_1 = self.spd_add_rem_policy( # outbound, priority 5 - 1, self.pg0, self.pg1, socket.IPPROTO_UDP, - is_out=1, priority=5, policy_type="discard") + 1, + self.pg0, + self.pg1, + socket.IPPROTO_UDP, + is_out=1, + priority=5, + policy_type="discard", + ) # check flow cache is empty before sending traffic self.verify_num_outbound_flow_cache_entries(0) @@ -75,6 +85,7 @@ class IPSec4SpdTestCaseAdd(SpdFlowCacheOutbound): class IPSec4SpdTestCaseRemove(SpdFlowCacheOutbound): """ IPSec/IPv4 outbound: Policy mode test case with flow cache \ (remove rule)""" + def test_ipsec_spd_outbound_remove(self): # In this test case, packets in IPv4 FWD path are configured # to go through IPSec outbound SPD policy lookup. @@ -88,11 +99,23 @@ class IPSec4SpdTestCaseRemove(SpdFlowCacheOutbound): pkt_count = 5 self.spd_create_and_intf_add(1, [self.pg1]) policy_0 = self.spd_add_rem_policy( # outbound, priority 10 - 1, self.pg0, self.pg1, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="bypass") + 1, + self.pg0, + self.pg1, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="bypass", + ) policy_1 = self.spd_add_rem_policy( # outbound, priority 5 - 1, self.pg0, self.pg1, socket.IPPROTO_UDP, - is_out=1, priority=5, policy_type="discard") + 1, + self.pg0, + self.pg1, + socket.IPPROTO_UDP, + is_out=1, + priority=5, + policy_type="discard", + ) # check flow cache is empty before sending traffic self.verify_num_outbound_flow_cache_entries(0) @@ -128,9 +151,15 @@ class IPSec4SpdTestCaseRemove(SpdFlowCacheOutbound): # now remove the bypass rule self.spd_add_rem_policy( # outbound, priority 10 - 1, self.pg0, self.pg1, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="bypass", - remove=True) + 1, + self.pg0, + self.pg1, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="bypass", + remove=True, + ) # verify flow cache counter has been reset by rule removal self.verify_num_outbound_flow_cache_entries(0) @@ -154,6 +183,7 @@ class IPSec4SpdTestCaseRemove(SpdFlowCacheOutbound): class IPSec4SpdTestCaseReadd(SpdFlowCacheOutbound): """ IPSec/IPv4 outbound: Policy mode test case with flow cache \ (add, remove, re-add)""" + def test_ipsec_spd_outbound_readd(self): # In this test case, packets in IPv4 FWD path are configured # to go through IPSec outbound SPD policy lookup. @@ -172,11 +202,23 @@ class IPSec4SpdTestCaseReadd(SpdFlowCacheOutbound): pkt_count = 5 self.spd_create_and_intf_add(1, [self.pg1]) policy_0 = self.spd_add_rem_policy( # outbound, priority 10 - 1, self.pg0, self.pg1, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="bypass") + 1, + self.pg0, + self.pg1, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="bypass", + ) policy_1 = self.spd_add_rem_policy( # outbound, priority 5 - 1, self.pg0, self.pg1, socket.IPPROTO_UDP, - is_out=1, priority=5, policy_type="discard") + 1, + self.pg0, + self.pg1, + socket.IPPROTO_UDP, + is_out=1, + priority=5, + policy_type="discard", + ) # check flow cache is empty before sending traffic self.verify_num_outbound_flow_cache_entries(0) @@ -212,9 +254,15 @@ class IPSec4SpdTestCaseReadd(SpdFlowCacheOutbound): # now remove the bypass rule, leaving only the discard rule self.spd_add_rem_policy( # outbound, priority 10 - 1, self.pg0, self.pg1, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="bypass", - remove=True) + 1, + self.pg0, + self.pg1, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="bypass", + remove=True, + ) # verify flow cache counter has been reset by rule removal self.verify_num_outbound_flow_cache_entries(0) @@ -236,8 +284,14 @@ class IPSec4SpdTestCaseReadd(SpdFlowCacheOutbound): # now readd the bypass rule policy_0 = self.spd_add_rem_policy( # outbound, priority 10 - 1, self.pg0, self.pg1, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="bypass") + 1, + self.pg0, + self.pg1, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="bypass", + ) # verify flow cache counter has been reset by rule addition self.verify_num_outbound_flow_cache_entries(0) @@ -271,6 +325,7 @@ class IPSec4SpdTestCaseReadd(SpdFlowCacheOutbound): class IPSec4SpdTestCaseMultiple(SpdFlowCacheOutbound): """ IPSec/IPv4 outbound: Policy mode test case with flow cache \ (multiple interfaces, multiple rules)""" + def test_ipsec_spd_outbound_multiple(self): # In this test case, packets in IPv4 FWD path are configured to go # through IPSec outbound SPD policy lookup. @@ -286,32 +341,75 @@ class IPSec4SpdTestCaseMultiple(SpdFlowCacheOutbound): self.spd_create_and_intf_add(1, self.pg_interfaces) # add rules on all interfaces policy_01 = self.spd_add_rem_policy( # outbound, priority 10 - 1, self.pg0, self.pg1, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="bypass") + 1, + self.pg0, + self.pg1, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="bypass", + ) policy_02 = self.spd_add_rem_policy( # outbound, priority 5 - 1, self.pg0, self.pg1, socket.IPPROTO_UDP, - is_out=1, priority=5, policy_type="discard") + 1, + self.pg0, + self.pg1, + socket.IPPROTO_UDP, + is_out=1, + priority=5, + policy_type="discard", + ) policy_11 = self.spd_add_rem_policy( # outbound, priority 10 - 1, self.pg1, self.pg2, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="bypass") + 1, + self.pg1, + self.pg2, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="bypass", + ) policy_12 = self.spd_add_rem_policy( # outbound, priority 5 - 1, self.pg1, self.pg2, socket.IPPROTO_UDP, - is_out=1, priority=5, policy_type="discard") + 1, + self.pg1, + self.pg2, + socket.IPPROTO_UDP, + is_out=1, + priority=5, + policy_type="discard", + ) policy_21 = self.spd_add_rem_policy( # outbound, priority 5 - 1, self.pg2, self.pg0, socket.IPPROTO_UDP, - is_out=1, priority=5, policy_type="bypass") + 1, + self.pg2, + self.pg0, + socket.IPPROTO_UDP, + is_out=1, + priority=5, + policy_type="bypass", + ) policy_22 = self.spd_add_rem_policy( # outbound, priority 10 - 1, self.pg2, self.pg0, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="discard") + 1, + self.pg2, + self.pg0, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="discard", + ) # interfaces bound to an SPD, will by default drop inbound # traffic with no matching policies. add catch-all inbound # bypass rule to SPD: self.spd_add_rem_policy( # inbound, all interfaces - 1, None, None, socket.IPPROTO_UDP, is_out=0, priority=10, - policy_type="bypass", all_ips=True) + 1, + None, + None, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="bypass", + all_ips=True, + ) # check flow cache is empty (0 active elements) before sending traffic self.verify_num_outbound_flow_cache_entries(0) @@ -338,8 +436,7 @@ class IPSec4SpdTestCaseMultiple(SpdFlowCacheOutbound): try: self.logger.debug(ppp("SPD - Got packet:", packet)) except Exception: - self.logger.error( - ppp("Unexpected or invalid packet:", packet)) + self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise self.logger.debug("SPD: Num packets: %s", len(if_caps[0].res)) self.logger.debug("SPD: Num packets: %s", len(if_caps[1].res)) @@ -366,6 +463,7 @@ class IPSec4SpdTestCaseMultiple(SpdFlowCacheOutbound): class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheOutbound): """ IPSec/IPv4 outbound: Policy mode test case with flow cache \ (overwrite stale entries)""" + def test_ipsec_spd_outbound_overwrite(self): # The operation of the flow cache is setup so that the entire cache # is invalidated when adding or removing an SPD policy rule. @@ -386,23 +484,48 @@ class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheOutbound): # add output rules on all interfaces # pg0 -> pg1 policy_0 = self.spd_add_rem_policy( # outbound - 1, self.pg0, self.pg1, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="bypass") + 1, + self.pg0, + self.pg1, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="bypass", + ) # pg1 -> pg2 policy_1 = self.spd_add_rem_policy( # outbound - 1, self.pg1, self.pg2, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="bypass") + 1, + self.pg1, + self.pg2, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="bypass", + ) # pg2 -> pg0 policy_2 = self.spd_add_rem_policy( # outbound - 1, self.pg2, self.pg0, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="discard") + 1, + self.pg2, + self.pg0, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="discard", + ) # interfaces bound to an SPD, will by default drop inbound # traffic with no matching policies. add catch-all inbound # bypass rule to SPD: self.spd_add_rem_policy( # inbound, all interfaces - 1, None, None, socket.IPPROTO_UDP, is_out=0, priority=10, - policy_type="bypass", all_ips=True) + 1, + None, + None, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="bypass", + all_ips=True, + ) # check flow cache is empty (0 active elements) before sending traffic self.verify_num_outbound_flow_cache_entries(0) @@ -429,8 +552,7 @@ class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheOutbound): try: self.logger.debug(ppp("SPD Add - Got packet:", packet)) except Exception: - self.logger.error( - ppp("Unexpected or invalid packet:", packet)) + self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise # verify captures that matched BYPASS rules @@ -447,21 +569,39 @@ class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheOutbound): # adding an inbound policy should not invalidate output flow cache self.spd_add_rem_policy( # inbound - 1, self.pg0, self.pg1, socket.IPPROTO_UDP, - is_out=0, priority=10, policy_type="bypass") + 1, + self.pg0, + self.pg1, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="bypass", + ) # check flow cache counter has not been reset self.verify_num_outbound_flow_cache_entries(3) # remove a bypass policy - flow cache counter will be reset, and # there will be 3x stale entries in flow cache self.spd_add_rem_policy( # outbound - 1, self.pg0, self.pg1, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="bypass", - remove=True) + 1, + self.pg0, + self.pg1, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="bypass", + remove=True, + ) # readd policy policy_0 = self.spd_add_rem_policy( # outbound - 1, self.pg0, self.pg1, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="bypass") + 1, + self.pg0, + self.pg1, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="bypass", + ) # check counter was reset with flow cache invalidation self.verify_num_outbound_flow_cache_entries(0) @@ -481,8 +621,7 @@ class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheOutbound): try: self.logger.debug(ppp("SPD Add - Got packet:", packet)) except Exception: - self.logger.error( - ppp("Unexpected or invalid packet:", packet)) + self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise # verify captures that matched BYPASS rules @@ -492,8 +631,8 @@ class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheOutbound): self.pg0.assert_nothing_captured() # verify all policies matched the expected number of times self.verify_policy_match(pkt_count, policy_0) - self.verify_policy_match(pkt_count*2, policy_1) - self.verify_policy_match(pkt_count*2, policy_2) + self.verify_policy_match(pkt_count * 2, policy_1) + self.verify_policy_match(pkt_count * 2, policy_2) # we are overwriting 3x stale entries - check flow cache counter # is correct self.verify_num_outbound_flow_cache_entries(3) @@ -502,18 +641,23 @@ class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheOutbound): class IPSec4SpdTestCaseCollision(SpdFlowCacheOutbound): """ IPSec/IPv4 outbound: Policy mode test case with flow cache \ (hash collision)""" + # Override class setup to restrict vector size to 16 elements. # This forces using only the lower 4 bits of the hash as a key, # making hash collisions easy to find. @classmethod def setUpConstants(cls): super(SpdFlowCacheOutbound, cls).setUpConstants() - cls.vpp_cmdline.extend(["ipsec", "{", - "ipv4-outbound-spd-flow-cache on", - "ipv4-outbound-spd-hash-buckets 16", - "}"]) - cls.logger.info("VPP modified cmdline is %s" % " " - .join(cls.vpp_cmdline)) + cls.vpp_cmdline.extend( + [ + "ipsec", + "{", + "ipv4-outbound-spd-flow-cache on", + "ipv4-outbound-spd-hash-buckets 16", + "}", + ] + ) + cls.logger.info("VPP modified cmdline is %s" % " ".join(cls.vpp_cmdline)) def test_ipsec_spd_outbound_collision(self): # The flow cache operation is setup to overwrite an entry @@ -535,18 +679,37 @@ class IPSec4SpdTestCaseCollision(SpdFlowCacheOutbound): self.spd_create_and_intf_add(1, self.pg_interfaces) # add rules policy_0 = self.spd_add_rem_policy( # outbound, priority 10 - 1, self.pg1, self.pg2, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="bypass") + 1, + self.pg1, + self.pg2, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="bypass", + ) policy_1 = self.spd_add_rem_policy( # outbound, priority 10 - 1, self.pg2, self.pg0, socket.IPPROTO_UDP, - is_out=1, priority=10, policy_type="bypass") + 1, + self.pg2, + self.pg0, + socket.IPPROTO_UDP, + is_out=1, + priority=10, + policy_type="bypass", + ) # interfaces bound to an SPD, will by default drop inbound # traffic with no matching policies. add catch-all inbound # bypass rule to SPD: self.spd_add_rem_policy( # inbound, all interfaces - 1, None, None, socket.IPPROTO_UDP, is_out=0, priority=10, - policy_type="bypass", all_ips=True) + 1, + None, + None, + socket.IPPROTO_UDP, + is_out=0, + priority=10, + policy_type="bypass", + all_ips=True, + ) # check flow cache is empty (0 active elements) before sending traffic self.verify_num_outbound_flow_cache_entries(0) @@ -580,11 +743,9 @@ class IPSec4SpdTestCaseCollision(SpdFlowCacheOutbound): if_caps.append(pg.get_capture()) for packet in if_caps[-1]: try: - self.logger.debug(ppp( - "SPD - Got packet:", packet)) + self.logger.debug(ppp("SPD - Got packet:", packet)) except Exception: - self.logger.error(ppp( - "Unexpected or invalid packet:", packet)) + self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise self.logger.debug("SPD: Num packets: %s", len(if_caps[0].res)) self.logger.debug("SPD: Num packets: %s", len(if_caps[1].res)) @@ -600,5 +761,5 @@ class IPSec4SpdTestCaseCollision(SpdFlowCacheOutbound): self.verify_num_outbound_flow_cache_entries(1) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_ipsec_tun_if_esp.py b/test/test_ipsec_tun_if_esp.py index 14c9b3e3f11..9da75f0a4aa 100644 --- a/test/test_ipsec_tun_if_esp.py +++ b/test/test_ipsec_tun_if_esp.py @@ -10,13 +10,29 @@ from scapy.layers.inet6 import IPv6 from scapy.contrib.mpls import MPLS from framework import tag_fixme_vpp_workers from framework import VppTestRunner -from template_ipsec import TemplateIpsec, IpsecTun4Tests, IpsecTun6Tests, \ - IpsecTun4, IpsecTun6, IpsecTcpTests, mk_scapy_crypt_key, \ - IpsecTun6HandoffTests, IpsecTun4HandoffTests, config_tun_params +from template_ipsec import ( + TemplateIpsec, + IpsecTun4Tests, + IpsecTun6Tests, + IpsecTun4, + IpsecTun6, + IpsecTcpTests, + mk_scapy_crypt_key, + IpsecTun6HandoffTests, + IpsecTun4HandoffTests, + config_tun_params, +) from vpp_gre_interface import VppGreInterface from vpp_ipip_tun_interface import VppIpIpTunInterface -from vpp_ip_route import VppIpRoute, VppRoutePath, DpoProto, VppMplsLabel, \ - VppMplsTable, VppMplsRoute, FibPathProto +from vpp_ip_route import ( + VppIpRoute, + VppRoutePath, + DpoProto, + VppMplsLabel, + VppMplsTable, + VppMplsRoute, + FibPathProto, +) from vpp_ipsec import VppIpsecSA, VppIpsecTunProtect, VppIpsecInterface from vpp_l2 import VppBridgeDomain, VppBridgeDomainPort from vpp_sub_interface import L2_VTR_OP, VppDot1QSubint @@ -30,8 +46,9 @@ from vpp_policer import PolicerAction, VppPolicer, Dir def config_tun_params(p, encryption_type, tun_if, src=None, dst=None): ip_class_by_addr_type = {socket.AF_INET: IP, socket.AF_INET6: IPv6} - esn_en = bool(p.flags & (VppEnum.vl_api_ipsec_sad_flags_t. - IPSEC_API_SAD_FLAG_USE_ESN)) + esn_en = bool( + p.flags & (VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_USE_ESN) + ) crypt_key = mk_scapy_crypt_key(p) if tun_if: p.tun_dst = tun_if.remote_ip @@ -41,77 +58,84 @@ def config_tun_params(p, encryption_type, tun_if, src=None, dst=None): p.tun_src = src if p.nat_header: - is_default_port = (p.nat_header.dport == 4500) + is_default_port = p.nat_header.dport == 4500 else: is_default_port = True if is_default_port: outbound_nat_header = p.nat_header else: - outbound_nat_header = UDP(sport=p.nat_header.dport, - dport=p.nat_header.sport) + outbound_nat_header = UDP(sport=p.nat_header.dport, dport=p.nat_header.sport) bind_layers(UDP, ESP, dport=p.nat_header.dport) p.scapy_tun_sa = SecurityAssociation( - encryption_type, spi=p.vpp_tun_spi, + encryption_type, + spi=p.vpp_tun_spi, crypt_algo=p.crypt_algo, crypt_key=crypt_key, - auth_algo=p.auth_algo, auth_key=p.auth_key, - tunnel_header=ip_class_by_addr_type[p.addr_type]( - src=p.tun_dst, - dst=p.tun_src), + auth_algo=p.auth_algo, + auth_key=p.auth_key, + tunnel_header=ip_class_by_addr_type[p.addr_type](src=p.tun_dst, dst=p.tun_src), nat_t_header=outbound_nat_header, - esn_en=esn_en) + esn_en=esn_en, + ) p.vpp_tun_sa = SecurityAssociation( - encryption_type, spi=p.scapy_tun_spi, + encryption_type, + spi=p.scapy_tun_spi, crypt_algo=p.crypt_algo, crypt_key=crypt_key, - auth_algo=p.auth_algo, auth_key=p.auth_key, - tunnel_header=ip_class_by_addr_type[p.addr_type]( - dst=p.tun_dst, - src=p.tun_src), + auth_algo=p.auth_algo, + auth_key=p.auth_key, + tunnel_header=ip_class_by_addr_type[p.addr_type](dst=p.tun_dst, src=p.tun_src), nat_t_header=p.nat_header, - esn_en=esn_en) + esn_en=esn_en, + ) def config_tra_params(p, encryption_type, tun_if): ip_class_by_addr_type = {socket.AF_INET: IP, socket.AF_INET6: IPv6} - esn_en = bool(p.flags & (VppEnum.vl_api_ipsec_sad_flags_t. - IPSEC_API_SAD_FLAG_USE_ESN)) + esn_en = bool( + p.flags & (VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_USE_ESN) + ) crypt_key = mk_scapy_crypt_key(p) p.tun_dst = tun_if.remote_ip p.tun_src = tun_if.local_ip if p.nat_header: - is_default_port = (p.nat_header.dport == 4500) + is_default_port = p.nat_header.dport == 4500 else: is_default_port = True if is_default_port: outbound_nat_header = p.nat_header else: - outbound_nat_header = UDP(sport=p.nat_header.dport, - dport=p.nat_header.sport) + outbound_nat_header = UDP(sport=p.nat_header.dport, dport=p.nat_header.sport) bind_layers(UDP, ESP, dport=p.nat_header.dport) p.scapy_tun_sa = SecurityAssociation( - encryption_type, spi=p.vpp_tun_spi, + encryption_type, + spi=p.vpp_tun_spi, crypt_algo=p.crypt_algo, crypt_key=crypt_key, - auth_algo=p.auth_algo, auth_key=p.auth_key, + auth_algo=p.auth_algo, + auth_key=p.auth_key, esn_en=esn_en, - nat_t_header=outbound_nat_header) + nat_t_header=outbound_nat_header, + ) p.vpp_tun_sa = SecurityAssociation( - encryption_type, spi=p.scapy_tun_spi, + encryption_type, + spi=p.scapy_tun_spi, crypt_algo=p.crypt_algo, crypt_key=crypt_key, - auth_algo=p.auth_algo, auth_key=p.auth_key, + auth_algo=p.auth_algo, + auth_key=p.auth_key, esn_en=esn_en, - nat_t_header=p.nat_header) + nat_t_header=p.nat_header, + ) class TemplateIpsec4TunProtect(object): - """ IPsec IPv4 Tunnel protect """ + """IPsec IPv4 Tunnel protect""" encryption_type = ESP tun4_encrypt_node_name = "esp4-encrypt-tun" @@ -121,69 +145,97 @@ class TemplateIpsec4TunProtect(object): def config_sa_tra(self, p): config_tun_params(p, self.encryption_type, p.tun_if) - p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol, - flags=p.flags) + p.tun_sa_out = VppIpsecSA( + self, + p.scapy_tun_sa_id, + p.scapy_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + flags=p.flags, + ) p.tun_sa_out.add_vpp_config() - p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol, - flags=p.flags) + p.tun_sa_in = VppIpsecSA( + self, + p.vpp_tun_sa_id, + p.vpp_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + flags=p.flags, + ) p.tun_sa_in.add_vpp_config() def config_sa_tun(self, p): config_tun_params(p, self.encryption_type, p.tun_if) - p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol, - self.tun_if.local_addr[p.addr_type], - self.tun_if.remote_addr[p.addr_type], - flags=p.flags) + p.tun_sa_out = VppIpsecSA( + self, + p.scapy_tun_sa_id, + p.scapy_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + self.tun_if.local_addr[p.addr_type], + self.tun_if.remote_addr[p.addr_type], + flags=p.flags, + ) p.tun_sa_out.add_vpp_config() - p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol, - self.tun_if.remote_addr[p.addr_type], - self.tun_if.local_addr[p.addr_type], - flags=p.flags) + p.tun_sa_in = VppIpsecSA( + self, + p.vpp_tun_sa_id, + p.vpp_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + self.tun_if.remote_addr[p.addr_type], + self.tun_if.local_addr[p.addr_type], + flags=p.flags, + ) p.tun_sa_in.add_vpp_config() def config_protect(self, p): - p.tun_protect = VppIpsecTunProtect(self, - p.tun_if, - p.tun_sa_out, - [p.tun_sa_in]) + p.tun_protect = VppIpsecTunProtect(self, p.tun_if, p.tun_sa_out, [p.tun_sa_in]) p.tun_protect.add_vpp_config() def config_network(self, p): - if hasattr(p, 'tun_dst'): + if hasattr(p, "tun_dst"): tun_dst = p.tun_dst else: tun_dst = self.pg0.remote_ip4 - p.tun_if = VppIpIpTunInterface(self, self.pg0, - self.pg0.local_ip4, - tun_dst) + p.tun_if = VppIpIpTunInterface(self, self.pg0, self.pg0.local_ip4, tun_dst) p.tun_if.add_vpp_config() p.tun_if.admin_up() p.tun_if.config_ip4() p.tun_if.config_ip6() - p.route = VppIpRoute(self, p.remote_tun_if_host, 32, - [VppRoutePath(p.tun_if.remote_ip4, - 0xffffffff)]) + p.route = VppIpRoute( + self, + p.remote_tun_if_host, + 32, + [VppRoutePath(p.tun_if.remote_ip4, 0xFFFFFFFF)], + ) p.route.add_vpp_config() - r = VppIpRoute(self, p.remote_tun_if_host6, 128, - [VppRoutePath(p.tun_if.remote_ip6, - 0xffffffff, - proto=DpoProto.DPO_PROTO_IP6)]) + r = VppIpRoute( + self, + p.remote_tun_if_host6, + 128, + [ + VppRoutePath( + p.tun_if.remote_ip6, 0xFFFFFFFF, proto=DpoProto.DPO_PROTO_IP6 + ) + ], + ) r.add_vpp_config() def unconfig_network(self, p): @@ -198,9 +250,8 @@ class TemplateIpsec4TunProtect(object): p.tun_sa_in.remove_vpp_config() -class TemplateIpsec4TunIfEsp(TemplateIpsec4TunProtect, - TemplateIpsec): - """ IPsec tunnel interface tests """ +class TemplateIpsec4TunIfEsp(TemplateIpsec4TunProtect, TemplateIpsec): + """IPsec tunnel interface tests""" encryption_type = ESP @@ -227,9 +278,8 @@ class TemplateIpsec4TunIfEsp(TemplateIpsec4TunProtect, super(TemplateIpsec4TunIfEsp, self).tearDown() -class TemplateIpsec4TunIfEspUdp(TemplateIpsec4TunProtect, - TemplateIpsec): - """ IPsec UDP tunnel interface tests """ +class TemplateIpsec4TunIfEspUdp(TemplateIpsec4TunProtect, TemplateIpsec): + """IPsec UDP tunnel interface tests""" tun4_encrypt_node_name = "esp4-encrypt-tun" tun4_decrypt_node_name = ["esp4-decrypt-tun", "esp4-decrypt-tun-post"] @@ -270,30 +320,41 @@ class TemplateIpsec4TunIfEspUdp(TemplateIpsec4TunProtect, def config_sa_tra(self, p): config_tun_params(p, self.encryption_type, p.tun_if) - p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol, - flags=p.flags, - udp_src=p.nat_header.sport, - udp_dst=p.nat_header.dport) + p.tun_sa_out = VppIpsecSA( + self, + p.scapy_tun_sa_id, + p.scapy_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + flags=p.flags, + udp_src=p.nat_header.sport, + udp_dst=p.nat_header.dport, + ) p.tun_sa_out.add_vpp_config() - p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol, - flags=p.flags, - udp_src=p.nat_header.sport, - udp_dst=p.nat_header.dport) + p.tun_sa_in = VppIpsecSA( + self, + p.vpp_tun_sa_id, + p.vpp_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + flags=p.flags, + udp_src=p.nat_header.sport, + udp_dst=p.nat_header.dport, + ) p.tun_sa_in.add_vpp_config() def setUp(self): super(TemplateIpsec4TunIfEspUdp, self).setUp() p = self.ipv4_params - p.flags = (VppEnum.vl_api_ipsec_sad_flags_t. - IPSEC_API_SAD_FLAG_UDP_ENCAP) + p.flags = VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_UDP_ENCAP p.nat_header = UDP(sport=5454, dport=4500) self.tun_if = self.pg0 @@ -307,38 +368,38 @@ class TemplateIpsec4TunIfEspUdp(TemplateIpsec4TunProtect, class TestIpsec4TunIfEsp1(TemplateIpsec4TunIfEsp, IpsecTun4Tests): - """ Ipsec ESP - TUN tests """ + """Ipsec ESP - TUN tests""" + tun4_encrypt_node_name = "esp4-encrypt-tun" tun4_decrypt_node_name = ["esp4-decrypt-tun", "esp4-decrypt-tun-post"] def test_tun_basic64(self): - """ ipsec 6o4 tunnel basic test """ + """ipsec 6o4 tunnel basic test""" self.tun4_encrypt_node_name = "esp4-encrypt-tun" self.verify_tun_64(self.params[socket.AF_INET], count=1) def test_tun_burst64(self): - """ ipsec 6o4 tunnel basic test """ + """ipsec 6o4 tunnel basic test""" self.tun4_encrypt_node_name = "esp4-encrypt-tun" self.verify_tun_64(self.params[socket.AF_INET], count=257) def test_tun_basic_frag44(self): - """ ipsec 4o4 tunnel frag basic test """ + """ipsec 4o4 tunnel frag basic test""" self.tun4_encrypt_node_name = "esp4-encrypt-tun" p = self.ipv4_params - self.vapi.sw_interface_set_mtu(p.tun_if.sw_if_index, - [1500, 0, 0, 0]) - self.verify_tun_44(self.params[socket.AF_INET], - count=1, payload_size=1800, n_rx=2) - self.vapi.sw_interface_set_mtu(p.tun_if.sw_if_index, - [9000, 0, 0, 0]) + self.vapi.sw_interface_set_mtu(p.tun_if.sw_if_index, [1500, 0, 0, 0]) + self.verify_tun_44( + self.params[socket.AF_INET], count=1, payload_size=1800, n_rx=2 + ) + self.vapi.sw_interface_set_mtu(p.tun_if.sw_if_index, [9000, 0, 0, 0]) class TestIpsec4TunIfEspUdp(TemplateIpsec4TunIfEspUdp, IpsecTun4Tests): - """ Ipsec ESP UDP tests """ + """Ipsec ESP UDP tests""" tun4_input_node = "ipsec4-tun-input" @@ -346,22 +407,22 @@ class TestIpsec4TunIfEspUdp(TemplateIpsec4TunIfEspUdp, IpsecTun4Tests): super(TestIpsec4TunIfEspUdp, self).setUp() def test_keepalive(self): - """ IPSEC NAT Keepalive """ + """IPSEC NAT Keepalive""" self.verify_keepalive(self.ipv4_params) class TestIpsec4TunIfEspUdpGCM(TemplateIpsec4TunIfEspUdp, IpsecTun4Tests): - """ Ipsec ESP UDP GCM tests """ + """Ipsec ESP UDP GCM tests""" tun4_input_node = "ipsec4-tun-input" def setUp(self): super(TestIpsec4TunIfEspUdpGCM, self).setUp() p = self.ipv4_params - p.auth_algo_vpp_id = (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_NONE) - p.crypt_algo_vpp_id = (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_AES_GCM_256) + p.auth_algo_vpp_id = VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_NONE + p.crypt_algo_vpp_id = ( + VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_GCM_256 + ) p.crypt_algo = "AES-GCM" p.auth_algo = "NULL" p.crypt_key = b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h" @@ -369,75 +430,104 @@ class TestIpsec4TunIfEspUdpGCM(TemplateIpsec4TunIfEspUdp, IpsecTun4Tests): class TestIpsec4TunIfEsp2(TemplateIpsec4TunIfEsp, IpsecTcpTests): - """ Ipsec ESP - TCP tests """ + """Ipsec ESP - TCP tests""" + pass class TemplateIpsec6TunProtect(object): - """ IPsec IPv6 Tunnel protect """ + """IPsec IPv6 Tunnel protect""" def config_sa_tra(self, p): config_tun_params(p, self.encryption_type, p.tun_if) - p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol) + p.tun_sa_out = VppIpsecSA( + self, + p.scapy_tun_sa_id, + p.scapy_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + ) p.tun_sa_out.add_vpp_config() - p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol) + p.tun_sa_in = VppIpsecSA( + self, + p.vpp_tun_sa_id, + p.vpp_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + ) p.tun_sa_in.add_vpp_config() def config_sa_tun(self, p): config_tun_params(p, self.encryption_type, p.tun_if) - p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol, - self.tun_if.local_addr[p.addr_type], - self.tun_if.remote_addr[p.addr_type]) + p.tun_sa_out = VppIpsecSA( + self, + p.scapy_tun_sa_id, + p.scapy_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + self.tun_if.local_addr[p.addr_type], + self.tun_if.remote_addr[p.addr_type], + ) p.tun_sa_out.add_vpp_config() - p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol, - self.tun_if.remote_addr[p.addr_type], - self.tun_if.local_addr[p.addr_type]) + p.tun_sa_in = VppIpsecSA( + self, + p.vpp_tun_sa_id, + p.vpp_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + self.tun_if.remote_addr[p.addr_type], + self.tun_if.local_addr[p.addr_type], + ) p.tun_sa_in.add_vpp_config() def config_protect(self, p): - p.tun_protect = VppIpsecTunProtect(self, - p.tun_if, - p.tun_sa_out, - [p.tun_sa_in]) + p.tun_protect = VppIpsecTunProtect(self, p.tun_if, p.tun_sa_out, [p.tun_sa_in]) p.tun_protect.add_vpp_config() def config_network(self, p): - if hasattr(p, 'tun_dst'): + if hasattr(p, "tun_dst"): tun_dst = p.tun_dst else: tun_dst = self.pg0.remote_ip6 - p.tun_if = VppIpIpTunInterface(self, self.pg0, - self.pg0.local_ip6, - tun_dst) + p.tun_if = VppIpIpTunInterface(self, self.pg0, self.pg0.local_ip6, tun_dst) p.tun_if.add_vpp_config() p.tun_if.admin_up() p.tun_if.config_ip6() p.tun_if.config_ip4() - p.route = VppIpRoute(self, p.remote_tun_if_host, 128, - [VppRoutePath(p.tun_if.remote_ip6, - 0xffffffff, - proto=DpoProto.DPO_PROTO_IP6)]) + p.route = VppIpRoute( + self, + p.remote_tun_if_host, + 128, + [ + VppRoutePath( + p.tun_if.remote_ip6, 0xFFFFFFFF, proto=DpoProto.DPO_PROTO_IP6 + ) + ], + ) p.route.add_vpp_config() - r = VppIpRoute(self, p.remote_tun_if_host4, 32, - [VppRoutePath(p.tun_if.remote_ip4, - 0xffffffff)]) + r = VppIpRoute( + self, + p.remote_tun_if_host4, + 32, + [VppRoutePath(p.tun_if.remote_ip4, 0xFFFFFFFF)], + ) r.add_vpp_config() def unconfig_network(self, p): @@ -452,9 +542,8 @@ class TemplateIpsec6TunProtect(object): p.tun_sa_in.remove_vpp_config() -class TemplateIpsec6TunIfEsp(TemplateIpsec6TunProtect, - TemplateIpsec): - """ IPsec tunnel interface tests """ +class TemplateIpsec6TunIfEsp(TemplateIpsec6TunProtect, TemplateIpsec): + """IPsec tunnel interface tests""" encryption_type = ESP @@ -472,31 +561,31 @@ class TemplateIpsec6TunIfEsp(TemplateIpsec6TunProtect, super(TemplateIpsec6TunIfEsp, self).tearDown() -class TestIpsec6TunIfEsp1(TemplateIpsec6TunIfEsp, - IpsecTun6Tests): - """ Ipsec ESP - TUN tests """ +class TestIpsec6TunIfEsp1(TemplateIpsec6TunIfEsp, IpsecTun6Tests): + """Ipsec ESP - TUN tests""" + tun6_encrypt_node_name = "esp6-encrypt-tun" tun6_decrypt_node_name = ["esp6-decrypt-tun", "esp6-decrypt-tun-post"] def test_tun_basic46(self): - """ ipsec 4o6 tunnel basic test """ + """ipsec 4o6 tunnel basic test""" self.tun6_encrypt_node_name = "esp6-encrypt-tun" self.verify_tun_46(self.params[socket.AF_INET6], count=1) def test_tun_burst46(self): - """ ipsec 4o6 tunnel burst test """ + """ipsec 4o6 tunnel burst test""" self.tun6_encrypt_node_name = "esp6-encrypt-tun" self.verify_tun_46(self.params[socket.AF_INET6], count=257) -class TestIpsec6TunIfEspHandoff(TemplateIpsec6TunIfEsp, - IpsecTun6HandoffTests): - """ Ipsec ESP 6 Handoff tests """ +class TestIpsec6TunIfEspHandoff(TemplateIpsec6TunIfEsp, IpsecTun6HandoffTests): + """Ipsec ESP 6 Handoff tests""" + tun6_encrypt_node_name = "esp6-encrypt-tun" tun6_decrypt_node_name = ["esp6-decrypt-tun", "esp6-decrypt-tun-post"] def test_tun_handoff_66_police(self): - """ ESP 6o6 tunnel with policer worker hand-off test """ + """ESP 6o6 tunnel with policer worker hand-off test""" self.vapi.cli("clear errors") self.vapi.cli("clear ipsec sa") @@ -504,12 +593,19 @@ class TestIpsec6TunIfEspHandoff(TemplateIpsec6TunIfEsp, p = self.params[socket.AF_INET6] action_tx = PolicerAction( - VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT, - 0) - policer = VppPolicer(self, "pol1", 80, 0, 1000, 0, - conform_action=action_tx, - exceed_action=action_tx, - violate_action=action_tx) + VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT, 0 + ) + policer = VppPolicer( + self, + "pol1", + 80, + 0, + 1000, + 0, + conform_action=action_tx, + exceed_action=action_tx, + violate_action=action_tx, + ) policer.add_vpp_config() # Start policing on tun @@ -520,13 +616,17 @@ class TestIpsec6TunIfEspHandoff(TemplateIpsec6TunIfEsp, # inject alternately on worker 0 and 1. for worker in [0, 1, 0, 1]: - send_pkts = self.gen_encrypt_pkts6(p, p.scapy_tun_sa, - self.tun_if, - src=p.remote_tun_if_host, - dst=self.pg1.remote_ip6, - count=N_PKTS) - recv_pkts = self.send_and_expect(self.tun_if, send_pkts, - self.pg1, worker=worker) + send_pkts = self.gen_encrypt_pkts6( + p, + p.scapy_tun_sa, + self.tun_if, + src=p.remote_tun_if_host, + dst=self.pg1.remote_ip6, + count=N_PKTS, + ) + recv_pkts = self.send_and_expect( + self.tun_if, send_pkts, self.pg1, worker=worker + ) self.verify_decrypted6(p, recv_pkts) self.logger.debug(self.vapi.cli("show trace max 100")) @@ -539,36 +639,36 @@ class TestIpsec6TunIfEspHandoff(TemplateIpsec6TunIfEsp, self.assertEqual(stats, stats1) # Worker 0, should have handed everything off - self.assertEqual(stats0['conform_packets'], 0) - self.assertEqual(stats0['exceed_packets'], 0) - self.assertEqual(stats0['violate_packets'], 0) + self.assertEqual(stats0["conform_packets"], 0) + self.assertEqual(stats0["exceed_packets"], 0) + self.assertEqual(stats0["violate_packets"], 0) else: # Second pass: both workers should have policed equal amounts - self.assertGreater(stats1['conform_packets'], 0) - self.assertEqual(stats1['exceed_packets'], 0) - self.assertGreater(stats1['violate_packets'], 0) + self.assertGreater(stats1["conform_packets"], 0) + self.assertEqual(stats1["exceed_packets"], 0) + self.assertGreater(stats1["violate_packets"], 0) - self.assertGreater(stats0['conform_packets'], 0) - self.assertEqual(stats0['exceed_packets'], 0) - self.assertGreater(stats0['violate_packets'], 0) + self.assertGreater(stats0["conform_packets"], 0) + self.assertEqual(stats0["exceed_packets"], 0) + self.assertGreater(stats0["violate_packets"], 0) - self.assertEqual(stats0['conform_packets'] + - stats0['violate_packets'], - stats1['conform_packets'] + - stats1['violate_packets']) + self.assertEqual( + stats0["conform_packets"] + stats0["violate_packets"], + stats1["conform_packets"] + stats1["violate_packets"], + ) policer.apply_vpp_config(p.tun_if.sw_if_index, Dir.RX, False) policer.remove_vpp_config() -class TestIpsec4TunIfEspHandoff(TemplateIpsec4TunIfEsp, - IpsecTun4HandoffTests): - """ Ipsec ESP 4 Handoff tests """ +class TestIpsec4TunIfEspHandoff(TemplateIpsec4TunIfEsp, IpsecTun4HandoffTests): + """Ipsec ESP 4 Handoff tests""" + tun4_encrypt_node_name = "esp4-encrypt-tun" tun4_decrypt_node_name = ["esp4-decrypt-tun", "esp4-decrypt-tun-post"] def test_tun_handoff_44_police(self): - """ ESP 4o4 tunnel with policer worker hand-off test """ + """ESP 4o4 tunnel with policer worker hand-off test""" self.vapi.cli("clear errors") self.vapi.cli("clear ipsec sa") @@ -576,12 +676,19 @@ class TestIpsec4TunIfEspHandoff(TemplateIpsec4TunIfEsp, p = self.params[socket.AF_INET] action_tx = PolicerAction( - VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT, - 0) - policer = VppPolicer(self, "pol1", 80, 0, 1000, 0, - conform_action=action_tx, - exceed_action=action_tx, - violate_action=action_tx) + VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT, 0 + ) + policer = VppPolicer( + self, + "pol1", + 80, + 0, + 1000, + 0, + conform_action=action_tx, + exceed_action=action_tx, + violate_action=action_tx, + ) policer.add_vpp_config() # Start policing on tun @@ -592,13 +699,17 @@ class TestIpsec4TunIfEspHandoff(TemplateIpsec4TunIfEsp, # inject alternately on worker 0 and 1. for worker in [0, 1, 0, 1]: - send_pkts = self.gen_encrypt_pkts(p, p.scapy_tun_sa, - self.tun_if, - src=p.remote_tun_if_host, - dst=self.pg1.remote_ip4, - count=N_PKTS) - recv_pkts = self.send_and_expect(self.tun_if, send_pkts, - self.pg1, worker=worker) + send_pkts = self.gen_encrypt_pkts( + p, + p.scapy_tun_sa, + self.tun_if, + src=p.remote_tun_if_host, + dst=self.pg1.remote_ip4, + count=N_PKTS, + ) + recv_pkts = self.send_and_expect( + self.tun_if, send_pkts, self.pg1, worker=worker + ) self.verify_decrypted(p, recv_pkts) self.logger.debug(self.vapi.cli("show trace max 100")) @@ -611,33 +722,31 @@ class TestIpsec4TunIfEspHandoff(TemplateIpsec4TunIfEsp, self.assertEqual(stats, stats1) # Worker 0, should have handed everything off - self.assertEqual(stats0['conform_packets'], 0) - self.assertEqual(stats0['exceed_packets'], 0) - self.assertEqual(stats0['violate_packets'], 0) + self.assertEqual(stats0["conform_packets"], 0) + self.assertEqual(stats0["exceed_packets"], 0) + self.assertEqual(stats0["violate_packets"], 0) else: # Second pass: both workers should have policed equal amounts - self.assertGreater(stats1['conform_packets'], 0) - self.assertEqual(stats1['exceed_packets'], 0) - self.assertGreater(stats1['violate_packets'], 0) + self.assertGreater(stats1["conform_packets"], 0) + self.assertEqual(stats1["exceed_packets"], 0) + self.assertGreater(stats1["violate_packets"], 0) - self.assertGreater(stats0['conform_packets'], 0) - self.assertEqual(stats0['exceed_packets'], 0) - self.assertGreater(stats0['violate_packets'], 0) + self.assertGreater(stats0["conform_packets"], 0) + self.assertEqual(stats0["exceed_packets"], 0) + self.assertGreater(stats0["violate_packets"], 0) - self.assertEqual(stats0['conform_packets'] + - stats0['violate_packets'], - stats1['conform_packets'] + - stats1['violate_packets']) + self.assertEqual( + stats0["conform_packets"] + stats0["violate_packets"], + stats1["conform_packets"] + stats1["violate_packets"], + ) policer.apply_vpp_config(p.tun_if.sw_if_index, Dir.RX, False) policer.remove_vpp_config() @tag_fixme_vpp_workers -class TestIpsec4MultiTunIfEsp(TemplateIpsec4TunProtect, - TemplateIpsec, - IpsecTun4): - """ IPsec IPv4 Multi Tunnel interface """ +class TestIpsec4MultiTunIfEsp(TemplateIpsec4TunProtect, TemplateIpsec, IpsecTun4): + """IPsec IPv4 Multi Tunnel interface""" encryption_type = ESP tun4_encrypt_node_name = "esp4-encrypt-tun" @@ -676,19 +785,23 @@ class TestIpsec4MultiTunIfEsp(TemplateIpsec4TunProtect, super(TestIpsec4MultiTunIfEsp, self).tearDown() def test_tun_44(self): - """Multiple IPSEC tunnel interfaces """ + """Multiple IPSEC tunnel interfaces""" for p in self.multi_params: self.verify_tun_44(p, count=127) self.assertEqual(p.tun_if.get_rx_stats(), 127) self.assertEqual(p.tun_if.get_tx_stats(), 127) def test_tun_rr_44(self): - """ Round-robin packets acrros multiple interface """ + """Round-robin packets acrros multiple interface""" tx = [] for p in self.multi_params: - tx = tx + self.gen_encrypt_pkts(p, p.scapy_tun_sa, self.tun_if, - src=p.remote_tun_if_host, - dst=self.pg1.remote_ip4) + tx = tx + self.gen_encrypt_pkts( + p, + p.scapy_tun_sa, + self.tun_if, + src=p.remote_tun_if_host, + dst=self.pg1.remote_ip4, + ) rxs = self.send_and_expect(self.tun_if, tx, self.pg1) for rx, p in zip(rxs, self.multi_params): @@ -696,18 +809,17 @@ class TestIpsec4MultiTunIfEsp(TemplateIpsec4TunProtect, tx = [] for p in self.multi_params: - tx = tx + self.gen_pkts(self.pg1, src=self.pg1.remote_ip4, - dst=p.remote_tun_if_host) + tx = tx + self.gen_pkts( + self.pg1, src=self.pg1.remote_ip4, dst=p.remote_tun_if_host + ) rxs = self.send_and_expect(self.pg1, tx, self.tun_if) for rx, p in zip(rxs, self.multi_params): self.verify_encrypted(p, p.vpp_tun_sa, [rx]) -class TestIpsec4TunIfEspAll(TemplateIpsec4TunProtect, - TemplateIpsec, - IpsecTun4): - """ IPsec IPv4 Tunnel interface all Algos """ +class TestIpsec4TunIfEspAll(TemplateIpsec4TunProtect, TemplateIpsec, IpsecTun4): + """IPsec IPv4 Tunnel interface all Algos""" encryption_type = ESP tun4_encrypt_node_name = "esp4-encrypt-tun" @@ -736,7 +848,7 @@ class TestIpsec4TunIfEspAll(TemplateIpsec4TunProtect, # change the key and the SPI # np = copy.copy(p) - p.crypt_key = b'X' + p.crypt_key[1:] + p.crypt_key = b"X" + p.crypt_key[1:] p.scapy_tun_spi += 1 p.scapy_tun_sa_id += 1 p.vpp_tun_spi += 1 @@ -746,26 +858,30 @@ class TestIpsec4TunIfEspAll(TemplateIpsec4TunProtect, config_tun_params(p, self.encryption_type, p.tun_if) - p.tun_sa_out = VppIpsecSA(self, - p.scapy_tun_sa_id, - p.scapy_tun_spi, - p.auth_algo_vpp_id, - p.auth_key, - p.crypt_algo_vpp_id, - p.crypt_key, - self.vpp_esp_protocol, - flags=p.flags, - salt=p.salt) - p.tun_sa_in = VppIpsecSA(self, - p.vpp_tun_sa_id, - p.vpp_tun_spi, - p.auth_algo_vpp_id, - p.auth_key, - p.crypt_algo_vpp_id, - p.crypt_key, - self.vpp_esp_protocol, - flags=p.flags, - salt=p.salt) + p.tun_sa_out = VppIpsecSA( + self, + p.scapy_tun_sa_id, + p.scapy_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + flags=p.flags, + salt=p.salt, + ) + p.tun_sa_in = VppIpsecSA( + self, + p.vpp_tun_sa_id, + p.vpp_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + flags=p.flags, + salt=p.salt, + ) p.tun_sa_in.add_vpp_config() p.tun_sa_out.add_vpp_config() @@ -775,68 +891,98 @@ class TestIpsec4TunIfEspAll(TemplateIpsec4TunProtect, self.logger.info(self.vapi.cli("sh ipsec sa")) def test_tun_44(self): - """IPSEC tunnel all algos """ + """IPSEC tunnel all algos""" # foreach VPP crypto engine engines = ["ia32", "ipsecmb", "openssl"] # foreach crypto algorithm - algos = [{'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_AES_GCM_128), - 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_NONE), - 'scapy-crypto': "AES-GCM", - 'scapy-integ': "NULL", - 'key': b"JPjyOWBeVEQiMe7h", - 'salt': 3333}, - {'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_AES_GCM_192), - 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_NONE), - 'scapy-crypto': "AES-GCM", - 'scapy-integ': "NULL", - 'key': b"JPjyOWBeVEQiMe7hJPjyOWBe", - 'salt': 0}, - {'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_AES_GCM_256), - 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_NONE), - 'scapy-crypto': "AES-GCM", - 'scapy-integ': "NULL", - 'key': b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h", - 'salt': 9999}, - {'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_AES_CBC_128), - 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_SHA1_96), - 'scapy-crypto': "AES-CBC", - 'scapy-integ': "HMAC-SHA1-96", - 'salt': 0, - 'key': b"JPjyOWBeVEQiMe7h"}, - {'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_AES_CBC_192), - 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_SHA_512_256), - 'scapy-crypto': "AES-CBC", - 'scapy-integ': "SHA2-512-256", - 'salt': 0, - 'key': b"JPjyOWBeVEQiMe7hJPjyOWBe"}, - {'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_AES_CBC_256), - 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_SHA_256_128), - 'scapy-crypto': "AES-CBC", - 'scapy-integ': "SHA2-256-128", - 'salt': 0, - 'key': b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h"}, - {'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_NONE), - 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_SHA1_96), - 'scapy-crypto': "NULL", - 'scapy-integ': "HMAC-SHA1-96", - 'salt': 0, - 'key': b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h"}] + algos = [ + { + "vpp-crypto": ( + VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_GCM_128 + ), + "vpp-integ": ( + VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_NONE + ), + "scapy-crypto": "AES-GCM", + "scapy-integ": "NULL", + "key": b"JPjyOWBeVEQiMe7h", + "salt": 3333, + }, + { + "vpp-crypto": ( + VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_GCM_192 + ), + "vpp-integ": ( + VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_NONE + ), + "scapy-crypto": "AES-GCM", + "scapy-integ": "NULL", + "key": b"JPjyOWBeVEQiMe7hJPjyOWBe", + "salt": 0, + }, + { + "vpp-crypto": ( + VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_GCM_256 + ), + "vpp-integ": ( + VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_NONE + ), + "scapy-crypto": "AES-GCM", + "scapy-integ": "NULL", + "key": b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h", + "salt": 9999, + }, + { + "vpp-crypto": ( + VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CBC_128 + ), + "vpp-integ": ( + VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96 + ), + "scapy-crypto": "AES-CBC", + "scapy-integ": "HMAC-SHA1-96", + "salt": 0, + "key": b"JPjyOWBeVEQiMe7h", + }, + { + "vpp-crypto": ( + VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CBC_192 + ), + "vpp-integ": ( + VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA_512_256 + ), + "scapy-crypto": "AES-CBC", + "scapy-integ": "SHA2-512-256", + "salt": 0, + "key": b"JPjyOWBeVEQiMe7hJPjyOWBe", + }, + { + "vpp-crypto": ( + VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CBC_256 + ), + "vpp-integ": ( + VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA_256_128 + ), + "scapy-crypto": "AES-CBC", + "scapy-integ": "SHA2-256-128", + "salt": 0, + "key": b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h", + }, + { + "vpp-crypto": ( + VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_NONE + ), + "vpp-integ": ( + VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96 + ), + "scapy-crypto": "NULL", + "scapy-integ": "HMAC-SHA1-96", + "salt": 0, + "key": b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h", + }, + ] for engine in engines: self.vapi.cli("set crypto handler all %s" % engine) @@ -848,12 +994,12 @@ class TestIpsec4TunIfEspAll(TemplateIpsec4TunProtect, # with self.subTest(algo=algo['scapy']): p = self.ipv4_params - p.auth_algo_vpp_id = algo['vpp-integ'] - p.crypt_algo_vpp_id = algo['vpp-crypto'] - p.crypt_algo = algo['scapy-crypto'] - p.auth_algo = algo['scapy-integ'] - p.crypt_key = algo['key'] - p.salt = algo['salt'] + p.auth_algo_vpp_id = algo["vpp-integ"] + p.crypt_algo_vpp_id = algo["vpp-crypto"] + p.crypt_algo = algo["scapy-crypto"] + p.auth_algo = algo["scapy-integ"] + p.crypt_key = algo["key"] + p.salt = algo["salt"] # # rekey the tunnel @@ -862,10 +1008,8 @@ class TestIpsec4TunIfEspAll(TemplateIpsec4TunProtect, self.verify_tun_44(p, count=127) -class TestIpsec4TunIfEspNoAlgo(TemplateIpsec4TunProtect, - TemplateIpsec, - IpsecTun4): - """ IPsec IPv4 Tunnel interface no Algos """ +class TestIpsec4TunIfEspNoAlgo(TemplateIpsec4TunProtect, TemplateIpsec, IpsecTun4): + """IPsec IPv4 Tunnel interface no Algos""" encryption_type = ESP tun4_encrypt_node_name = "esp4-encrypt-tun" @@ -876,29 +1020,28 @@ class TestIpsec4TunIfEspNoAlgo(TemplateIpsec4TunProtect, self.tun_if = self.pg0 p = self.ipv4_params - p.auth_algo_vpp_id = (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_NONE) - p.auth_algo = 'NULL' + p.auth_algo_vpp_id = VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_NONE + p.auth_algo = "NULL" p.auth_key = [] - p.crypt_algo_vpp_id = (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_NONE) - p.crypt_algo = 'NULL' + p.crypt_algo_vpp_id = ( + VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_NONE + ) + p.crypt_algo = "NULL" p.crypt_key = [] def tearDown(self): super(TestIpsec4TunIfEspNoAlgo, self).tearDown() def test_tun_44(self): - """ IPSec SA with NULL algos """ + """IPSec SA with NULL algos""" p = self.ipv4_params self.config_network(p) self.config_sa_tra(p) self.config_protect(p) - tx = self.gen_pkts(self.pg1, src=self.pg1.remote_ip4, - dst=p.remote_tun_if_host) + tx = self.gen_pkts(self.pg1, src=self.pg1.remote_ip4, dst=p.remote_tun_if_host) self.send_and_assert_no_replies(self.pg1, tx) self.unconfig_protect(p) @@ -907,10 +1050,8 @@ class TestIpsec4TunIfEspNoAlgo(TemplateIpsec4TunProtect, @tag_fixme_vpp_workers -class TestIpsec6MultiTunIfEsp(TemplateIpsec6TunProtect, - TemplateIpsec, - IpsecTun6): - """ IPsec IPv6 Multi Tunnel interface """ +class TestIpsec6MultiTunIfEsp(TemplateIpsec6TunProtect, TemplateIpsec, IpsecTun6): + """IPsec IPv6 Multi Tunnel interface""" encryption_type = ESP tun6_encrypt_node_name = "esp6-encrypt-tun" @@ -949,40 +1090,43 @@ class TestIpsec6MultiTunIfEsp(TemplateIpsec6TunProtect, super(TestIpsec6MultiTunIfEsp, self).tearDown() def test_tun_66(self): - """Multiple IPSEC tunnel interfaces """ + """Multiple IPSEC tunnel interfaces""" for p in self.multi_params: self.verify_tun_66(p, count=127) self.assertEqual(p.tun_if.get_rx_stats(), 127) self.assertEqual(p.tun_if.get_tx_stats(), 127) -class TestIpsecGreTebIfEsp(TemplateIpsec, - IpsecTun4Tests): - """ Ipsec GRE TEB ESP - TUN tests """ +class TestIpsecGreTebIfEsp(TemplateIpsec, IpsecTun4Tests): + """Ipsec GRE TEB ESP - TUN tests""" + tun4_encrypt_node_name = "esp4-encrypt-tun" tun4_decrypt_node_name = ["esp4-decrypt-tun", "esp4-decrypt-tun-post"] encryption_type = ESP omac = "00:11:22:33:44:55" - def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - sa.encrypt(IP(src=self.pg0.remote_ip4, - dst=self.pg0.local_ip4) / - GRE() / - Ether(dst=self.omac) / - IP(src="1.1.1.1", dst="1.1.1.2") / - UDP(sport=1144, dport=2233) / - Raw(b'X' * payload_size)) - for i in range(count)] - - def gen_pkts(self, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(dst=self.omac) / - IP(src="1.1.1.1", dst="1.1.1.2") / - UDP(sport=1144, dport=2233) / - Raw(b'X' * payload_size) - for i in range(count)] + def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / sa.encrypt( + IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / GRE() + / Ether(dst=self.omac) + / IP(src="1.1.1.1", dst="1.1.1.2") + / UDP(sport=1144, dport=2233) + / Raw(b"X" * payload_size) + ) + for i in range(count) + ] + + def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(dst=self.omac) + / IP(src="1.1.1.1", dst="1.1.1.2") + / UDP(sport=1144, dport=2233) + / Raw(b"X" * payload_size) + for i in range(count) + ] def verify_decrypted(self, p, rxs): for rx in rxs: @@ -1020,33 +1164,43 @@ class TestIpsecGreTebIfEsp(TemplateIpsec, bd1 = VppBridgeDomain(self, 1) bd1.add_vpp_config() - p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol, - self.pg0.local_ip4, - self.pg0.remote_ip4) + p.tun_sa_out = VppIpsecSA( + self, + p.scapy_tun_sa_id, + p.scapy_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + self.pg0.local_ip4, + self.pg0.remote_ip4, + ) p.tun_sa_out.add_vpp_config() - p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol, - self.pg0.remote_ip4, - self.pg0.local_ip4) + p.tun_sa_in = VppIpsecSA( + self, + p.vpp_tun_sa_id, + p.vpp_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + self.pg0.remote_ip4, + self.pg0.local_ip4, + ) p.tun_sa_in.add_vpp_config() - p.tun_if = VppGreInterface(self, - self.pg0.local_ip4, - self.pg0.remote_ip4, - type=(VppEnum.vl_api_gre_tunnel_type_t. - GRE_API_TUNNEL_TYPE_TEB)) + p.tun_if = VppGreInterface( + self, + self.pg0.local_ip4, + self.pg0.remote_ip4, + type=(VppEnum.vl_api_gre_tunnel_type_t.GRE_API_TUNNEL_TYPE_TEB), + ) p.tun_if.add_vpp_config() - p.tun_protect = VppIpsecTunProtect(self, - p.tun_if, - p.tun_sa_out, - [p.tun_sa_in]) + p.tun_protect = VppIpsecTunProtect(self, p.tun_if, p.tun_sa_out, [p.tun_sa_in]) p.tun_protect.add_vpp_config() @@ -1067,34 +1221,37 @@ class TestIpsecGreTebIfEsp(TemplateIpsec, super(TestIpsecGreTebIfEsp, self).tearDown() -class TestIpsecGreTebVlanIfEsp(TemplateIpsec, - IpsecTun4Tests): - """ Ipsec GRE TEB ESP - TUN tests """ +class TestIpsecGreTebVlanIfEsp(TemplateIpsec, IpsecTun4Tests): + """Ipsec GRE TEB ESP - TUN tests""" + tun4_encrypt_node_name = "esp4-encrypt-tun" tun4_decrypt_node_name = ["esp4-decrypt-tun", "esp4-decrypt-tun-post"] encryption_type = ESP omac = "00:11:22:33:44:55" - def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - sa.encrypt(IP(src=self.pg0.remote_ip4, - dst=self.pg0.local_ip4) / - GRE() / - Ether(dst=self.omac) / - IP(src="1.1.1.1", dst="1.1.1.2") / - UDP(sport=1144, dport=2233) / - Raw(b'X' * payload_size)) - for i in range(count)] - - def gen_pkts(self, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(dst=self.omac) / - Dot1Q(vlan=11) / - IP(src="1.1.1.1", dst="1.1.1.2") / - UDP(sport=1144, dport=2233) / - Raw(b'X' * payload_size) - for i in range(count)] + def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / sa.encrypt( + IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / GRE() + / Ether(dst=self.omac) + / IP(src="1.1.1.1", dst="1.1.1.2") + / UDP(sport=1144, dport=2233) + / Raw(b"X" * payload_size) + ) + for i in range(count) + ] + + def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(dst=self.omac) + / Dot1Q(vlan=11) + / IP(src="1.1.1.1", dst="1.1.1.2") + / UDP(sport=1144, dport=2233) + / Raw(b"X" * payload_size) + for i in range(count) + ] def verify_decrypted(self, p, rxs): for rx in rxs: @@ -1136,37 +1293,49 @@ class TestIpsecGreTebVlanIfEsp(TemplateIpsec, self.pg1_11 = VppDot1QSubint(self, self.pg1, 11) self.vapi.l2_interface_vlan_tag_rewrite( - sw_if_index=self.pg1_11.sw_if_index, vtr_op=L2_VTR_OP.L2_POP_1, - push_dot1q=11) + sw_if_index=self.pg1_11.sw_if_index, + vtr_op=L2_VTR_OP.L2_POP_1, + push_dot1q=11, + ) self.pg1_11.admin_up() - p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol, - self.pg0.local_ip4, - self.pg0.remote_ip4) + p.tun_sa_out = VppIpsecSA( + self, + p.scapy_tun_sa_id, + p.scapy_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + self.pg0.local_ip4, + self.pg0.remote_ip4, + ) p.tun_sa_out.add_vpp_config() - p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol, - self.pg0.remote_ip4, - self.pg0.local_ip4) + p.tun_sa_in = VppIpsecSA( + self, + p.vpp_tun_sa_id, + p.vpp_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + self.pg0.remote_ip4, + self.pg0.local_ip4, + ) p.tun_sa_in.add_vpp_config() - p.tun_if = VppGreInterface(self, - self.pg0.local_ip4, - self.pg0.remote_ip4, - type=(VppEnum.vl_api_gre_tunnel_type_t. - GRE_API_TUNNEL_TYPE_TEB)) + p.tun_if = VppGreInterface( + self, + self.pg0.local_ip4, + self.pg0.remote_ip4, + type=(VppEnum.vl_api_gre_tunnel_type_t.GRE_API_TUNNEL_TYPE_TEB), + ) p.tun_if.add_vpp_config() - p.tun_protect = VppIpsecTunProtect(self, - p.tun_if, - p.tun_sa_out, - [p.tun_sa_in]) + p.tun_protect = VppIpsecTunProtect(self, p.tun_if, p.tun_sa_out, [p.tun_sa_in]) p.tun_protect.add_vpp_config() @@ -1187,33 +1356,36 @@ class TestIpsecGreTebVlanIfEsp(TemplateIpsec, self.pg1_11.remove_vpp_config() -class TestIpsecGreTebIfEspTra(TemplateIpsec, - IpsecTun4Tests): - """ Ipsec GRE TEB ESP - Tra tests """ +class TestIpsecGreTebIfEspTra(TemplateIpsec, IpsecTun4Tests): + """Ipsec GRE TEB ESP - Tra tests""" + tun4_encrypt_node_name = "esp4-encrypt-tun" tun4_decrypt_node_name = ["esp4-decrypt-tun", "esp4-decrypt-tun-post"] encryption_type = ESP omac = "00:11:22:33:44:55" - def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - sa.encrypt(IP(src=self.pg0.remote_ip4, - dst=self.pg0.local_ip4) / - GRE() / - Ether(dst=self.omac) / - IP(src="1.1.1.1", dst="1.1.1.2") / - UDP(sport=1144, dport=2233) / - Raw(b'X' * payload_size)) - for i in range(count)] - - def gen_pkts(self, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(dst=self.omac) / - IP(src="1.1.1.1", dst="1.1.1.2") / - UDP(sport=1144, dport=2233) / - Raw(b'X' * payload_size) - for i in range(count)] + def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / sa.encrypt( + IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / GRE() + / Ether(dst=self.omac) + / IP(src="1.1.1.1", dst="1.1.1.2") + / UDP(sport=1144, dport=2233) + / Raw(b"X" * payload_size) + ) + for i in range(count) + ] + + def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(dst=self.omac) + / IP(src="1.1.1.1", dst="1.1.1.2") + / UDP(sport=1144, dport=2233) + / Raw(b"X" * payload_size) + for i in range(count) + ] def verify_decrypted(self, p, rxs): for rx in rxs: @@ -1251,29 +1423,39 @@ class TestIpsecGreTebIfEspTra(TemplateIpsec, bd1 = VppBridgeDomain(self, 1) bd1.add_vpp_config() - p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol) + p.tun_sa_out = VppIpsecSA( + self, + p.scapy_tun_sa_id, + p.scapy_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + ) p.tun_sa_out.add_vpp_config() - p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol) + p.tun_sa_in = VppIpsecSA( + self, + p.vpp_tun_sa_id, + p.vpp_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + ) p.tun_sa_in.add_vpp_config() - p.tun_if = VppGreInterface(self, - self.pg0.local_ip4, - self.pg0.remote_ip4, - type=(VppEnum.vl_api_gre_tunnel_type_t. - GRE_API_TUNNEL_TYPE_TEB)) + p.tun_if = VppGreInterface( + self, + self.pg0.local_ip4, + self.pg0.remote_ip4, + type=(VppEnum.vl_api_gre_tunnel_type_t.GRE_API_TUNNEL_TYPE_TEB), + ) p.tun_if.add_vpp_config() - p.tun_protect = VppIpsecTunProtect(self, - p.tun_if, - p.tun_sa_out, - [p.tun_sa_in]) + p.tun_protect = VppIpsecTunProtect(self, p.tun_if, p.tun_sa_out, [p.tun_sa_in]) p.tun_protect.add_vpp_config() @@ -1292,33 +1474,36 @@ class TestIpsecGreTebIfEspTra(TemplateIpsec, super(TestIpsecGreTebIfEspTra, self).tearDown() -class TestIpsecGreTebUdpIfEspTra(TemplateIpsec, - IpsecTun4Tests): - """ Ipsec GRE TEB UDP ESP - Tra tests """ +class TestIpsecGreTebUdpIfEspTra(TemplateIpsec, IpsecTun4Tests): + """Ipsec GRE TEB UDP ESP - Tra tests""" + tun4_encrypt_node_name = "esp4-encrypt-tun" tun4_decrypt_node_name = ["esp4-decrypt-tun", "esp4-decrypt-tun-post"] encryption_type = ESP omac = "00:11:22:33:44:55" - def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - sa.encrypt(IP(src=self.pg0.remote_ip4, - dst=self.pg0.local_ip4) / - GRE() / - Ether(dst=self.omac) / - IP(src="1.1.1.1", dst="1.1.1.2") / - UDP(sport=1144, dport=2233) / - Raw(b'X' * payload_size)) - for i in range(count)] - - def gen_pkts(self, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(dst=self.omac) / - IP(src="1.1.1.1", dst="1.1.1.2") / - UDP(sport=1144, dport=2233) / - Raw(b'X' * payload_size) - for i in range(count)] + def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / sa.encrypt( + IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / GRE() + / Ether(dst=self.omac) + / IP(src="1.1.1.1", dst="1.1.1.2") + / UDP(sport=1144, dport=2233) + / Raw(b"X" * payload_size) + ) + for i in range(count) + ] + + def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(dst=self.omac) + / IP(src="1.1.1.1", dst="1.1.1.2") + / UDP(sport=1144, dport=2233) + / Raw(b"X" * payload_size) + for i in range(count) + ] def verify_decrypted(self, p, rxs): for rx in rxs: @@ -1356,44 +1541,53 @@ class TestIpsecGreTebUdpIfEspTra(TemplateIpsec, p = self.ipv4_params p = self.ipv4_params - p.flags = (VppEnum.vl_api_ipsec_sad_flags_t. - IPSEC_API_SAD_FLAG_UDP_ENCAP) + p.flags = VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_UDP_ENCAP p.nat_header = UDP(sport=5454, dport=4545) bd1 = VppBridgeDomain(self, 1) bd1.add_vpp_config() - p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol, - flags=p.flags, - udp_src=5454, - udp_dst=4545) + p.tun_sa_out = VppIpsecSA( + self, + p.scapy_tun_sa_id, + p.scapy_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + flags=p.flags, + udp_src=5454, + udp_dst=4545, + ) p.tun_sa_out.add_vpp_config() - p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol, - flags=(p.flags | - VppEnum.vl_api_ipsec_sad_flags_t. - IPSEC_API_SAD_FLAG_IS_INBOUND), - udp_src=4545, - udp_dst=5454) + p.tun_sa_in = VppIpsecSA( + self, + p.vpp_tun_sa_id, + p.vpp_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + flags=( + p.flags | VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_IS_INBOUND + ), + udp_src=4545, + udp_dst=5454, + ) p.tun_sa_in.add_vpp_config() - p.tun_if = VppGreInterface(self, - self.pg0.local_ip4, - self.pg0.remote_ip4, - type=(VppEnum.vl_api_gre_tunnel_type_t. - GRE_API_TUNNEL_TYPE_TEB)) + p.tun_if = VppGreInterface( + self, + self.pg0.local_ip4, + self.pg0.remote_ip4, + type=(VppEnum.vl_api_gre_tunnel_type_t.GRE_API_TUNNEL_TYPE_TEB), + ) p.tun_if.add_vpp_config() - p.tun_protect = VppIpsecTunProtect(self, - p.tun_if, - p.tun_sa_out, - [p.tun_sa_in]) + p.tun_protect = VppIpsecTunProtect(self, p.tun_if, p.tun_sa_out, [p.tun_sa_in]) p.tun_protect.add_vpp_config() @@ -1413,32 +1607,34 @@ class TestIpsecGreTebUdpIfEspTra(TemplateIpsec, super(TestIpsecGreTebUdpIfEspTra, self).tearDown() -class TestIpsecGreIfEsp(TemplateIpsec, - IpsecTun4Tests): - """ Ipsec GRE ESP - TUN tests """ +class TestIpsecGreIfEsp(TemplateIpsec, IpsecTun4Tests): + """Ipsec GRE ESP - TUN tests""" + tun4_encrypt_node_name = "esp4-encrypt-tun" tun4_decrypt_node_name = ["esp4-decrypt-tun", "esp4-decrypt-tun-post"] encryption_type = ESP - def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - sa.encrypt(IP(src=self.pg0.remote_ip4, - dst=self.pg0.local_ip4) / - GRE() / - IP(src=self.pg1.local_ip4, - dst=self.pg1.remote_ip4) / - UDP(sport=1144, dport=2233) / - Raw(b'X' * payload_size)) - for i in range(count)] - - def gen_pkts(self, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - IP(src="1.1.1.1", dst="1.1.1.2") / - UDP(sport=1144, dport=2233) / - Raw(b'X' * payload_size) - for i in range(count)] + def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / sa.encrypt( + IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / GRE() + / IP(src=self.pg1.local_ip4, dst=self.pg1.remote_ip4) + / UDP(sport=1144, dport=2233) + / Raw(b"X" * payload_size) + ) + for i in range(count) + ] + + def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / IP(src="1.1.1.1", dst="1.1.1.2") + / UDP(sport=1144, dport=2233) + / Raw(b"X" * payload_size) + for i in range(count) + ] def verify_decrypted(self, p, rxs): for rx in rxs: @@ -1475,40 +1671,47 @@ class TestIpsecGreIfEsp(TemplateIpsec, bd1 = VppBridgeDomain(self, 1) bd1.add_vpp_config() - p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol, - self.pg0.local_ip4, - self.pg0.remote_ip4) + p.tun_sa_out = VppIpsecSA( + self, + p.scapy_tun_sa_id, + p.scapy_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + self.pg0.local_ip4, + self.pg0.remote_ip4, + ) p.tun_sa_out.add_vpp_config() - p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol, - self.pg0.remote_ip4, - self.pg0.local_ip4) + p.tun_sa_in = VppIpsecSA( + self, + p.vpp_tun_sa_id, + p.vpp_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + self.pg0.remote_ip4, + self.pg0.local_ip4, + ) p.tun_sa_in.add_vpp_config() - p.tun_if = VppGreInterface(self, - self.pg0.local_ip4, - self.pg0.remote_ip4) + p.tun_if = VppGreInterface(self, self.pg0.local_ip4, self.pg0.remote_ip4) p.tun_if.add_vpp_config() - p.tun_protect = VppIpsecTunProtect(self, - p.tun_if, - p.tun_sa_out, - [p.tun_sa_in]) + p.tun_protect = VppIpsecTunProtect(self, p.tun_if, p.tun_sa_out, [p.tun_sa_in]) p.tun_protect.add_vpp_config() p.tun_if.admin_up() p.tun_if.config_ip4() config_tun_params(p, self.encryption_type, p.tun_if) - VppIpRoute(self, "1.1.1.2", 32, - [VppRoutePath(p.tun_if.remote_ip4, - 0xffffffff)]).add_vpp_config() + VppIpRoute( + self, "1.1.1.2", 32, [VppRoutePath(p.tun_if.remote_ip4, 0xFFFFFFFF)] + ).add_vpp_config() def tearDown(self): p = self.ipv4_params @@ -1516,42 +1719,46 @@ class TestIpsecGreIfEsp(TemplateIpsec, super(TestIpsecGreIfEsp, self).tearDown() -class TestIpsecGreIfEspTra(TemplateIpsec, - IpsecTun4Tests): - """ Ipsec GRE ESP - TRA tests """ +class TestIpsecGreIfEspTra(TemplateIpsec, IpsecTun4Tests): + """Ipsec GRE ESP - TRA tests""" + tun4_encrypt_node_name = "esp4-encrypt-tun" tun4_decrypt_node_name = ["esp4-decrypt-tun", "esp4-decrypt-tun-post"] encryption_type = ESP - def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - sa.encrypt(IP(src=self.pg0.remote_ip4, - dst=self.pg0.local_ip4) / - GRE() / - IP(src=self.pg1.local_ip4, - dst=self.pg1.remote_ip4) / - UDP(sport=1144, dport=2233) / - Raw(b'X' * payload_size)) - for i in range(count)] - - def gen_encrypt_non_ip_pkts(self, sa, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - sa.encrypt(IP(src=self.pg0.remote_ip4, - dst=self.pg0.local_ip4) / - GRE() / - UDP(sport=1144, dport=2233) / - Raw(b'X' * payload_size)) - for i in range(count)] - - def gen_pkts(self, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - IP(src="1.1.1.1", dst="1.1.1.2") / - UDP(sport=1144, dport=2233) / - Raw(b'X' * payload_size) - for i in range(count)] + def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / sa.encrypt( + IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / GRE() + / IP(src=self.pg1.local_ip4, dst=self.pg1.remote_ip4) + / UDP(sport=1144, dport=2233) + / Raw(b"X" * payload_size) + ) + for i in range(count) + ] + + def gen_encrypt_non_ip_pkts(self, sa, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / sa.encrypt( + IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / GRE() + / UDP(sport=1144, dport=2233) + / Raw(b"X" * payload_size) + ) + for i in range(count) + ] + + def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / IP(src="1.1.1.1", dst="1.1.1.2") + / UDP(sport=1144, dport=2233) + / Raw(b"X" * payload_size) + for i in range(count) + ] def verify_decrypted(self, p, rxs): for rx in rxs: @@ -1583,36 +1790,43 @@ class TestIpsecGreIfEspTra(TemplateIpsec, p = self.ipv4_params - p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol) + p.tun_sa_out = VppIpsecSA( + self, + p.scapy_tun_sa_id, + p.scapy_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + ) p.tun_sa_out.add_vpp_config() - p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol) + p.tun_sa_in = VppIpsecSA( + self, + p.vpp_tun_sa_id, + p.vpp_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + ) p.tun_sa_in.add_vpp_config() - p.tun_if = VppGreInterface(self, - self.pg0.local_ip4, - self.pg0.remote_ip4) + p.tun_if = VppGreInterface(self, self.pg0.local_ip4, self.pg0.remote_ip4) p.tun_if.add_vpp_config() - p.tun_protect = VppIpsecTunProtect(self, - p.tun_if, - p.tun_sa_out, - [p.tun_sa_in]) + p.tun_protect = VppIpsecTunProtect(self, p.tun_if, p.tun_sa_out, [p.tun_sa_in]) p.tun_protect.add_vpp_config() p.tun_if.admin_up() p.tun_if.config_ip4() config_tra_params(p, self.encryption_type, p.tun_if) - VppIpRoute(self, "1.1.1.2", 32, - [VppRoutePath(p.tun_if.remote_ip4, - 0xffffffff)]).add_vpp_config() + VppIpRoute( + self, "1.1.1.2", 32, [VppRoutePath(p.tun_if.remote_ip4, 0xFFFFFFFF)] + ).add_vpp_config() def tearDown(self): p = self.ipv4_params @@ -1621,41 +1835,45 @@ class TestIpsecGreIfEspTra(TemplateIpsec, def test_gre_non_ip(self): p = self.ipv4_params - tx = self.gen_encrypt_non_ip_pkts(p.scapy_tun_sa, self.tun_if, - src=p.remote_tun_if_host, - dst=self.pg1.remote_ip6) + tx = self.gen_encrypt_non_ip_pkts( + p.scapy_tun_sa, + self.tun_if, + src=p.remote_tun_if_host, + dst=self.pg1.remote_ip6, + ) self.send_and_assert_no_replies(self.tun_if, tx) - node_name = ('/err/%s/unsupported payload' % - self.tun4_decrypt_node_name[0]) + node_name = "/err/%s/unsupported payload" % self.tun4_decrypt_node_name[0] self.assertEqual(1, self.statistics.get_err_counter(node_name)) -class TestIpsecGre6IfEspTra(TemplateIpsec, - IpsecTun6Tests): - """ Ipsec GRE ESP - TRA tests """ +class TestIpsecGre6IfEspTra(TemplateIpsec, IpsecTun6Tests): + """Ipsec GRE ESP - TRA tests""" + tun6_encrypt_node_name = "esp6-encrypt-tun" tun6_decrypt_node_name = ["esp6-decrypt-tun", "esp6-decrypt-tun-post"] encryption_type = ESP - def gen_encrypt_pkts6(self, p, sa, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - sa.encrypt(IPv6(src=self.pg0.remote_ip6, - dst=self.pg0.local_ip6) / - GRE() / - IPv6(src=self.pg1.local_ip6, - dst=self.pg1.remote_ip6) / - UDP(sport=1144, dport=2233) / - Raw(b'X' * payload_size)) - for i in range(count)] - - def gen_pkts6(self, p, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - IPv6(src="1::1", dst="1::2") / - UDP(sport=1144, dport=2233) / - Raw(b'X' * payload_size) - for i in range(count)] + def gen_encrypt_pkts6(self, p, sa, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / sa.encrypt( + IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) + / GRE() + / IPv6(src=self.pg1.local_ip6, dst=self.pg1.remote_ip6) + / UDP(sport=1144, dport=2233) + / Raw(b"X" * payload_size) + ) + for i in range(count) + ] + + def gen_pkts6(self, p, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / IPv6(src="1::1", dst="1::2") + / UDP(sport=1144, dport=2233) + / Raw(b"X" * payload_size) + for i in range(count) + ] def verify_decrypted6(self, p, rxs): for rx in rxs: @@ -1690,37 +1908,50 @@ class TestIpsecGre6IfEspTra(TemplateIpsec, bd1 = VppBridgeDomain(self, 1) bd1.add_vpp_config() - p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol) + p.tun_sa_out = VppIpsecSA( + self, + p.scapy_tun_sa_id, + p.scapy_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + ) p.tun_sa_out.add_vpp_config() - p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol) + p.tun_sa_in = VppIpsecSA( + self, + p.vpp_tun_sa_id, + p.vpp_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + ) p.tun_sa_in.add_vpp_config() - p.tun_if = VppGreInterface(self, - self.pg0.local_ip6, - self.pg0.remote_ip6) + p.tun_if = VppGreInterface(self, self.pg0.local_ip6, self.pg0.remote_ip6) p.tun_if.add_vpp_config() - p.tun_protect = VppIpsecTunProtect(self, - p.tun_if, - p.tun_sa_out, - [p.tun_sa_in]) + p.tun_protect = VppIpsecTunProtect(self, p.tun_if, p.tun_sa_out, [p.tun_sa_in]) p.tun_protect.add_vpp_config() p.tun_if.admin_up() p.tun_if.config_ip6() config_tra_params(p, self.encryption_type, p.tun_if) - r = VppIpRoute(self, "1::2", 128, - [VppRoutePath(p.tun_if.remote_ip6, - 0xffffffff, - proto=DpoProto.DPO_PROTO_IP6)]) + r = VppIpRoute( + self, + "1::2", + 128, + [ + VppRoutePath( + p.tun_if.remote_ip6, 0xFFFFFFFF, proto=DpoProto.DPO_PROTO_IP6 + ) + ], + ) r.add_vpp_config() def tearDown(self): @@ -1730,30 +1961,33 @@ class TestIpsecGre6IfEspTra(TemplateIpsec, class TestIpsecMGreIfEspTra4(TemplateIpsec, IpsecTun4): - """ Ipsec mGRE ESP v4 TRA tests """ + """Ipsec mGRE ESP v4 TRA tests""" + tun4_encrypt_node_name = "esp4-encrypt-tun" tun4_decrypt_node_name = ["esp4-decrypt-tun", "esp4-decrypt-tun-post"] encryption_type = ESP - def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - sa.encrypt(IP(src=p.tun_dst, - dst=self.pg0.local_ip4) / - GRE() / - IP(src=self.pg1.local_ip4, - dst=self.pg1.remote_ip4) / - UDP(sport=1144, dport=2233) / - Raw(b'X' * payload_size)) - for i in range(count)] - - def gen_pkts(self, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - IP(src="1.1.1.1", dst=dst) / - UDP(sport=1144, dport=2233) / - Raw(b'X' * payload_size) - for i in range(count)] + def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / sa.encrypt( + IP(src=p.tun_dst, dst=self.pg0.local_ip4) + / GRE() + / IP(src=self.pg1.local_ip4, dst=self.pg1.remote_ip4) + / UDP(sport=1144, dport=2233) + / Raw(b"X" * payload_size) + ) + for i in range(count) + ] + + def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / IP(src="1.1.1.1", dst=dst) + / UDP(sport=1144, dport=2233) + / Raw(b"X" * payload_size) + for i in range(count) + ] def verify_decrypted(self, p, rxs): for rx in rxs: @@ -1784,11 +2018,12 @@ class TestIpsecMGreIfEspTra4(TemplateIpsec, IpsecTun4): N_NHS = 16 self.tun_if = self.pg0 p = self.ipv4_params - p.tun_if = VppGreInterface(self, - self.pg0.local_ip4, - "0.0.0.0", - mode=(VppEnum.vl_api_tunnel_mode_t. - TUNNEL_API_MODE_MP)) + p.tun_if = VppGreInterface( + self, + self.pg0.local_ip4, + "0.0.0.0", + mode=(VppEnum.vl_api_tunnel_mode_t.TUNNEL_API_MODE_MP), + ) p.tun_if.add_vpp_config() p.tun_if.admin_up() p.tun_if.config_ip4() @@ -1812,16 +2047,28 @@ class TestIpsecMGreIfEspTra4(TemplateIpsec, IpsecTun4): p.scapy_tra_spi = p.scapy_tra_spi + ii p.vpp_tra_sa_id = p.vpp_tra_sa_id + ii p.vpp_tra_spi = p.vpp_tra_spi + ii - p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol) + p.tun_sa_out = VppIpsecSA( + self, + p.scapy_tun_sa_id, + p.scapy_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + ) p.tun_sa_out.add_vpp_config() - p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol) + p.tun_sa_in = VppIpsecSA( + self, + p.vpp_tun_sa_id, + p.vpp_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + ) p.tun_sa_in.add_vpp_config() p.tun_protect = VppIpsecTunProtect( @@ -1829,19 +2076,26 @@ class TestIpsecMGreIfEspTra4(TemplateIpsec, IpsecTun4): p.tun_if, p.tun_sa_out, [p.tun_sa_in], - nh=p.tun_if.remote_hosts[ii].ip4) + nh=p.tun_if.remote_hosts[ii].ip4, + ) p.tun_protect.add_vpp_config() config_tra_params(p, self.encryption_type, p.tun_if) self.multi_params.append(p) - VppIpRoute(self, p.remote_tun_if_host, 32, - [VppRoutePath(p.tun_if.remote_hosts[ii].ip4, - p.tun_if.sw_if_index)]).add_vpp_config() + VppIpRoute( + self, + p.remote_tun_if_host, + 32, + [VppRoutePath(p.tun_if.remote_hosts[ii].ip4, p.tun_if.sw_if_index)], + ).add_vpp_config() # in this v4 variant add the teibs after the protect - p.teib = VppTeib(self, p.tun_if, - p.tun_if.remote_hosts[ii].ip4, - self.pg0.remote_hosts[ii].ip4).add_vpp_config() + p.teib = VppTeib( + self, + p.tun_if, + p.tun_if.remote_hosts[ii].ip4, + self.pg0.remote_hosts[ii].ip4, + ).add_vpp_config() p.tun_dst = self.pg0.remote_hosts[ii].ip4 self.logger.info(self.vapi.cli("sh ipsec protect-hash")) @@ -1862,30 +2116,33 @@ class TestIpsecMGreIfEspTra4(TemplateIpsec, IpsecTun4): class TestIpsecMGreIfEspTra6(TemplateIpsec, IpsecTun6): - """ Ipsec mGRE ESP v6 TRA tests """ + """Ipsec mGRE ESP v6 TRA tests""" + tun6_encrypt_node_name = "esp6-encrypt-tun" tun6_decrypt_node_name = ["esp6-decrypt-tun", "esp6-decrypt-tun-post"] encryption_type = ESP - def gen_encrypt_pkts6(self, p, sa, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - sa.encrypt(IPv6(src=p.tun_dst, - dst=self.pg0.local_ip6) / - GRE() / - IPv6(src=self.pg1.local_ip6, - dst=self.pg1.remote_ip6) / - UDP(sport=1144, dport=2233) / - Raw(b'X' * payload_size)) - for i in range(count)] - - def gen_pkts6(self, p, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - IPv6(src="1::1", dst=dst) / - UDP(sport=1144, dport=2233) / - Raw(b'X' * payload_size) - for i in range(count)] + def gen_encrypt_pkts6(self, p, sa, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / sa.encrypt( + IPv6(src=p.tun_dst, dst=self.pg0.local_ip6) + / GRE() + / IPv6(src=self.pg1.local_ip6, dst=self.pg1.remote_ip6) + / UDP(sport=1144, dport=2233) + / Raw(b"X" * payload_size) + ) + for i in range(count) + ] + + def gen_pkts6(self, p, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / IPv6(src="1::1", dst=dst) + / UDP(sport=1144, dport=2233) + / Raw(b"X" * payload_size) + for i in range(count) + ] def verify_decrypted6(self, p, rxs): for rx in rxs: @@ -1918,11 +2175,12 @@ class TestIpsecMGreIfEspTra6(TemplateIpsec, IpsecTun6): N_NHS = 16 self.tun_if = self.pg0 p = self.ipv6_params - p.tun_if = VppGreInterface(self, - self.pg0.local_ip6, - "::", - mode=(VppEnum.vl_api_tunnel_mode_t. - TUNNEL_API_MODE_MP)) + p.tun_if = VppGreInterface( + self, + self.pg0.local_ip6, + "::", + mode=(VppEnum.vl_api_tunnel_mode_t.TUNNEL_API_MODE_MP), + ) p.tun_if.add_vpp_config() p.tun_if.admin_up() p.tun_if.config_ip6() @@ -1946,37 +2204,53 @@ class TestIpsecMGreIfEspTra6(TemplateIpsec, IpsecTun6): p.scapy_tra_spi = p.scapy_tra_spi + ii p.vpp_tra_sa_id = p.vpp_tra_sa_id + ii p.vpp_tra_spi = p.vpp_tra_spi + ii - p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol) + p.tun_sa_out = VppIpsecSA( + self, + p.scapy_tun_sa_id, + p.scapy_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + ) p.tun_sa_out.add_vpp_config() - p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol) + p.tun_sa_in = VppIpsecSA( + self, + p.vpp_tun_sa_id, + p.vpp_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + ) p.tun_sa_in.add_vpp_config() # in this v6 variant add the teibs first then the protection p.tun_dst = self.pg0.remote_hosts[ii].ip6 - VppTeib(self, p.tun_if, - p.tun_if.remote_hosts[ii].ip6, - p.tun_dst).add_vpp_config() + VppTeib( + self, p.tun_if, p.tun_if.remote_hosts[ii].ip6, p.tun_dst + ).add_vpp_config() p.tun_protect = VppIpsecTunProtect( self, p.tun_if, p.tun_sa_out, [p.tun_sa_in], - nh=p.tun_if.remote_hosts[ii].ip6) + nh=p.tun_if.remote_hosts[ii].ip6, + ) p.tun_protect.add_vpp_config() config_tra_params(p, self.encryption_type, p.tun_if) self.multi_params.append(p) - VppIpRoute(self, p.remote_tun_if_host, 128, - [VppRoutePath(p.tun_if.remote_hosts[ii].ip6, - p.tun_if.sw_if_index)]).add_vpp_config() + VppIpRoute( + self, + p.remote_tun_if_host, + 128, + [VppRoutePath(p.tun_if.remote_hosts[ii].ip6, p.tun_if.sw_if_index)], + ).add_vpp_config() p.tun_dst = self.pg0.remote_hosts[ii].ip6 self.logger.info(self.vapi.cli("sh log")) @@ -1995,10 +2269,8 @@ class TestIpsecMGreIfEspTra6(TemplateIpsec, IpsecTun6): @tag_fixme_vpp_workers -class TestIpsec4TunProtect(TemplateIpsec, - TemplateIpsec4TunProtect, - IpsecTun4): - """ IPsec IPv4 Tunnel protect - transport mode""" +class TestIpsec4TunProtect(TemplateIpsec, TemplateIpsec4TunProtect, IpsecTun4): + """IPsec IPv4 Tunnel protect - transport mode""" def setUp(self): super(TestIpsec4TunProtect, self).setUp() @@ -2028,7 +2300,7 @@ class TestIpsec4TunProtect(TemplateIpsec, # rekey - create new SAs and update the tunnel protection np = copy.copy(p) - np.crypt_key = b'X' + p.crypt_key[1:] + np.crypt_key = b"X" + p.crypt_key[1:] np.scapy_tun_spi += 100 np.scapy_tun_sa_id += 1 np.vpp_tun_spi += 100 @@ -2051,10 +2323,8 @@ class TestIpsec4TunProtect(TemplateIpsec, @tag_fixme_vpp_workers -class TestIpsec4TunProtectUdp(TemplateIpsec, - TemplateIpsec4TunProtect, - IpsecTun4): - """ IPsec IPv4 Tunnel protect - transport mode""" +class TestIpsec4TunProtectUdp(TemplateIpsec, TemplateIpsec4TunProtect, IpsecTun4): + """IPsec IPv4 Tunnel protect - transport mode""" def setUp(self): super(TestIpsec4TunProtectUdp, self).setUp() @@ -2062,8 +2332,7 @@ class TestIpsec4TunProtectUdp(TemplateIpsec, self.tun_if = self.pg0 p = self.ipv4_params - p.flags = (VppEnum.vl_api_ipsec_sad_flags_t. - IPSEC_API_SAD_FLAG_UDP_ENCAP) + p.flags = VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_UDP_ENCAP p.nat_header = UDP(sport=4500, dport=4500) self.config_network(p) self.config_sa_tra(p) @@ -2093,15 +2362,13 @@ class TestIpsec4TunProtectUdp(TemplateIpsec, self.assertEqual(p.tun_if.get_tx_stats(), 127) def test_keepalive(self): - """ IPSEC NAT Keepalive """ + """IPSEC NAT Keepalive""" self.verify_keepalive(self.ipv4_params) @tag_fixme_vpp_workers -class TestIpsec4TunProtectTun(TemplateIpsec, - TemplateIpsec4TunProtect, - IpsecTun4): - """ IPsec IPv4 Tunnel protect - tunnel mode""" +class TestIpsec4TunProtectTun(TemplateIpsec, TemplateIpsec4TunProtect, IpsecTun4): + """IPsec IPv4 Tunnel protect - tunnel mode""" encryption_type = ESP tun4_encrypt_node_name = "esp4-encrypt-tun" @@ -2115,23 +2382,26 @@ class TestIpsec4TunProtectTun(TemplateIpsec, def tearDown(self): super(TestIpsec4TunProtectTun, self).tearDown() - def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - sa.encrypt(IP(src=sw_intf.remote_ip4, - dst=sw_intf.local_ip4) / - IP(src=src, dst=dst) / - UDP(sport=1144, dport=2233) / - Raw(b'X' * payload_size)) - for i in range(count)] - - def gen_pkts(self, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - IP(src=src, dst=dst) / - UDP(sport=1144, dport=2233) / - Raw(b'X' * payload_size) - for i in range(count)] + def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / sa.encrypt( + IP(src=sw_intf.remote_ip4, dst=sw_intf.local_ip4) + / IP(src=src, dst=dst) + / UDP(sport=1144, dport=2233) + / Raw(b"X" * payload_size) + ) + for i in range(count) + ] + + def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / IP(src=src, dst=dst) + / UDP(sport=1144, dport=2233) + / Raw(b"X" * payload_size) + for i in range(count) + ] def verify_decrypted(self, p, rxs): for rx in rxs: @@ -2160,7 +2430,7 @@ class TestIpsec4TunProtectTun(TemplateIpsec, raise def test_tun_44(self): - """IPSEC tunnel protect """ + """IPSEC tunnel protect""" p = self.ipv4_params @@ -2170,10 +2440,7 @@ class TestIpsec4TunProtectTun(TemplateIpsec, # also add an output features on the tunnel and physical interface # so we test they still work - r_all = AclRule(True, - src_prefix="0.0.0.0/0", - dst_prefix="0.0.0.0/0", - proto=0) + r_all = AclRule(True, src_prefix="0.0.0.0/0", dst_prefix="0.0.0.0/0", proto=0) a = VppAcl(self, [r_all]).add_vpp_config() VppAclInterface(self, self.pg0.sw_if_index, [a]).add_vpp_config() @@ -2186,7 +2453,7 @@ class TestIpsec4TunProtectTun(TemplateIpsec, # rekey - create new SAs and update the tunnel protection np = copy.copy(p) - np.crypt_key = b'X' + p.crypt_key[1:] + np.crypt_key = b"X" + p.crypt_key[1:] np.scapy_tun_spi += 100 np.scapy_tun_sa_id += 1 np.vpp_tun_spi += 100 @@ -2208,10 +2475,8 @@ class TestIpsec4TunProtectTun(TemplateIpsec, self.unconfig_network(p) -class TestIpsec4TunProtectTunDrop(TemplateIpsec, - TemplateIpsec4TunProtect, - IpsecTun4): - """ IPsec IPv4 Tunnel protect - tunnel mode - drop""" +class TestIpsec4TunProtectTunDrop(TemplateIpsec, TemplateIpsec4TunProtect, IpsecTun4): + """IPsec IPv4 Tunnel protect - tunnel mode - drop""" encryption_type = ESP tun4_encrypt_node_name = "esp4-encrypt-tun" @@ -2225,18 +2490,20 @@ class TestIpsec4TunProtectTunDrop(TemplateIpsec, def tearDown(self): super(TestIpsec4TunProtectTunDrop, self).tearDown() - def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - sa.encrypt(IP(src=sw_intf.remote_ip4, - dst="5.5.5.5") / - IP(src=src, dst=dst) / - UDP(sport=1144, dport=2233) / - Raw(b'X' * payload_size)) - for i in range(count)] + def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / sa.encrypt( + IP(src=sw_intf.remote_ip4, dst="5.5.5.5") + / IP(src=src, dst=dst) + / UDP(sport=1144, dport=2233) + / Raw(b"X" * payload_size) + ) + for i in range(count) + ] def test_tun_drop_44(self): - """IPSEC tunnel protect bogus tunnel header """ + """IPSEC tunnel protect bogus tunnel header""" p = self.ipv4_params @@ -2244,10 +2511,14 @@ class TestIpsec4TunProtectTunDrop(TemplateIpsec, self.config_sa_tun(p) self.config_protect(p) - tx = self.gen_encrypt_pkts(p, p.scapy_tun_sa, self.tun_if, - src=p.remote_tun_if_host, - dst=self.pg1.remote_ip4, - count=63) + tx = self.gen_encrypt_pkts( + p, + p.scapy_tun_sa, + self.tun_if, + src=p.remote_tun_if_host, + dst=self.pg1.remote_ip4, + count=63, + ) self.send_and_assert_no_replies(self.tun_if, tx) # teardown @@ -2257,10 +2528,8 @@ class TestIpsec4TunProtectTunDrop(TemplateIpsec, @tag_fixme_vpp_workers -class TestIpsec6TunProtect(TemplateIpsec, - TemplateIpsec6TunProtect, - IpsecTun6): - """ IPsec IPv6 Tunnel protect - transport mode""" +class TestIpsec6TunProtect(TemplateIpsec, TemplateIpsec6TunProtect, IpsecTun6): + """IPsec IPv6 Tunnel protect - transport mode""" encryption_type = ESP tun6_encrypt_node_name = "esp6-encrypt-tun" @@ -2289,7 +2558,7 @@ class TestIpsec6TunProtect(TemplateIpsec, # rekey - create new SAs and update the tunnel protection np = copy.copy(p) - np.crypt_key = b'X' + p.crypt_key[1:] + np.crypt_key = b"X" + p.crypt_key[1:] np.scapy_tun_spi += 100 np.scapy_tun_sa_id += 1 np.vpp_tun_spi += 100 @@ -2308,8 +2577,9 @@ class TestIpsec6TunProtect(TemplateIpsec, # bounce the interface state p.tun_if.admin_down() self.verify_drop_tun_66(np, count=127) - node = ('/err/ipsec6-tun-input/%s' % - 'ipsec packets received on disabled interface') + node = ( + "/err/ipsec6-tun-input/%s" % "ipsec packets received on disabled interface" + ) self.assertEqual(127, self.statistics.get_err_counter(node)) p.tun_if.admin_up() self.verify_tun_66(np, count=127) @@ -2319,7 +2589,7 @@ class TestIpsec6TunProtect(TemplateIpsec, # 2) swap output SA to [new] # 3) use only [new] input SA np3 = copy.copy(np) - np3.crypt_key = b'Z' + p.crypt_key[1:] + np3.crypt_key = b"Z" + p.crypt_key[1:] np3.scapy_tun_spi += 100 np3.scapy_tun_sa_id += 1 np3.vpp_tun_spi += 100 @@ -2330,25 +2600,22 @@ class TestIpsec6TunProtect(TemplateIpsec, self.config_sa_tra(np3) # step 1; - p.tun_protect.update_vpp_config(np.tun_sa_out, - [np.tun_sa_in, np3.tun_sa_in]) + p.tun_protect.update_vpp_config(np.tun_sa_out, [np.tun_sa_in, np3.tun_sa_in]) self.verify_tun_66(np, np, count=127) self.verify_tun_66(np3, np, count=127) # step 2; - p.tun_protect.update_vpp_config(np3.tun_sa_out, - [np.tun_sa_in, np3.tun_sa_in]) + p.tun_protect.update_vpp_config(np3.tun_sa_out, [np.tun_sa_in, np3.tun_sa_in]) self.verify_tun_66(np, np3, count=127) self.verify_tun_66(np3, np3, count=127) # step 1; - p.tun_protect.update_vpp_config(np3.tun_sa_out, - [np3.tun_sa_in]) + p.tun_protect.update_vpp_config(np3.tun_sa_out, [np3.tun_sa_in]) self.verify_tun_66(np3, np3, count=127) self.verify_drop_tun_rx_66(np, count=127) - self.assertEqual(p.tun_if.get_rx_stats(), 127*9) - self.assertEqual(p.tun_if.get_tx_stats(), 127*8) + self.assertEqual(p.tun_if.get_rx_stats(), 127 * 9) + self.assertEqual(p.tun_if.get_tx_stats(), 127 * 8) self.unconfig_sa(np) # teardown @@ -2376,10 +2643,8 @@ class TestIpsec6TunProtect(TemplateIpsec, @tag_fixme_vpp_workers -class TestIpsec6TunProtectTun(TemplateIpsec, - TemplateIpsec6TunProtect, - IpsecTun6): - """ IPsec IPv6 Tunnel protect - tunnel mode""" +class TestIpsec6TunProtectTun(TemplateIpsec, TemplateIpsec6TunProtect, IpsecTun6): + """IPsec IPv6 Tunnel protect - tunnel mode""" encryption_type = ESP tun6_encrypt_node_name = "esp6-encrypt-tun" @@ -2393,23 +2658,26 @@ class TestIpsec6TunProtectTun(TemplateIpsec, def tearDown(self): super(TestIpsec6TunProtectTun, self).tearDown() - def gen_encrypt_pkts6(self, p, sa, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - sa.encrypt(IPv6(src=sw_intf.remote_ip6, - dst=sw_intf.local_ip6) / - IPv6(src=src, dst=dst) / - UDP(sport=1166, dport=2233) / - Raw(b'X' * payload_size)) - for i in range(count)] - - def gen_pkts6(self, p, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - IPv6(src=src, dst=dst) / - UDP(sport=1166, dport=2233) / - Raw(b'X' * payload_size) - for i in range(count)] + def gen_encrypt_pkts6(self, p, sa, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / sa.encrypt( + IPv6(src=sw_intf.remote_ip6, dst=sw_intf.local_ip6) + / IPv6(src=src, dst=dst) + / UDP(sport=1166, dport=2233) + / Raw(b"X" * payload_size) + ) + for i in range(count) + ] + + def gen_pkts6(self, p, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / IPv6(src=src, dst=dst) + / UDP(sport=1166, dport=2233) + / Raw(b"X" * payload_size) + for i in range(count) + ] def verify_decrypted6(self, p, rxs): for rx in rxs: @@ -2438,7 +2706,7 @@ class TestIpsec6TunProtectTun(TemplateIpsec, raise def test_tun_66(self): - """IPSEC tunnel protect """ + """IPSEC tunnel protect""" p = self.ipv6_params @@ -2453,7 +2721,7 @@ class TestIpsec6TunProtectTun(TemplateIpsec, # rekey - create new SAs and update the tunnel protection np = copy.copy(p) - np.crypt_key = b'X' + p.crypt_key[1:] + np.crypt_key = b"X" + p.crypt_key[1:] np.scapy_tun_spi += 100 np.scapy_tun_sa_id += 1 np.vpp_tun_spi += 100 @@ -2475,10 +2743,8 @@ class TestIpsec6TunProtectTun(TemplateIpsec, self.unconfig_network(p) -class TestIpsec6TunProtectTunDrop(TemplateIpsec, - TemplateIpsec6TunProtect, - IpsecTun6): - """ IPsec IPv6 Tunnel protect - tunnel mode - drop""" +class TestIpsec6TunProtectTunDrop(TemplateIpsec, TemplateIpsec6TunProtect, IpsecTun6): + """IPsec IPv6 Tunnel protect - tunnel mode - drop""" encryption_type = ESP tun6_encrypt_node_name = "esp6-encrypt-tun" @@ -2492,20 +2758,22 @@ class TestIpsec6TunProtectTunDrop(TemplateIpsec, def tearDown(self): super(TestIpsec6TunProtectTunDrop, self).tearDown() - def gen_encrypt_pkts6(self, p, sa, sw_intf, src, dst, count=1, - payload_size=100): + def gen_encrypt_pkts6(self, p, sa, sw_intf, src, dst, count=1, payload_size=100): # the IP destination of the revelaed packet does not match # that assigned to the tunnel - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - sa.encrypt(IPv6(src=sw_intf.remote_ip6, - dst="5::5") / - IPv6(src=src, dst=dst) / - UDP(sport=1144, dport=2233) / - Raw(b'X' * payload_size)) - for i in range(count)] + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / sa.encrypt( + IPv6(src=sw_intf.remote_ip6, dst="5::5") + / IPv6(src=src, dst=dst) + / UDP(sport=1144, dport=2233) + / Raw(b"X" * payload_size) + ) + for i in range(count) + ] def test_tun_drop_66(self): - """IPSEC 6 tunnel protect bogus tunnel header """ + """IPSEC 6 tunnel protect bogus tunnel header""" p = self.ipv6_params @@ -2513,10 +2781,14 @@ class TestIpsec6TunProtectTunDrop(TemplateIpsec, self.config_sa_tun(p) self.config_protect(p) - tx = self.gen_encrypt_pkts6(p, p.scapy_tun_sa, self.tun_if, - src=p.remote_tun_if_host, - dst=self.pg1.remote_ip6, - count=63) + tx = self.gen_encrypt_pkts6( + p, + p.scapy_tun_sa, + self.tun_if, + src=p.remote_tun_if_host, + dst=self.pg1.remote_ip6, + count=63, + ) self.send_and_assert_no_replies(self.tun_if, tx) self.unconfig_protect(p) @@ -2525,7 +2797,7 @@ class TestIpsec6TunProtectTunDrop(TemplateIpsec, class TemplateIpsecItf4(object): - """ IPsec Interface IPv4 """ + """IPsec Interface IPv4""" encryption_type = ESP tun4_encrypt_node_name = "esp4-encrypt-tun" @@ -2535,30 +2807,41 @@ class TemplateIpsecItf4(object): def config_sa_tun(self, p, src, dst): config_tun_params(p, self.encryption_type, None, src, dst) - p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol, - src, dst, - flags=p.flags) + p.tun_sa_out = VppIpsecSA( + self, + p.scapy_tun_sa_id, + p.scapy_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + src, + dst, + flags=p.flags, + ) p.tun_sa_out.add_vpp_config() - p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol, - dst, src, - flags=p.flags) + p.tun_sa_in = VppIpsecSA( + self, + p.vpp_tun_sa_id, + p.vpp_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + dst, + src, + flags=p.flags, + ) p.tun_sa_in.add_vpp_config() def config_protect(self, p): - p.tun_protect = VppIpsecTunProtect(self, - p.tun_if, - p.tun_sa_out, - [p.tun_sa_in]) + p.tun_protect = VppIpsecTunProtect(self, p.tun_if, p.tun_sa_out, [p.tun_sa_in]) p.tun_protect.add_vpp_config() - def config_network(self, p, instance=0xffffffff): + def config_network(self, p, instance=0xFFFFFFFF): p.tun_if = VppIpsecInterface(self, instance=instance) p.tun_if.add_vpp_config() @@ -2566,14 +2849,23 @@ class TemplateIpsecItf4(object): p.tun_if.config_ip4() p.tun_if.config_ip6() - p.route = VppIpRoute(self, p.remote_tun_if_host, 32, - [VppRoutePath(p.tun_if.remote_ip4, - 0xffffffff)]) + p.route = VppIpRoute( + self, + p.remote_tun_if_host, + 32, + [VppRoutePath(p.tun_if.remote_ip4, 0xFFFFFFFF)], + ) p.route.add_vpp_config() - r = VppIpRoute(self, p.remote_tun_if_host6, 128, - [VppRoutePath(p.tun_if.remote_ip6, - 0xffffffff, - proto=DpoProto.DPO_PROTO_IP6)]) + r = VppIpRoute( + self, + p.remote_tun_if_host6, + 128, + [ + VppRoutePath( + p.tun_if.remote_ip6, 0xFFFFFFFF, proto=DpoProto.DPO_PROTO_IP6 + ) + ], + ) r.add_vpp_config() def unconfig_network(self, p): @@ -2589,10 +2881,8 @@ class TemplateIpsecItf4(object): @tag_fixme_vpp_workers -class TestIpsecItf4(TemplateIpsec, - TemplateIpsecItf4, - IpsecTun4): - """ IPsec Interface IPv4 """ +class TestIpsecItf4(TemplateIpsec, TemplateIpsecItf4, IpsecTun4): + """IPsec Interface IPv4""" def setUp(self): super(TestIpsecItf4, self).setUp() @@ -2621,13 +2911,11 @@ class TestIpsecItf4(TemplateIpsec, p = self.ipv4_params self.config_network(p) - config_tun_params(p, self.encryption_type, None, - self.pg0.local_ip4, - self.pg0.remote_ip4) + config_tun_params( + p, self.encryption_type, None, self.pg0.local_ip4, self.pg0.remote_ip4 + ) self.verify_tun_dropped_44(p, count=n_pkts) - self.config_sa_tun(p, - self.pg0.local_ip4, - self.pg0.remote_ip4) + self.config_sa_tun(p, self.pg0.local_ip4, self.pg0.remote_ip4) self.config_protect(p) self.verify_tun_44(p, count=n_pkts) @@ -2639,15 +2927,15 @@ class TestIpsecItf4(TemplateIpsec, p.tun_if.admin_up() self.verify_tun_44(p, count=n_pkts) - self.assertEqual(p.tun_if.get_rx_stats(), 3*n_pkts) - self.assertEqual(p.tun_if.get_tx_stats(), 2*n_pkts) + self.assertEqual(p.tun_if.get_rx_stats(), 3 * n_pkts) + self.assertEqual(p.tun_if.get_tx_stats(), 2 * n_pkts) # it's a v6 packet when its encrypted self.tun4_encrypt_node_name = "esp6-encrypt-tun" self.verify_tun_64(p, count=n_pkts) - self.assertEqual(p.tun_if.get_rx_stats(), 4*n_pkts) - self.assertEqual(p.tun_if.get_tx_stats(), 3*n_pkts) + self.assertEqual(p.tun_if.get_rx_stats(), 4 * n_pkts) + self.assertEqual(p.tun_if.get_tx_stats(), 3 * n_pkts) self.tun4_encrypt_node_name = "esp4-encrypt-tun" @@ -2655,7 +2943,7 @@ class TestIpsecItf4(TemplateIpsec, # rekey - create new SAs and update the tunnel protection np = copy.copy(p) - np.crypt_key = b'X' + p.crypt_key[1:] + np.crypt_key = b"X" + p.crypt_key[1:] np.scapy_tun_spi += 100 np.scapy_tun_sa_id += 1 np.vpp_tun_spi += 100 @@ -2663,9 +2951,7 @@ class TestIpsecItf4(TemplateIpsec, np.tun_if.local_spi = p.vpp_tun_spi np.tun_if.remote_spi = p.scapy_tun_spi - self.config_sa_tun(np, - self.pg0.local_ip4, - self.pg0.remote_ip4) + self.config_sa_tun(np, self.pg0.local_ip4, self.pg0.remote_ip4) self.config_protect(np) self.unconfig_sa(p) @@ -2684,17 +2970,15 @@ class TestIpsecItf4(TemplateIpsec, n_pkts = 127 p = copy.copy(self.ipv4_params) - p.auth_algo_vpp_id = (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_NONE) - p.crypt_algo_vpp_id = (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_NONE) + p.auth_algo_vpp_id = VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_NONE + p.crypt_algo_vpp_id = ( + VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_NONE + ) p.crypt_algo = "NULL" p.auth_algo = "NULL" self.config_network(p) - self.config_sa_tun(p, - self.pg0.local_ip4, - self.pg0.remote_ip4) + self.config_sa_tun(p, self.pg0.local_ip4, self.pg0.remote_ip4) self.config_protect(p) self.logger.info(self.vapi.cli("sh ipsec sa")) @@ -2711,18 +2995,23 @@ class TestIpsecItf4(TemplateIpsec, p = self.ipv4_params self.config_network(p) - self.config_sa_tun(p, - self.pg0.local_ip4, - self.pg0.remote_ip4) + self.config_sa_tun(p, self.pg0.local_ip4, self.pg0.remote_ip4) self.config_protect(p) action_tx = PolicerAction( - VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT, - 0) - policer = VppPolicer(self, "pol1", 80, 0, 1000, 0, - conform_action=action_tx, - exceed_action=action_tx, - violate_action=action_tx) + VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT, 0 + ) + policer = VppPolicer( + self, + "pol1", + 80, + 0, + 1000, + 0, + conform_action=action_tx, + exceed_action=action_tx, + violate_action=action_tx, + ) policer.add_vpp_config() # Start policing on tun @@ -2735,9 +3024,9 @@ class TestIpsecItf4(TemplateIpsec, stats = policer.get_stats() # Single rate, 2 colour policer - expect conform, violate but no exceed - self.assertGreater(stats['conform_packets'], 0) - self.assertEqual(stats['exceed_packets'], 0) - self.assertGreater(stats['violate_packets'], 0) + self.assertGreater(stats["conform_packets"], 0) + self.assertEqual(stats["exceed_packets"], 0) + self.assertGreater(stats["violate_packets"], 0) # Stop policing on tun policer.apply_vpp_config(p.tun_if.sw_if_index, Dir.RX, False) @@ -2754,10 +3043,8 @@ class TestIpsecItf4(TemplateIpsec, self.unconfig_network(p) -class TestIpsecItf4MPLS(TemplateIpsec, - TemplateIpsecItf4, - IpsecTun4): - """ IPsec Interface MPLSoIPv4 """ +class TestIpsecItf4MPLS(TemplateIpsec, TemplateIpsecItf4, IpsecTun4): + """IPsec Interface MPLSoIPv4""" tun4_encrypt_node_name = "esp-mpls-encrypt-tun" @@ -2769,14 +3056,17 @@ class TestIpsecItf4MPLS(TemplateIpsec, def tearDown(self): super(TestIpsecItf4MPLS, self).tearDown() - def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - sa.encrypt(MPLS(label=44, ttl=3) / - IP(src=src, dst=dst) / - UDP(sport=1166, dport=2233) / - Raw(b'X' * payload_size)) - for i in range(count)] + def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / sa.encrypt( + MPLS(label=44, ttl=3) + / IP(src=src, dst=dst) + / UDP(sport=1166, dport=2233) + / Raw(b"X" * payload_size) + ) + for i in range(count) + ] def verify_encrypted(self, p, sa, rxs): for rx in rxs: @@ -2807,18 +3097,19 @@ class TestIpsecItf4MPLS(TemplateIpsec, self.config_network(p) # deag MPLS routes from the tunnel - r4 = VppMplsRoute(self, 44, 1, - [VppRoutePath( - self.pg1.remote_ip4, - self.pg1.sw_if_index)]).add_vpp_config() - p.route.modify([VppRoutePath(p.tun_if.remote_ip4, - p.tun_if.sw_if_index, - labels=[VppMplsLabel(44)])]) + r4 = VppMplsRoute( + self, 44, 1, [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)] + ).add_vpp_config() + p.route.modify( + [ + VppRoutePath( + p.tun_if.remote_ip4, p.tun_if.sw_if_index, labels=[VppMplsLabel(44)] + ) + ] + ) p.tun_if.enable_mpls() - self.config_sa_tun(p, - self.pg0.local_ip4, - self.pg0.remote_ip4) + self.config_sa_tun(p, self.pg0.local_ip4, self.pg0.remote_ip4) self.config_protect(p) self.verify_tun_44(p, count=n_pkts) @@ -2831,7 +3122,7 @@ class TestIpsecItf4MPLS(TemplateIpsec, class TemplateIpsecItf6(object): - """ IPsec Interface IPv6 """ + """IPsec Interface IPv6""" encryption_type = ESP tun6_encrypt_node_name = "esp6-encrypt-tun" @@ -2841,34 +3132,45 @@ class TemplateIpsecItf6(object): def config_sa_tun(self, p, src, dst): config_tun_params(p, self.encryption_type, None, src, dst) - if not hasattr(p, 'tun_flags'): + if not hasattr(p, "tun_flags"): p.tun_flags = None - if not hasattr(p, 'hop_limit'): + if not hasattr(p, "hop_limit"): p.hop_limit = 255 - p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol, - src, dst, - flags=p.flags, - tun_flags=p.tun_flags, - hop_limit=p.hop_limit) + p.tun_sa_out = VppIpsecSA( + self, + p.scapy_tun_sa_id, + p.scapy_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + src, + dst, + flags=p.flags, + tun_flags=p.tun_flags, + hop_limit=p.hop_limit, + ) p.tun_sa_out.add_vpp_config() - p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, - self.vpp_esp_protocol, - dst, src, - flags=p.flags) + p.tun_sa_in = VppIpsecSA( + self, + p.vpp_tun_sa_id, + p.vpp_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, + self.vpp_esp_protocol, + dst, + src, + flags=p.flags, + ) p.tun_sa_in.add_vpp_config() def config_protect(self, p): - p.tun_protect = VppIpsecTunProtect(self, - p.tun_if, - p.tun_sa_out, - [p.tun_sa_in]) + p.tun_protect = VppIpsecTunProtect(self, p.tun_if, p.tun_sa_out, [p.tun_sa_in]) p.tun_protect.add_vpp_config() def config_network(self, p): @@ -2879,15 +3181,24 @@ class TemplateIpsecItf6(object): p.tun_if.config_ip4() p.tun_if.config_ip6() - r = VppIpRoute(self, p.remote_tun_if_host4, 32, - [VppRoutePath(p.tun_if.remote_ip4, - 0xffffffff)]) + r = VppIpRoute( + self, + p.remote_tun_if_host4, + 32, + [VppRoutePath(p.tun_if.remote_ip4, 0xFFFFFFFF)], + ) r.add_vpp_config() - p.route = VppIpRoute(self, p.remote_tun_if_host, 128, - [VppRoutePath(p.tun_if.remote_ip6, - 0xffffffff, - proto=DpoProto.DPO_PROTO_IP6)]) + p.route = VppIpRoute( + self, + p.remote_tun_if_host, + 128, + [ + VppRoutePath( + p.tun_if.remote_ip6, 0xFFFFFFFF, proto=DpoProto.DPO_PROTO_IP6 + ) + ], + ) p.route.add_vpp_config() def unconfig_network(self, p): @@ -2903,10 +3214,8 @@ class TemplateIpsecItf6(object): @tag_fixme_vpp_workers -class TestIpsecItf6(TemplateIpsec, - TemplateIpsecItf6, - IpsecTun6): - """ IPsec Interface IPv6 """ +class TestIpsecItf6(TemplateIpsec, TemplateIpsecItf6, IpsecTun6): + """IPsec Interface IPv6""" def setUp(self): super(TestIpsecItf6, self).setUp() @@ -2928,13 +3237,11 @@ class TestIpsecItf6(TemplateIpsec, p.tun_flags = tf.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_HOP_LIMIT self.config_network(p) - config_tun_params(p, self.encryption_type, None, - self.pg0.local_ip6, - self.pg0.remote_ip6) + config_tun_params( + p, self.encryption_type, None, self.pg0.local_ip6, self.pg0.remote_ip6 + ) self.verify_drop_tun_66(p, count=n_pkts) - self.config_sa_tun(p, - self.pg0.local_ip6, - self.pg0.remote_ip6) + self.config_sa_tun(p, self.pg0.local_ip6, self.pg0.remote_ip6) self.config_protect(p) self.verify_tun_66(p, count=n_pkts) @@ -2946,15 +3253,15 @@ class TestIpsecItf6(TemplateIpsec, p.tun_if.admin_up() self.verify_tun_66(p, count=n_pkts) - self.assertEqual(p.tun_if.get_rx_stats(), 3*n_pkts) - self.assertEqual(p.tun_if.get_tx_stats(), 2*n_pkts) + self.assertEqual(p.tun_if.get_rx_stats(), 3 * n_pkts) + self.assertEqual(p.tun_if.get_tx_stats(), 2 * n_pkts) # it's a v4 packet when its encrypted self.tun6_encrypt_node_name = "esp4-encrypt-tun" self.verify_tun_46(p, count=n_pkts) - self.assertEqual(p.tun_if.get_rx_stats(), 4*n_pkts) - self.assertEqual(p.tun_if.get_tx_stats(), 3*n_pkts) + self.assertEqual(p.tun_if.get_rx_stats(), 4 * n_pkts) + self.assertEqual(p.tun_if.get_tx_stats(), 3 * n_pkts) self.tun6_encrypt_node_name = "esp6-encrypt-tun" @@ -2962,7 +3269,7 @@ class TestIpsecItf6(TemplateIpsec, # rekey - create new SAs and update the tunnel protection np = copy.copy(p) - np.crypt_key = b'X' + p.crypt_key[1:] + np.crypt_key = b"X" + p.crypt_key[1:] np.scapy_tun_spi += 100 np.scapy_tun_sa_id += 1 np.vpp_tun_spi += 100 @@ -2971,14 +3278,12 @@ class TestIpsecItf6(TemplateIpsec, np.tun_if.remote_spi = p.scapy_tun_spi np.inner_hop_limit = 24 np.outer_hop_limit = 128 - np.inner_flow_label = 0xabcde - np.outer_flow_label = 0xabcde + np.inner_flow_label = 0xABCDE + np.outer_flow_label = 0xABCDE np.hop_limit = 128 np.tun_flags = tf.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_FLOW_LABEL - self.config_sa_tun(np, - self.pg0.local_ip6, - self.pg0.remote_ip6) + self.config_sa_tun(np, self.pg0.local_ip6, self.pg0.remote_ip6) self.config_protect(np) self.unconfig_sa(p) @@ -3002,18 +3307,23 @@ class TestIpsecItf6(TemplateIpsec, p.tun_flags = tf.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_HOP_LIMIT self.config_network(p) - self.config_sa_tun(p, - self.pg0.local_ip6, - self.pg0.remote_ip6) + self.config_sa_tun(p, self.pg0.local_ip6, self.pg0.remote_ip6) self.config_protect(p) action_tx = PolicerAction( - VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT, - 0) - policer = VppPolicer(self, "pol1", 80, 0, 1000, 0, - conform_action=action_tx, - exceed_action=action_tx, - violate_action=action_tx) + VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT, 0 + ) + policer = VppPolicer( + self, + "pol1", + 80, + 0, + 1000, + 0, + conform_action=action_tx, + exceed_action=action_tx, + violate_action=action_tx, + ) policer.add_vpp_config() # Start policing on tun @@ -3026,9 +3336,9 @@ class TestIpsecItf6(TemplateIpsec, stats = policer.get_stats() # Single rate, 2 colour policer - expect conform, violate but no exceed - self.assertGreater(stats['conform_packets'], 0) - self.assertEqual(stats['exceed_packets'], 0) - self.assertGreater(stats['violate_packets'], 0) + self.assertGreater(stats["conform_packets"], 0) + self.assertEqual(stats["exceed_packets"], 0) + self.assertGreater(stats["violate_packets"], 0) # Stop policing on tun policer.apply_vpp_config(p.tun_if.sw_if_index, Dir.RX, False) @@ -3046,27 +3356,31 @@ class TestIpsecItf6(TemplateIpsec, class TestIpsecMIfEsp4(TemplateIpsec, IpsecTun4): - """ Ipsec P2MP ESP v4 tests """ + """Ipsec P2MP ESP v4 tests""" + tun4_encrypt_node_name = "esp4-encrypt-tun" tun4_decrypt_node_name = ["esp4-decrypt-tun", "esp4-decrypt-tun-post"] encryption_type = ESP - def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - sa.encrypt(IP(src=self.pg1.local_ip4, - dst=self.pg1.remote_ip4) / - UDP(sport=1144, dport=2233) / - Raw(b'X' * payload_size)) - for i in range(count)] - - def gen_pkts(self, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - IP(src="1.1.1.1", dst=dst) / - UDP(sport=1144, dport=2233) / - Raw(b'X' * payload_size) - for i in range(count)] + def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / sa.encrypt( + IP(src=self.pg1.local_ip4, dst=self.pg1.remote_ip4) + / UDP(sport=1144, dport=2233) + / Raw(b"X" * payload_size) + ) + for i in range(count) + ] + + def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / IP(src="1.1.1.1", dst=dst) + / UDP(sport=1144, dport=2233) + / Raw(b"X" * payload_size) + for i in range(count) + ] def verify_decrypted(self, p, rxs): for rx in rxs: @@ -3076,8 +3390,9 @@ class TestIpsecMIfEsp4(TemplateIpsec, IpsecTun4): def verify_encrypted(self, p, sa, rxs): for rx in rxs: try: - self.assertEqual(rx[IP].tos, - VppEnum.vl_api_ip_dscp_t.IP_API_DSCP_EF << 2) + self.assertEqual( + rx[IP].tos, VppEnum.vl_api_ip_dscp_t.IP_API_DSCP_EF << 2 + ) self.assertEqual(rx[IP].ttl, p.hop_limit) pkt = sa.decrypt(rx[IP]) if not pkt.haslayer(IP): @@ -3099,9 +3414,9 @@ class TestIpsecMIfEsp4(TemplateIpsec, IpsecTun4): N_NHS = 16 self.tun_if = self.pg0 p = self.ipv4_params - p.tun_if = VppIpsecInterface(self, - mode=(VppEnum.vl_api_tunnel_mode_t. - TUNNEL_API_MODE_MP)) + p.tun_if = VppIpsecInterface( + self, mode=(VppEnum.vl_api_tunnel_mode_t.TUNNEL_API_MODE_MP) + ) p.tun_if.add_vpp_config() p.tun_if.admin_up() p.tun_if.config_ip4() @@ -3111,10 +3426,7 @@ class TestIpsecMIfEsp4(TemplateIpsec, IpsecTun4): self.pg0.generate_remote_hosts(N_NHS) self.pg0.configure_ipv4_neighbors() - r_all = AclRule(True, - src_prefix="0.0.0.0/0", - dst_prefix="0.0.0.0/0", - proto=0) + r_all = AclRule(True, src_prefix="0.0.0.0/0", dst_prefix="0.0.0.0/0", proto=0) a = VppAcl(self, [r_all]).add_vpp_config() VppAclInterface(self, self.pg0.sw_if_index, [a]).add_vpp_config() @@ -3136,27 +3448,37 @@ class TestIpsecMIfEsp4(TemplateIpsec, IpsecTun4): p.scapy_tra_spi = p.scapy_tra_spi + ii p.vpp_tra_sa_id = p.vpp_tra_sa_id + ii p.vpp_tra_spi = p.vpp_tra_spi + ii - p.hop_limit = ii+10 + p.hop_limit = ii + 10 p.tun_sa_out = VppIpsecSA( - self, p.scapy_tun_sa_id, p.scapy_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, + self, + p.scapy_tun_sa_id, + p.scapy_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, self.vpp_esp_protocol, self.pg0.local_ip4, self.pg0.remote_hosts[ii].ip4, dscp=VppEnum.vl_api_ip_dscp_t.IP_API_DSCP_EF, - hop_limit=p.hop_limit) + hop_limit=p.hop_limit, + ) p.tun_sa_out.add_vpp_config() p.tun_sa_in = VppIpsecSA( - self, p.vpp_tun_sa_id, p.vpp_tun_spi, - p.auth_algo_vpp_id, p.auth_key, - p.crypt_algo_vpp_id, p.crypt_key, + self, + p.vpp_tun_sa_id, + p.vpp_tun_spi, + p.auth_algo_vpp_id, + p.auth_key, + p.crypt_algo_vpp_id, + p.crypt_key, self.vpp_esp_protocol, self.pg0.remote_hosts[ii].ip4, self.pg0.local_ip4, dscp=VppEnum.vl_api_ip_dscp_t.IP_API_DSCP_EF, - hop_limit=p.hop_limit) + hop_limit=p.hop_limit, + ) p.tun_sa_in.add_vpp_config() p.tun_protect = VppIpsecTunProtect( @@ -3164,17 +3486,24 @@ class TestIpsecMIfEsp4(TemplateIpsec, IpsecTun4): p.tun_if, p.tun_sa_out, [p.tun_sa_in], - nh=p.tun_if.remote_hosts[ii].ip4) + nh=p.tun_if.remote_hosts[ii].ip4, + ) p.tun_protect.add_vpp_config() - config_tun_params(p, self.encryption_type, None, - self.pg0.local_ip4, - self.pg0.remote_hosts[ii].ip4) + config_tun_params( + p, + self.encryption_type, + None, + self.pg0.local_ip4, + self.pg0.remote_hosts[ii].ip4, + ) self.multi_params.append(p) p.via_tun_route = VppIpRoute( - self, p.remote_tun_if_host, 32, - [VppRoutePath(p.tun_if.remote_hosts[ii].ip4, - p.tun_if.sw_if_index)]).add_vpp_config() + self, + p.remote_tun_if_host, + 32, + [VppRoutePath(p.tun_if.remote_hosts[ii].ip4, p.tun_if.sw_if_index)], + ).add_vpp_config() p.tun_dst = self.pg0.remote_hosts[ii].ip4 @@ -3205,10 +3534,8 @@ class TestIpsecMIfEsp4(TemplateIpsec, IpsecTun4): self.verify_tun_44(p, count=N_PKTS) -class TestIpsecItf6MPLS(TemplateIpsec, - TemplateIpsecItf6, - IpsecTun6): - """ IPsec Interface MPLSoIPv6 """ +class TestIpsecItf6MPLS(TemplateIpsec, TemplateIpsecItf6, IpsecTun6): + """IPsec Interface MPLSoIPv6""" tun6_encrypt_node_name = "esp-mpls-encrypt-tun" @@ -3220,14 +3547,17 @@ class TestIpsecItf6MPLS(TemplateIpsec, def tearDown(self): super(TestIpsecItf6MPLS, self).tearDown() - def gen_encrypt_pkts6(self, p, sa, sw_intf, src, dst, count=1, - payload_size=100): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - sa.encrypt(MPLS(label=66, ttl=3) / - IPv6(src=src, dst=dst) / - UDP(sport=1166, dport=2233) / - Raw(b'X' * payload_size)) - for i in range(count)] + def gen_encrypt_pkts6(self, p, sa, sw_intf, src, dst, count=1, payload_size=100): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / sa.encrypt( + MPLS(label=66, ttl=3) + / IPv6(src=src, dst=dst) + / UDP(sport=1166, dport=2233) + / Raw(b"X" * payload_size) + ) + for i in range(count) + ] def verify_encrypted6(self, p, sa, rxs): for rx in rxs: @@ -3258,19 +3588,23 @@ class TestIpsecItf6MPLS(TemplateIpsec, self.config_network(p) # deag MPLS routes from the tunnel - r6 = VppMplsRoute(self, 66, 1, - [VppRoutePath( - self.pg1.remote_ip6, - self.pg1.sw_if_index)], - eos_proto=f.FIB_PATH_NH_PROTO_IP6).add_vpp_config() - p.route.modify([VppRoutePath(p.tun_if.remote_ip6, - p.tun_if.sw_if_index, - labels=[VppMplsLabel(66)])]) + r6 = VppMplsRoute( + self, + 66, + 1, + [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)], + eos_proto=f.FIB_PATH_NH_PROTO_IP6, + ).add_vpp_config() + p.route.modify( + [ + VppRoutePath( + p.tun_if.remote_ip6, p.tun_if.sw_if_index, labels=[VppMplsLabel(66)] + ) + ] + ) p.tun_if.enable_mpls() - self.config_sa_tun(p, - self.pg0.local_ip6, - self.pg0.remote_ip6) + self.config_sa_tun(p, self.pg0.local_ip6, self.pg0.remote_ip6) self.config_protect(p) self.verify_tun_66(p, count=n_pkts) @@ -3282,5 +3616,5 @@ class TestIpsecItf6MPLS(TemplateIpsec, self.unconfig_network(p) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_l2_fib.py b/test/test_l2_fib.py index 065e57e5343..fe1ea458182 100644 --- a/test/test_l2_fib.py +++ b/test/test_l2_fib.py @@ -73,12 +73,11 @@ from vpp_papi import mac_pton, VppEnum class TestL2fib(VppTestCase): - """ L2 FIB Test Case """ + """L2 FIB Test Case""" @classmethod def bd_ifs(cls, bd_id): - return range((bd_id - 1) * cls.n_ifs_per_bd, - bd_id * cls.n_ifs_per_bd - 1) + return range((bd_id - 1) * cls.n_ifs_per_bd, bd_id * cls.n_ifs_per_bd - 1) @classmethod def setUpClass(cls): @@ -104,7 +103,8 @@ class TestL2fib(VppTestCase): ifs = cls.bd_ifs(bd_id) for j in ifs: cls.flows[cls.pg_interfaces[j]] = [ - cls.pg_interfaces[x] for x in ifs if x != j] + cls.pg_interfaces[x] for x in ifs if x != j + ] # Packet sizes cls.pg_if_packet_sizes = [64, 512, 1518, 9018] @@ -112,12 +112,12 @@ class TestL2fib(VppTestCase): for bd_id in n_brs: # Create BD with MAC learning and unknown unicast flooding # disabled and put interfaces to this BD - cls.vapi.bridge_domain_add_del(bd_id=bd_id, uu_flood=0, - learn=0) + cls.vapi.bridge_domain_add_del(bd_id=bd_id, uu_flood=0, learn=0) ifs = [cls.pg_interfaces[i] for i in cls.bd_ifs(bd_id)] for pg_if in ifs: cls.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=pg_if.sw_if_index, bd_id=bd_id) + rx_sw_if_index=pg_if.sw_if_index, bd_id=bd_id + ) # Set up all interfaces for i in cls.pg_interfaces: @@ -141,8 +141,9 @@ class TestL2fib(VppTestCase): super(TestL2fib, self).tearDown() if not self.vpp_dead: for bd_id in self.n_brs: - self.logger.info(self.vapi.ppcli("show bridge-domain %s detail" - % bd_id)) + self.logger.info( + self.vapi.ppcli("show bridge-domain %s detail" % bd_id) + ) def show_commands_at_teardown(self): self.logger.info(self.vapi.ppcli("show l2fib verbose")) @@ -160,11 +161,15 @@ class TestL2fib(VppTestCase): for pg_if in self.pg_interfaces: swif = pg_if.sw_if_index - def mac(j): return "00:00:%02x:ff:%02x:%02x" % (subnet, swif, j) + def mac(j): + return "00:00:%02x:ff:%02x:%02x" % (subnet, swif, j) - def ip(j): return "172.%02u.1%02x.%u" % (subnet, swif, j) + def ip(j): + return "172.%02u.1%02x.%u" % (subnet, swif, j) + + def h(j): + return Host(mac(j), ip(j)) - def h(j): return Host(mac(j), ip(j)) hosts[swif] = [h(j) for j in range(n_hosts_per_if)] return hosts @@ -188,8 +193,9 @@ class TestL2fib(VppTestCase): ifs = [self.pg_interfaces[i] for i in self.bd_ifs(bd_id)] for pg_if in ifs: swif = pg_if.sw_if_index - packets = [Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac) - for host in hosts[swif]] + packets = [ + Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac) for host in hosts[swif] + ] pg_if.add_stream(packets) self.logger.info("Sending broadcast eth frames for MAC learning") self.pg_start() @@ -206,8 +212,7 @@ class TestL2fib(VppTestCase): for pg_if in ifs: swif = pg_if.sw_if_index for host in hosts[swif]: - self.vapi.l2fib_add_del( - mac_pton(host.mac), bd_id, swif, static_mac=1) + self.vapi.l2fib_add_del(mac_pton(host.mac), bd_id, swif, static_mac=1) def delete_l2_fib_entry(self, bd_id, hosts): """ @@ -219,8 +224,7 @@ class TestL2fib(VppTestCase): for pg_if in ifs: swif = pg_if.sw_if_index for host in hosts[swif]: - self.vapi.l2fib_add_del( - mac_pton(host.mac), bd_id, swif, is_add=0) + self.vapi.l2fib_add_del(mac_pton(host.mac), bd_id, swif, is_add=0) def flush_int(self, swif, learned_hosts): """ @@ -278,10 +282,12 @@ class TestL2fib(VppTestCase): src_host = random.choice(src_hosts) pkt_info = self.create_packet_info(src_if, dst_if) payload = self.info_to_payload(pkt_info) - p = (Ether(dst=dst_host.mac, src=src_host.mac) / - IP(src=src_host.ip4, dst=dst_host.ip4) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + Ether(dst=dst_host.mac, src=src_host.mac) + / IP(src=src_host.ip4, dst=dst_host.ip4) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) pkt_info.data = p.copy() size = random.choice(packet_sizes) self.extend_packet(p, size) @@ -306,11 +312,13 @@ class TestL2fib(VppTestCase): udp = packet[UDP] packet_index = payload_info.index self.assertEqual(payload_info.dst, dst_sw_if_index) - self.logger.debug("Got packet on port %s: src=%u (id=%u)" % - (pg_if.name, payload_info.src, packet_index)) + self.logger.debug( + "Got packet on port %s: src=%u (id=%u)" + % (pg_if.name, payload_info.src, packet_index) + ) next_info = self.get_next_packet_info_for_interface2( - payload_info.src, dst_sw_if_index, - last_info[payload_info.src]) + payload_info.src, dst_sw_if_index, last_info[payload_info.src] + ) last_info[payload_info.src] = next_info self.assertTrue(next_info is not None) self.assertEqual(packet_index, next_info.index) @@ -325,11 +333,13 @@ class TestL2fib(VppTestCase): raise for i in self.pg_interfaces: remaining_packet = self.get_next_packet_info_for_interface2( - i, dst_sw_if_index, last_info[i.sw_if_index]) + i, dst_sw_if_index, last_info[i.sw_if_index] + ) self.assertTrue( remaining_packet is None, - "Port %u: Packet expected from source %u didn't arrive" % - (dst_sw_if_index, i.sw_if_index)) + "Port %u: Packet expected from source %u didn't arrive" + % (dst_sw_if_index, i.sw_if_index), + ) def run_verify_test(self, bd_id, src_hosts, dst_hosts): # Test @@ -338,9 +348,11 @@ class TestL2fib(VppTestCase): ifs = [self.pg_interfaces[i] for i in self.bd_ifs(bd_id)] for i in ifs: pkts = self.create_stream( - i, self.pg_if_packet_sizes, + i, + self.pg_if_packet_sizes, if_src_hosts=src_hosts, - if_dst_hosts=dst_hosts) + if_dst_hosts=dst_hosts, + ) if pkts: i.add_stream(pkts) @@ -366,9 +378,11 @@ class TestL2fib(VppTestCase): ifs = [self.pg_interfaces[i] for i in self.bd_ifs(bd_id)] for i in ifs: pkts = self.create_stream( - i, self.pg_if_packet_sizes, + i, + self.pg_if_packet_sizes, if_src_hosts=src_hosts, - if_dst_hosts=dst_hosts) + if_dst_hosts=dst_hosts, + ) if pkts: i.add_stream(pkts) @@ -386,16 +400,14 @@ class TestL2fib(VppTestCase): timeout = 0.1 def test_l2_fib_program100(self): - """ L2 FIB - program 100 MACs - """ + """L2 FIB - program 100 MACs""" bd_id = 1 hosts = self.create_hosts(100, subnet=17) self.config_l2_fib_entries(bd_id, hosts) self.run_verify_test(bd_id, hosts, hosts) def test_l2_fib_program100_delete12(self): - """ L2 FIB - program 100, delete 12 MACs - """ + """L2 FIB - program 100, delete 12 MACs""" bd_id = 1 hosts = self.create_hosts(100, subnet=17) self.config_l2_fib_entries(bd_id, hosts) @@ -406,8 +418,7 @@ class TestL2fib(VppTestCase): self.run_verify_negat_test(bd_id, hosts, del_hosts) def test_l2_fib_program100_add100(self): - """ L2 FIB - program 100, add 100 MACs - """ + """L2 FIB - program 100, add 100 MACs""" bd_id = 1 hosts = self.create_hosts(100, subnet=17) self.config_l2_fib_entries(bd_id, hosts) @@ -416,8 +427,7 @@ class TestL2fib(VppTestCase): self.run_verify_test(bd_id, hosts, hosts2) def test_l2_fib_program10_learn10(self): - """ L2 FIB - program 10 MACs, learn 10 - """ + """L2 FIB - program 10 MACs, learn 10""" hosts = self.create_hosts(20, subnet=35) lhosts = self.split_hosts(hosts, 10) @@ -431,8 +441,7 @@ class TestL2fib(VppTestCase): self.run_verify_test(bd2, lhosts, hosts) def test_l2_fib_flush_int(self): - """ L2 FIB - flush interface - """ + """L2 FIB - flush interface""" hosts = self.create_hosts(20, subnet=36) lhosts = self.split_hosts(hosts, 10) @@ -445,8 +454,7 @@ class TestL2fib(VppTestCase): self.run_verify_negat_test(bd1, hosts, flushed) def test_l2_fib_flush_bd(self): - """ L2 FIB - flush BD - """ + """L2 FIB - flush BD""" hosts = self.create_hosts(20, subnet=37) lhosts = self.split_hosts(hosts, 10) @@ -458,8 +466,7 @@ class TestL2fib(VppTestCase): self.run_verify_negat_test(bd1, hosts, flushed) def test_l2_fib_flush_all(self): - """ L2 FIB - flush all - """ + """L2 FIB - flush all""" hosts = self.create_hosts(20, subnet=38) lhosts = self.split_hosts(hosts, 10) @@ -478,8 +485,7 @@ class TestL2fib(VppTestCase): self.run_verify_negat_test(bd2, hosts, lhosts) def test_l2_fib_mac_learn_evs(self): - """ L2 FIB - mac learning events - """ + """L2 FIB - mac learning events""" bd1 = 1 hosts = self.create_hosts(10, subnet=39) @@ -491,16 +497,21 @@ class TestL2fib(VppTestCase): evs = self.vapi.collect_events() action = VppEnum.vl_api_mac_event_action_t.MAC_EVENT_ACTION_API_ADD learned_macs = { - e.mac[i].mac_addr.packed for e in evs for i in range(e.n_macs) - if e.mac[i].action == action} - macs = {h.bin_mac for swif in self.bd_ifs(bd1) - for h in hosts[self.pg_interfaces[swif].sw_if_index]} + e.mac[i].mac_addr.packed + for e in evs + for i in range(e.n_macs) + if e.mac[i].action == action + } + macs = { + h.bin_mac + for swif in self.bd_ifs(bd1) + for h in hosts[self.pg_interfaces[swif].sw_if_index] + } self.vapi.want_l2_macs_events(enable_disable=0) self.assertEqual(len(learned_macs ^ macs), 0) def test_l2_fib_mac_learn_evs2(self): - """ L2 FIB - mac learning events using want_l2_macs_events2 - """ + """L2 FIB - mac learning events using want_l2_macs_events2""" bd1 = 1 hosts = self.create_hosts(10, subnet=39) @@ -514,16 +525,21 @@ class TestL2fib(VppTestCase): evs = self.vapi.collect_events() action = VppEnum.vl_api_mac_event_action_t.MAC_EVENT_ACTION_API_ADD learned_macs = { - e.mac[i].mac_addr.packed for e in evs for i in range(e.n_macs) - if e.mac[i].action == action} - macs = {h.bin_mac for swif in self.bd_ifs(bd1) - for h in hosts[self.pg_interfaces[swif].sw_if_index]} + e.mac[i].mac_addr.packed + for e in evs + for i in range(e.n_macs) + if e.mac[i].action == action + } + macs = { + h.bin_mac + for swif in self.bd_ifs(bd1) + for h in hosts[self.pg_interfaces[swif].sw_if_index] + } self.vapi.want_l2_macs_events2(enable_disable=0) self.assertEqual(len(learned_macs ^ macs), 0) def test_l2_fib_macs_learn_max(self): - """ L2 FIB - mac learning max macs in event - """ + """L2 FIB - mac learning max macs in event""" bd1 = 1 hosts = self.create_hosts(10, subnet=40) @@ -539,18 +555,23 @@ class TestL2fib(VppTestCase): self.assertGreater(len(evs), 0) action = VppEnum.vl_api_mac_event_action_t.MAC_EVENT_ACTION_API_ADD learned_macs = { - e.mac[i].mac_addr.packed for e in evs for i in range(e.n_macs) - if e.mac[i].action == action} - macs = {h.bin_mac for swif in self.bd_ifs(bd1) - for h in hosts[self.pg_interfaces[swif].sw_if_index]} + e.mac[i].mac_addr.packed + for e in evs + for i in range(e.n_macs) + if e.mac[i].action == action + } + macs = { + h.bin_mac + for swif in self.bd_ifs(bd1) + for h in hosts[self.pg_interfaces[swif].sw_if_index] + } for e in evs: self.assertLess(len(e), ev_macs * 10) self.assertEqual(len(learned_macs ^ macs), 0) def test_l2_fib_macs_learn_max2(self): - """ L2 FIB - mac learning max macs in event using want_l2_macs_events2 - """ + """L2 FIB - mac learning max macs in event using want_l2_macs_events2""" bd1 = 1 hosts = self.create_hosts(10, subnet=40) @@ -568,14 +589,21 @@ class TestL2fib(VppTestCase): self.assertGreater(len(evs), 0) action = VppEnum.vl_api_mac_event_action_t.MAC_EVENT_ACTION_API_ADD learned_macs = { - e.mac[i].mac_addr.packed for e in evs for i in range(e.n_macs) - if e.mac[i].action == action} - macs = {h.bin_mac for swif in self.bd_ifs(bd1) - for h in hosts[self.pg_interfaces[swif].sw_if_index]} + e.mac[i].mac_addr.packed + for e in evs + for i in range(e.n_macs) + if e.mac[i].action == action + } + macs = { + h.bin_mac + for swif in self.bd_ifs(bd1) + for h in hosts[self.pg_interfaces[swif].sw_if_index] + } for e in evs: self.assertLess(len(e), ev_macs * 10) self.assertEqual(len(learned_macs ^ macs), 0) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_l2_flood.py b/test/test_l2_flood.py index 7f3c57a399d..db4af607451 100644 --- a/test/test_l2_flood.py +++ b/test/test_l2_flood.py @@ -15,7 +15,7 @@ NUM_PKTS = 67 class TestL2Flood(VppTestCase): - """ L2-flood """ + """L2-flood""" @classmethod def setUpClass(cls): @@ -52,7 +52,7 @@ class TestL2Flood(VppTestCase): super(TestL2Flood, self).tearDown() def test_flood(self): - """ L2 Flood Tests """ + """L2 Flood Tests""" # # Create a single bridge Domain @@ -63,31 +63,35 @@ class TestL2Flood(VppTestCase): # add each interface to the BD. 3 interfaces per split horizon group # for i in self.pg_interfaces[0:4]: - self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=i.sw_if_index, - bd_id=1, shg=0) + self.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=i.sw_if_index, bd_id=1, shg=0 + ) for i in self.pg_interfaces[4:8]: - self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=i.sw_if_index, - bd_id=1, shg=1) + self.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=i.sw_if_index, bd_id=1, shg=1 + ) for i in self.pg_interfaces[8:12]: - self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=i.sw_if_index, - bd_id=1, shg=2) + self.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=i.sw_if_index, bd_id=1, shg=2 + ) for i in self.bvi_interfaces: - self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=i.sw_if_index, - bd_id=1, shg=2, - port_type=L2_PORT_TYPE.BVI) + self.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=i.sw_if_index, bd_id=1, shg=2, port_type=L2_PORT_TYPE.BVI + ) - p = (Ether(dst="ff:ff:ff:ff:ff:ff", - src="00:00:de:ad:be:ef") / - IP(src="10.10.10.10", dst="1.1.1.1") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p = ( + Ether(dst="ff:ff:ff:ff:ff:ff", src="00:00:de:ad:be:ef") + / IP(src="10.10.10.10", dst="1.1.1.1") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) # # input on pg0 expect copies on pg1->11 # this is in SHG=0 so its flooded to all, expect the pg0 since that's # the ingress link # - self.pg0.add_stream(p*NUM_PKTS) + self.pg0.add_stream(p * NUM_PKTS) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -98,7 +102,7 @@ class TestL2Flood(VppTestCase): # input on pg4 (SHG=1) expect copies on pg0->3 (SHG=0) # and pg8->11 (SHG=2) # - self.pg4.add_stream(p*NUM_PKTS) + self.pg4.add_stream(p * NUM_PKTS) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -112,9 +116,12 @@ class TestL2Flood(VppTestCase): # # An IP route so the packet that hits the BVI is sent out of pg12 # - ip_route = VppIpRoute(self, "1.1.1.1", 32, - [VppRoutePath(self.pg12.remote_ip4, - self.pg12.sw_if_index)]) + ip_route = VppIpRoute( + self, + "1.1.1.1", + 32, + [VppRoutePath(self.pg12.remote_ip4, self.pg12.sw_if_index)], + ) ip_route.add_vpp_config() self.logger.info(self.vapi.cli("sh bridge 1 detail")) @@ -124,7 +131,7 @@ class TestL2Flood(VppTestCase): # this is in SHG=0 so its flooded to all, expect the pg0 since that's # the ingress link # - self.pg0.add_stream(p*NUM_PKTS) + self.pg0.add_stream(p * NUM_PKTS) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -135,7 +142,7 @@ class TestL2Flood(VppTestCase): # input on pg4 (SHG=1) expect copies on pg0->3 (SHG=0) # and pg8->12 (SHG=2) # - self.pg4.add_stream(p*NUM_PKTS) + self.pg4.add_stream(p * NUM_PKTS) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -150,18 +157,22 @@ class TestL2Flood(VppTestCase): # cleanup # for i in self.pg_interfaces[:12]: - self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=i.sw_if_index, - bd_id=1, enable=0) + self.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=i.sw_if_index, bd_id=1, enable=0 + ) for i in self.bvi_interfaces: - self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=i.sw_if_index, - bd_id=1, shg=2, - port_type=L2_PORT_TYPE.BVI, - enable=0) + self.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=i.sw_if_index, + bd_id=1, + shg=2, + port_type=L2_PORT_TYPE.BVI, + enable=0, + ) self.vapi.bridge_domain_add_del(bd_id=1, is_add=0) def test_flood_one(self): - """ L2 no-Flood Test """ + """L2 no-Flood Test""" # # Create a single bridge Domain @@ -173,30 +184,33 @@ class TestL2Flood(VppTestCase): # one member # for i in self.pg_interfaces[:2]: - self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=i.sw_if_index, - bd_id=1, shg=0) + self.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=i.sw_if_index, bd_id=1, shg=0 + ) - p = (Ether(dst="ff:ff:ff:ff:ff:ff", - src="00:00:de:ad:be:ef") / - IP(src="10.10.10.10", dst="1.1.1.1") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p = ( + Ether(dst="ff:ff:ff:ff:ff:ff", src="00:00:de:ad:be:ef") + / IP(src="10.10.10.10", dst="1.1.1.1") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) # # input on pg0 expect copies on pg1 # - self.send_and_expect(self.pg0, p*NUM_PKTS, self.pg1) + self.send_and_expect(self.pg0, p * NUM_PKTS, self.pg1) # # cleanup # for i in self.pg_interfaces[:2]: - self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=i.sw_if_index, - bd_id=1, enable=0) + self.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=i.sw_if_index, bd_id=1, enable=0 + ) self.vapi.bridge_domain_add_del(bd_id=1, is_add=0) def test_uu_fwd(self): - """ UU Flood """ + """UU Flood""" # # Create a single bridge Domain @@ -207,34 +221,37 @@ class TestL2Flood(VppTestCase): # add each interface to the BD. 3 interfaces per split horizon group # for i in self.pg_interfaces[0:4]: - self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=i.sw_if_index, - bd_id=1, shg=0) + self.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=i.sw_if_index, bd_id=1, shg=0 + ) # # an unknown unicast and broadcast packets # - p_uu = (Ether(dst="00:00:00:c1:5c:00", - src="00:00:de:ad:be:ef") / - IP(src="10.10.10.10", dst="1.1.1.1") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - p_bm = (Ether(dst="ff:ff:ff:ff:ff:ff", - src="00:00:de:ad:be:ef") / - IP(src="10.10.10.10", dst="1.1.1.1") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p_uu = ( + Ether(dst="00:00:00:c1:5c:00", src="00:00:de:ad:be:ef") + / IP(src="10.10.10.10", dst="1.1.1.1") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + p_bm = ( + Ether(dst="ff:ff:ff:ff:ff:ff", src="00:00:de:ad:be:ef") + / IP(src="10.10.10.10", dst="1.1.1.1") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) # # input on pg0, expected copies on pg1->4 # - self.pg0.add_stream(p_uu*NUM_PKTS) + self.pg0.add_stream(p_uu * NUM_PKTS) self.pg_enable_capture(self.pg_interfaces) self.pg_start() for i in self.pg_interfaces[1:4]: rx0 = i.get_capture(NUM_PKTS, timeout=1) - self.pg0.add_stream(p_bm*NUM_PKTS) + self.pg0.add_stream(p_bm * NUM_PKTS) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -245,13 +262,16 @@ class TestL2Flood(VppTestCase): # use pg8 as the uu-fwd interface # self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg8.sw_if_index, bd_id=1, shg=0, - port_type=L2_PORT_TYPE.UU_FWD) + rx_sw_if_index=self.pg8.sw_if_index, + bd_id=1, + shg=0, + port_type=L2_PORT_TYPE.UU_FWD, + ) # # expect the UU packet on the uu-fwd interface and not be flooded # - self.pg0.add_stream(p_uu*NUM_PKTS) + self.pg0.add_stream(p_uu * NUM_PKTS) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -260,7 +280,7 @@ class TestL2Flood(VppTestCase): for i in self.pg_interfaces[0:4]: i.assert_nothing_captured(remark="UU not flooded") - self.pg0.add_stream(p_bm*NUM_PKTS) + self.pg0.add_stream(p_bm * NUM_PKTS) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -271,10 +291,14 @@ class TestL2Flood(VppTestCase): # remove the uu-fwd interface and expect UU to be flooded again # self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg8.sw_if_index, bd_id=1, shg=0, - port_type=L2_PORT_TYPE.UU_FWD, enable=0) - - self.pg0.add_stream(p_uu*NUM_PKTS) + rx_sw_if_index=self.pg8.sw_if_index, + bd_id=1, + shg=0, + port_type=L2_PORT_TYPE.UU_FWD, + enable=0, + ) + + self.pg0.add_stream(p_uu * NUM_PKTS) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -292,11 +316,14 @@ class TestL2Flood(VppTestCase): # re-add the uu-fwd interface # self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg8.sw_if_index, bd_id=1, shg=0, - port_type=L2_PORT_TYPE.UU_FWD) + rx_sw_if_index=self.pg8.sw_if_index, + bd_id=1, + shg=0, + port_type=L2_PORT_TYPE.UU_FWD, + ) self.logger.info(self.vapi.cli("sh bridge 1 detail")) - self.pg0.add_stream(p_uu*NUM_PKTS) + self.pg0.add_stream(p_uu * NUM_PKTS) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -309,19 +336,24 @@ class TestL2Flood(VppTestCase): # remove the uu-fwd interface # self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg8.sw_if_index, bd_id=1, shg=0, - port_type=L2_PORT_TYPE.UU_FWD, enable=0) + rx_sw_if_index=self.pg8.sw_if_index, + bd_id=1, + shg=0, + port_type=L2_PORT_TYPE.UU_FWD, + enable=0, + ) self.send_and_assert_no_replies(self.pg0, p_uu) # # cleanup # for i in self.pg_interfaces[:4]: - self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=i.sw_if_index, - bd_id=1, enable=0) + self.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=i.sw_if_index, bd_id=1, enable=0 + ) self.vapi.bridge_domain_add_del(bd_id=1, is_add=0) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_l2bd.py b/test/test_l2bd.py index 5eca48c6e9b..63ed2deeb68 100644 --- a/test/test_l2bd.py +++ b/test/test_l2bd.py @@ -13,7 +13,7 @@ from vpp_sub_interface import VppDot1QSubint, VppDot1ADSubint class TestL2bd(VppTestCase): - """ L2BD Test Case """ + """L2BD Test Case""" @classmethod def setUpClass(cls): @@ -54,8 +54,14 @@ class TestL2bd(VppTestCase): # create 2 sub-interfaces for pg1 and pg2 cls.sub_interfaces = [ VppDot1QSubint(cls, cls.pg1, cls.dot1q_tag), - VppDot1ADSubint(cls, cls.pg2, cls.dot1ad_sub_id, - cls.dot1ad_outer_tag, cls.dot1ad_inner_tag)] + VppDot1ADSubint( + cls, + cls.pg2, + cls.dot1ad_sub_id, + cls.dot1ad_outer_tag, + cls.dot1ad_inner_tag, + ), + ] # packet flows mapping pg0 -> pg1, pg2, etc. cls.flows = dict() @@ -73,10 +79,14 @@ class TestL2bd(VppTestCase): # Create BD with MAC learning enabled and put interfaces and # sub-interfaces to this BD for pg_if in cls.pg_interfaces: - sw_if_index = pg_if.sub_if.sw_if_index \ - if hasattr(pg_if, 'sub_if') else pg_if.sw_if_index - cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=sw_if_index, - bd_id=cls.bd_id) + sw_if_index = ( + pg_if.sub_if.sw_if_index + if hasattr(pg_if, "sub_if") + else pg_if.sw_if_index + ) + cls.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=sw_if_index, bd_id=cls.bd_id + ) # setup all interfaces for i in cls.interfaces: @@ -112,8 +122,9 @@ class TestL2bd(VppTestCase): super(TestL2bd, self).tearDown() if not self.vpp_dead: self.logger.info(self.vapi.ppcli("show l2fib verbose")) - self.logger.info(self.vapi.ppcli("show bridge-domain %s detail" % - self.bd_id)) + self.logger.info( + self.vapi.ppcli("show bridge-domain %s detail" % self.bd_id) + ) @classmethod def create_hosts_and_learn(cls, count): @@ -138,10 +149,11 @@ class TestL2bd(VppTestCase): for j in range(start_nr, end_nr): host = Host( "00:00:00:ff:%02x:%02x" % (pg_if.sw_if_index, j), - "172.17.1%02x.%u" % (pg_if.sw_if_index, j)) - packet = (Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac)) + "172.17.1%02x.%u" % (pg_if.sw_if_index, j), + ) + packet = Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac) hosts.append(host) - if hasattr(pg_if, 'sub_if'): + if hasattr(pg_if, "sub_if"): packet = pg_if.sub_if.add_dot1_layer(packet) packets.append(packet) pg_if.add_stream(packets) @@ -164,12 +176,14 @@ class TestL2bd(VppTestCase): src_host = random.choice(self.hosts_by_pg_idx[src_if.sw_if_index]) pkt_info = self.create_packet_info(src_if, dst_if) payload = self.info_to_payload(pkt_info) - p = (Ether(dst=dst_host.mac, src=src_host.mac) / - IP(src=src_host.ip4, dst=dst_host.ip4) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + Ether(dst=dst_host.mac, src=src_host.mac) + / IP(src=src_host.ip4, dst=dst_host.ip4) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) pkt_info.data = p.copy() - if hasattr(src_if, 'sub_if'): + if hasattr(src_if, "sub_if"): p = src_if.sub_if.add_dot1_layer(p) size = random.choice(packet_sizes) self.extend_packet(p, size) @@ -196,7 +210,7 @@ class TestL2bd(VppTestCase): if ifc.sw_if_index == src_sw_if_index: src_if = ifc break - if hasattr(src_if, 'sub_if'): + if hasattr(src_if, "sub_if"): # Check VLAN tags and Ethernet header packet = src_if.sub_if.remove_dot1_layer(packet) self.assertTrue(Dot1Q not in packet) @@ -205,11 +219,13 @@ class TestL2bd(VppTestCase): udp = packet[UDP] packet_index = payload_info.index self.assertEqual(payload_info.dst, dst_sw_if_index) - self.logger.debug("Got packet on port %s: src=%u (id=%u)" % - (pg_if.name, payload_info.src, packet_index)) + self.logger.debug( + "Got packet on port %s: src=%u (id=%u)" + % (pg_if.name, payload_info.src, packet_index) + ) next_info = self.get_next_packet_info_for_interface2( - payload_info.src, dst_sw_if_index, - last_info[payload_info.src]) + payload_info.src, dst_sw_if_index, last_info[payload_info.src] + ) last_info[payload_info.src] = next_info self.assertTrue(next_info is not None) self.assertEqual(packet_index, next_info.index) @@ -224,19 +240,24 @@ class TestL2bd(VppTestCase): raise for i in self.pg_interfaces: remaining_packet = self.get_next_packet_info_for_interface2( - i, dst_sw_if_index, last_info[i.sw_if_index]) + i, dst_sw_if_index, last_info[i.sw_if_index] + ) self.assertTrue( remaining_packet is None, - "Port %u: Packet expected from source %u didn't arrive" % - (dst_sw_if_index, i.sw_if_index)) + "Port %u: Packet expected from source %u didn't arrive" + % (dst_sw_if_index, i.sw_if_index), + ) def run_l2bd_test(self, pkts_per_burst): - """ L2BD MAC learning test """ + """L2BD MAC learning test""" # Create incoming packet streams for packet-generator interfaces for i in self.pg_interfaces: - packet_sizes = self.sub_if_packet_sizes if hasattr(i, 'sub_if') \ + packet_sizes = ( + self.sub_if_packet_sizes + if hasattr(i, "sub_if") else self.pg_if_packet_sizes + ) pkts = self.create_stream(i, packet_sizes, pkts_per_burst) i.add_stream(pkts) @@ -251,7 +272,7 @@ class TestL2bd(VppTestCase): self.verify_capture(i, capture) def test_l2bd_sl(self): - """ L2BD MAC learning single-loop test + """L2BD MAC learning single-loop test Test scenario: 1.config @@ -268,22 +289,22 @@ class TestL2bd(VppTestCase): self.run_l2bd_test(self.sl_pkts_per_burst) def test_l2bd_dl(self): - """ L2BD MAC learning dual-loop test + """L2BD MAC learning dual-loop test - Test scenario: - 1.config - MAC learning enabled - learn 100 MAC entries - 3 interfaces: untagged, dot1q, dot1ad (dot1q used instead of - dot1ad in the first version) - - 2.sending l2 eth pkts between 3 interface - 64B, 512B, 1518B, 9200B (ether_size) - burst of 257 pkts per interface + Test scenario: + 1.config + MAC learning enabled + learn 100 MAC entries + 3 interfaces: untagged, dot1q, dot1ad (dot1q used instead of + dot1ad in the first version) + + 2.sending l2 eth pkts between 3 interface + 64B, 512B, 1518B, 9200B (ether_size) + burst of 257 pkts per interface """ self.run_l2bd_test(self.dl_pkts_per_burst) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_l2bd_arp_term.py b/test/test_l2bd_arp_term.py index c64d5d4f01c..598203950d9 100644 --- a/test/test_l2bd_arp_term.py +++ b/test/test_l2bd_arp_term.py @@ -10,19 +10,38 @@ from socket import AF_INET, AF_INET6, inet_pton, inet_ntop from scapy.packet import Raw from scapy.layers.l2 import Ether, ARP from scapy.layers.inet import IP -from scapy.utils6 import in6_getnsma, in6_getnsmac, in6_ptop, in6_islladdr, \ - in6_mactoifaceid, in6_ismaddr -from scapy.layers.inet6 import IPv6, UDP, ICMPv6ND_NS, ICMPv6ND_RS, \ - ICMPv6ND_RA, ICMPv6NDOptSrcLLAddr, getmacbyip6, ICMPv6MRD_Solicitation, \ - ICMPv6NDOptMTU, ICMPv6NDOptSrcLLAddr, ICMPv6NDOptPrefixInfo, \ - ICMPv6ND_NA, ICMPv6NDOptDstLLAddr, ICMPv6DestUnreach, icmp6types +from scapy.utils6 import ( + in6_getnsma, + in6_getnsmac, + in6_ptop, + in6_islladdr, + in6_mactoifaceid, + in6_ismaddr, +) +from scapy.layers.inet6 import ( + IPv6, + UDP, + ICMPv6ND_NS, + ICMPv6ND_RS, + ICMPv6ND_RA, + ICMPv6NDOptSrcLLAddr, + getmacbyip6, + ICMPv6MRD_Solicitation, + ICMPv6NDOptMTU, + ICMPv6NDOptSrcLLAddr, + ICMPv6NDOptPrefixInfo, + ICMPv6ND_NA, + ICMPv6NDOptDstLLAddr, + ICMPv6DestUnreach, + icmp6types, +) from framework import VppTestCase, VppTestRunner from util import Host, ppp class TestL2bdArpTerm(VppTestCase): - """ L2BD arp termination Test Case """ + """L2BD arp termination Test Case""" @classmethod def setUpClass(cls): @@ -77,11 +96,9 @@ class TestL2bdArpTerm(VppTestCase): def add_del_arp_term_hosts(self, entries, bd_id=1, is_add=1, is_ipv6=0): for e in entries: ip = e.ip4 if is_ipv6 == 0 else e.ip6 - self.vapi.bd_ip_mac_add_del(is_add=is_add, - entry={ - 'bd_id': bd_id, - 'ip': ip, - 'mac': e.mac}) + self.vapi.bd_ip_mac_add_del( + is_add=is_add, entry={"bd_id": bd_id, "ip": ip, "mac": e.mac} + ) @classmethod def mac_list(cls, b6_range): @@ -89,23 +106,23 @@ class TestL2bdArpTerm(VppTestCase): @classmethod def ip4_host(cls, subnet, host, mac): - return Host(mac=mac, - ip4="172.17.1%02u.%u" % (subnet, host)) + return Host(mac=mac, ip4="172.17.1%02u.%u" % (subnet, host)) @classmethod def ip4_hosts(cls, subnet, start, mac_list): - return {cls.ip4_host(subnet, start + j, mac_list[j]) - for j in range(len(mac_list))} + return { + cls.ip4_host(subnet, start + j, mac_list[j]) for j in range(len(mac_list)) + } @classmethod def ip6_host(cls, subnet, host, mac): - return Host(mac=mac, - ip6="fd01:%x::%x" % (subnet, host)) + return Host(mac=mac, ip6="fd01:%x::%x" % (subnet, host)) @classmethod def ip6_hosts(cls, subnet, start, mac_list): - return {cls.ip6_host(subnet, start + j, mac_list[j]) - for j in range(len(mac_list))} + return { + cls.ip6_host(subnet, start + j, mac_list[j]) for j in range(len(mac_list)) + } @classmethod def bd_swifs(cls, b): @@ -118,18 +135,17 @@ class TestL2bdArpTerm(VppTestCase): self.vapi.bridge_domain_add_del(bd_id=bd_id, is_add=is_add) for swif in self.bd_swifs(bd_id): swif_idx = swif.sw_if_index - self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=swif_idx, - bd_id=bd_id, enable=is_add) + self.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=swif_idx, bd_id=bd_id, enable=is_add + ) if not is_add: self.vapi.bridge_domain_add_del(bd_id=bd_id, is_add=is_add) @classmethod def arp_req(cls, src_host, host): - return (Ether(dst="ff:ff:ff:ff:ff:ff", src=src_host.mac) / - ARP(op="who-has", - hwsrc=src_host.bin_mac, - pdst=host.ip4, - psrc=src_host.ip4)) + return Ether(dst="ff:ff:ff:ff:ff:ff", src=src_host.mac) / ARP( + op="who-has", hwsrc=src_host.bin_mac, pdst=host.ip4, psrc=src_host.ip4 + ) @classmethod def arp_reqs(cls, src_host, entries): @@ -167,7 +183,7 @@ class TestL2bdArpTerm(VppTestCase): o2 = int(ip / 65536) % 256 o3 = int(ip / 256) % 256 o4 = int(ip) % 256 - return '%s.%s.%s.%s' % (o1, o2, o3, o4) + return "%s.%s.%s.%s" % (o1, o2, o3, o4) def arp_event_host(self, e): return Host(str(e.mac), ip4=str(e.ip)) @@ -185,10 +201,12 @@ class TestL2bdArpTerm(VppTestCase): def ns_req(cls, src_host, host): nsma = in6_getnsma(inet_pton(AF_INET6, "fd10::ffff")) d = inet_ntop(AF_INET6, nsma) - return (Ether(dst="ff:ff:ff:ff:ff:ff", src=src_host.mac) / - IPv6(dst=d, src=src_host.ip6) / - ICMPv6ND_NS(tgt=host.ip6) / - ICMPv6NDOptSrcLLAddr(lladdr=src_host.mac)) + return ( + Ether(dst="ff:ff:ff:ff:ff:ff", src=src_host.mac) + / IPv6(dst=d, src=src_host.ip6) + / ICMPv6ND_NS(tgt=host.ip6) + / ICMPv6NDOptSrcLLAddr(lladdr=src_host.mac) + ) @classmethod def ns_reqs_dst(cls, entries, dst_host): @@ -200,8 +218,7 @@ class TestL2bdArpTerm(VppTestCase): def na_resp_host(self, src_host, rx): self.assertEqual(rx[Ether].dst, src_host.mac) - self.assertEqual(in6_ptop(rx[IPv6].dst), - in6_ptop(src_host.ip6)) + self.assertEqual(in6_ptop(rx[IPv6].dst), in6_ptop(src_host.ip6)) self.assertTrue(rx.haslayer(ICMPv6ND_NA)) self.assertTrue(rx.haslayer(ICMPv6NDOptDstLLAddr)) @@ -236,8 +253,7 @@ class TestL2bdArpTerm(VppTestCase): else: raise ValueError("Unknown feature used: %s" % flag) is_set = 1 if args[flag] else 0 - self.vapi.bridge_flags(bd_id=bd_id, is_set=is_set, - flags=feature_bitmap) + self.vapi.bridge_flags(bd_id=bd_id, is_set=is_set, flags=feature_bitmap) self.logger.info("Bridge domain ID %d updated" % bd_id) def verify_arp(self, src_host, req_hosts, resp_hosts, bd_id=1): @@ -269,12 +285,10 @@ class TestL2bdArpTerm(VppTestCase): self.assertEqual(len(resps ^ resp_hosts), 0) def test_l2bd_arp_term_01(self): - """ L2BD arp term - add 5 hosts, verify arp responses - """ + """L2BD arp term - add 5 hosts, verify arp responses""" src_host = self.ip4_host(50, 50, "00:00:11:22:33:44") self.bd_add_del(1, is_add=1) - self.set_bd_flags(1, arp_term=True, flood=False, - uu_flood=False, learn=False) + self.set_bd_flags(1, arp_term=True, flood=False, uu_flood=False, learn=False) macs = self.mac_list(range(1, 5)) hosts = self.ip4_hosts(4, 1, macs) self.add_del_arp_term_hosts(hosts, is_add=1) @@ -283,8 +297,7 @@ class TestL2bdArpTerm(VppTestCase): type(self).hosts = hosts def test_l2bd_arp_term_02(self): - """ L2BD arp term - delete 3 hosts, verify arp responses - """ + """L2BD arp term - delete 3 hosts, verify arp responses""" src_host = self.ip4_host(50, 50, "00:00:11:22:33:44") macs = self.mac_list(range(1, 3)) deleted = self.ip4_hosts(4, 1, macs) @@ -295,12 +308,10 @@ class TestL2bdArpTerm(VppTestCase): self.bd_add_del(1, is_add=0) def test_l2bd_arp_term_03(self): - """ L2BD arp term - recreate BD1, readd 3 hosts, verify arp responses - """ + """L2BD arp term - recreate BD1, readd 3 hosts, verify arp responses""" src_host = self.ip4_host(50, 50, "00:00:11:22:33:44") self.bd_add_del(1, is_add=1) - self.set_bd_flags(1, arp_term=True, flood=False, - uu_flood=False, learn=False) + self.set_bd_flags(1, arp_term=True, flood=False, uu_flood=False, learn=False) macs = self.mac_list(range(1, 3)) readded = self.ip4_hosts(4, 1, macs) self.add_del_arp_term_hosts(readded, is_add=1) @@ -308,8 +319,7 @@ class TestL2bdArpTerm(VppTestCase): type(self).hosts = readded def test_l2bd_arp_term_04(self): - """ L2BD arp term - 2 IP4 addrs per host - """ + """L2BD arp term - 2 IP4 addrs per host""" src_host = self.ip4_host(50, 50, "00:00:11:22:33:44") macs = self.mac_list(range(1, 3)) sub5_hosts = self.ip4_hosts(5, 1, macs) @@ -320,12 +330,10 @@ class TestL2bdArpTerm(VppTestCase): self.bd_add_del(1, is_add=0) def test_l2bd_arp_term_05(self): - """ L2BD arp term - create and update 10 IP4-mac pairs - """ + """L2BD arp term - create and update 10 IP4-mac pairs""" src_host = self.ip4_host(50, 50, "00:00:11:22:33:44") self.bd_add_del(1, is_add=1) - self.set_bd_flags(1, arp_term=True, flood=False, - uu_flood=False, learn=False) + self.set_bd_flags(1, arp_term=True, flood=False, uu_flood=False, learn=False) macs1 = self.mac_list(range(10, 20)) hosts1 = self.ip4_hosts(5, 1, macs1) self.add_del_arp_term_hosts(hosts1, is_add=1) @@ -337,14 +345,12 @@ class TestL2bdArpTerm(VppTestCase): self.bd_add_del(1, is_add=0) def test_l2bd_arp_term_06(self): - """ L2BD arp/ND term - hosts with both ip4/ip6 - """ + """L2BD arp/ND term - hosts with both ip4/ip6""" src_host4 = self.ip4_host(50, 50, "00:00:11:22:33:44") src_host6 = self.ip6_host(50, 50, "00:00:11:22:33:44") self.bd_add_del(1, is_add=1) # enable flood to make sure requests are not flooded - self.set_bd_flags(1, arp_term=True, flood=True, - uu_flood=False, learn=False) + self.set_bd_flags(1, arp_term=True, flood=True, uu_flood=False, learn=False) macs = self.mac_list(range(10, 20)) hosts6 = self.ip6_hosts(5, 1, macs) hosts4 = self.ip4_hosts(5, 1, macs) @@ -355,12 +361,10 @@ class TestL2bdArpTerm(VppTestCase): self.bd_add_del(1, is_add=0) def test_l2bd_arp_term_07(self): - """ L2BD ND term - Add and Del hosts, verify ND replies - """ + """L2BD ND term - Add and Del hosts, verify ND replies""" src_host6 = self.ip6_host(50, 50, "00:00:11:22:33:44") self.bd_add_del(1, is_add=1) - self.set_bd_flags(1, arp_term=True, flood=False, - uu_flood=False, learn=False) + self.set_bd_flags(1, arp_term=True, flood=False, uu_flood=False, learn=False) macs = self.mac_list(range(10, 20)) hosts6 = self.ip6_hosts(5, 1, macs) self.add_del_arp_term_hosts(hosts6, is_add=1, is_ipv6=1) @@ -372,12 +376,10 @@ class TestL2bdArpTerm(VppTestCase): self.bd_add_del(1, is_add=0) def test_l2bd_arp_term_08(self): - """ L2BD ND term - Add and update IP+mac, verify ND replies - """ + """L2BD ND term - Add and update IP+mac, verify ND replies""" src_host = self.ip6_host(50, 50, "00:00:11:22:33:44") self.bd_add_del(1, is_add=1) - self.set_bd_flags(1, arp_term=True, flood=False, - uu_flood=False, learn=False) + self.set_bd_flags(1, arp_term=True, flood=False, uu_flood=False, learn=False) macs1 = self.mac_list(range(10, 20)) hosts = self.ip6_hosts(5, 1, macs1) self.add_del_arp_term_hosts(hosts, is_add=1, is_ipv6=1) @@ -389,12 +391,10 @@ class TestL2bdArpTerm(VppTestCase): self.bd_add_del(1, is_add=0) def test_l2bd_arp_term_09(self): - """ L2BD arp term - send garps, verify arp event reports - """ + """L2BD arp term - send garps, verify arp event reports""" self.vapi.want_l2_arp_term_events(enable=1) self.bd_add_del(1, is_add=1) - self.set_bd_flags(1, arp_term=True, flood=False, - uu_flood=False, learn=False) + self.set_bd_flags(1, arp_term=True, flood=False, uu_flood=False, learn=False) macs = self.mac_list(range(90, 95)) hosts = self.ip4_hosts(5, 1, macs) @@ -403,14 +403,14 @@ class TestL2bdArpTerm(VppTestCase): self.pg_enable_capture(self.pg_interfaces) self.pg_start() - evs = [self.vapi.wait_for_event(1, "l2_arp_term_event") - for i in range(len(hosts))] + evs = [ + self.vapi.wait_for_event(1, "l2_arp_term_event") for i in range(len(hosts)) + ] ev_hosts = self.arp_event_hosts(evs) self.assertEqual(len(ev_hosts ^ hosts), 0) def test_l2bd_arp_term_10(self): - """ L2BD arp term - send duplicate garps, verify suppression - """ + """L2BD arp term - send duplicate garps, verify suppression""" macs = self.mac_list(range(70, 71)) hosts = self.ip4_hosts(6, 1, macs) @@ -421,14 +421,14 @@ class TestL2bdArpTerm(VppTestCase): self.pg_enable_capture(self.pg_interfaces) self.pg_start() - evs = [self.vapi.wait_for_event(1, "l2_arp_term_event") - for i in range(len(hosts))] + evs = [ + self.vapi.wait_for_event(1, "l2_arp_term_event") for i in range(len(hosts)) + ] ev_hosts = self.arp_event_hosts(evs) self.assertEqual(len(ev_hosts ^ hosts), 0) def test_l2bd_arp_term_11(self): - """ L2BD arp term - disable ip4 arp events,send garps, verify no events - """ + """L2BD arp term - disable ip4 arp events,send garps, verify no events""" self.vapi.want_l2_arp_term_events(enable=0) macs = self.mac_list(range(90, 95)) hosts = self.ip4_hosts(5, 1, macs) @@ -443,13 +443,11 @@ class TestL2bdArpTerm(VppTestCase): self.bd_add_del(1, is_add=0) def test_l2bd_arp_term_12(self): - """ L2BD ND term - send NS packets verify reports - """ + """L2BD ND term - send NS packets verify reports""" self.vapi.want_l2_arp_term_events(enable=1) dst_host = self.ip6_host(50, 50, "00:00:11:22:33:44") self.bd_add_del(1, is_add=1) - self.set_bd_flags(1, arp_term=True, flood=False, - uu_flood=False, learn=False) + self.set_bd_flags(1, arp_term=True, flood=False, uu_flood=False, learn=False) macs = self.mac_list(range(10, 15)) hosts = self.ip6_hosts(5, 1, macs) reqs = self.ns_reqs_dst(hosts, dst_host) @@ -457,14 +455,14 @@ class TestL2bdArpTerm(VppTestCase): self.pg_enable_capture(self.pg_interfaces) self.pg_start() - evs = [self.vapi.wait_for_event(2, "l2_arp_term_event") - for i in range(len(hosts))] + evs = [ + self.vapi.wait_for_event(2, "l2_arp_term_event") for i in range(len(hosts)) + ] ev_hosts = self.nd_event_hosts(evs) self.assertEqual(len(ev_hosts ^ hosts), 0) def test_l2bd_arp_term_13(self): - """ L2BD ND term - send duplicate ns, verify suppression - """ + """L2BD ND term - send duplicate ns, verify suppression""" dst_host = self.ip6_host(50, 50, "00:00:11:22:33:44") macs = self.mac_list(range(16, 17)) hosts = self.ip6_hosts(5, 1, macs) @@ -473,14 +471,14 @@ class TestL2bdArpTerm(VppTestCase): self.pg_enable_capture(self.pg_interfaces) self.pg_start() - evs = [self.vapi.wait_for_event(2, "l2_arp_term_event") - for i in range(len(hosts))] + evs = [ + self.vapi.wait_for_event(2, "l2_arp_term_event") for i in range(len(hosts)) + ] ev_hosts = self.nd_event_hosts(evs) self.assertEqual(len(ev_hosts ^ hosts), 0) def test_l2bd_arp_term_14(self): - """ L2BD ND term - disable ip4 arp events,send ns, verify no events - """ + """L2BD ND term - disable ip4 arp events,send ns, verify no events""" self.vapi.want_l2_arp_term_events(enable=0) dst_host = self.ip6_host(50, 50, "00:00:11:22:33:44") macs = self.mac_list(range(10, 15)) @@ -495,5 +493,5 @@ class TestL2bdArpTerm(VppTestCase): self.bd_add_del(1, is_add=0) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_l2bd_learnlimit.py b/test/test_l2bd_learnlimit.py index 91740590151..1ae25da2686 100644 --- a/test/test_l2bd_learnlimit.py +++ b/test/test_l2bd_learnlimit.py @@ -12,7 +12,7 @@ from util import Host, ppp class TestL2LearnLimit(VppTestCase): - """ L2 Learn no limit Test Case """ + """L2 Learn no limit Test Case""" @classmethod def setUpClass(self): @@ -35,11 +35,15 @@ class TestL2LearnLimit(VppTestCase): hosts = dict() swif = pg_if.sw_if_index - def mac(j): return "00:00:%02x:ff:%02x:%02x" % (subnet, swif, j) + def mac(j): + return "00:00:%02x:ff:%02x:%02x" % (subnet, swif, j) - def ip(j): return "172.%02u.1%02x.%u" % (subnet, swif, j) + def ip(j): + return "172.%02u.1%02x.%u" % (subnet, swif, j) + + def h(j): + return Host(mac(j), ip(j)) - def h(j): return Host(mac(j), ip(j)) hosts[swif] = [h(j) for j in range(n_hosts_per_if)] return hosts @@ -56,15 +60,13 @@ class TestL2LearnLimit(VppTestCase): self.vapi.bridge_flags(bd_id=bd_id, is_set=1, flags=1) swif = pg_if.sw_if_index - packets = [Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac) - for host in hosts[swif]] + packets = [Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac) for host in hosts[swif]] pg_if.add_stream(packets) self.logger.info("Sending broadcast eth frames for MAC learning") self.pg_start() def test_l2bd_learnlimit(self): - """ L2BD test without learn Limit - """ + """L2BD test without learn Limit""" hosts = self.create_hosts(self.pg_interfaces[0], 20, 1) self.learn_hosts(self.pg_interfaces[0], 1, hosts) lfs = self.vapi.l2_fib_table_dump(1) @@ -78,22 +80,20 @@ class TestL2LearnLimit(VppTestCase): self.vapi.bridge_domain_add_del(bd_id=1) self.vapi.bridge_domain_add_del(bd_id=2) - self.vapi.sw_interface_set_l2_bridge( - self.pg_interfaces[0].sw_if_index, bd_id=1) - self.vapi.sw_interface_set_l2_bridge( - self.pg_interfaces[1].sw_if_index, bd_id=2) + self.vapi.sw_interface_set_l2_bridge(self.pg_interfaces[0].sw_if_index, bd_id=1) + self.vapi.sw_interface_set_l2_bridge(self.pg_interfaces[1].sw_if_index, bd_id=2) def tearDown(self): super(TestL2LearnLimit, self).tearDown() self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg_interfaces[0].sw_if_index, - bd_id=1, enable=0) + rx_sw_if_index=self.pg_interfaces[0].sw_if_index, bd_id=1, enable=0 + ) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg_interfaces[1].sw_if_index, - bd_id=2, enable=0) + rx_sw_if_index=self.pg_interfaces[1].sw_if_index, bd_id=2, enable=0 + ) self.vapi.bridge_domain_add_del(bd_id=1, is_add=0) self.vapi.bridge_domain_add_del(bd_id=2, is_add=0) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_l2bd_learnlimit_bdenabled.py b/test/test_l2bd_learnlimit_bdenabled.py index 63dc5d10542..0578cedbe4a 100644 --- a/test/test_l2bd_learnlimit_bdenabled.py +++ b/test/test_l2bd_learnlimit_bdenabled.py @@ -12,7 +12,7 @@ from util import Host, ppp class TestL2LearnLimitBdEnable(VppTestCase): - """ L2 Bridge Domain Learn limit Test Case """ + """L2 Bridge Domain Learn limit Test Case""" @classmethod def setUpClass(self): @@ -35,11 +35,15 @@ class TestL2LearnLimitBdEnable(VppTestCase): hosts = dict() swif = pg_if.sw_if_index - def mac(j): return "00:00:%02x:ff:%02x:%02x" % (subnet, swif, j) + def mac(j): + return "00:00:%02x:ff:%02x:%02x" % (subnet, swif, j) - def ip(j): return "172.%02u.1%02x.%u" % (subnet, swif, j) + def ip(j): + return "172.%02u.1%02x.%u" % (subnet, swif, j) + + def h(j): + return Host(mac(j), ip(j)) - def h(j): return Host(mac(j), ip(j)) hosts[swif] = [h(j) for j in range(n_hosts_per_if)] return hosts @@ -56,20 +60,17 @@ class TestL2LearnLimitBdEnable(VppTestCase): self.vapi.bridge_flags(bd_id=bd_id, is_set=1, flags=1) swif = pg_if.sw_if_index - packets = [Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac) - for host in hosts[swif]] + packets = [Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac) for host in hosts[swif]] pg_if.add_stream(packets) self.logger.info("Sending broadcast eth frames for MAC learning") self.pg_start() def test_l2bd_learnlimit(self): - """ L2BD test with bridge domain limit - """ + """L2BD test with bridge domain limit""" self.vapi.want_l2_macs_events(enable_disable=1, learn_limit=1000) self.vapi.bridge_domain_set_default_learn_limit(4) self.vapi.bridge_domain_add_del(bd_id=3) - self.vapi.sw_interface_set_l2_bridge( - self.pg_interfaces[2].sw_if_index, bd_id=3) + self.vapi.sw_interface_set_l2_bridge(self.pg_interfaces[2].sw_if_index, bd_id=3) self.vapi.bridge_domain_set_learn_limit(2, 5) @@ -92,8 +93,8 @@ class TestL2LearnLimitBdEnable(VppTestCase): self.assertEqual(len(lfs2), 4) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg_interfaces[2].sw_if_index, - bd_id=3, enable=0) + rx_sw_if_index=self.pg_interfaces[2].sw_if_index, bd_id=3, enable=0 + ) self.vapi.bridge_domain_add_del(is_add=0, bd_id=3) def setUp(self): @@ -102,22 +103,20 @@ class TestL2LearnLimitBdEnable(VppTestCase): self.vapi.bridge_domain_add_del(bd_id=1) self.vapi.bridge_domain_add_del(bd_id=2) - self.vapi.sw_interface_set_l2_bridge( - self.pg_interfaces[0].sw_if_index, bd_id=1) - self.vapi.sw_interface_set_l2_bridge( - self.pg_interfaces[1].sw_if_index, bd_id=2) + self.vapi.sw_interface_set_l2_bridge(self.pg_interfaces[0].sw_if_index, bd_id=1) + self.vapi.sw_interface_set_l2_bridge(self.pg_interfaces[1].sw_if_index, bd_id=2) def tearDown(self): super(TestL2LearnLimitBdEnable, self).tearDown() self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg_interfaces[0].sw_if_index, - bd_id=1, enable=0) + rx_sw_if_index=self.pg_interfaces[0].sw_if_index, bd_id=1, enable=0 + ) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg_interfaces[1].sw_if_index, - bd_id=2, enable=0) + rx_sw_if_index=self.pg_interfaces[1].sw_if_index, bd_id=2, enable=0 + ) self.vapi.bridge_domain_add_del(bd_id=1, is_add=0) self.vapi.bridge_domain_add_del(bd_id=2, is_add=0) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_l2bd_learnlimit_enabled.py b/test/test_l2bd_learnlimit_enabled.py index 5fcd54cb8f2..8bb3b4029b0 100644 --- a/test/test_l2bd_learnlimit_enabled.py +++ b/test/test_l2bd_learnlimit_enabled.py @@ -12,7 +12,7 @@ from util import Host, ppp class TestL2LearnLimitEnable(VppTestCase): - """ L2 Global Learn limit Test Case """ + """L2 Global Learn limit Test Case""" @classmethod def setUpClass(self): @@ -35,11 +35,15 @@ class TestL2LearnLimitEnable(VppTestCase): hosts = dict() swif = pg_if.sw_if_index - def mac(j): return "00:00:%02x:ff:%02x:%02x" % (subnet, swif, j) + def mac(j): + return "00:00:%02x:ff:%02x:%02x" % (subnet, swif, j) - def ip(j): return "172.%02u.1%02x.%u" % (subnet, swif, j) + def ip(j): + return "172.%02u.1%02x.%u" % (subnet, swif, j) + + def h(j): + return Host(mac(j), ip(j)) - def h(j): return Host(mac(j), ip(j)) hosts[swif] = [h(j) for j in range(n_hosts_per_if)] return hosts @@ -56,15 +60,13 @@ class TestL2LearnLimitEnable(VppTestCase): self.vapi.bridge_flags(bd_id=bd_id, is_set=1, flags=1) swif = pg_if.sw_if_index - packets = [Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac) - for host in hosts[swif]] + packets = [Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac) for host in hosts[swif]] pg_if.add_stream(packets) self.logger.info("Sending broadcast eth frames for MAC learning") self.pg_start() def test_l2bd_learnlimit01(self): - """ L2BD test with learn Limit - """ + """L2BD test with learn Limit""" self.vapi.want_l2_macs_events(enable_disable=1, learn_limit=10) hosts = self.create_hosts(self.pg_interfaces[0], 20, 1) fhosts = self.create_hosts(self.pg_interfaces[1], 1, 2) @@ -90,22 +92,20 @@ class TestL2LearnLimitEnable(VppTestCase): self.vapi.bridge_domain_add_del(bd_id=1) self.vapi.bridge_domain_add_del(bd_id=2) - self.vapi.sw_interface_set_l2_bridge( - self.pg_interfaces[0].sw_if_index, bd_id=1) - self.vapi.sw_interface_set_l2_bridge( - self.pg_interfaces[1].sw_if_index, bd_id=2) + self.vapi.sw_interface_set_l2_bridge(self.pg_interfaces[0].sw_if_index, bd_id=1) + self.vapi.sw_interface_set_l2_bridge(self.pg_interfaces[1].sw_if_index, bd_id=2) def tearDown(self): super(TestL2LearnLimitEnable, self).tearDown() self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg_interfaces[0].sw_if_index, - bd_id=1, enable=0) + rx_sw_if_index=self.pg_interfaces[0].sw_if_index, bd_id=1, enable=0 + ) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg_interfaces[1].sw_if_index, - bd_id=2, enable=0) + rx_sw_if_index=self.pg_interfaces[1].sw_if_index, bd_id=2, enable=0 + ) self.vapi.bridge_domain_add_del(bd_id=1, is_add=0) self.vapi.bridge_domain_add_del(bd_id=2, is_add=0) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_l2bd_multi_instance.py b/test/test_l2bd_multi_instance.py index c4692d686b0..1266afcb690 100644 --- a/test/test_l2bd_multi_instance.py +++ b/test/test_l2bd_multi_instance.py @@ -74,7 +74,7 @@ from util import Host, ppp class TestL2bdMultiInst(VppTestCase): - """ L2BD Multi-instance Test Case """ + """L2BD Multi-instance Test Case""" @classmethod def setUpClass(cls): @@ -98,9 +98,9 @@ class TestL2bdMultiInst(VppTestCase): bd_ifs = cls.bd_if_range(b + 1) for j in bd_ifs: cls.flows[cls.pg_interfaces[j]] = [ - cls.pg_interfaces[x] for x in bd_ifs if x != j] - assert( - len(cls.flows[cls.pg_interfaces[j]]) == ifs_per_bd - 1) + cls.pg_interfaces[x] for x in bd_ifs if x != j + ] + assert len(cls.flows[cls.pg_interfaces[j]]) == ifs_per_bd - 1 # Mapping between packet-generator index and lists of test hosts cls.hosts_by_pg_idx = dict() @@ -158,12 +158,16 @@ class TestL2bdMultiInst(VppTestCase): addresses for. """ c = hosts_per_if - assert(not cls.hosts_by_pg_idx) + assert not cls.hosts_by_pg_idx for i in range(len(cls.pg_interfaces)): pg_idx = cls.pg_interfaces[i].sw_if_index - cls.hosts_by_pg_idx[pg_idx] = [Host( - "00:00:00:ff:%02x:%02x" % (pg_idx, j + 1), - "172.17.1%02u.%u" % (pg_idx, j + 1)) for j in range(c)] + cls.hosts_by_pg_idx[pg_idx] = [ + Host( + "00:00:00:ff:%02x:%02x" % (pg_idx, j + 1), + "172.17.1%02u.%u" % (pg_idx, j + 1), + ) + for j in range(c) + ] @classmethod def bd_if_range(cls, b): @@ -191,13 +195,16 @@ class TestL2bdMultiInst(VppTestCase): for j in self.bd_if_range(b): pg_if = self.pg_interfaces[j] self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=pg_if.sw_if_index, bd_id=b) - self.logger.info("pg-interface %s added to bridge domain ID %d" - % (pg_if.name, b)) + rx_sw_if_index=pg_if.sw_if_index, bd_id=b + ) + self.logger.info( + "pg-interface %s added to bridge domain ID %d" % (pg_if.name, b) + ) self.pg_in_bd.append(pg_if) hosts = self.hosts_by_pg_idx[pg_if.sw_if_index] - packets = [Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac) - for host in hosts] + packets = [ + Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac) for host in hosts + ] pg_if.add_stream(packets) self.logger.info("Sending broadcast eth frames for MAC learning") self.pg_start() @@ -216,7 +223,8 @@ class TestL2bdMultiInst(VppTestCase): for j in self.bd_if_range(b): pg_if = self.pg_interfaces[j] self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=pg_if.sw_if_index, bd_id=b, enable=0) + rx_sw_if_index=pg_if.sw_if_index, bd_id=b, enable=0 + ) self.pg_in_bd.remove(pg_if) self.vapi.bridge_domain_add_del(bd_id=b, is_add=0) self.bd_list.remove(b) @@ -240,16 +248,20 @@ class TestL2bdMultiInst(VppTestCase): pkt_info = self.create_packet_info(src_if, dst_if) payload = self.info_to_payload(pkt_info) src_host = random.choice(src_hosts) - p = (Ether(dst=dst_host.mac, src=src_host.mac) / - IP(src=src_host.ip4, dst=dst_host.ip4) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + Ether(dst=dst_host.mac, src=src_host.mac) + / IP(src=src_host.ip4, dst=dst_host.ip4) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) pkt_info.data = p.copy() size = random.choice(packet_sizes) self.extend_packet(p, size) pkts.append(p) - self.logger.debug("Input stream created for port %s. Length: %u pkt(s)" - % (src_if.name, len(pkts))) + self.logger.debug( + "Input stream created for port %s. Length: %u pkt(s)" + % (src_if.name, len(pkts)) + ) return pkts def verify_capture(self, dst_if): @@ -268,10 +280,13 @@ class TestL2bdMultiInst(VppTestCase): udp = packet[UDP] info = self.payload_to_info(packet[Raw]) self.assertEqual(info.dst, dst) - self.logger.debug("Got packet on port %s: src=%u (id=%u)" % - (dst_if.name, info.src, info.index)) + self.logger.debug( + "Got packet on port %s: src=%u (id=%u)" + % (dst_if.name, info.src, info.index) + ) last_info[info.src] = self.get_next_packet_info_for_interface2( - info.src, dst, last_info[info.src]) + info.src, dst, last_info[info.src] + ) pkt_info = last_info[info.src] self.assertTrue(pkt_info is not None) self.assertEqual(info.index, pkt_info.index) @@ -288,10 +303,13 @@ class TestL2bdMultiInst(VppTestCase): remaining = 0 for src in self.flows[dst_if]: remaining_packet = self.get_next_packet_info_for_interface2( - src.sw_if_index, dst, last_info[src.sw_if_index]) + src.sw_if_index, dst, last_info[src.sw_if_index] + ) if remaining_packet is None: - s += "Port %u: Packet expected from source %u didn't arrive\n"\ - % (dst, src.sw_if_index) + s += "Port %u: Packet expected from source %u didn't arrive\n" % ( + dst, + src.sw_if_index, + ) remaining += 1 self.assertNotEqual(0, remaining, s) @@ -319,8 +337,7 @@ class TestL2bdMultiInst(VppTestCase): else: raise ValueError("Unknown feature used: %s" % flag) is_set = 1 if args[flag] else 0 - self.vapi.bridge_flags(bd_id=bd_id, is_set=is_set, - flags=feature_bitmap) + self.vapi.bridge_flags(bd_id=bd_id, is_set=is_set, flags=feature_bitmap) self.logger.info("Bridge domain ID %d updated" % bd_id) def verify_bd(self, bd_id, **args): @@ -376,7 +393,7 @@ class TestL2bdMultiInst(VppTestCase): # Test # Create incoming packet streams for packet-generator interfaces # for pg_if in self.pg_interfaces: - assert(len(self._packet_count_for_dst_if_idx) == 0) + assert len(self._packet_count_for_dst_if_idx) == 0 for pg_if in self.pg_in_bd: pkts = self.create_stream(pg_if) pg_if.add_stream(pkts) @@ -391,8 +408,7 @@ class TestL2bdMultiInst(VppTestCase): self.verify_capture(pg_if) def test_l2bd_inst_01(self): - """ L2BD Multi-instance test 1 - create 5 BDs - """ + """L2BD Multi-instance test 1 - create 5 BDs""" # Config 1 # Create 5 BDs, put interfaces to these BDs and send MAC learning # packets @@ -408,13 +424,13 @@ class TestL2bdMultiInst(VppTestCase): self.delete_bd(5) def test_l2bd_inst_02(self): - """ L2BD Multi-instance test 2 - update data of 5 BDs - """ + """L2BD Multi-instance test 2 - update data of 5 BDs""" # Config 2 # Update data of 5 BDs (disable learn, forward, flood, uu-flood) self.create_bd_and_mac_learn(5) - self.set_bd_flags(self.bd_list[0], learn=False, forward=False, - flood=False, uu_flood=False) + self.set_bd_flags( + self.bd_list[0], learn=False, forward=False, flood=False, uu_flood=False + ) self.set_bd_flags(self.bd_list[1], forward=False) self.set_bd_flags(self.bd_list[2], flood=False) self.set_bd_flags(self.bd_list[3], uu_flood=False) @@ -423,21 +439,25 @@ class TestL2bdMultiInst(VppTestCase): # Verify 2 # Skipping check of uu_flood as it is not returned by # bridge_domain_dump api command - self.verify_bd(self.bd_list[0], learn=False, forward=False, - flood=False, uu_flood=False) - self.verify_bd(self.bd_list[1], learn=True, forward=False, - flood=True, uu_flood=True) - self.verify_bd(self.bd_list[2], learn=True, forward=True, - flood=False, uu_flood=True) - self.verify_bd(self.bd_list[3], learn=True, forward=True, - flood=True, uu_flood=False) - self.verify_bd(self.bd_list[4], learn=False, forward=True, - flood=True, uu_flood=True) + self.verify_bd( + self.bd_list[0], learn=False, forward=False, flood=False, uu_flood=False + ) + self.verify_bd( + self.bd_list[1], learn=True, forward=False, flood=True, uu_flood=True + ) + self.verify_bd( + self.bd_list[2], learn=True, forward=True, flood=False, uu_flood=True + ) + self.verify_bd( + self.bd_list[3], learn=True, forward=True, flood=True, uu_flood=False + ) + self.verify_bd( + self.bd_list[4], learn=False, forward=True, flood=True, uu_flood=True + ) self.delete_bd(5) def test_l2bd_inst_03(self): - """ L2BD Multi-instance test 3 - delete 2 BDs - """ + """L2BD Multi-instance test 3 - delete 2 BDs""" # Config 3 # Delete 2 BDs self.create_bd_and_mac_learn(5) @@ -454,8 +474,7 @@ class TestL2bdMultiInst(VppTestCase): self.delete_bd(3, 3) def test_l2bd_inst_04(self): - """ L2BD Multi-instance test 4 - add 2 BDs - """ + """L2BD Multi-instance test 4 - add 2 BDs""" # Config 4 # Create 5 BDs, put interfaces to these BDs and send MAC learning # packets @@ -471,8 +490,7 @@ class TestL2bdMultiInst(VppTestCase): self.delete_bd(2) def test_l2bd_inst_05(self): - """ L2BD Multi-instance test 5 - delete 5 BDs - """ + """L2BD Multi-instance test 5 - delete 5 BDs""" # Config 5 # Delete 5 BDs self.create_bd_and_mac_learn(5) @@ -485,5 +503,5 @@ class TestL2bdMultiInst(VppTestCase): self.assertEqual(self.verify_bd(bd_id), 1) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_l2tp.py b/test/test_l2tp.py index 5a665238260..13fa02ecc2c 100644 --- a/test/test_l2tp.py +++ b/test/test_l2tp.py @@ -11,7 +11,7 @@ from framework import VppTestCase @tag_fixme_vpp_workers class TestL2tp(VppTestCase): - """ L2TP Test Case """ + """L2TP Test Case""" @classmethod def setUpClass(cls): @@ -22,28 +22,32 @@ class TestL2tp(VppTestCase): cls.pg0.config_ip6() def test_l2tp_decap_local(self): - """ L2TP don't accept packets unless configured """ + """L2TP don't accept packets unless configured""" - pkt = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6, nh=115)) + pkt = Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / IPv6( + src=self.pg0.remote_ip6, dst=self.pg0.local_ip6, nh=115 + ) self.pg0.add_stream(pkt) self.pg_start() # l2tp should not accept packets err = self.statistics.get_counter( - '/err/l2tp-decap-local/l2tpv3 session not found')[0] + "/err/l2tp-decap-local/l2tpv3 session not found" + )[0] self.assertEqual(err, 0) err_count = err - self.vapi.l2tpv3_create_tunnel(client_address=self.pg0.local_ip6, - our_address=self.pg0.remote_ip6) + self.vapi.l2tpv3_create_tunnel( + client_address=self.pg0.local_ip6, our_address=self.pg0.remote_ip6 + ) self.pg0.add_stream(pkt) self.pg_start() # l2tp accepts packets err = self.statistics.get_counter( - '/err/l2tp-decap-local/l2tpv3 session not found')[0] + "/err/l2tp-decap-local/l2tpv3 session not found" + )[0] self.assertEqual(err, 1) err_count = err diff --git a/test/test_l2xc.py b/test/test_l2xc.py index bc653f0b4fb..eba349a2a0f 100644 --- a/test/test_l2xc.py +++ b/test/test_l2xc.py @@ -12,7 +12,7 @@ from util import Host, ppp class TestL2xc(VppTestCase): - """ L2XC Test Case """ + """L2XC Test Case""" @classmethod def setUpClass(cls): @@ -52,15 +52,19 @@ class TestL2xc(VppTestCase): # Create bi-directional cross-connects between pg0 and pg1 cls.vapi.sw_interface_set_l2_xconnect( - cls.pg0.sw_if_index, cls.pg1.sw_if_index, enable=1) + cls.pg0.sw_if_index, cls.pg1.sw_if_index, enable=1 + ) cls.vapi.sw_interface_set_l2_xconnect( - cls.pg1.sw_if_index, cls.pg0.sw_if_index, enable=1) + cls.pg1.sw_if_index, cls.pg0.sw_if_index, enable=1 + ) # Create bi-directional cross-connects between pg2 and pg3 cls.vapi.sw_interface_set_l2_xconnect( - cls.pg2.sw_if_index, cls.pg3.sw_if_index, enable=1) + cls.pg2.sw_if_index, cls.pg3.sw_if_index, enable=1 + ) cls.vapi.sw_interface_set_l2_xconnect( - cls.pg3.sw_if_index, cls.pg2.sw_if_index, enable=1) + cls.pg3.sw_if_index, cls.pg2.sw_if_index, enable=1 + ) # mapping between packet-generator index and lists of test hosts cls.hosts_by_pg_idx = dict() @@ -108,7 +112,8 @@ class TestL2xc(VppTestCase): for j in range(0, count): host = Host( "00:00:00:ff:%02x:%02x" % (pg_if.sw_if_index, j), - "172.17.1%02x.%u" % (pg_if.sw_if_index, j)) + "172.17.1%02x.%u" % (pg_if.sw_if_index, j), + ) hosts.append(host) def create_stream(self, src_if, packet_sizes, packets_per_burst): @@ -127,10 +132,12 @@ class TestL2xc(VppTestCase): src_host = random.choice(self.hosts_by_pg_idx[src_if.sw_if_index]) pkt_info = self.create_packet_info(src_if, dst_if) payload = self.info_to_payload(pkt_info) - p = (Ether(dst=dst_host.mac, src=src_host.mac) / - IP(src=src_host.ip4, dst=dst_host.ip4) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + Ether(dst=dst_host.mac, src=src_host.mac) + / IP(src=src_host.ip4, dst=dst_host.ip4) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) pkt_info.data = p.copy() size = random.choice(packet_sizes) self.extend_packet(p, size) @@ -155,11 +162,13 @@ class TestL2xc(VppTestCase): payload_info = self.payload_to_info(packet[Raw]) packet_index = payload_info.index self.assertEqual(payload_info.dst, dst_sw_if_index) - self.logger.debug("Got packet on port %s: src=%u (id=%u)" % - (pg_if.name, payload_info.src, packet_index)) + self.logger.debug( + "Got packet on port %s: src=%u (id=%u)" + % (pg_if.name, payload_info.src, packet_index) + ) next_info = self.get_next_packet_info_for_interface2( - payload_info.src, dst_sw_if_index, - last_info[payload_info.src]) + payload_info.src, dst_sw_if_index, last_info[payload_info.src] + ) last_info[payload_info.src] = next_info self.assertTrue(next_info is not None) self.assertEqual(packet_index, next_info.index) @@ -174,18 +183,20 @@ class TestL2xc(VppTestCase): raise for i in self.interfaces: remaining_packet = self.get_next_packet_info_for_interface2( - i, dst_sw_if_index, last_info[i.sw_if_index]) - self.assertTrue(remaining_packet is None, - "Port %u: Packet expected from source %u didn't" - " arrive" % (dst_sw_if_index, i.sw_if_index)) + i, dst_sw_if_index, last_info[i.sw_if_index] + ) + self.assertTrue( + remaining_packet is None, + "Port %u: Packet expected from source %u didn't" + " arrive" % (dst_sw_if_index, i.sw_if_index), + ) def run_l2xc_test(self, pkts_per_burst): - """ L2XC test """ + """L2XC test""" # Create incoming packet streams for packet-generator interfaces for i in self.interfaces: - pkts = self.create_stream(i, self.pg_if_packet_sizes, - pkts_per_burst) + pkts = self.create_stream(i, self.pg_if_packet_sizes, pkts_per_burst) i.add_stream(pkts) # Enable packet capturing and start packet sending @@ -199,7 +210,7 @@ class TestL2xc(VppTestCase): self.verify_capture(i, capture) def test_l2xc_sl(self): - """ L2XC single-loop test + """L2XC single-loop test Test scenario: 1. config @@ -213,7 +224,7 @@ class TestL2xc(VppTestCase): self.run_l2xc_test(self.sl_pkts_per_burst) def test_l2xc_dl(self): - """ L2XC dual-loop test + """L2XC dual-loop test Test scenario: 1. config @@ -227,5 +238,5 @@ class TestL2xc(VppTestCase): self.run_l2xc_test(self.dl_pkts_per_burst) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_l2xc_multi_instance.py b/test/test_l2xc_multi_instance.py index 2a6e41c8791..801951657af 100644 --- a/test/test_l2xc_multi_instance.py +++ b/test/test_l2xc_multi_instance.py @@ -63,7 +63,7 @@ from util import Host, ppp class TestL2xcMultiInst(VppTestCase): - """ L2XC Multi-instance Test Case """ + """L2XC Multi-instance Test Case""" @classmethod def setUpClass(cls): @@ -82,8 +82,7 @@ class TestL2xcMultiInst(VppTestCase): cls.flows = dict() for i in range(len(cls.pg_interfaces)): delta = 1 if i % 2 == 0 else -1 - cls.flows[cls.pg_interfaces[i]] =\ - [cls.pg_interfaces[i + delta]] + cls.flows[cls.pg_interfaces[i]] = [cls.pg_interfaces[i + delta]] # Mapping between packet-generator index and lists of test hosts cls.hosts_by_pg_idx = dict() @@ -151,7 +150,8 @@ class TestL2xcMultiInst(VppTestCase): for j in range(start_nr, end_nr): host = Host( "00:00:00:ff:%02x:%02x" % (pg_if.sw_if_index, j), - "172.17.1%02u.%u" % (pg_if.sw_if_index, j)) + "172.17.1%02u.%u" % (pg_if.sw_if_index, j), + ) hosts.append(host) def create_xconnects(self, count, start=0): @@ -167,10 +167,12 @@ class TestL2xcMultiInst(VppTestCase): rx_if = self.pg_interfaces[i + start] delta = 1 if i % 2 == 0 else -1 tx_if = self.pg_interfaces[i + start + delta] - self.vapi.sw_interface_set_l2_xconnect(rx_if.sw_if_index, - tx_if.sw_if_index, 1) - self.logger.info("Cross-connect from %s to %s created" - % (tx_if.name, rx_if.name)) + self.vapi.sw_interface_set_l2_xconnect( + rx_if.sw_if_index, tx_if.sw_if_index, 1 + ) + self.logger.info( + "Cross-connect from %s to %s created" % (tx_if.name, rx_if.name) + ) if self.pg_in_xc.count(rx_if) == 0: self.pg_in_xc.append(rx_if) if self.pg_not_in_xc.count(rx_if) == 1: @@ -189,10 +191,12 @@ class TestL2xcMultiInst(VppTestCase): rx_if = self.pg_interfaces[i + start] delta = 1 if i % 2 == 0 else -1 tx_if = self.pg_interfaces[i + start + delta] - self.vapi.sw_interface_set_l2_xconnect(rx_if.sw_if_index, - tx_if.sw_if_index, 0) - self.logger.info("Cross-connect from %s to %s deleted" - % (tx_if.name, rx_if.name)) + self.vapi.sw_interface_set_l2_xconnect( + rx_if.sw_if_index, tx_if.sw_if_index, 0 + ) + self.logger.info( + "Cross-connect from %s to %s deleted" % (tx_if.name, rx_if.name) + ) if self.pg_not_in_xc.count(rx_if) == 0: self.pg_not_in_xc.append(rx_if) if self.pg_in_xc.count(rx_if) == 1: @@ -216,16 +220,20 @@ class TestL2xcMultiInst(VppTestCase): src_host = random.choice(src_hosts) pkt_info = self.create_packet_info(src_if, dst_if) payload = self.info_to_payload(pkt_info) - p = (Ether(dst=dst_host.mac, src=src_host.mac) / - IP(src=src_host.ip4, dst=dst_host.ip4) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + Ether(dst=dst_host.mac, src=src_host.mac) + / IP(src=src_host.ip4, dst=dst_host.ip4) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) pkt_info.data = p.copy() size = random.choice(packet_sizes) self.extend_packet(p, size) pkts.append(p) - self.logger.debug("Input stream created for port %s. Length: %u pkt(s)" - % (src_if.name, len(pkts))) + self.logger.debug( + "Input stream created for port %s. Length: %u pkt(s)" + % (src_if.name, len(pkts)) + ) return pkts def verify_capture(self, pg_if, capture): @@ -246,11 +254,13 @@ class TestL2xcMultiInst(VppTestCase): udp = packet[UDP] packet_index = payload_info.index self.assertEqual(payload_info.dst, dst_sw_if_index) - self.logger.debug("Got packet on port %s: src=%u (id=%u)" % - (pg_if.name, payload_info.src, packet_index)) + self.logger.debug( + "Got packet on port %s: src=%u (id=%u)" + % (pg_if.name, payload_info.src, packet_index) + ) next_info = self.get_next_packet_info_for_interface2( - payload_info.src, dst_sw_if_index, - last_info[payload_info.src]) + payload_info.src, dst_sw_if_index, last_info[payload_info.src] + ) last_info[payload_info.src] = next_info self.assertTrue(next_info is not None) self.assertEqual(packet_index, next_info.index) @@ -265,11 +275,13 @@ class TestL2xcMultiInst(VppTestCase): raise for i in self.pg_interfaces: remaining_packet = self.get_next_packet_info_for_interface2( - i, dst_sw_if_index, last_info[i.sw_if_index]) + i, dst_sw_if_index, last_info[i.sw_if_index] + ) self.assertTrue( remaining_packet is None, - "Port %u: Packet expected from source %u didn't arrive" % - (dst_sw_if_index, i.sw_if_index)) + "Port %u: Packet expected from source %u didn't arrive" + % (dst_sw_if_index, i.sw_if_index), + ) def run_verify_test(self): """ @@ -299,18 +311,17 @@ class TestL2xcMultiInst(VppTestCase): # Verify outgoing packet streams per packet-generator interface for pg_if in self.pg_interfaces: if pg_if in self.pg_in_xc: - capture = pg_if.get_capture( - remark="interface is a cross-connect sink") + capture = pg_if.get_capture(remark="interface is a cross-connect sink") self.verify_capture(pg_if, capture) elif pg_if in self.pg_not_in_xc: pg_if.assert_nothing_captured( - remark="interface is not a cross-connect sink") + remark="interface is not a cross-connect sink" + ) else: raise Exception("Unexpected interface: %s" % pg_if.name) def test_l2xc_inst_01(self): - """ L2XC Multi-instance test 1 - create 10 cross-connects - """ + """L2XC Multi-instance test 1 - create 10 cross-connects""" # Config 1 # Create 10 cross-connects self.create_xconnects(10) @@ -319,8 +330,7 @@ class TestL2xcMultiInst(VppTestCase): self.run_verify_test() def test_l2xc_inst_02(self): - """ L2XC Multi-instance test 2 - delete 4 cross-connects - """ + """L2XC Multi-instance test 2 - delete 4 cross-connects""" # Config 2 # Delete 4 cross-connects self.delete_xconnects(4) @@ -329,8 +339,7 @@ class TestL2xcMultiInst(VppTestCase): self.run_verify_test() def test_l2xc_inst_03(self): - """ L2BD Multi-instance 3 - add new 4 cross-connects - """ + """L2BD Multi-instance 3 - add new 4 cross-connects""" # Config 3 # Add new 4 cross-connects self.create_xconnects(4, start=10) @@ -339,8 +348,7 @@ class TestL2xcMultiInst(VppTestCase): self.run_verify_test() def test_l2xc_inst_04(self): - """ L2XC Multi-instance test 4 - delete 10 cross-connects - """ + """L2XC Multi-instance test 4 - delete 10 cross-connects""" # Config 4 # Delete 10 cross-connects self.delete_xconnects(10, start=4) @@ -349,5 +357,5 @@ class TestL2xcMultiInst(VppTestCase): self.run_verify_test() -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_l3xc.py b/test/test_l3xc.py index 2bcb6d5ae23..66eb242ff52 100644 --- a/test/test_l3xc.py +++ b/test/test_l3xc.py @@ -28,8 +28,7 @@ def find_l3xc(test, sw_if_index, dump_sw_if_index=None): class VppL3xc(VppObject): - - def __init__(self, test, intf, paths, is_ip6=False): + def __init__(self, test, intf, paths, is_ip6=False): self._test = test self.intf = intf self.is_ip6 = is_ip6 @@ -41,27 +40,26 @@ class VppL3xc(VppObject): def add_vpp_config(self): self._test.vapi.l3xc_update( l3xc={ - 'is_ip6': self.is_ip6, - 'sw_if_index': self.intf.sw_if_index, - 'n_paths': len(self.paths), - 'paths': self.encoded_paths - }) + "is_ip6": self.is_ip6, + "sw_if_index": self.intf.sw_if_index, + "n_paths": len(self.paths), + "paths": self.encoded_paths, + } + ) self._test.registry.register(self, self._test.logger) def remove_vpp_config(self): - self._test.vapi.l3xc_del( - is_ip6=self.is_ip6, - sw_if_index=self.intf.sw_if_index) + self._test.vapi.l3xc_del(is_ip6=self.is_ip6, sw_if_index=self.intf.sw_if_index) def query_vpp_config(self): return find_l3xc(self._test, self.intf.sw_if_index) def object_id(self): - return ("l3xc-%d" % self.intf.sw_if_index) + return "l3xc-%d" % self.intf.sw_if_index class TestL3xc(VppTestCase): - """ L3XC Test Case """ + """L3XC Test Case""" @classmethod def setUpClass(cls): @@ -91,25 +89,27 @@ class TestL3xc(VppTestCase): super(TestL3xc, self).tearDown() def test_l3xc4(self): - """ IPv4 X-Connect """ + """IPv4 X-Connect""" # # x-connect pg0 to pg1 and pg2 to pg3->5 # - l3xc_1 = VppL3xc(self, self.pg0, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index)]) + l3xc_1 = VppL3xc( + self, self.pg0, [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)] + ) l3xc_1.add_vpp_config() - l3xc_2 = VppL3xc(self, self.pg2, - [VppRoutePath(self.pg3.remote_ip4, - self.pg3.sw_if_index), - VppRoutePath(self.pg4.remote_ip4, - self.pg4.sw_if_index), - VppRoutePath(self.pg5.remote_ip4, - self.pg5.sw_if_index)]) + l3xc_2 = VppL3xc( + self, + self.pg2, + [ + VppRoutePath(self.pg3.remote_ip4, self.pg3.sw_if_index), + VppRoutePath(self.pg4.remote_ip4, self.pg4.sw_if_index), + VppRoutePath(self.pg5.remote_ip4, self.pg5.sw_if_index), + ], + ) l3xc_2.add_vpp_config() - self.assertTrue(find_l3xc(self, self.pg2.sw_if_index, 0xffffffff)) + self.assertTrue(find_l3xc(self, self.pg2.sw_if_index, 0xFFFFFFFF)) self.logger.info(self.vapi.cli("sh l3xc")) @@ -117,26 +117,29 @@ class TestL3xc(VppTestCase): # fire in packets. If it's forwarded then the L3XC was successful, # since default routing will drop it # - p_1 = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src="1.1.1.1", dst="1.1.1.2") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p_1 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src="1.1.1.1", dst="1.1.1.2") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) # self.send_and_expect(self.pg0, p_1*NUM_PKTS, self.pg1) p_2 = [] for ii in range(NUM_PKTS): - p_2.append(Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src="1.1.1.1", dst="1.1.1.2") / - UDP(sport=1000 + ii, dport=1234) / - Raw(b'\xa5' * 100)) - self.send_and_expect_load_balancing(self.pg2, p_2, - [self.pg3, self.pg4, self.pg5]) + p_2.append( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src="1.1.1.1", dst="1.1.1.2") + / UDP(sport=1000 + ii, dport=1234) + / Raw(b"\xa5" * 100) + ) + self.send_and_expect_load_balancing( + self.pg2, p_2, [self.pg3, self.pg4, self.pg5] + ) l3xc_2.remove_vpp_config() self.send_and_assert_no_replies(self.pg2, p_2) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_lacp.py b/test/test_lacp.py index b5f2dae2cd3..016e8de4d61 100644 --- a/test/test_lacp.py +++ b/test/test_lacp.py @@ -12,20 +12,18 @@ from vpp_bond_interface import VppBondInterface from vpp_papi import VppEnum, MACAddress bond_mac = "02:02:02:02:02:02" -lacp_dst_mac = '01:80:c2:00:00:02' +lacp_dst_mac = "01:80:c2:00:00:02" LACP_COLLECTION_AND_DISTRIBUTION_STATE = 63 class TestMarker(VppTestCase): - """LACP Marker Protocol Test Case - - """ + """LACP Marker Protocol Test Case""" @classmethod def setUpClass(cls): super().setUpClass() # Test variables - cls.pkts_per_burst = 257 # Number of packets per burst + cls.pkts_per_burst = 257 # Number of packets per burst # create 3 pg interfaces cls.create_pg_interfaces(range(1)) @@ -50,7 +48,7 @@ class TestMarker(VppTestCase): self.logger.info(self.vapi.ppcli("show interface")) def test_marker_request(self): - """ Marker Request test """ + """Marker Request test""" # topology # @@ -63,22 +61,21 @@ class TestMarker(VppTestCase): # +-+ +-+ socket1 = VppSocketFilename( - self, - socket_id=1, - socket_filename="%s/memif.sock1" % self.tempdir) + self, socket_id=1, socket_filename="%s/memif.sock1" % self.tempdir + ) socket1.add_vpp_config() socket11 = VppSocketFilename( - self, - socket_id=2, - socket_filename="%s/memif.sock1" % self.tempdir) + self, socket_id=2, socket_filename="%s/memif.sock1" % self.tempdir + ) socket11.add_vpp_config() memif1 = VppMemif( self, role=VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_MASTER, mode=VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET, - socket_id=1) + socket_id=1, + ) memif1.add_vpp_config() memif1.admin_up() @@ -86,7 +83,8 @@ class TestMarker(VppTestCase): self, role=VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_SLAVE, mode=VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET, - socket_id=2) + socket_id=2, + ) memif11.add_vpp_config() memif11.admin_up() @@ -94,14 +92,15 @@ class TestMarker(VppTestCase): self, mode=VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP, use_custom_mac=1, - mac_address=bond_mac) + mac_address=bond_mac, + ) bond0.add_vpp_config() bond0.admin_up() bond1 = VppBondInterface( - self, - mode=VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP) + self, mode=VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP + ) bond1.add_vpp_config() bond1.admin_up() @@ -113,26 +112,28 @@ class TestMarker(VppTestCase): self.assertEqual(memif11.wait_for_link_up(10), True) # verify memif1 in bond0 - intfs = self.vapi.sw_member_interface_dump( - sw_if_index=bond0.sw_if_index) + intfs = self.vapi.sw_member_interface_dump(sw_if_index=bond0.sw_if_index) for intf in intfs: self.assertEqual(intf.sw_if_index, memif1.sw_if_index) # verify memif11 in bond1 - intfs = self.vapi.sw_member_interface_dump( - sw_if_index=bond1.sw_if_index) + intfs = self.vapi.sw_member_interface_dump(sw_if_index=bond1.sw_if_index) for intf in intfs: self.assertEqual(intf.sw_if_index, memif11.sw_if_index) self.vapi.ppcli("trace add memif-input 100") # create marker request - marker = (Ether(src=bond_mac, dst=lacp_dst_mac) / - SlowProtocol() / - MarkerProtocol(marker_type=1, - requester_port=1, - requester_system=bond_mac, - requester_transaction_id=1)) + marker = ( + Ether(src=bond_mac, dst=lacp_dst_mac) + / SlowProtocol() + / MarkerProtocol( + marker_type=1, + requester_port=1, + requester_system=bond_mac, + requester_transaction_id=1, + ) + ) bond1.add_member_vpp_bond_interface(sw_if_index=self.pg0.sw_if_index) self.pg0.add_stream(marker) @@ -147,9 +148,7 @@ class TestMarker(VppTestCase): class TestLACP(VppTestCase): - """LACP Test Case - - """ + """LACP Test Case""" @classmethod def setUpClass(cls): @@ -173,12 +172,11 @@ class TestLACP(VppTestCase): intfs = self.vapi.sw_interface_lacp_dump() all_good = 1 for intf in intfs: - if ((intf.actor_state != - LACP_COLLECTION_AND_DISTRIBUTION_STATE) or - (intf.partner_state != - LACP_COLLECTION_AND_DISTRIBUTION_STATE)): + if (intf.actor_state != LACP_COLLECTION_AND_DISTRIBUTION_STATE) or ( + intf.partner_state != LACP_COLLECTION_AND_DISTRIBUTION_STATE + ): all_good = 0 - if (all_good == 1): + if all_good == 1: return 1 self.sleep(step) timeout -= step @@ -187,20 +185,18 @@ class TestLACP(VppTestCase): def wait_for_member_detach(self, bond, timeout, count, step=1): while 1: - intfs = self.vapi.sw_bond_interface_dump( - sw_if_index=bond.sw_if_index) + intfs = self.vapi.sw_bond_interface_dump(sw_if_index=bond.sw_if_index) for intf in intfs: - if ((intf.members == count) and - (intf.active_members == count)): + if (intf.members == count) and (intf.active_members == count): return 1 else: self.sleep(1) timeout -= step - if (timeouut <= 0): + if timeouut <= 0: return 0 def test_lacp_connect(self): - """ LACP protocol connect test """ + """LACP protocol connect test""" # topology # @@ -213,34 +209,31 @@ class TestLACP(VppTestCase): # +-+ +-+ socket1 = VppSocketFilename( - self, - socket_id=1, - socket_filename="%s/memif.sock1" % self.tempdir) + self, socket_id=1, socket_filename="%s/memif.sock1" % self.tempdir + ) socket1.add_vpp_config() socket11 = VppSocketFilename( - self, - socket_id=2, - socket_filename="%s/memif.sock1" % self.tempdir) + self, socket_id=2, socket_filename="%s/memif.sock1" % self.tempdir + ) socket11.add_vpp_config() socket2 = VppSocketFilename( - self, - socket_id=3, - socket_filename="%s/memif.sock2" % self.tempdir) + self, socket_id=3, socket_filename="%s/memif.sock2" % self.tempdir + ) socket2.add_vpp_config() socket22 = VppSocketFilename( - self, - socket_id=4, - socket_filename="%s/memif.sock2" % self.tempdir) + self, socket_id=4, socket_filename="%s/memif.sock2" % self.tempdir + ) socket22.add_vpp_config() memif1 = VppMemif( self, role=VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_MASTER, mode=VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET, - socket_id=1) + socket_id=1, + ) memif1.add_vpp_config() memif1.admin_up() @@ -248,7 +241,8 @@ class TestLACP(VppTestCase): self, role=VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_SLAVE, mode=VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET, - socket_id=2) + socket_id=2, + ) memif11.add_vpp_config() memif11.admin_up() @@ -256,7 +250,8 @@ class TestLACP(VppTestCase): self, role=VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_MASTER, mode=VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET, - socket_id=3) + socket_id=3, + ) memif2.add_vpp_config() memif2.admin_up() @@ -264,7 +259,8 @@ class TestLACP(VppTestCase): self, role=VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_SLAVE, mode=VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET, - socket_id=4) + socket_id=4, + ) memif12.add_vpp_config() memif12.admin_up() @@ -273,14 +269,15 @@ class TestLACP(VppTestCase): self, mode=VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP, use_custom_mac=1, - mac_address=bond_mac) + mac_address=bond_mac, + ) bond0.add_vpp_config() bond0.admin_up() bond1 = VppBondInterface( - self, - mode=VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP) + self, mode=VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP + ) bond1.add_vpp_config() bond1.admin_up() @@ -299,18 +296,14 @@ class TestLACP(VppTestCase): self.assertEqual(memif12.wait_for_link_up(10), True) # verify memif1 and memif2 in bond0 - intfs = self.vapi.sw_member_interface_dump( - sw_if_index=bond0.sw_if_index) + intfs = self.vapi.sw_member_interface_dump(sw_if_index=bond0.sw_if_index) for intf in intfs: - self.assertIn( - intf.sw_if_index, (memif1.sw_if_index, memif2.sw_if_index)) + self.assertIn(intf.sw_if_index, (memif1.sw_if_index, memif2.sw_if_index)) # verify memif11 and memif12 in bond1 - intfs = self.vapi.sw_member_interface_dump( - sw_if_index=bond1.sw_if_index) + intfs = self.vapi.sw_member_interface_dump(sw_if_index=bond1.sw_if_index) for intf in intfs: - self.assertIn( - intf.sw_if_index, (memif11.sw_if_index, memif12.sw_if_index)) + self.assertIn(intf.sw_if_index, (memif11.sw_if_index, memif12.sw_if_index)) self.assertEqual(intf.is_long_timeout, 0) self.assertEqual(intf.is_passive, 0) @@ -319,17 +312,14 @@ class TestLACP(VppTestCase): intfs = self.vapi.sw_interface_lacp_dump() for intf in intfs: - self.assertEqual( - intf.actor_state, LACP_COLLECTION_AND_DISTRIBUTION_STATE) - self.assertEqual( - intf.partner_state, LACP_COLLECTION_AND_DISTRIBUTION_STATE) + self.assertEqual(intf.actor_state, LACP_COLLECTION_AND_DISTRIBUTION_STATE) + self.assertEqual(intf.partner_state, LACP_COLLECTION_AND_DISTRIBUTION_STATE) intfs = self.vapi.sw_bond_interface_dump(sw_if_index=0xFFFFFFFF) for intf in intfs: self.assertEqual(intf.members, 2) self.assertEqual(intf.active_members, 2) - self.assertEqual( - intf.mode, VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP) + self.assertEqual(intf.mode, VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP) self.logger.info(self.vapi.ppcli("show lacp")) self.logger.info(self.vapi.ppcli("show lacp details")) @@ -338,20 +328,17 @@ class TestLACP(VppTestCase): bond0.detach_vpp_bond_interface(sw_if_index=memif1.sw_if_index) self.wait_for_member_detach(bond0, timeout=10, count=1) - intfs = self.vapi.sw_bond_interface_dump( - sw_if_index=bond0.sw_if_index) + intfs = self.vapi.sw_bond_interface_dump(sw_if_index=bond0.sw_if_index) for intf in intfs: self.assertEqual(intf.members, 1) self.assertEqual(intf.active_members, 1) - self.assertEqual( - intf.mode, VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP) + self.assertEqual(intf.mode, VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP) # detach member memif2 bond0.detach_vpp_bond_interface(sw_if_index=memif2.sw_if_index) self.wait_for_member_detach(bond0, timeout=10, count=0) - intfs = self.vapi.sw_bond_interface_dump( - sw_if_index=bond0.sw_if_index) + intfs = self.vapi.sw_bond_interface_dump(sw_if_index=bond0.sw_if_index) for intf in intfs: self.assertEqual(intf.members, 0) self.assertEqual(intf.active_members, 0) @@ -360,5 +347,5 @@ class TestLACP(VppTestCase): bond1.remove_vpp_config() -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_lb.py b/test/test_lb.py index fafb87b62d9..dca9ea3f7ef 100644 --- a/test/test_lb.py +++ b/test/test_lb.py @@ -32,7 +32,7 @@ from vpp_ip import INVALID_INDEX class TestLB(VppTestCase): - """ Load Balancer Test Case """ + """Load Balancer Test Case""" @classmethod def setUpClass(cls): @@ -53,18 +53,23 @@ class TestLB(VppTestCase): i.resolve_arp() i.resolve_ndp() - dst4 = VppIpRoute(cls, "10.0.0.0", 24, - [VppRoutePath(cls.pg1.remote_ip4, - INVALID_INDEX)], - register=False) + dst4 = VppIpRoute( + cls, + "10.0.0.0", + 24, + [VppRoutePath(cls.pg1.remote_ip4, INVALID_INDEX)], + register=False, + ) dst4.add_vpp_config() - dst6 = VppIpRoute(cls, "2002::", 16, - [VppRoutePath(cls.pg1.remote_ip6, - INVALID_INDEX)], - register=False) + dst6 = VppIpRoute( + cls, + "2002::", + 16, + [VppRoutePath(cls.pg1.remote_ip6, INVALID_INDEX)], + register=False, + ) dst6.add_vpp_config() - cls.vapi.lb_conf(ip4_src_address="39.40.41.42", - ip6_src_address="2004::1") + cls.vapi.lb_conf(ip4_src_address="39.40.41.42", ip6_src_address="2004::1") except Exception: super(TestLB, cls).tearDownClass() raise @@ -80,13 +85,15 @@ class TestLB(VppTestCase): self.logger.info(self.vapi.cli("show lb vip verbose")) def getIPv4Flow(self, id): - return (IP(dst="90.0.%u.%u" % (id / 255, id % 255), - src="40.0.%u.%u" % (id / 255, id % 255)) / - UDP(sport=10000 + id, dport=20000)) + return IP( + dst="90.0.%u.%u" % (id / 255, id % 255), + src="40.0.%u.%u" % (id / 255, id % 255), + ) / UDP(sport=10000 + id, dport=20000) def getIPv6Flow(self, id): - return (IPv6(dst="2001::%u" % (id), src="fd00:f00d:ffff::%u" % (id)) / - UDP(sport=10000 + id, dport=20000)) + return IPv6(dst="2001::%u" % (id), src="fd00:f00d:ffff::%u" % (id)) / UDP( + sport=10000 + id, dport=20000 + ) def generatePackets(self, src_if, isv4): self.reset_packet_infos() @@ -95,9 +102,9 @@ class TestLB(VppTestCase): info = self.create_packet_info(src_if, self.pg1) payload = self.info_to_payload(info) ip = self.getIPv4Flow(pktid) if isv4 else self.getIPv6Flow(pktid) - packet = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - ip / - Raw(payload)) + packet = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) / ip / Raw(payload) + ) self.extend_packet(packet, 128) info.data = packet.copy() pkts.append(packet) @@ -112,8 +119,9 @@ class TestLB(VppTestCase): payload_info = self.payload_to_info(inner[Raw]) self.info = self.packet_infos[payload_info.index] self.assertEqual(payload_info.src, self.pg0.sw_if_index) - self.assertEqual(scapy.compat.raw(inner), - scapy.compat.raw(self.info.data[IPver])) + self.assertEqual( + scapy.compat.raw(inner), scapy.compat.raw(self.info.data[IPver]) + ) def checkCapture(self, encap, isv4): self.pg0.assert_nothing_captured() @@ -125,7 +133,7 @@ class TestLB(VppTestCase): try: asid = 0 gre = None - if (encap == 'gre4'): + if encap == "gre4": ip = p[IP] asid = int(ip.dst.split(".")[3]) self.assertEqual(ip.version, 4) @@ -136,7 +144,7 @@ class TestLB(VppTestCase): self.assertEqual(len(ip.options), 0) gre = p[GRE] self.checkInner(gre, isv4) - elif (encap == 'gre6'): + elif encap == "gre6": ip = p[IPv6] asid = ip.dst.split(":") asid = asid[len(asid) - 1] @@ -147,26 +155,26 @@ class TestLB(VppTestCase): self.assertEqual(ip.src, "2004::1") self.assertEqual( socket.inet_pton(socket.AF_INET6, ip.dst), - socket.inet_pton(socket.AF_INET6, "2002::%u" % asid) + socket.inet_pton(socket.AF_INET6, "2002::%u" % asid), ) self.assertEqual(ip.nh, 47) # self.assertEqual(len(ip.options), 0) gre = GRE(scapy.compat.raw(p[IPv6].payload)) self.checkInner(gre, isv4) - elif (encap == 'l3dsr'): + elif encap == "l3dsr": ip = p[IP] asid = int(ip.dst.split(".")[3]) self.assertEqual(ip.version, 4) self.assertEqual(ip.flags, 0) self.assertEqual(ip.dst, "10.0.0.%u" % asid) - self.assertEqual(ip.tos, 0x1c) + self.assertEqual(ip.tos, 0x1C) self.assertEqual(len(ip.options), 0) self.assert_ip_checksum_valid(p) if ip.proto == IP_PROTOS.tcp: self.assert_tcp_checksum_valid(p) elif ip.proto == IP_PROTOS.udp: self.assert_udp_checksum_valid(p) - elif (encap == 'nat4'): + elif encap == "nat4": ip = p[IP] asid = int(ip.dst.split(".")[3]) self.assertEqual(ip.version, 4) @@ -176,7 +184,7 @@ class TestLB(VppTestCase): self.assertEqual(len(ip.options), 0) udp = p[UDP] self.assertEqual(udp.dport, 3307) - elif (encap == 'nat6'): + elif encap == "nat6": ip = p[IPv6] asid = ip.dst.split(":") asid = asid[len(asid) - 1] @@ -186,7 +194,7 @@ class TestLB(VppTestCase): self.assertEqual(ip.fl, 0) self.assertEqual( socket.inet_pton(socket.AF_INET6, ip.dst), - socket.inet_pton(socket.AF_INET6, "2002::%u" % asid) + socket.inet_pton(socket.AF_INET6, "2002::%u" % asid), ) self.assertEqual(ip.nh, 17) self.assertGreaterEqual(ip.hlim, 63) @@ -202,301 +210,268 @@ class TestLB(VppTestCase): for asid in self.ass: if load[asid] < int(len(self.packets) / (len(self.ass) * 2)): self.logger.error( - "ASS is not balanced: load[%d] = %d" % (asid, load[asid])) + "ASS is not balanced: load[%d] = %d" % (asid, load[asid]) + ) raise Exception("Load Balancer algorithm is biased") def test_lb_ip4_gre4(self): - """ Load Balancer IP4 GRE4 on vip case """ + """Load Balancer IP4 GRE4 on vip case""" try: - self.vapi.cli( - "lb vip 90.0.0.0/8 encap gre4") + self.vapi.cli("lb vip 90.0.0.0/8 encap gre4") for asid in self.ass: - self.vapi.cli( - "lb as 90.0.0.0/8 10.0.0.%u" - % (asid)) + self.vapi.cli("lb as 90.0.0.0/8 10.0.0.%u" % (asid)) self.pg0.add_stream(self.generatePackets(self.pg0, isv4=True)) self.pg_enable_capture(self.pg_interfaces) self.pg_start() - self.checkCapture(encap='gre4', isv4=True) + self.checkCapture(encap="gre4", isv4=True) finally: for asid in self.ass: - self.vapi.cli( - "lb as 90.0.0.0/8 10.0.0.%u del" - % (asid)) - self.vapi.cli( - "lb vip 90.0.0.0/8 encap gre4 del") + self.vapi.cli("lb as 90.0.0.0/8 10.0.0.%u del" % (asid)) + self.vapi.cli("lb vip 90.0.0.0/8 encap gre4 del") self.vapi.cli("test lb flowtable flush") def test_lb_ip6_gre4(self): - """ Load Balancer IP6 GRE4 on vip case """ + """Load Balancer IP6 GRE4 on vip case""" try: - self.vapi.cli( - "lb vip 2001::/16 encap gre4") + self.vapi.cli("lb vip 2001::/16 encap gre4") for asid in self.ass: - self.vapi.cli( - "lb as 2001::/16 10.0.0.%u" - % (asid)) + self.vapi.cli("lb as 2001::/16 10.0.0.%u" % (asid)) self.pg0.add_stream(self.generatePackets(self.pg0, isv4=False)) self.pg_enable_capture(self.pg_interfaces) self.pg_start() - self.checkCapture(encap='gre4', isv4=False) + self.checkCapture(encap="gre4", isv4=False) finally: for asid in self.ass: - self.vapi.cli( - "lb as 2001::/16 10.0.0.%u del" - % (asid)) - self.vapi.cli( - "lb vip 2001::/16 encap gre4 del") + self.vapi.cli("lb as 2001::/16 10.0.0.%u del" % (asid)) + self.vapi.cli("lb vip 2001::/16 encap gre4 del") self.vapi.cli("test lb flowtable flush") def test_lb_ip4_gre6(self): - """ Load Balancer IP4 GRE6 on vip case """ + """Load Balancer IP4 GRE6 on vip case""" try: - self.vapi.cli( - "lb vip 90.0.0.0/8 encap gre6") + self.vapi.cli("lb vip 90.0.0.0/8 encap gre6") for asid in self.ass: - self.vapi.cli( - "lb as 90.0.0.0/8 2002::%u" - % (asid)) + self.vapi.cli("lb as 90.0.0.0/8 2002::%u" % (asid)) self.pg0.add_stream(self.generatePackets(self.pg0, isv4=True)) self.pg_enable_capture(self.pg_interfaces) self.pg_start() - self.checkCapture(encap='gre6', isv4=True) + self.checkCapture(encap="gre6", isv4=True) finally: for asid in self.ass: - self.vapi.cli( - "lb as 90.0.0.0/8 2002::%u del" - % (asid)) - self.vapi.cli( - "lb vip 90.0.0.0/8 encap gre6 del") + self.vapi.cli("lb as 90.0.0.0/8 2002::%u del" % (asid)) + self.vapi.cli("lb vip 90.0.0.0/8 encap gre6 del") self.vapi.cli("test lb flowtable flush") def test_lb_ip6_gre6(self): - """ Load Balancer IP6 GRE6 on vip case """ + """Load Balancer IP6 GRE6 on vip case""" try: - self.vapi.cli( - "lb vip 2001::/16 encap gre6") + self.vapi.cli("lb vip 2001::/16 encap gre6") for asid in self.ass: - self.vapi.cli( - "lb as 2001::/16 2002::%u" - % (asid)) + self.vapi.cli("lb as 2001::/16 2002::%u" % (asid)) self.pg0.add_stream(self.generatePackets(self.pg0, isv4=False)) self.pg_enable_capture(self.pg_interfaces) self.pg_start() - self.checkCapture(encap='gre6', isv4=False) + self.checkCapture(encap="gre6", isv4=False) finally: for asid in self.ass: - self.vapi.cli( - "lb as 2001::/16 2002::%u del" - % (asid)) - self.vapi.cli( - "lb vip 2001::/16 encap gre6 del") + self.vapi.cli("lb as 2001::/16 2002::%u del" % (asid)) + self.vapi.cli("lb vip 2001::/16 encap gre6 del") self.vapi.cli("test lb flowtable flush") def test_lb_ip4_gre4_port(self): - """ Load Balancer IP4 GRE4 on per-port-vip case """ + """Load Balancer IP4 GRE4 on per-port-vip case""" try: - self.vapi.cli( - "lb vip 90.0.0.0/8 protocol udp port 20000 encap gre4") + self.vapi.cli("lb vip 90.0.0.0/8 protocol udp port 20000 encap gre4") for asid in self.ass: self.vapi.cli( - "lb as 90.0.0.0/8 protocol udp port 20000 10.0.0.%u" - % (asid)) + "lb as 90.0.0.0/8 protocol udp port 20000 10.0.0.%u" % (asid) + ) self.pg0.add_stream(self.generatePackets(self.pg0, isv4=True)) self.pg_enable_capture(self.pg_interfaces) self.pg_start() - self.checkCapture(encap='gre4', isv4=True) + self.checkCapture(encap="gre4", isv4=True) finally: for asid in self.ass: self.vapi.cli( - "lb as 90.0.0.0/8 protocol udp port 20000 10.0.0.%u del" - % (asid)) - self.vapi.cli( - "lb vip 90.0.0.0/8 protocol udp port 20000 encap gre4 del") + "lb as 90.0.0.0/8 protocol udp port 20000 10.0.0.%u del" % (asid) + ) + self.vapi.cli("lb vip 90.0.0.0/8 protocol udp port 20000 encap gre4 del") self.vapi.cli("test lb flowtable flush") def test_lb_ip6_gre4_port(self): - """ Load Balancer IP6 GRE4 on per-port-vip case """ + """Load Balancer IP6 GRE4 on per-port-vip case""" try: - self.vapi.cli( - "lb vip 2001::/16 protocol udp port 20000 encap gre4") + self.vapi.cli("lb vip 2001::/16 protocol udp port 20000 encap gre4") for asid in self.ass: self.vapi.cli( - "lb as 2001::/16 protocol udp port 20000 10.0.0.%u" - % (asid)) + "lb as 2001::/16 protocol udp port 20000 10.0.0.%u" % (asid) + ) self.pg0.add_stream(self.generatePackets(self.pg0, isv4=False)) self.pg_enable_capture(self.pg_interfaces) self.pg_start() - self.checkCapture(encap='gre4', isv4=False) + self.checkCapture(encap="gre4", isv4=False) finally: for asid in self.ass: self.vapi.cli( - "lb as 2001::/16 protocol udp port 20000 10.0.0.%u del" - % (asid)) - self.vapi.cli( - "lb vip 2001::/16 protocol udp port 20000 encap gre4 del") + "lb as 2001::/16 protocol udp port 20000 10.0.0.%u del" % (asid) + ) + self.vapi.cli("lb vip 2001::/16 protocol udp port 20000 encap gre4 del") self.vapi.cli("test lb flowtable flush") def test_lb_ip4_gre6_port(self): - """ Load Balancer IP4 GRE6 on per-port-vip case """ + """Load Balancer IP4 GRE6 on per-port-vip case""" try: - self.vapi.cli( - "lb vip 90.0.0.0/8 protocol udp port 20000 encap gre6") + self.vapi.cli("lb vip 90.0.0.0/8 protocol udp port 20000 encap gre6") for asid in self.ass: self.vapi.cli( - "lb as 90.0.0.0/8 protocol udp port 20000 2002::%u" - % (asid)) + "lb as 90.0.0.0/8 protocol udp port 20000 2002::%u" % (asid) + ) self.pg0.add_stream(self.generatePackets(self.pg0, isv4=True)) self.pg_enable_capture(self.pg_interfaces) self.pg_start() - self.checkCapture(encap='gre6', isv4=True) + self.checkCapture(encap="gre6", isv4=True) finally: for asid in self.ass: self.vapi.cli( - "lb as 90.0.0.0/8 protocol udp port 20000 2002::%u del" - % (asid)) - self.vapi.cli( - "lb vip 90.0.0.0/8 protocol udp port 20000 encap gre6 del") + "lb as 90.0.0.0/8 protocol udp port 20000 2002::%u del" % (asid) + ) + self.vapi.cli("lb vip 90.0.0.0/8 protocol udp port 20000 encap gre6 del") self.vapi.cli("test lb flowtable flush") def test_lb_ip6_gre6_port(self): - """ Load Balancer IP6 GRE6 on per-port-vip case """ + """Load Balancer IP6 GRE6 on per-port-vip case""" try: - self.vapi.cli( - "lb vip 2001::/16 protocol udp port 20000 encap gre6") + self.vapi.cli("lb vip 2001::/16 protocol udp port 20000 encap gre6") for asid in self.ass: self.vapi.cli( - "lb as 2001::/16 protocol udp port 20000 2002::%u" - % (asid)) + "lb as 2001::/16 protocol udp port 20000 2002::%u" % (asid) + ) self.pg0.add_stream(self.generatePackets(self.pg0, isv4=False)) self.pg_enable_capture(self.pg_interfaces) self.pg_start() - self.checkCapture(encap='gre6', isv4=False) + self.checkCapture(encap="gre6", isv4=False) finally: for asid in self.ass: self.vapi.cli( - "lb as 2001::/16 protocol udp port 20000 2002::%u del" - % (asid)) - self.vapi.cli( - "lb vip 2001::/16 protocol udp port 20000 encap gre6 del") + "lb as 2001::/16 protocol udp port 20000 2002::%u del" % (asid) + ) + self.vapi.cli("lb vip 2001::/16 protocol udp port 20000 encap gre6 del") self.vapi.cli("test lb flowtable flush") def test_lb_ip4_l3dsr(self): - """ Load Balancer IP4 L3DSR on vip case """ + """Load Balancer IP4 L3DSR on vip case""" try: - self.vapi.cli( - "lb vip 90.0.0.0/8 encap l3dsr dscp 7") + self.vapi.cli("lb vip 90.0.0.0/8 encap l3dsr dscp 7") for asid in self.ass: - self.vapi.cli( - "lb as 90.0.0.0/8 10.0.0.%u" - % (asid)) + self.vapi.cli("lb as 90.0.0.0/8 10.0.0.%u" % (asid)) self.pg0.add_stream(self.generatePackets(self.pg0, isv4=True)) self.pg_enable_capture(self.pg_interfaces) self.pg_start() - self.checkCapture(encap='l3dsr', isv4=True) + self.checkCapture(encap="l3dsr", isv4=True) finally: for asid in self.ass: - self.vapi.cli( - "lb as 90.0.0.0/8 10.0.0.%u del" - % (asid)) - self.vapi.cli( - "lb vip 90.0.0.0/8 encap l3dsr" - " dscp 7 del") + self.vapi.cli("lb as 90.0.0.0/8 10.0.0.%u del" % (asid)) + self.vapi.cli("lb vip 90.0.0.0/8 encap l3dsr dscp 7 del") self.vapi.cli("test lb flowtable flush") def test_lb_ip4_l3dsr_port(self): - """ Load Balancer IP4 L3DSR on per-port-vip case """ + """Load Balancer IP4 L3DSR on per-port-vip case""" try: self.vapi.cli( - "lb vip 90.0.0.0/8 protocol udp port 20000 encap l3dsr dscp 7") + "lb vip 90.0.0.0/8 protocol udp port 20000 encap l3dsr dscp 7" + ) for asid in self.ass: self.vapi.cli( - "lb as 90.0.0.0/8 protocol udp port 20000 10.0.0.%u" - % (asid)) + "lb as 90.0.0.0/8 protocol udp port 20000 10.0.0.%u" % (asid) + ) self.pg0.add_stream(self.generatePackets(self.pg0, isv4=True)) self.pg_enable_capture(self.pg_interfaces) self.pg_start() - self.checkCapture(encap='l3dsr', isv4=True) + self.checkCapture(encap="l3dsr", isv4=True) finally: for asid in self.ass: self.vapi.cli( - "lb as 90.0.0.0/8 protocol udp port 20000 10.0.0.%u del" - % (asid)) + "lb as 90.0.0.0/8 protocol udp port 20000 10.0.0.%u del" % (asid) + ) self.vapi.cli( - "lb vip 90.0.0.0/8 protocol udp port 20000 encap l3dsr" - " dscp 7 del") + "lb vip 90.0.0.0/8 protocol udp port 20000 encap l3dsr dscp 7 del" + ) self.vapi.cli("test lb flowtable flush") def test_lb_ip4_nat4_port(self): - """ Load Balancer IP4 NAT4 on per-port-vip case """ + """Load Balancer IP4 NAT4 on per-port-vip case""" try: self.vapi.cli( "lb vip 90.0.0.0/8 protocol udp port 20000 encap nat4" - " type clusterip target_port 3307") + " type clusterip target_port 3307" + ) for asid in self.ass: self.vapi.cli( - "lb as 90.0.0.0/8 protocol udp port 20000 10.0.0.%u" - % (asid)) + "lb as 90.0.0.0/8 protocol udp port 20000 10.0.0.%u" % (asid) + ) self.pg0.add_stream(self.generatePackets(self.pg0, isv4=True)) self.pg_enable_capture(self.pg_interfaces) self.pg_start() - self.checkCapture(encap='nat4', isv4=True) + self.checkCapture(encap="nat4", isv4=True) finally: for asid in self.ass: self.vapi.cli( - "lb as 90.0.0.0/8 protocol udp port 20000 10.0.0.%u del" - % (asid)) + "lb as 90.0.0.0/8 protocol udp port 20000 10.0.0.%u del" % (asid) + ) self.vapi.cli( "lb vip 90.0.0.0/8 protocol udp port 20000 encap nat4" - " type clusterip target_port 3307 del") + " type clusterip target_port 3307 del" + ) self.vapi.cli("test lb flowtable flush") def test_lb_ip6_nat6_port(self): - """ Load Balancer IP6 NAT6 on per-port-vip case """ + """Load Balancer IP6 NAT6 on per-port-vip case""" try: self.vapi.cli( "lb vip 2001::/16 protocol udp port 20000 encap nat6" - " type clusterip target_port 3307") + " type clusterip target_port 3307" + ) for asid in self.ass: self.vapi.cli( - "lb as 2001::/16 protocol udp port 20000 2002::%u" - % (asid)) + "lb as 2001::/16 protocol udp port 20000 2002::%u" % (asid) + ) self.pg0.add_stream(self.generatePackets(self.pg0, isv4=False)) self.pg_enable_capture(self.pg_interfaces) self.pg_start() - self.checkCapture(encap='nat6', isv4=False) + self.checkCapture(encap="nat6", isv4=False) finally: for asid in self.ass: self.vapi.cli( - "lb as 2001::/16 protocol udp port 20000 2002::%u del" - % (asid)) + "lb as 2001::/16 protocol udp port 20000 2002::%u del" % (asid) + ) self.vapi.cli( "lb vip 2001::/16 protocol udp port 20000 encap nat6" - " type clusterip target_port 3307 del") + " type clusterip target_port 3307 del" + ) self.vapi.cli("test lb flowtable flush") diff --git a/test/test_lb_api.py b/test/test_lb_api.py index 70d41d432a7..048f7bf44e8 100644 --- a/test/test_lb_api.py +++ b/test/test_lb_api.py @@ -19,7 +19,7 @@ DEFAULT_VIP = "lb_vip_details(_0=978, context=12, vip=vl_api_lb_ip_addr_t(pfx=IP class TestLbEmptyApi(framework.VppTestCase): - """TestLbEmptyApi """ + """TestLbEmptyApi""" def test_lb_empty_vip_dump(self): @@ -27,18 +27,18 @@ class TestLbEmptyApi(framework.VppTestCase): # lb initializes with a default VIP rv = self.vapi.lb_vip_dump() # print(rv) - self.assertEqual(rv, [], 'Expected: [] Received: %r.' % rv) + self.assertEqual(rv, [], "Expected: [] Received: %r." % rv) def test_lb_empty_as_dump(self): # no records should return [] rv = self.vapi.lb_as_dump() # print(rv) - self.assertEqual(rv, [], 'Expected: [] Received: %r.' % rv) + self.assertEqual(rv, [], "Expected: [] Received: %r." % rv) class TestLbApi(framework.VppTestCase): - """TestLbApi """ + """TestLbApi""" def test_lb_vip_dump(self): # add some vips @@ -49,14 +49,17 @@ class TestLbApi(framework.VppTestCase): self.vapi.cli("lb vip 2001::/16 encap gre6") rv = self.vapi.lb_vip_dump() # print(rv) - self.assertEqual(str(rv[-1].vip.pfx), "2001::/16", - 'Expected: 2001::/16 Received: %r.' % rv[-1].vip.pfx) + self.assertEqual( + str(rv[-1].vip.pfx), + "2001::/16", + "Expected: 2001::/16 Received: %r." % rv[-1].vip.pfx, + ) self.vapi.cli("lb vip 2001::/16 del") class TestLbAsApi(framework.VppTestCase): - """TestLbAsApi """ + """TestLbAsApi""" def test_lb_as_dump(self): # add some vips @@ -70,7 +73,13 @@ class TestLbAsApi(framework.VppTestCase): # print(rv) rv = self.vapi.lb_as_dump() # print(rv) - self.assertEqual(str(rv[0].vip.pfx), "2001::/16", - 'Expected: "2001::/16" Received: %r.' % rv[0].vip.pfx) - self.assertEqual(str(rv[0].app_srv), "2000::1", - 'Expected: "2000::1" Received: %r.' % rv[0].app_srv) + self.assertEqual( + str(rv[0].vip.pfx), + "2001::/16", + 'Expected: "2001::/16" Received: %r.' % rv[0].vip.pfx, + ) + self.assertEqual( + str(rv[0].app_srv), + "2000::1", + 'Expected: "2000::1" Received: %r.' % rv[0].app_srv, + ) diff --git a/test/test_linux_cp.py b/test/test_linux_cp.py index b683954e1da..2d7669b717a 100644 --- a/test/test_linux_cp.py +++ b/test/test_linux_cp.py @@ -10,10 +10,20 @@ from util import reassemble4 from vpp_object import VppObject from framework import VppTestCase, VppTestRunner from vpp_ipip_tun_interface import VppIpIpTunInterface -from template_ipsec import TemplateIpsec, IpsecTun4Tests, \ - IpsecTun4, mk_scapy_crypt_key, config_tun_params -from template_ipsec import TemplateIpsec, IpsecTun4Tests, \ - IpsecTun4, mk_scapy_crypt_key, config_tun_params +from template_ipsec import ( + TemplateIpsec, + IpsecTun4Tests, + IpsecTun4, + mk_scapy_crypt_key, + config_tun_params, +) +from template_ipsec import ( + TemplateIpsec, + IpsecTun4Tests, + IpsecTun4, + mk_scapy_crypt_key, + config_tun_params, +) from test_ipsec_tun_if_esp import TemplateIpsecItf4 from vpp_ipsec import VppIpsecSA, VppIpsecTunProtect, VppIpsecInterface @@ -25,39 +35,43 @@ class VppLcpPair(VppObject): self.host = host def add_vpp_config(self): - self._test.vapi.cli("test lcp add phy %s host %s" % - (self.phy, self.host)) + self._test.vapi.cli("test lcp add phy %s host %s" % (self.phy, self.host)) self._test.registry.register(self, self._test.logger) return self def remove_vpp_config(self): - self._test.vapi.cli("test lcp del phy %s host %s" % - (self.phy, self.host)) + self._test.vapi.cli("test lcp del phy %s host %s" % (self.phy, self.host)) def object_id(self): - return "lcp:%d:%d" % (self.phy.sw_if_index, - self.host.sw_if_index) + return "lcp:%d:%d" % (self.phy.sw_if_index, self.host.sw_if_index) def query_vpp_config(self): - pairs = list(self._test.vapi.vpp.details_iter( - self._test.vapi.lcp_itf_pair_get)) + pairs = list(self._test.vapi.vpp.details_iter(self._test.vapi.lcp_itf_pair_get)) for p in pairs: - if p.phy_sw_if_index == self.phy.sw_if_index and \ - p.host_sw_if_index == self.host.sw_if_index: + if ( + p.phy_sw_if_index == self.phy.sw_if_index + and p.host_sw_if_index == self.host.sw_if_index + ): return True return False class TestLinuxCP(VppTestCase): - """ Linux Control Plane """ - - extra_vpp_plugin_config = ["plugin", - "linux_cp_plugin.so", - "{", "enable", "}", - "plugin", - "linux_cp_unittest_plugin.so", - "{", "enable", "}"] + """Linux Control Plane""" + + extra_vpp_plugin_config = [ + "plugin", + "linux_cp_plugin.so", + "{", + "enable", + "}", + "plugin", + "linux_cp_unittest_plugin.so", + "{", + "enable", + "}", + ] @classmethod def setUpClass(cls): @@ -86,7 +100,7 @@ class TestLinuxCP(VppTestCase): super(TestLinuxCP, self).tearDown() def test_linux_cp_tap(self): - """ Linux CP TAP """ + """Linux CP TAP""" # # Setup @@ -117,12 +131,12 @@ class TestLinuxCP(VppTestCase): # hosts to phys for phy, host in zip(phys, hosts): for j in range(N_HOSTS): - p = (Ether(src=phy.local_mac, - dst=phy.remote_hosts[j].mac) / - IP(src=phy.local_ip4, - dst=phy.remote_hosts[j].ip4) / - UDP(sport=1234, dport=1234) / - Raw()) + p = ( + Ether(src=phy.local_mac, dst=phy.remote_hosts[j].mac) + / IP(src=phy.local_ip4, dst=phy.remote_hosts[j].ip4) + / UDP(sport=1234, dport=1234) + / Raw() + ) rxs = self.send_and_expect(host, [p], phy) @@ -131,13 +145,13 @@ class TestLinuxCP(VppTestCase): self.assertEqual(p.show2(True), rx.show2(True)) # ARPs x-connect to phy - p = (Ether(dst="ff:ff:ff:ff:ff:ff", - src=phy.remote_hosts[j].mac) / - ARP(op="who-has", - hwdst=phy.remote_hosts[j].mac, - hwsrc=phy.local_mac, - psrc=phy.local_ip4, - pdst=phy.remote_hosts[j].ip4)) + p = Ether(dst="ff:ff:ff:ff:ff:ff", src=phy.remote_hosts[j].mac) / ARP( + op="who-has", + hwdst=phy.remote_hosts[j].mac, + hwsrc=phy.local_mac, + psrc=phy.local_ip4, + pdst=phy.remote_hosts[j].ip4, + ) rxs = self.send_and_expect(host, [p], phy) @@ -148,12 +162,12 @@ class TestLinuxCP(VppTestCase): # phy to host for phy, host in zip(phys, hosts): for j in range(N_HOSTS): - p = (Ether(dst=phy.local_mac, - src=phy.remote_hosts[j].mac) / - IP(dst=phy.local_ip4, - src=phy.remote_hosts[j].ip4) / - UDP(sport=1234, dport=1234) / - Raw()) + p = ( + Ether(dst=phy.local_mac, src=phy.remote_hosts[j].mac) + / IP(dst=phy.local_ip4, src=phy.remote_hosts[j].ip4) + / UDP(sport=1234, dport=1234) + / Raw() + ) rxs = self.send_and_expect(phy, [p], host) @@ -162,13 +176,13 @@ class TestLinuxCP(VppTestCase): self.assertEqual(p.show2(True), rx.show2(True)) # ARPs rx'd on the phy are sent to the host - p = (Ether(dst="ff:ff:ff:ff:ff:ff", - src=phy.remote_hosts[j].mac) / - ARP(op="is-at", - hwsrc=phy.remote_hosts[j].mac, - hwdst=phy.local_mac, - pdst=phy.local_ip4, - psrc=phy.remote_hosts[j].ip4)) + p = Ether(dst="ff:ff:ff:ff:ff:ff", src=phy.remote_hosts[j].mac) / ARP( + op="is-at", + hwsrc=phy.remote_hosts[j].mac, + hwdst=phy.local_mac, + pdst=phy.local_ip4, + psrc=phy.remote_hosts[j].ip4, + ) rxs = self.send_and_expect(phy, [p], host) @@ -181,7 +195,7 @@ class TestLinuxCP(VppTestCase): phy.unconfig_ip4() def test_linux_cp_tun(self): - """ Linux CP TUN """ + """Linux CP TUN""" # # Setup @@ -198,15 +212,11 @@ class TestLinuxCP(VppTestCase): phy.resolve_ndp() tun4 = VppIpIpTunInterface( - self, - phy, - phy.local_ip4, - phy.remote_ip4).add_vpp_config() + self, phy, phy.local_ip4, phy.remote_ip4 + ).add_vpp_config() tun6 = VppIpIpTunInterface( - self, - phy, - phy.local_ip6, - phy.remote_ip6).add_vpp_config() + self, phy, phy.local_ip6, phy.remote_ip6 + ).add_vpp_config() tuns = [tun4, tun6] tun4.admin_up() @@ -226,9 +236,7 @@ class TestLinuxCP(VppTestCase): # # host to phy for v4 - p = (IP(src=tun4.local_ip4, dst="2.2.2.2") / - UDP(sport=1234, dport=1234) / - Raw()) + p = IP(src=tun4.local_ip4, dst="2.2.2.2") / UDP(sport=1234, dport=1234) / Raw() rxs = self.send_and_expect(self.pg4, p * N_PKTS, phy) @@ -242,9 +250,7 @@ class TestLinuxCP(VppTestCase): self.assertEqual(inner.dst, "2.2.2.2") # host to phy for v6 - p = (IPv6(src=tun6.local_ip6, dst="2::2") / - UDP(sport=1234, dport=1234) / - Raw()) + p = IPv6(src=tun6.local_ip6, dst="2::2") / UDP(sport=1234, dport=1234) / Raw() rxs = self.send_and_expect(self.pg5, p * N_PKTS, phy) @@ -257,11 +263,13 @@ class TestLinuxCP(VppTestCase): self.assertEqual(inner.dst, "2::2") # phy to host v4 - p = (Ether(dst=phy.local_mac, src=phy.remote_mac) / - IP(dst=phy.local_ip4, src=phy.remote_ip4) / - IP(dst=tun4.local_ip4, src=tun4.remote_ip4) / - UDP(sport=1234, dport=1234) / - Raw()) + p = ( + Ether(dst=phy.local_mac, src=phy.remote_mac) + / IP(dst=phy.local_ip4, src=phy.remote_ip4) + / IP(dst=tun4.local_ip4, src=tun4.remote_ip4) + / UDP(sport=1234, dport=1234) + / Raw() + ) rxs = self.send_and_expect(phy, p * N_PKTS, self.pg4) for rx in rxs: @@ -270,11 +278,13 @@ class TestLinuxCP(VppTestCase): self.assertEqual(rx[IP].src, tun4.remote_ip4) # phy to host v6 - p = (Ether(dst=phy.local_mac, src=phy.remote_mac) / - IPv6(dst=phy.local_ip6, src=phy.remote_ip6) / - IPv6(dst=tun6.local_ip6, src=tun6.remote_ip6) / - UDP(sport=1234, dport=1234) / - Raw()) + p = ( + Ether(dst=phy.local_mac, src=phy.remote_mac) + / IPv6(dst=phy.local_ip6, src=phy.remote_ip6) + / IPv6(dst=tun6.local_ip6, src=tun6.remote_ip6) + / UDP(sport=1234, dport=1234) + / Raw() + ) rxs = self.send_and_expect(phy, p * N_PKTS, self.pg5) for rx in rxs: @@ -290,17 +300,21 @@ class TestLinuxCP(VppTestCase): tun6.unconfig_ip6() -class TestLinuxCPIpsec(TemplateIpsec, - TemplateIpsecItf4, - IpsecTun4): - """ IPsec Interface IPv4 """ +class TestLinuxCPIpsec(TemplateIpsec, TemplateIpsecItf4, IpsecTun4): + """IPsec Interface IPv4""" - extra_vpp_plugin_config = ["plugin", - "linux_cp_plugin.so", - "{", "enable", "}", - "plugin", - "linux_cp_unittest_plugin.so", - "{", "enable", "}"] + extra_vpp_plugin_config = [ + "plugin", + "linux_cp_plugin.so", + "{", + "enable", + "}", + "plugin", + "linux_cp_unittest_plugin.so", + "{", + "enable", + "}", + ] def setUp(self): super(TestLinuxCPIpsec, self).setUp() @@ -347,16 +361,19 @@ class TestLinuxCPIpsec(TemplateIpsec, self.assert_equal(rx[IP].dst, p.tun_if.local_ip4) self.assert_packet_checksums_valid(rx) - def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, - payload_size=54): - return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) / - sa.encrypt(IP(src=src, dst=dst) / - UDP(sport=1111, dport=2222) / - Raw(b'X' * payload_size)) - for i in range(count)] + def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=54): + return [ + Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) + / sa.encrypt( + IP(src=src, dst=dst) + / UDP(sport=1111, dport=2222) + / Raw(b"X" * payload_size) + ) + for i in range(count) + ] def test_linux_cp_ipsec4_tun(self): - """ Linux CP Ipsec TUN """ + """Linux CP Ipsec TUN""" # # Setup @@ -370,9 +387,7 @@ class TestLinuxCPIpsec(TemplateIpsec, p = self.ipv4_params self.config_network(p) - self.config_sa_tun(p, - self.pg0.local_ip4, - self.pg0.remote_ip4) + self.config_sa_tun(p, self.pg0.local_ip4, self.pg0.remote_ip4) self.config_protect(p) pair = VppLcpPair(self, p.tun_if, self.host).add_vpp_config() @@ -386,19 +401,24 @@ class TestLinuxCPIpsec(TemplateIpsec, # # host to phy for v4 - pkt = (IP(src=p.tun_if.local_ip4, - dst=p.tun_if.remote_ip4) / - UDP(sport=1234, dport=1234) / - Raw()) + pkt = ( + IP(src=p.tun_if.local_ip4, dst=p.tun_if.remote_ip4) + / UDP(sport=1234, dport=1234) + / Raw() + ) rxs = self.send_and_expect(self.host, pkt * N_PKTS, self.tun_if) self.verify_encrypted(p, p.vpp_tun_sa, rxs) # phy to host for v4 - pkts = self.gen_encrypt_pkts(p, p.scapy_tun_sa, self.tun_if, - src=p.tun_if.remote_ip4, - dst=p.tun_if.local_ip4, - count=N_PKTS) + pkts = self.gen_encrypt_pkts( + p, + p.scapy_tun_sa, + self.tun_if, + src=p.tun_if.remote_ip4, + dst=p.tun_if.local_ip4, + count=N_PKTS, + ) rxs = self.send_and_expect(self.tun_if, pkts, self.host) self.verify_decrypted(p, rxs) @@ -409,5 +429,5 @@ class TestLinuxCPIpsec(TemplateIpsec, self.unconfig_network(p) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_lisp.py b/test/test_lisp.py index 0a6e7525159..5ff9de13d24 100644 --- a/test/test_lisp.py +++ b/test/test_lisp.py @@ -9,8 +9,14 @@ from scapy.layers.inet import IP, UDP, Ether from scapy.layers.inet6 import IPv6 from framework import VppTestCase, VppTestRunner -from lisp import VppLocalMapping, VppLispAdjacency, VppLispLocator, \ - VppLispLocatorSet, VppRemoteMapping, LispRemoteLocator +from lisp import ( + VppLocalMapping, + VppLispAdjacency, + VppLispLocator, + VppLispLocatorSet, + VppRemoteMapping, + LispRemoteLocator, +) from util import ppp # From py_lispnetworking.lisp.py: # GNU General Public License v2.0 @@ -24,6 +30,8 @@ class LISP_GPE_Header(Packet): ByteField("next_proto", 0), IntField("iid", 0), ] + + bind_layers(UDP, LISP_GPE_Header, dport=4341) bind_layers(UDP, LISP_GPE_Header, sport=4341) bind_layers(LISP_GPE_Header, IP, next_proto=1) @@ -34,8 +42,8 @@ bind_layers(LISP_GPE_Header, Ether, next_proto=3) class ForeignAddressFactory(object): count = 0 prefix_len = 24 - net_template = '10.10.10.{}' - net = net_template.format(0) + '/' + str(prefix_len) + net_template = "10.10.10.{}" + net = net_template.format(0) + "/" + str(prefix_len) def get_ip4(self): if self.count > 255: @@ -46,13 +54,16 @@ class ForeignAddressFactory(object): class Driver(metaclass=abc.ABCMeta): - config_order = ['locator-sets', - 'locators', - 'local-mappings', - 'remote-mappings', - 'adjacencies'] + config_order = [ + "locator-sets", + "locators", + "local-mappings", + "remote-mappings", + "adjacencies", + ] """ Basic class for data driven testing """ + def __init__(self, test, test_cases): self._test_cases = test_cases self._test = test @@ -65,26 +76,29 @@ class Driver(metaclass=abc.ABCMeta): def test(self): return self._test - def create_packet(self, src_if, dst_if, deid, payload=''): + def create_packet(self, src_if, dst_if, deid, payload=""): """ Create IPv4 packet param: src_if param: dst_if """ - packet = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - IP(src=src_if.remote_ip4, dst=deid) / - Raw(payload)) + packet = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / IP(src=src_if.remote_ip4, dst=deid) + / Raw(payload) + ) return packet @abc.abstractmethod def run(self): - """ testing procedure """ + """testing procedure""" pass class SimpleDriver(Driver): - """ Implements simple test procedure """ + """Implements simple test procedure""" + def __init__(self, test, test_cases): super(SimpleDriver, self).__init__(test, test_cases) @@ -96,27 +110,27 @@ class SimpleDriver(Driver): :param dst_loc: destination locator address :param capture: list of captured packets """ - self.test.assertEqual(len(capture), 1, "Unexpected number of " - "packets! Expected 1 but {} received" - .format(len(capture))) + self.test.assertEqual( + len(capture), + 1, + "Unexpected number of " + "packets! Expected 1 but {} received".format(len(capture)), + ) packet = capture[0] try: ip_hdr = packet[IP] # assert the values match self.test.assertEqual(ip_hdr.src, src_loc, "IP source address") - self.test.assertEqual(ip_hdr.dst, dst_loc, - "IP destination address") + self.test.assertEqual(ip_hdr.dst, dst_loc, "IP destination address") gpe_hdr = packet[LISP_GPE_Header] - self.test.assertEqual(gpe_hdr.next_proto, 1, - "next_proto is not ipv4!") + self.test.assertEqual(gpe_hdr.next_proto, 1, "next_proto is not ipv4!") ih = gpe_hdr[IP] - self.test.assertEqual(ih.src, self.test.pg0.remote_ip4, - "unexpected source EID!") - self.test.assertEqual(ih.dst, self.test.deid_ip4, - "unexpected dest EID!") + self.test.assertEqual( + ih.src, self.test.pg0.remote_ip4, "unexpected source EID!" + ) + self.test.assertEqual(ih.dst, self.test.deid_ip4, "unexpected dest EID!") except: - self.test.logger.error(ppp("Unexpected or invalid packet:", - packet)) + self.test.logger.error(ppp("Unexpected or invalid packet:", packet)) raise def configure_tc(self, tc): @@ -125,26 +139,26 @@ class SimpleDriver(Driver): vpp_object.add_vpp_config() def run(self, dest): - """ Send traffic for each test case and verify that it - is encapsulated """ + """Send traffic for each test case and verify that it + is encapsulated""" for tc in enumerate(self.test_cases): - self.test.logger.info('Running {}'.format(tc[1]['name'])) + self.test.logger.info("Running {}".format(tc[1]["name"])) self.configure_tc(tc[1]) - packet = self.create_packet(self.test.pg0, self.test.pg1, dest, - 'data') + packet = self.create_packet(self.test.pg0, self.test.pg1, dest, "data") self.test.pg0.add_stream(packet) self.test.pg0.enable_capture() self.test.pg1.enable_capture() self.test.pg_start() capture = self.test.pg1.get_capture(1) - self.verify_capture(self.test.pg1.local_ip4, - self.test.pg1.remote_ip4, capture) + self.verify_capture( + self.test.pg1.local_ip4, self.test.pg1.remote_ip4, capture + ) self.test.pg0.assert_nothing_captured() class TestLisp(VppTestCase): - """ Basic LISP test """ + """Basic LISP test""" @classmethod def setUpClass(cls): @@ -169,26 +183,23 @@ class TestLisp(VppTestCase): self.deid_ip4_net = self.faf.net self.deid_ip4 = self.faf.get_ip4() - self.seid_ip4 = '{!s}/{!s}'.format(self.pg0.local_ip4, 32) + self.seid_ip4 = "{!s}/{!s}".format(self.pg0.local_ip4, 32) self.rloc_ip4 = self.pg1.remote_ip4 test_cases = [ { - 'name': 'basic ip4 over ip4', - 'locator-sets': [VppLispLocatorSet(self, 'ls-4o4')], - 'locators': [ - VppLispLocator(self, self.pg1.sw_if_index, 'ls-4o4') - ], - 'local-mappings': [ - VppLocalMapping(self, self.seid_ip4, 'ls-4o4') + "name": "basic ip4 over ip4", + "locator-sets": [VppLispLocatorSet(self, "ls-4o4")], + "locators": [VppLispLocator(self, self.pg1.sw_if_index, "ls-4o4")], + "local-mappings": [VppLocalMapping(self, self.seid_ip4, "ls-4o4")], + "remote-mappings": [ + VppRemoteMapping( + self, self.deid_ip4_net, [LispRemoteLocator(self.rloc_ip4)] + ) ], - 'remote-mappings': [ - VppRemoteMapping(self, self.deid_ip4_net, - [LispRemoteLocator(self.rloc_ip4)]) - ], - 'adjacencies': [ + "adjacencies": [ VppLispAdjacency(self, self.seid_ip4, self.deid_ip4_net) - ] + ], } ] self.test_driver = SimpleDriver(self, test_cases) @@ -196,7 +207,7 @@ class TestLisp(VppTestCase): class TestLispUT(VppTestCase): - """ Lisp UT """ + """Lisp UT""" @classmethod def setUpClass(cls): @@ -207,7 +218,7 @@ class TestLispUT(VppTestCase): super(TestLispUT, cls).tearDownClass() def test_fib(self): - """ LISP Unit Tests """ + """LISP Unit Tests""" error = self.vapi.cli("test lisp cp") if error: @@ -215,5 +226,5 @@ class TestLispUT(VppTestCase): self.assertNotIn("Failed", error) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_mactime.py b/test/test_mactime.py index 1eaeeb53a9d..a9f981e6261 100644 --- a/test/test_mactime.py +++ b/test/test_mactime.py @@ -8,7 +8,7 @@ from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath class TestMactime(VppTestCase): - """ Mactime Unit Test Cases """ + """Mactime Unit Test Cases""" @classmethod def setUpClass(cls): @@ -25,137 +25,140 @@ class TestMactime(VppTestCase): super(TestMactime, self).tearDown() def test_mactime_range_unittest(self): - """ Time Range Test """ + """Time Range Test""" error = self.vapi.cli("test time-range") if error: self.logger.critical(error) - self.assertNotIn('FAILED', error) + self.assertNotIn("FAILED", error) @unittest.skipUnless(config.gcov, "part of code coverage tests") def test_mactime_unittest(self): - """ Mactime Plugin Code Coverage Test """ - cmds = ["loopback create", - "mactime enable-disable disable", - "mactime enable-disable loop0", - "mactime enable-disable loop0 disable", - "mactime enable-disable sw_if_index 9999", - "bin mactime_enable_disable loop0", - "bin mactime_enable_disable loop0 disable", - "bin mactime_enable_disable sw_if_index 1", - "set interface state loop0 up", - "clear mactime", - "set ip neighbor loop0 192.168.1.1 00:d0:2d:5e:86:85", - "bin mactime_add_del_range name sallow " - "mac 00:d0:2d:5e:86:85 allow-static del", - "bin mactime_add_del_range name sallow " - "mac 00:d0:2d:5e:86:85 allow-static", - "bin mactime_add_del_range name sallow " - "mac 00:d0:2d:5e:86:85 allow-static del", - "bin mactime_add_del_range name sallow " - "mac 00:d0:2d:5e:86:85 allow-static", - "bin mactime_add_del_range name sblock " - "mac 01:00:5e:7f:ff:fa drop-static", - "bin mactime_add_del_range name ddrop " - "mac c8:bc:c8:5a:ba:f3 drop-range Sun - Sat " - "00:00 - 23:59", - "bin mactime_add_del_range name dallow " - "mac c8:bc:c8:5a:ba:f4 allow-range Sun - Sat " - "00:00 - 23:59", - "bin mactime_add_del_range name multi " - "mac c8:bc:c8:f0:f0:f0 allow-range Sun - Mon " - "00:00 - 23:59 Tue - Sat 00:00 - 23:59", - "bin mactime_add_del_range bogus", - "bin mactime_add_del_range mac 01:00:5e:7f:f0:f0 allow-static", - "bin mactime_add_del_range " - "name tooloooooooooooooooooooooooooooooooooooooooooooooooo" - "nnnnnnnnnnnnnnnnnnnnnnnnnnnng mac 00:00:de:ad:be:ef " - "allow-static", - "packet-generator new {\n" - " name allow\n" - " limit 15\n" - " size 128-128\n" - " interface loop0\n" - " node ethernet-input\n" - " data {\n" - " IP6: 00:d0:2d:5e:86:85 -> 00:0d:ea:d0:00:00\n" - " ICMP: db00::1 -> db00::2\n" - " incrementing 30\n" - " }\n", - "}\n", - "packet-generator new {\n" - " name deny\n" - " limit 15\n" - " size 128-128\n" - " interface loop0\n" - " node ethernet-input\n" - " data {\n" - " IP6: 01:00:5e:7f:ff:fa -> 00:0d:ea:d0:00:00\n" - " ICMP: db00::1 -> db00::2\n" - " incrementing 30\n" - " }\n", - "}\n", - "packet-generator new {\n" - " name ddrop\n" - " limit 15\n" - " size 128-128\n" - " interface loop0\n" - " node ethernet-input\n" - " data {\n" - " IP6: c8:bc:c8:5a:ba:f3 -> 00:0d:ea:d0:00:00\n" - " ICMP: db00::1 -> db00::2\n" - " incrementing 30\n" - " }\n", - "}\n", - "packet-generator new {\n" - " name dallow\n" - " limit 15\n" - " size 128-128\n" - " interface loop0\n" - " node ethernet-input\n" - " data {\n" - " IP6: c8:bc:c8:5a:ba:f4 -> 00:0d:ea:d0:00:00\n" - " ICMP: db00::1 -> db00::2\n" - " incrementing 30\n" - " }\n" - "}\n" - "packet-generator new {\n" - " name makeentry\n" - " limit 15\n" - " size 128-128\n" - " interface loop0\n" - " node ethernet-input\n" - " data {\n" - " IP6: c8:bc:c8:5a:b0:0b -> 00:0d:ea:d0:00:00\n" - " ICMP: db00::1 -> db00::2\n" - " incrementing 30\n" - " }\n" - "}\n" - "packet-generator new {\n" - " name tx\n" - " limit 15\n" - " size 128-128\n" - " interface local0\n" - " tx-interface loop0\n" - " node loop0-output\n" - " data {\n" - " hex 0x01005e7ffffa000dead000000800" - "0102030405060708090a0b0c0d0e0f0102030405\n" - " }\n" - "}\n" - "trace add pg-input 2", - "pa en", - "show mactime verbose 2", - "show trace", - "show error"] + """Mactime Plugin Code Coverage Test""" + cmds = [ + "loopback create", + "mactime enable-disable disable", + "mactime enable-disable loop0", + "mactime enable-disable loop0 disable", + "mactime enable-disable sw_if_index 9999", + "bin mactime_enable_disable loop0", + "bin mactime_enable_disable loop0 disable", + "bin mactime_enable_disable sw_if_index 1", + "set interface state loop0 up", + "clear mactime", + "set ip neighbor loop0 192.168.1.1 00:d0:2d:5e:86:85", + "bin mactime_add_del_range name sallow " + "mac 00:d0:2d:5e:86:85 allow-static del", + "bin mactime_add_del_range name sallow " + "mac 00:d0:2d:5e:86:85 allow-static", + "bin mactime_add_del_range name sallow " + "mac 00:d0:2d:5e:86:85 allow-static del", + "bin mactime_add_del_range name sallow " + "mac 00:d0:2d:5e:86:85 allow-static", + "bin mactime_add_del_range name sblock " + "mac 01:00:5e:7f:ff:fa drop-static", + "bin mactime_add_del_range name ddrop " + "mac c8:bc:c8:5a:ba:f3 drop-range Sun - Sat " + "00:00 - 23:59", + "bin mactime_add_del_range name dallow " + "mac c8:bc:c8:5a:ba:f4 allow-range Sun - Sat " + "00:00 - 23:59", + "bin mactime_add_del_range name multi " + "mac c8:bc:c8:f0:f0:f0 allow-range Sun - Mon " + "00:00 - 23:59 Tue - Sat 00:00 - 23:59", + "bin mactime_add_del_range bogus", + "bin mactime_add_del_range mac 01:00:5e:7f:f0:f0 allow-static", + "bin mactime_add_del_range " + "name tooloooooooooooooooooooooooooooooooooooooooooooooooo" + "nnnnnnnnnnnnnnnnnnnnnnnnnnnng mac 00:00:de:ad:be:ef " + "allow-static", + "packet-generator new {\n" + " name allow\n" + " limit 15\n" + " size 128-128\n" + " interface loop0\n" + " node ethernet-input\n" + " data {\n" + " IP6: 00:d0:2d:5e:86:85 -> 00:0d:ea:d0:00:00\n" + " ICMP: db00::1 -> db00::2\n" + " incrementing 30\n" + " }\n", + "}\n", + "packet-generator new {\n" + " name deny\n" + " limit 15\n" + " size 128-128\n" + " interface loop0\n" + " node ethernet-input\n" + " data {\n" + " IP6: 01:00:5e:7f:ff:fa -> 00:0d:ea:d0:00:00\n" + " ICMP: db00::1 -> db00::2\n" + " incrementing 30\n" + " }\n", + "}\n", + "packet-generator new {\n" + " name ddrop\n" + " limit 15\n" + " size 128-128\n" + " interface loop0\n" + " node ethernet-input\n" + " data {\n" + " IP6: c8:bc:c8:5a:ba:f3 -> 00:0d:ea:d0:00:00\n" + " ICMP: db00::1 -> db00::2\n" + " incrementing 30\n" + " }\n", + "}\n", + "packet-generator new {\n" + " name dallow\n" + " limit 15\n" + " size 128-128\n" + " interface loop0\n" + " node ethernet-input\n" + " data {\n" + " IP6: c8:bc:c8:5a:ba:f4 -> 00:0d:ea:d0:00:00\n" + " ICMP: db00::1 -> db00::2\n" + " incrementing 30\n" + " }\n" + "}\n" + "packet-generator new {\n" + " name makeentry\n" + " limit 15\n" + " size 128-128\n" + " interface loop0\n" + " node ethernet-input\n" + " data {\n" + " IP6: c8:bc:c8:5a:b0:0b -> 00:0d:ea:d0:00:00\n" + " ICMP: db00::1 -> db00::2\n" + " incrementing 30\n" + " }\n" + "}\n" + "packet-generator new {\n" + " name tx\n" + " limit 15\n" + " size 128-128\n" + " interface local0\n" + " tx-interface loop0\n" + " node loop0-output\n" + " data {\n" + " hex 0x01005e7ffffa000dead000000800" + "0102030405060708090a0b0c0d0e0f0102030405\n" + " }\n" + "}\n" + "trace add pg-input 2", + "pa en", + "show mactime verbose 2", + "show trace", + "show error", + ] for cmd in cmds: r = self.vapi.cli_return_response(cmd) if r.retval != 0: - if hasattr(r, 'reply'): + if hasattr(r, "reply"): self.logger.info(cmd + " FAIL reply " + r.reply) else: self.logger.info(cmd + " FAIL retval " + str(r.retval)) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_map.py b/test/test_map.py index 22fe1e1d20a..16e9607cedc 100644 --- a/test/test_map.py +++ b/test/test_map.py @@ -12,12 +12,17 @@ import scapy.compat from scapy.layers.l2 import Ether from scapy.packet import Raw from scapy.layers.inet import IP, UDP, ICMP, TCP -from scapy.layers.inet6 import IPv6, ICMPv6TimeExceeded, IPv6ExtHdrFragment, \ - ICMPv6EchoRequest, ICMPv6DestUnreach +from scapy.layers.inet6 import ( + IPv6, + ICMPv6TimeExceeded, + IPv6ExtHdrFragment, + ICMPv6EchoRequest, + ICMPv6DestUnreach, +) class TestMAP(VppTestCase): - """ MAP Test Case """ + """MAP Test Case""" @classmethod def setUpClass(cls): @@ -69,27 +74,24 @@ class TestMAP(VppTestCase): self.assertEqual(rx[IPv6].src, ip6_src) self.assertEqual(rx[IPv6].dst, ip6_dst) - def send_and_assert_encapped_one(self, packet, ip6_src, ip6_dst, - dmac=None): + def send_and_assert_encapped_one(self, packet, ip6_src, ip6_dst, dmac=None): return self.send_and_assert_encapped([packet], ip6_src, ip6_dst, dmac) def test_api_map_domain_dump(self): - map_dst = '2001::/64' - map_src = '3000::1/128' - client_pfx = '192.168.0.0/16' - tag = 'MAP-E tag.' - index = self.vapi.map_add_domain(ip4_prefix=client_pfx, - ip6_prefix=map_dst, - ip6_src=map_src, - tag=tag).index + map_dst = "2001::/64" + map_src = "3000::1/128" + client_pfx = "192.168.0.0/16" + tag = "MAP-E tag." + index = self.vapi.map_add_domain( + ip4_prefix=client_pfx, ip6_prefix=map_dst, ip6_src=map_src, tag=tag + ).index rv = self.vapi.map_domain_dump() # restore the state early so as to not impact subsequent tests. # If an assert fails, we will not get the chance to do it at the end. self.vapi.map_del_domain(index=index) - self.assertGreater(len(rv), 0, - "Expected output from 'map_domain_dump'") + self.assertGreater(len(rv), 0, "Expected output from 'map_domain_dump'") # typedefs are returned as ipaddress objects. # wrap results in str() ugh! to avoid the need to call unicode. @@ -97,8 +99,7 @@ class TestMAP(VppTestCase): self.assertEqual(str(rv[0].ip6_prefix), map_dst) self.assertEqual(str(rv[0].ip6_src), map_src) - self.assertEqual(rv[0].tag, tag, - "output produced incorrect tag value.") + self.assertEqual(rv[0].tag, tag, "output produced incorrect tag value.") def create_domains(self, ip4_pfx_str, ip6_pfx_str, ip6_src_str): ip4_pfx = ipaddress.ip_network(ip4_pfx_str) @@ -106,24 +107,25 @@ class TestMAP(VppTestCase): mod = ip4_pfx.num_addresses / 1024 indicies = [] for i in range(ip4_pfx.num_addresses): - rv = self.vapi.map_add_domain(ip6_prefix=ip6_pfx_str, - ip4_prefix=str(ip4_pfx[i]) + "/32", - ip6_src=ip6_src_str) + rv = self.vapi.map_add_domain( + ip6_prefix=ip6_pfx_str, + ip4_prefix=str(ip4_pfx[i]) + "/32", + ip6_src=ip6_src_str, + ) indicies.append(rv.index) return indicies def test_api_map_domains_get(self): # Create a bunch of domains no_domains = 4096 # This must be large enough to ensure VPP suspends - domains = self.create_domains('130.67.0.0/20', '2001::/32', - '2001::1/128') + domains = self.create_domains("130.67.0.0/20", "2001::/32", "2001::1/128") self.assertEqual(len(domains), no_domains) d = [] cursor = 0 # Invalid cursor - rv, details = self.vapi.map_domains_get(cursor=no_domains+10) + rv, details = self.vapi.map_domains_get(cursor=no_domains + 10) self.assertEqual(rv.retval, -7) # Delete a domain in the middle of walk @@ -144,48 +146,53 @@ class TestMAP(VppTestCase): self.vapi.map_del_domain(index=i) def test_map_e_udp(self): - """ MAP-E UDP""" + """MAP-E UDP""" # # Add a route to the MAP-BR # map_br_pfx = "2001::" map_br_pfx_len = 32 - map_route = VppIpRoute(self, - map_br_pfx, - map_br_pfx_len, - [VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index)]) + map_route = VppIpRoute( + self, + map_br_pfx, + map_br_pfx_len, + [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)], + ) map_route.add_vpp_config() # # Add a domain that maps from pg0 to pg1 # - map_dst = '2001::/32' - map_src = '3000::1/128' - client_pfx = '192.168.0.0/16' - map_translated_addr = '2001:0:101:7000:0:c0a8:101:7' - tag = 'MAP-E tag.' - self.vapi.map_add_domain(ip4_prefix=client_pfx, - ip6_prefix=map_dst, - ip6_src=map_src, - ea_bits_len=20, - psid_offset=4, - psid_length=4, - tag=tag) + map_dst = "2001::/32" + map_src = "3000::1/128" + client_pfx = "192.168.0.0/16" + map_translated_addr = "2001:0:101:7000:0:c0a8:101:7" + tag = "MAP-E tag." + self.vapi.map_add_domain( + ip4_prefix=client_pfx, + ip6_prefix=map_dst, + ip6_src=map_src, + ea_bits_len=20, + psid_offset=4, + psid_length=4, + tag=tag, + ) self.vapi.map_param_set_security_check(enable=1, fragments=1) # Enable MAP on interface. - self.vapi.map_if_enable_disable(is_enable=1, - sw_if_index=self.pg0.sw_if_index, - is_translation=0) + self.vapi.map_if_enable_disable( + is_enable=1, sw_if_index=self.pg0.sw_if_index, is_translation=0 + ) # Ensure MAP doesn't steal all packets! - v4 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg0.remote_ip4) / - UDP(sport=20000, dport=10000) / - Raw(b'\xa5' * 100)) + v4 = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.remote_ip4) + / UDP(sport=20000, dport=10000) + / Raw(b"\xa5" * 100) + ) rx = self.send_and_expect(self.pg0, v4 * 4, self.pg0) v4_reply = v4[1] v4_reply.ttl -= 1 @@ -195,20 +202,24 @@ class TestMAP(VppTestCase): # # Fire in a v4 packet that will be encapped to the BR # - v4 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst='192.168.1.1') / - UDP(sport=20000, dport=10000) / - Raw(b'\xa5' * 100)) + v4 = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst="192.168.1.1") + / UDP(sport=20000, dport=10000) + / Raw(b"\xa5" * 100) + ) self.send_and_assert_encapped(v4 * 4, "3000::1", map_translated_addr) # # Verify reordered fragments are able to pass as well # - v4 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(id=1, src=self.pg0.remote_ip4, dst='192.168.1.1') / - UDP(sport=20000, dport=10000) / - Raw(b'\xa5' * 1000)) + v4 = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(id=1, src=self.pg0.remote_ip4, dst="192.168.1.1") + / UDP(sport=20000, dport=10000) + / Raw(b"\xa5" * 1000) + ) frags = fragment_rfc791(v4, 400) frags.reverse() @@ -216,16 +227,18 @@ class TestMAP(VppTestCase): self.send_and_assert_encapped(frags, "3000::1", map_translated_addr) # Enable MAP on interface. - self.vapi.map_if_enable_disable(is_enable=1, - sw_if_index=self.pg1.sw_if_index, - is_translation=0) + self.vapi.map_if_enable_disable( + is_enable=1, sw_if_index=self.pg1.sw_if_index, is_translation=0 + ) # Ensure MAP doesn't steal all packets - v6 = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IPv6(src=self.pg1.remote_ip6, dst=self.pg1.remote_ip6) / - UDP(sport=20000, dport=10000) / - Raw(b'\xa5' * 100)) - rx = self.send_and_expect(self.pg1, v6*1, self.pg1) + v6 = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(src=self.pg1.remote_ip6, dst=self.pg1.remote_ip6) + / UDP(sport=20000, dport=10000) + / Raw(b"\xa5" * 100) + ) + rx = self.send_and_expect(self.pg1, v6 * 1, self.pg1) v6_reply = v6[1] v6_reply.hlim -= 1 for p in rx: @@ -235,11 +248,13 @@ class TestMAP(VppTestCase): # Fire in a V6 encapped packet. # expect a decapped packet on the inside ip4 link # - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IPv6(dst='3000::1', src=map_translated_addr) / - IP(dst=self.pg0.remote_ip4, src='192.168.1.1') / - UDP(sport=10000, dport=20000) / - Raw(b'\xa5' * 100)) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(dst="3000::1", src=map_translated_addr) + / IP(dst=self.pg0.remote_ip4, src="192.168.1.1") + / UDP(sport=10000, dport=20000) + / Raw(b"\xa5" * 100) + ) self.pg1.add_stream(p) @@ -256,15 +271,20 @@ class TestMAP(VppTestCase): # # Verify encapped reordered fragments pass as well # - p = (IP(id=1, dst=self.pg0.remote_ip4, src='192.168.1.1') / - UDP(sport=10000, dport=20000) / - Raw(b'\xa5' * 1500)) + p = ( + IP(id=1, dst=self.pg0.remote_ip4, src="192.168.1.1") + / UDP(sport=10000, dport=20000) + / Raw(b"\xa5" * 1500) + ) frags = fragment_rfc791(p, 400) frags.reverse() - stream = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IPv6(dst='3000::1', src=map_translated_addr) / - x for x in frags) + stream = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(dst="3000::1", src=map_translated_addr) + / x + for x in frags + ) self.pg1.add_stream(stream) @@ -279,15 +299,15 @@ class TestMAP(VppTestCase): self.assertEqual(r[IP].dst, p[IP].dst) # Verify that fragments pass even if ipv6 layer is fragmented - stream = (IPv6(dst='3000::1', src=map_translated_addr) / x - for x in frags) + stream = (IPv6(dst="3000::1", src=map_translated_addr) / x for x in frags) v6_stream = [ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / x for i in range(len(frags)) for x in fragment_rfc8200( - IPv6(dst='3000::1', src=map_translated_addr) / frags[i], - i, 200)] + IPv6(dst="3000::1", src=map_translated_addr) / frags[i], i, 200 + ) + ] self.pg1.add_stream(v6_stream) @@ -306,32 +326,35 @@ class TestMAP(VppTestCase): # self.vapi.ppcli("map params pre-resolve ip6-nh 4001::1") - self.send_and_assert_no_replies(self.pg0, v4, - "resolved via default route") + self.send_and_assert_no_replies(self.pg0, v4, "resolved via default route") # # Add a route to 4001::1. Expect the encapped traffic to be # sent via that routes next-hop # - pre_res_route = VppIpRoute(self, "4001::1", 128, - [VppRoutePath(self.pg1.remote_hosts[2].ip6, - self.pg1.sw_if_index)]) + pre_res_route = VppIpRoute( + self, + "4001::1", + 128, + [VppRoutePath(self.pg1.remote_hosts[2].ip6, self.pg1.sw_if_index)], + ) pre_res_route.add_vpp_config() - self.send_and_assert_encapped_one(v4, "3000::1", - map_translated_addr, - dmac=self.pg1.remote_hosts[2].mac) + self.send_and_assert_encapped_one( + v4, "3000::1", map_translated_addr, dmac=self.pg1.remote_hosts[2].mac + ) # # change the route to the pre-solved next-hop # - pre_res_route.modify([VppRoutePath(self.pg1.remote_hosts[3].ip6, - self.pg1.sw_if_index)]) + pre_res_route.modify( + [VppRoutePath(self.pg1.remote_hosts[3].ip6, self.pg1.sw_if_index)] + ) pre_res_route.add_vpp_config() - self.send_and_assert_encapped_one(v4, "3000::1", - map_translated_addr, - dmac=self.pg1.remote_hosts[3].mac) + self.send_and_assert_encapped_one( + v4, "3000::1", map_translated_addr, dmac=self.pg1.remote_hosts[3].mac + ) # # cleanup. The test infra's object registry will ensure @@ -341,51 +364,56 @@ class TestMAP(VppTestCase): self.vapi.ppcli("map params pre-resolve del ip6-nh 4001::1") def test_map_e_inner_frag(self): - """ MAP-E Inner fragmentation """ + """MAP-E Inner fragmentation""" # # Add a route to the MAP-BR # map_br_pfx = "2001::" map_br_pfx_len = 32 - map_route = VppIpRoute(self, - map_br_pfx, - map_br_pfx_len, - [VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index)]) + map_route = VppIpRoute( + self, + map_br_pfx, + map_br_pfx_len, + [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)], + ) map_route.add_vpp_config() # # Add a domain that maps from pg0 to pg1 # - map_dst = '2001::/32' - map_src = '3000::1/128' - client_pfx = '192.168.0.0/16' - map_translated_addr = '2001:0:101:7000:0:c0a8:101:7' - tag = 'MAP-E tag.' - self.vapi.map_add_domain(ip4_prefix=client_pfx, - ip6_prefix=map_dst, - ip6_src=map_src, - ea_bits_len=20, - psid_offset=4, - psid_length=4, - mtu=1000, - tag=tag) + map_dst = "2001::/32" + map_src = "3000::1/128" + client_pfx = "192.168.0.0/16" + map_translated_addr = "2001:0:101:7000:0:c0a8:101:7" + tag = "MAP-E tag." + self.vapi.map_add_domain( + ip4_prefix=client_pfx, + ip6_prefix=map_dst, + ip6_src=map_src, + ea_bits_len=20, + psid_offset=4, + psid_length=4, + mtu=1000, + tag=tag, + ) # Enable MAP on interface. - self.vapi.map_if_enable_disable(is_enable=1, - sw_if_index=self.pg0.sw_if_index, - is_translation=0) + self.vapi.map_if_enable_disable( + is_enable=1, sw_if_index=self.pg0.sw_if_index, is_translation=0 + ) # Enable inner fragmentation self.vapi.map_param_set_fragmentation(inner=1) - v4 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst='192.168.1.1') / - UDP(sport=20000, dport=10000) / - Raw(b'\xa5' * 1300)) + v4 = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst="192.168.1.1") + / UDP(sport=20000, dport=10000) + / Raw(b"\xa5" * 1300) + ) - self.pg_send(self.pg0, v4*1) + self.pg_send(self.pg0, v4 * 1) rx = self.pg1.get_capture(2) # 1000-sizeof(ip6_header_t) = 960. @@ -397,10 +425,8 @@ class TestMAP(VppTestCase): frags[0].chksum = 0 frags[1].chksum = 0 - v6_reply1 = (IPv6(src='3000::1', dst=map_translated_addr, hlim=63) / - frags[0]) - v6_reply2 = (IPv6(src='3000::1', dst=map_translated_addr, hlim=63) / - frags[1]) + v6_reply1 = IPv6(src="3000::1", dst=map_translated_addr, hlim=63) / frags[0] + v6_reply2 = IPv6(src="3000::1", dst=map_translated_addr, hlim=63) / frags[1] rx[0][1].fl = 0 rx[1][1].fl = 0 rx[0][1][IP].id = 0 @@ -412,45 +438,48 @@ class TestMAP(VppTestCase): self.validate(rx[1][1], v6_reply2) def test_map_e_tcp_mss(self): - """ MAP-E TCP MSS""" + """MAP-E TCP MSS""" # # Add a route to the MAP-BR # map_br_pfx = "2001::" map_br_pfx_len = 32 - map_route = VppIpRoute(self, - map_br_pfx, - map_br_pfx_len, - [VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index)]) + map_route = VppIpRoute( + self, + map_br_pfx, + map_br_pfx_len, + [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)], + ) map_route.add_vpp_config() # # Add a domain that maps from pg0 to pg1 # - map_dst = '2001::/32' - map_src = '3000::1/128' - client_pfx = '192.168.0.0/16' - map_translated_addr = '2001:0:101:5000:0:c0a8:101:5' - tag = 'MAP-E TCP tag.' - self.vapi.map_add_domain(ip4_prefix=client_pfx, - ip6_prefix=map_dst, - ip6_src=map_src, - ea_bits_len=20, - psid_offset=4, - psid_length=4, - tag=tag) + map_dst = "2001::/32" + map_src = "3000::1/128" + client_pfx = "192.168.0.0/16" + map_translated_addr = "2001:0:101:5000:0:c0a8:101:5" + tag = "MAP-E TCP tag." + self.vapi.map_add_domain( + ip4_prefix=client_pfx, + ip6_prefix=map_dst, + ip6_src=map_src, + ea_bits_len=20, + psid_offset=4, + psid_length=4, + tag=tag, + ) # Enable MAP on pg0 interface. - self.vapi.map_if_enable_disable(is_enable=1, - sw_if_index=self.pg0.sw_if_index, - is_translation=0) + self.vapi.map_if_enable_disable( + is_enable=1, sw_if_index=self.pg0.sw_if_index, is_translation=0 + ) # Enable MAP on pg1 interface. - self.vapi.map_if_enable_disable(is_enable=1, - sw_if_index=self.pg1.sw_if_index, - is_translation=0) + self.vapi.map_if_enable_disable( + is_enable=1, sw_if_index=self.pg1.sw_if_index, is_translation=0 + ) # TCP MSS clamping mss_clamp = 1300 @@ -460,9 +489,8 @@ class TestMAP(VppTestCase): # Send a v4 packet that will be encapped. # p_ether = Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) - p_ip4 = IP(src=self.pg0.remote_ip4, dst='192.168.1.1') - p_tcp = TCP(sport=20000, dport=30000, flags="S", - options=[("MSS", 1455)]) + p_ip4 = IP(src=self.pg0.remote_ip4, dst="192.168.1.1") + p_tcp = TCP(sport=20000, dport=30000, flags="S", options=[("MSS", 1455)]) p4 = p_ether / p_ip4 / p_tcp self.pg1.add_stream(p4) @@ -476,8 +504,7 @@ class TestMAP(VppTestCase): self.assertEqual(rx[IP].src, p4[IP].src) self.assertEqual(rx[IP].dst, p4[IP].dst) self.assertEqual(rx[IPv6].src, "3000::1") - self.assertEqual(rx[TCP].options, - TCP(options=[('MSS', mss_clamp)]).options) + self.assertEqual(rx[TCP].options, TCP(options=[("MSS", mss_clamp)]).options) def validate(self, rx, expected): self.assertEqual(rx, expected.__class__(scapy.compat.raw(expected))) @@ -520,173 +547,202 @@ class TestMAP(VppTestCase): self.assertEqual(payload_total, payload_len_expected) def payload(self, len): - return 'x' * len + return "x" * len def test_map_t(self): - """ MAP-T """ + """MAP-T""" # # Add a domain that maps from pg0 to pg1 # - map_dst = '2001:db8::/32' - map_src = '1234:5678:90ab:cdef::/64' - ip4_pfx = '192.168.0.0/24' - tag = 'MAP-T Tag.' - - self.vapi.map_add_domain(ip6_prefix=map_dst, - ip4_prefix=ip4_pfx, - ip6_src=map_src, - ea_bits_len=16, - psid_offset=6, - psid_length=4, - mtu=1500, - tag=tag) + map_dst = "2001:db8::/32" + map_src = "1234:5678:90ab:cdef::/64" + ip4_pfx = "192.168.0.0/24" + tag = "MAP-T Tag." + + self.vapi.map_add_domain( + ip6_prefix=map_dst, + ip4_prefix=ip4_pfx, + ip6_src=map_src, + ea_bits_len=16, + psid_offset=6, + psid_length=4, + mtu=1500, + tag=tag, + ) # Enable MAP-T on interfaces. - self.vapi.map_if_enable_disable(is_enable=1, - sw_if_index=self.pg0.sw_if_index, - is_translation=1) - self.vapi.map_if_enable_disable(is_enable=1, - sw_if_index=self.pg1.sw_if_index, - is_translation=1) + self.vapi.map_if_enable_disable( + is_enable=1, sw_if_index=self.pg0.sw_if_index, is_translation=1 + ) + self.vapi.map_if_enable_disable( + is_enable=1, sw_if_index=self.pg1.sw_if_index, is_translation=1 + ) # Ensure MAP doesn't steal all packets! - v4 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg0.remote_ip4) / - UDP(sport=20000, dport=10000) / - Raw(b'\xa5' * 100)) - rx = self.send_and_expect(self.pg0, v4*1, self.pg0) + v4 = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.remote_ip4) + / UDP(sport=20000, dport=10000) + / Raw(b"\xa5" * 100) + ) + rx = self.send_and_expect(self.pg0, v4 * 1, self.pg0) v4_reply = v4[1] v4_reply.ttl -= 1 for p in rx: self.validate(p[1], v4_reply) # Ensure MAP doesn't steal all packets - v6 = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IPv6(src=self.pg1.remote_ip6, dst=self.pg1.remote_ip6) / - UDP(sport=20000, dport=10000) / - Raw(b'\xa5' * 100)) - rx = self.send_and_expect(self.pg1, v6*1, self.pg1) + v6 = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(src=self.pg1.remote_ip6, dst=self.pg1.remote_ip6) + / UDP(sport=20000, dport=10000) + / Raw(b"\xa5" * 100) + ) + rx = self.send_and_expect(self.pg1, v6 * 1, self.pg1) v6_reply = v6[1] v6_reply.hlim -= 1 for p in rx: self.validate(p[1], v6_reply) - map_route = VppIpRoute(self, - "2001:db8::", - 32, - [VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index, - proto=DpoProto.DPO_PROTO_IP6)]) + map_route = VppIpRoute( + self, + "2001:db8::", + 32, + [ + VppRoutePath( + self.pg1.remote_ip6, + self.pg1.sw_if_index, + proto=DpoProto.DPO_PROTO_IP6, + ) + ], + ) map_route.add_vpp_config() # # Send a v4 packet that will be translated # p_ether = Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) - p_ip4 = IP(src=self.pg0.remote_ip4, dst='192.168.0.1') - payload = TCP(sport=0xabcd, dport=0xabcd) - - p4 = (p_ether / p_ip4 / payload) - p6_translated = (IPv6(src="1234:5678:90ab:cdef:ac:1001:200:0", - dst="2001:db8:1f0::c0a8:1:f") / payload) + p_ip4 = IP(src=self.pg0.remote_ip4, dst="192.168.0.1") + payload = TCP(sport=0xABCD, dport=0xABCD) + + p4 = p_ether / p_ip4 / payload + p6_translated = ( + IPv6(src="1234:5678:90ab:cdef:ac:1001:200:0", dst="2001:db8:1f0::c0a8:1:f") + / payload + ) p6_translated.hlim -= 1 - rx = self.send_and_expect(self.pg0, p4*1, self.pg1) + rx = self.send_and_expect(self.pg0, p4 * 1, self.pg1) for p in rx: self.validate(p[1], p6_translated) # Send back an IPv6 packet that will be "untranslated" p_ether6 = Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) - p_ip6 = IPv6(src='2001:db8:1f0::c0a8:1:f', - dst='1234:5678:90ab:cdef:ac:1001:200:0') - p6 = (p_ether6 / p_ip6 / payload) - p4_translated = (IP(src='192.168.0.1', - dst=self.pg0.remote_ip4) / payload) + p_ip6 = IPv6( + src="2001:db8:1f0::c0a8:1:f", dst="1234:5678:90ab:cdef:ac:1001:200:0" + ) + p6 = p_ether6 / p_ip6 / payload + p4_translated = IP(src="192.168.0.1", dst=self.pg0.remote_ip4) / payload p4_translated.id = 0 p4_translated.ttl -= 1 - rx = self.send_and_expect(self.pg1, p6*1, self.pg0) + rx = self.send_and_expect(self.pg1, p6 * 1, self.pg0) for p in rx: self.validate(p[1], p4_translated) # IPv4 TTL=0 - ip4_ttl_expired = IP(src=self.pg0.remote_ip4, dst='192.168.0.1', ttl=0) - p4 = (p_ether / ip4_ttl_expired / payload) - - icmp4_reply = (IP(id=0, ttl=254, src=self.pg0.local_ip4, - dst=self.pg0.remote_ip4) / - ICMP(type='time-exceeded', - code='ttl-zero-during-transit') / - IP(src=self.pg0.remote_ip4, - dst='192.168.0.1', ttl=0) / payload) - rx = self.send_and_expect(self.pg0, p4*1, self.pg0) + ip4_ttl_expired = IP(src=self.pg0.remote_ip4, dst="192.168.0.1", ttl=0) + p4 = p_ether / ip4_ttl_expired / payload + + icmp4_reply = ( + IP(id=0, ttl=254, src=self.pg0.local_ip4, dst=self.pg0.remote_ip4) + / ICMP(type="time-exceeded", code="ttl-zero-during-transit") + / IP(src=self.pg0.remote_ip4, dst="192.168.0.1", ttl=0) + / payload + ) + rx = self.send_and_expect(self.pg0, p4 * 1, self.pg0) for p in rx: self.validate(p[1], icmp4_reply) # IPv4 TTL=1 - ip4_ttl_expired = IP(src=self.pg0.remote_ip4, dst='192.168.0.1', ttl=1) - p4 = (p_ether / ip4_ttl_expired / payload) - - icmp4_reply = (IP(id=0, ttl=254, src=self.pg0.local_ip4, - dst=self.pg0.remote_ip4) / - ICMP(type='time-exceeded', - code='ttl-zero-during-transit') / - IP(src=self.pg0.remote_ip4, - dst='192.168.0.1', ttl=1) / payload) - rx = self.send_and_expect(self.pg0, p4*1, self.pg0) + ip4_ttl_expired = IP(src=self.pg0.remote_ip4, dst="192.168.0.1", ttl=1) + p4 = p_ether / ip4_ttl_expired / payload + + icmp4_reply = ( + IP(id=0, ttl=254, src=self.pg0.local_ip4, dst=self.pg0.remote_ip4) + / ICMP(type="time-exceeded", code="ttl-zero-during-transit") + / IP(src=self.pg0.remote_ip4, dst="192.168.0.1", ttl=1) + / payload + ) + rx = self.send_and_expect(self.pg0, p4 * 1, self.pg0) for p in rx: self.validate(p[1], icmp4_reply) # IPv6 Hop limit at BR - ip6_hlim_expired = IPv6(hlim=1, src='2001:db8:1ab::c0a8:1:ab', - dst='1234:5678:90ab:cdef:ac:1001:200:0') - p6 = (p_ether6 / ip6_hlim_expired / payload) - - icmp6_reply = (IPv6(hlim=255, src=self.pg1.local_ip6, - dst="2001:db8:1ab::c0a8:1:ab") / - ICMPv6TimeExceeded(code=0) / - IPv6(src="2001:db8:1ab::c0a8:1:ab", - dst='1234:5678:90ab:cdef:ac:1001:200:0', - hlim=1) / payload) - rx = self.send_and_expect(self.pg1, p6*1, self.pg1) + ip6_hlim_expired = IPv6( + hlim=1, + src="2001:db8:1ab::c0a8:1:ab", + dst="1234:5678:90ab:cdef:ac:1001:200:0", + ) + p6 = p_ether6 / ip6_hlim_expired / payload + + icmp6_reply = ( + IPv6(hlim=255, src=self.pg1.local_ip6, dst="2001:db8:1ab::c0a8:1:ab") + / ICMPv6TimeExceeded(code=0) + / IPv6( + src="2001:db8:1ab::c0a8:1:ab", + dst="1234:5678:90ab:cdef:ac:1001:200:0", + hlim=1, + ) + / payload + ) + rx = self.send_and_expect(self.pg1, p6 * 1, self.pg1) for p in rx: self.validate(p[1], icmp6_reply) # IPv6 Hop limit beyond BR - ip6_hlim_expired = IPv6(hlim=0, src='2001:db8:1ab::c0a8:1:ab', - dst='1234:5678:90ab:cdef:ac:1001:200:0') - p6 = (p_ether6 / ip6_hlim_expired / payload) - - icmp6_reply = (IPv6(hlim=255, src=self.pg1.local_ip6, - dst="2001:db8:1ab::c0a8:1:ab") / - ICMPv6TimeExceeded(code=0) / - IPv6(src="2001:db8:1ab::c0a8:1:ab", - dst='1234:5678:90ab:cdef:ac:1001:200:0', - hlim=0) / payload) - rx = self.send_and_expect(self.pg1, p6*1, self.pg1) + ip6_hlim_expired = IPv6( + hlim=0, + src="2001:db8:1ab::c0a8:1:ab", + dst="1234:5678:90ab:cdef:ac:1001:200:0", + ) + p6 = p_ether6 / ip6_hlim_expired / payload + + icmp6_reply = ( + IPv6(hlim=255, src=self.pg1.local_ip6, dst="2001:db8:1ab::c0a8:1:ab") + / ICMPv6TimeExceeded(code=0) + / IPv6( + src="2001:db8:1ab::c0a8:1:ab", + dst="1234:5678:90ab:cdef:ac:1001:200:0", + hlim=0, + ) + / payload + ) + rx = self.send_and_expect(self.pg1, p6 * 1, self.pg1) for p in rx: self.validate(p[1], icmp6_reply) # IPv4 Well-known port - p_ip4 = IP(src=self.pg0.remote_ip4, dst='192.168.0.1') + p_ip4 = IP(src=self.pg0.remote_ip4, dst="192.168.0.1") payload = UDP(sport=200, dport=200) - p4 = (p_ether / p_ip4 / payload) - self.send_and_assert_no_replies(self.pg0, p4*1) + p4 = p_ether / p_ip4 / payload + self.send_and_assert_no_replies(self.pg0, p4 * 1) # IPv6 Well-known port payload = UDP(sport=200, dport=200) - p6 = (p_ether6 / p_ip6 / payload) - self.send_and_assert_no_replies(self.pg1, p6*1) + p6 = p_ether6 / p_ip6 / payload + self.send_and_assert_no_replies(self.pg1, p6 * 1) # UDP packet fragmentation payload_len = 1453 payload = UDP(sport=40000, dport=4000) / self.payload(payload_len) - p4 = (p_ether / p_ip4 / payload) + p4 = p_ether / p_ip4 / payload self.pg_enable_capture() self.pg0.add_stream(p4) self.pg_start() rx = self.pg1.get_capture(2) - p_ip6_translated = IPv6(src='1234:5678:90ab:cdef:ac:1001:200:0', - dst='2001:db8:1e0::c0a8:1:e') + p_ip6_translated = IPv6( + src="1234:5678:90ab:cdef:ac:1001:200:0", dst="2001:db8:1e0::c0a8:1:e" + ) for p in rx: self.validate_frag6(p, p_ip6_translated) @@ -695,7 +751,7 @@ class TestMAP(VppTestCase): # UDP packet fragmentation send fragments payload_len = 1453 payload = UDP(sport=40000, dport=4000) / self.payload(payload_len) - p4 = (p_ether / p_ip4 / payload) + p4 = p_ether / p_ip4 / payload frags = fragment_rfc791(p4, fragsize=1000) self.pg_enable_capture() self.pg0.add_stream(frags) @@ -710,13 +766,14 @@ class TestMAP(VppTestCase): # Send back an fragmented IPv6 UDP packet that will be "untranslated" payload = UDP(sport=4000, dport=40000) / self.payload(payload_len) p_ether6 = Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) - p_ip6 = IPv6(src='2001:db8:1e0::c0a8:1:e', - dst='1234:5678:90ab:cdef:ac:1001:200:0') - p6 = (p_ether6 / p_ip6 / payload) - frags6 = fragment_rfc8200(p6, identification=0xdcba, fragsize=1000) - - p_ip4_translated = IP(src='192.168.0.1', dst=self.pg0.remote_ip4) - p4_translated = (p_ip4_translated / payload) + p_ip6 = IPv6( + src="2001:db8:1e0::c0a8:1:e", dst="1234:5678:90ab:cdef:ac:1001:200:0" + ) + p6 = p_ether6 / p_ip6 / payload + frags6 = fragment_rfc8200(p6, identification=0xDCBA, fragsize=1000) + + p_ip4_translated = IP(src="192.168.0.1", dst=self.pg0.remote_ip4) + p4_translated = p_ip4_translated / payload p4_translated.id = 0 p4_translated.ttl -= 1 @@ -732,14 +789,15 @@ class TestMAP(VppTestCase): # ICMP packet fragmentation payload = ICMP(id=6529) / self.payload(payload_len) - p4 = (p_ether / p_ip4 / payload) + p4 = p_ether / p_ip4 / payload self.pg_enable_capture() self.pg0.add_stream(p4) self.pg_start() rx = self.pg1.get_capture(2) - p_ip6_translated = IPv6(src='1234:5678:90ab:cdef:ac:1001:200:0', - dst='2001:db8:160::c0a8:1:6') + p_ip6_translated = IPv6( + src="1234:5678:90ab:cdef:ac:1001:200:0", dst="2001:db8:160::c0a8:1:6" + ) for p in rx: self.validate_frag6(p, p_ip6_translated) @@ -747,7 +805,7 @@ class TestMAP(VppTestCase): # ICMP packet fragmentation send fragments payload = ICMP(id=6529) / self.payload(payload_len) - p4 = (p_ether / p_ip4 / payload) + p4 = p_ether / p_ip4 / payload frags = fragment_rfc791(p4, fragsize=1000) self.pg_enable_capture() self.pg0.add_stream(frags) @@ -766,30 +824,31 @@ class TestMAP(VppTestCase): # Send a v4 TCP SYN packet that will be translated and MSS clamped # p_ether = Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) - p_ip4 = IP(src=self.pg0.remote_ip4, dst='192.168.0.1') - payload = TCP(sport=0xabcd, dport=0xabcd, flags="S", - options=[('MSS', 1460)]) - - p4 = (p_ether / p_ip4 / payload) - p6_translated = (IPv6(src="1234:5678:90ab:cdef:ac:1001:200:0", - dst="2001:db8:1f0::c0a8:1:f") / payload) + p_ip4 = IP(src=self.pg0.remote_ip4, dst="192.168.0.1") + payload = TCP(sport=0xABCD, dport=0xABCD, flags="S", options=[("MSS", 1460)]) + + p4 = p_ether / p_ip4 / payload + p6_translated = ( + IPv6(src="1234:5678:90ab:cdef:ac:1001:200:0", dst="2001:db8:1f0::c0a8:1:f") + / payload + ) p6_translated.hlim -= 1 - p6_translated[TCP].options = [('MSS', 1300)] - rx = self.send_and_expect(self.pg0, p4*1, self.pg1) + p6_translated[TCP].options = [("MSS", 1300)] + rx = self.send_and_expect(self.pg0, p4 * 1, self.pg1) for p in rx: self.validate(p[1], p6_translated) # Send back an IPv6 packet that will be "untranslated" p_ether6 = Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) - p_ip6 = IPv6(src='2001:db8:1f0::c0a8:1:f', - dst='1234:5678:90ab:cdef:ac:1001:200:0') - p6 = (p_ether6 / p_ip6 / payload) - p4_translated = (IP(src='192.168.0.1', - dst=self.pg0.remote_ip4) / payload) + p_ip6 = IPv6( + src="2001:db8:1f0::c0a8:1:f", dst="1234:5678:90ab:cdef:ac:1001:200:0" + ) + p6 = p_ether6 / p_ip6 / payload + p4_translated = IP(src="192.168.0.1", dst=self.pg0.remote_ip4) / payload p4_translated.id = 0 p4_translated.ttl -= 1 - p4_translated[TCP].options = [('MSS', 1300)] - rx = self.send_and_expect(self.pg1, p6*1, self.pg0) + p4_translated[TCP].options = [("MSS", 1300)] + rx = self.send_and_expect(self.pg1, p6 * 1, self.pg0) for p in rx: self.validate(p[1], p4_translated) @@ -803,19 +862,22 @@ class TestMAP(VppTestCase): # Send back an IPv6 packet that will be droppped due to security # check fail p_ether6 = Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) - p_ip6_sec_check_fail = IPv6(src='2001:db8:1fe::c0a8:1:f', - dst='1234:5678:90ab:cdef:ac:1001:200:0') - payload = TCP(sport=0xabcd, dport=0xabcd) - p6 = (p_ether6 / p_ip6_sec_check_fail / payload) + p_ip6_sec_check_fail = IPv6( + src="2001:db8:1fe::c0a8:1:f", dst="1234:5678:90ab:cdef:ac:1001:200:0" + ) + payload = TCP(sport=0xABCD, dport=0xABCD) + p6 = p_ether6 / p_ip6_sec_check_fail / payload - self.pg_send(self.pg1, p6*1) + self.pg_send(self.pg1, p6 * 1) self.pg0.get_capture(0, timeout=1) rx = self.pg1.get_capture(1) - icmp6_reply = (IPv6(hlim=255, src=self.pg1.local_ip6, - dst='2001:db8:1fe::c0a8:1:f') / - ICMPv6DestUnreach(code=5) / - p_ip6_sec_check_fail / payload) + icmp6_reply = ( + IPv6(hlim=255, src=self.pg1.local_ip6, dst="2001:db8:1fe::c0a8:1:f") + / ICMPv6DestUnreach(code=5) + / p_ip6_sec_check_fail + / payload + ) for p in rx: self.validate(p[1], icmp6_reply) @@ -824,142 +886,160 @@ class TestMAP(VppTestCase): self.vapi.map_param_set_icmp6(enable_unreachable=0) def test_map_t_ip6_psid(self): - """ MAP-T v6->v4 PSID validation""" + """MAP-T v6->v4 PSID validation""" # # Add a domain that maps from pg0 to pg1 # - map_dst = '2001:db8::/32' - map_src = '1234:5678:90ab:cdef::/64' - ip4_pfx = '192.168.0.0/24' - tag = 'MAP-T Test Domain' - - self.vapi.map_add_domain(ip6_prefix=map_dst, - ip4_prefix=ip4_pfx, - ip6_src=map_src, - ea_bits_len=16, - psid_offset=6, - psid_length=4, - mtu=1500, - tag=tag) + map_dst = "2001:db8::/32" + map_src = "1234:5678:90ab:cdef::/64" + ip4_pfx = "192.168.0.0/24" + tag = "MAP-T Test Domain" + + self.vapi.map_add_domain( + ip6_prefix=map_dst, + ip4_prefix=ip4_pfx, + ip6_src=map_src, + ea_bits_len=16, + psid_offset=6, + psid_length=4, + mtu=1500, + tag=tag, + ) # Enable MAP-T on interfaces. - self.vapi.map_if_enable_disable(is_enable=1, - sw_if_index=self.pg0.sw_if_index, - is_translation=1) - self.vapi.map_if_enable_disable(is_enable=1, - sw_if_index=self.pg1.sw_if_index, - is_translation=1) - - map_route = VppIpRoute(self, - "2001:db8::", - 32, - [VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index, - proto=DpoProto.DPO_PROTO_IP6)]) + self.vapi.map_if_enable_disable( + is_enable=1, sw_if_index=self.pg0.sw_if_index, is_translation=1 + ) + self.vapi.map_if_enable_disable( + is_enable=1, sw_if_index=self.pg1.sw_if_index, is_translation=1 + ) + + map_route = VppIpRoute( + self, + "2001:db8::", + 32, + [ + VppRoutePath( + self.pg1.remote_ip6, + self.pg1.sw_if_index, + proto=DpoProto.DPO_PROTO_IP6, + ) + ], + ) map_route.add_vpp_config() p_ether6 = Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) - p_ip6 = IPv6(src='2001:db8:1f0::c0a8:1:f', - dst='1234:5678:90ab:cdef:ac:1001:200:0') + p_ip6 = IPv6( + src="2001:db8:1f0::c0a8:1:f", dst="1234:5678:90ab:cdef:ac:1001:200:0" + ) # Send good IPv6 source port, ensure translated IPv4 received - payload = TCP(sport=0xabcd, dport=80) - p6 = (p_ether6 / p_ip6 / payload) - p4_translated = (IP(src='192.168.0.1', - dst=self.pg0.remote_ip4) / payload) + payload = TCP(sport=0xABCD, dport=80) + p6 = p_ether6 / p_ip6 / payload + p4_translated = IP(src="192.168.0.1", dst=self.pg0.remote_ip4) / payload p4_translated.id = 0 p4_translated.ttl -= 1 - rx = self.send_and_expect(self.pg1, p6*1, self.pg0) + rx = self.send_and_expect(self.pg1, p6 * 1, self.pg0) for p in rx: self.validate(p[1], p4_translated) # Send bad IPv6 source port, ensure translated IPv4 not received - payload = TCP(sport=0xdcba, dport=80) - p6 = (p_ether6 / p_ip6 / payload) - self.send_and_assert_no_replies(self.pg1, p6*1) + payload = TCP(sport=0xDCBA, dport=80) + p6 = p_ether6 / p_ip6 / payload + self.send_and_assert_no_replies(self.pg1, p6 * 1) def test_map_t_pre_resolve(self): - """ MAP-T pre-resolve""" + """MAP-T pre-resolve""" # Add a domain that maps from pg0 to pg1 - map_dst = '2001:db8::/32' - map_src = '1234:5678:90ab:cdef::/64' - ip4_pfx = '192.168.0.0/24' - tag = 'MAP-T Test Domain.' - - self.vapi.map_add_domain(ip6_prefix=map_dst, - ip4_prefix=ip4_pfx, - ip6_src=map_src, - ea_bits_len=16, - psid_offset=6, - psid_length=4, - mtu=1500, - tag=tag) + map_dst = "2001:db8::/32" + map_src = "1234:5678:90ab:cdef::/64" + ip4_pfx = "192.168.0.0/24" + tag = "MAP-T Test Domain." + + self.vapi.map_add_domain( + ip6_prefix=map_dst, + ip4_prefix=ip4_pfx, + ip6_src=map_src, + ea_bits_len=16, + psid_offset=6, + psid_length=4, + mtu=1500, + tag=tag, + ) # Enable MAP-T on interfaces. - self.vapi.map_if_enable_disable(is_enable=1, - sw_if_index=self.pg0.sw_if_index, - is_translation=1) - self.vapi.map_if_enable_disable(is_enable=1, - sw_if_index=self.pg1.sw_if_index, - is_translation=1) + self.vapi.map_if_enable_disable( + is_enable=1, sw_if_index=self.pg0.sw_if_index, is_translation=1 + ) + self.vapi.map_if_enable_disable( + is_enable=1, sw_if_index=self.pg1.sw_if_index, is_translation=1 + ) # Enable pre-resolve option - self.vapi.map_param_add_del_pre_resolve(ip4_nh_address="10.1.2.3", - ip6_nh_address="4001::1", - is_add=1) + self.vapi.map_param_add_del_pre_resolve( + ip4_nh_address="10.1.2.3", ip6_nh_address="4001::1", is_add=1 + ) # Add a route to 4001::1 and expect the translated traffic to be # sent via that route next-hop. - pre_res_route6 = VppIpRoute(self, "4001::1", 128, - [VppRoutePath(self.pg1.remote_hosts[2].ip6, - self.pg1.sw_if_index)]) + pre_res_route6 = VppIpRoute( + self, + "4001::1", + 128, + [VppRoutePath(self.pg1.remote_hosts[2].ip6, self.pg1.sw_if_index)], + ) pre_res_route6.add_vpp_config() # Add a route to 10.1.2.3 and expect the "untranslated" traffic to be # sent via that route next-hop. - pre_res_route4 = VppIpRoute(self, "10.1.2.3", 32, - [VppRoutePath(self.pg0.remote_hosts[1].ip4, - self.pg0.sw_if_index)]) + pre_res_route4 = VppIpRoute( + self, + "10.1.2.3", + 32, + [VppRoutePath(self.pg0.remote_hosts[1].ip4, self.pg0.sw_if_index)], + ) pre_res_route4.add_vpp_config() # Send an IPv4 packet that will be translated p_ether = Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) - p_ip4 = IP(src=self.pg0.remote_ip4, dst='192.168.0.1') - payload = TCP(sport=0xabcd, dport=0xabcd) - p4 = (p_ether / p_ip4 / payload) - - p6_translated = (IPv6(src="1234:5678:90ab:cdef:ac:1001:200:0", - dst="2001:db8:1f0::c0a8:1:f") / payload) + p_ip4 = IP(src=self.pg0.remote_ip4, dst="192.168.0.1") + payload = TCP(sport=0xABCD, dport=0xABCD) + p4 = p_ether / p_ip4 / payload + + p6_translated = ( + IPv6(src="1234:5678:90ab:cdef:ac:1001:200:0", dst="2001:db8:1f0::c0a8:1:f") + / payload + ) p6_translated.hlim -= 1 - rx = self.send_and_expect(self.pg0, p4*1, self.pg1) + rx = self.send_and_expect(self.pg0, p4 * 1, self.pg1) for p in rx: self.assertEqual(p[Ether].dst, self.pg1.remote_hosts[2].mac) self.validate(p[1], p6_translated) # Send back an IPv6 packet that will be "untranslated" p_ether6 = Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) - p_ip6 = IPv6(src='2001:db8:1f0::c0a8:1:f', - dst='1234:5678:90ab:cdef:ac:1001:200:0') - p6 = (p_ether6 / p_ip6 / payload) + p_ip6 = IPv6( + src="2001:db8:1f0::c0a8:1:f", dst="1234:5678:90ab:cdef:ac:1001:200:0" + ) + p6 = p_ether6 / p_ip6 / payload - p4_translated = (IP(src='192.168.0.1', - dst=self.pg0.remote_ip4) / payload) + p4_translated = IP(src="192.168.0.1", dst=self.pg0.remote_ip4) / payload p4_translated.id = 0 p4_translated.ttl -= 1 - rx = self.send_and_expect(self.pg1, p6*1, self.pg0) + rx = self.send_and_expect(self.pg1, p6 * 1, self.pg0) for p in rx: self.assertEqual(p[Ether].dst, self.pg0.remote_hosts[1].mac) self.validate(p[1], p4_translated) # Cleanup pre-resolve option - self.vapi.map_param_add_del_pre_resolve(ip4_nh_address="10.1.2.3", - ip6_nh_address="4001::1", - is_add=0) + self.vapi.map_param_add_del_pre_resolve( + ip4_nh_address="10.1.2.3", ip6_nh_address="4001::1", is_add=0 + ) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_map_br.py b/test/test_map_br.py index 3fe5c83ab75..ae09e9b7d7a 100644 --- a/test/test_map_br.py +++ b/test/test_map_br.py @@ -17,7 +17,7 @@ from scapy.layers.inet6 import ICMPv6EchoRequest, ICMPv6EchoReply, IPerror6 class TestMAPBR(VppTestCase): - """ MAP-T Test Cases """ + """MAP-T Test Cases""" @classmethod def setUpClass(cls): @@ -51,36 +51,37 @@ class TestMAPBR(VppTestCase): # # BR configuration parameters used for all test. # - self.ip4_prefix = '198.18.0.0/24' - self.ip6_prefix = '2001:db8:f0::/48' - self.ip6_src = '2001:db8:ffff:ff00::/64' + self.ip4_prefix = "198.18.0.0/24" + self.ip6_prefix = "2001:db8:f0::/48" + self.ip6_src = "2001:db8:ffff:ff00::/64" self.ea_bits_len = 12 self.psid_offset = 6 self.psid_length = 4 self.mtu = 1500 - self.tag = 'MAP-T BR' + self.tag = "MAP-T BR" self.ipv4_internet_address = self.pg0.remote_ip4 self.ipv4_map_address = "198.18.0.12" self.ipv4_udp_or_tcp_internet_port = 65000 self.ipv4_udp_or_tcp_map_port = 16606 - self.ipv6_cpe_address = "2001:db8:f0:c30:0:c612:c:3" # 198.18.0.12 - self.ipv6_spoof_address = "2001:db8:f0:c30:0:c612:1c:3" # 198.18.0.28 - self.ipv6_spoof_prefix = "2001:db8:f0:c30:0:a00:c:3" # 10.0.0.12 - self.ipv6_spoof_psid = "2001:db8:f0:c30:0:c612:c:4" # 4 - self.ipv6_spoof_subnet = "2001:db8:f1:c30:0:c612:c:3" # f1 + self.ipv6_cpe_address = "2001:db8:f0:c30:0:c612:c:3" # 198.18.0.12 + self.ipv6_spoof_address = "2001:db8:f0:c30:0:c612:1c:3" # 198.18.0.28 + self.ipv6_spoof_prefix = "2001:db8:f0:c30:0:a00:c:3" # 10.0.0.12 + self.ipv6_spoof_psid = "2001:db8:f0:c30:0:c612:c:4" # 4 + self.ipv6_spoof_subnet = "2001:db8:f1:c30:0:c612:c:3" # f1 self.ipv6_udp_or_tcp_internet_port = 65000 self.ipv6_udp_or_tcp_map_port = 16606 self.ipv6_udp_or_tcp_spoof_port = 16862 - self.ipv6_map_address = ( - "2001:db8:ffff:ff00:ac:1001:200:0") # 176.16.1.2 + self.ipv6_map_address = "2001:db8:ffff:ff00:ac:1001:200:0" # 176.16.1.2 self.ipv6_map_same_rule_diff_addr = ( - "2001:db8:ffff:ff00:c6:1200:1000:0") # 198.18.0.16 + "2001:db8:ffff:ff00:c6:1200:1000:0" # 198.18.0.16 + ) self.ipv6_map_same_rule_same_addr = ( - "2001:db8:ffff:ff00:c6:1200:c00:0") # 198.18.0.12 + "2001:db8:ffff:ff00:c6:1200:c00:0" # 198.18.0.12 + ) self.map_br_prefix = "2001:db8:f0::" self.map_br_prefix_len = 48 @@ -89,24 +90,27 @@ class TestMAPBR(VppTestCase): # # Add an IPv6 route to the MAP-BR. # - map_route = VppIpRoute(self, - self.map_br_prefix, - self.map_br_prefix_len, - [VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index)]) + map_route = VppIpRoute( + self, + self.map_br_prefix, + self.map_br_prefix_len, + [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)], + ) map_route.add_vpp_config() # # Add a MAP BR domain that maps from pg0 to pg1. # - self.vapi.map_add_domain(ip4_prefix=self.ip4_prefix, - ip6_prefix=self.ip6_prefix, - ip6_src=self.ip6_src, - ea_bits_len=self.ea_bits_len, - psid_offset=self.psid_offset, - psid_length=self.psid_length, - mtu=self.mtu, - tag=self.tag) + self.vapi.map_add_domain( + ip4_prefix=self.ip4_prefix, + ip6_prefix=self.ip6_prefix, + ip6_src=self.ip6_src, + ea_bits_len=self.ea_bits_len, + psid_offset=self.psid_offset, + psid_length=self.psid_length, + mtu=self.mtu, + tag=self.tag, + ) # # Set BR parameters. @@ -119,17 +123,17 @@ class TestMAPBR(VppTestCase): # # Enable MAP-T on interfaces. # - self.vapi.map_if_enable_disable(is_enable=1, - sw_if_index=self.pg0.sw_if_index, - is_translation=1) + self.vapi.map_if_enable_disable( + is_enable=1, sw_if_index=self.pg0.sw_if_index, is_translation=1 + ) - self.vapi.map_if_enable_disable(is_enable=1, - sw_if_index=self.pg1.sw_if_index, - is_translation=1) + self.vapi.map_if_enable_disable( + is_enable=1, sw_if_index=self.pg1.sw_if_index, is_translation=1 + ) - self.vapi.map_if_enable_disable(is_enable=1, - sw_if_index=self.pg1.sw_if_index, - is_translation=1) + self.vapi.map_if_enable_disable( + is_enable=1, sw_if_index=self.pg1.sw_if_index, is_translation=1 + ) def tearDown(self): super(TestMAPBR, self).tearDown() @@ -162,15 +166,14 @@ class TestMAPBR(VppTestCase): # def test_map_t_udp_ip4_to_ip6(self): - """ MAP-T UDP IPv4 -> IPv6 """ - - eth = Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) - ip = IP(src=self.pg0.remote_ip4, - dst=self.ipv4_map_address, - tos=0) - udp = UDP(sport=self.ipv4_udp_or_tcp_internet_port, - dport=self.ipv4_udp_or_tcp_map_port) + """MAP-T UDP IPv4 -> IPv6""" + + eth = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + ip = IP(src=self.pg0.remote_ip4, dst=self.ipv4_map_address, tos=0) + udp = UDP( + sport=self.ipv4_udp_or_tcp_internet_port, + dport=self.ipv4_udp_or_tcp_map_port, + ) payload = "a" * 82 tx_pkt = eth / ip / udp / payload @@ -181,7 +184,7 @@ class TestMAPBR(VppTestCase): self.v6_address_check(rx_pkt) self.v6_port_check(rx_pkt, UDP) - self.assertEqual(rx_pkt[IPv6].tc, 0) # IPv4 ToS passed to v6 TC + self.assertEqual(rx_pkt[IPv6].tc, 0) # IPv4 ToS passed to v6 TC self.assertEqual(rx_pkt[IPv6].nh, IPv6(nh="UDP").nh) # @@ -192,15 +195,14 @@ class TestMAPBR(VppTestCase): # def test_map_t_tcp_ip4_to_ip6(self): - """ MAP-T TCP IPv4 -> IPv6 """ - - eth = Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) - ip = IP(src=self.pg0.remote_ip4, - dst=self.ipv4_map_address, - tos=0) - tcp = TCP(sport=self.ipv4_udp_or_tcp_internet_port, - dport=self.ipv4_udp_or_tcp_map_port) + """MAP-T TCP IPv4 -> IPv6""" + + eth = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + ip = IP(src=self.pg0.remote_ip4, dst=self.ipv4_map_address, tos=0) + tcp = TCP( + sport=self.ipv4_udp_or_tcp_internet_port, + dport=self.ipv4_udp_or_tcp_map_port, + ) payload = "a" * 82 tx_pkt = eth / ip / tcp / payload @@ -211,7 +213,7 @@ class TestMAPBR(VppTestCase): self.v6_address_check(rx_pkt) self.v6_port_check(rx_pkt, TCP) - self.assertEqual(rx_pkt[IPv6].tc, 0) # IPv4 ToS passed to v6 TC + self.assertEqual(rx_pkt[IPv6].tc, 0) # IPv4 ToS passed to v6 TC self.assertEqual(rx_pkt[IPv6].nh, IPv6(nh="TCP").nh) # @@ -221,14 +223,14 @@ class TestMAPBR(VppTestCase): # def test_map_t_udp_ip6_to_ip4(self): - """ MAP-T UDP IPv6 -> IPv4 """ - - eth = Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) - ip = IPv6(src=self.ipv6_cpe_address, - dst=self.ipv6_map_address) - udp = UDP(sport=self.ipv6_udp_or_tcp_map_port, - dport=self.ipv6_udp_or_tcp_internet_port) + """MAP-T UDP IPv6 -> IPv4""" + + eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + ip = IPv6(src=self.ipv6_cpe_address, dst=self.ipv6_map_address) + udp = UDP( + sport=self.ipv6_udp_or_tcp_map_port, + dport=self.ipv6_udp_or_tcp_internet_port, + ) payload = "a" * 82 tx_pkt = eth / ip / udp / payload @@ -240,7 +242,7 @@ class TestMAPBR(VppTestCase): self.v4_address_check(rx_pkt) self.v4_port_check(rx_pkt, UDP) self.assertEqual(rx_pkt[IP].proto, IP(proto="udp").proto) - self.assertEqual(rx_pkt[IP].tos, 0) # IPv6 TC passed to v4 ToS + self.assertEqual(rx_pkt[IP].tos, 0) # IPv6 TC passed to v4 ToS df_bit = IP(flags="DF").flags self.assertNotEqual(rx_pkt[IP].flags & df_bit, df_bit) @@ -251,14 +253,14 @@ class TestMAPBR(VppTestCase): # def test_map_t_tcp_ip6_to_ip4(self): - """ MAP-T TCP IPv6 -> IPv4 """ - - eth = Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) - ip = IPv6(src=self.ipv6_cpe_address, - dst=self.ipv6_map_address) - tcp = TCP(sport=self.ipv6_udp_or_tcp_map_port, - dport=self.ipv6_udp_or_tcp_internet_port) + """MAP-T TCP IPv6 -> IPv4""" + + eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + ip = IPv6(src=self.ipv6_cpe_address, dst=self.ipv6_map_address) + tcp = TCP( + sport=self.ipv6_udp_or_tcp_map_port, + dport=self.ipv6_udp_or_tcp_internet_port, + ) payload = "a" * 82 tx_pkt = eth / ip / tcp / payload @@ -270,7 +272,7 @@ class TestMAPBR(VppTestCase): self.v4_address_check(rx_pkt) self.v4_port_check(rx_pkt, TCP) self.assertEqual(rx_pkt[IP].proto, IP(proto="tcp").proto) - self.assertEqual(rx_pkt[IP].tos, 0) # IPv6 TC passed to v4 ToS + self.assertEqual(rx_pkt[IP].tos, 0) # IPv6 TC passed to v4 ToS df_bit = IP(flags="DF").flags self.assertNotEqual(rx_pkt[IP].flags & df_bit, df_bit) @@ -280,14 +282,11 @@ class TestMAPBR(VppTestCase): # def test_map_t_echo_request_ip4_to_ip6(self): - """ MAP-T echo request IPv4 -> IPv6 """ - - eth = Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) - ip = IP(src=self.pg0.remote_ip4, - dst=self.ipv4_map_address) - icmp = ICMP(type="echo-request", - id=self.ipv6_udp_or_tcp_map_port) + """MAP-T echo request IPv4 -> IPv6""" + + eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + ip = IP(src=self.pg0.remote_ip4, dst=self.ipv4_map_address) + icmp = ICMP(type="echo-request", id=self.ipv6_udp_or_tcp_map_port) payload = "H" * 10 tx_pkt = eth / ip / icmp / payload @@ -297,11 +296,11 @@ class TestMAPBR(VppTestCase): rx_pkt = rx_pkts[0] self.assertEqual(rx_pkt[IPv6].nh, IPv6(nh="ICMPv6").nh) - self.assertEqual(rx_pkt[ICMPv6EchoRequest].type, - ICMPv6EchoRequest(type="Echo Request").type) + self.assertEqual( + rx_pkt[ICMPv6EchoRequest].type, ICMPv6EchoRequest(type="Echo Request").type + ) self.assertEqual(rx_pkt[ICMPv6EchoRequest].code, 0) - self.assertEqual(rx_pkt[ICMPv6EchoRequest].id, - self.ipv6_udp_or_tcp_map_port) + self.assertEqual(rx_pkt[ICMPv6EchoRequest].id, self.ipv6_udp_or_tcp_map_port) # # Translation of ICMP Echo Reply v4 -> v6 direction @@ -309,14 +308,11 @@ class TestMAPBR(VppTestCase): # def test_map_t_echo_reply_ip4_to_ip6(self): - """ MAP-T echo reply IPv4 -> IPv6 """ - - eth = Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) - ip = IP(src=self.pg0.remote_ip4, - dst=self.ipv4_map_address) - icmp = ICMP(type="echo-reply", - id=self.ipv6_udp_or_tcp_map_port) + """MAP-T echo reply IPv4 -> IPv6""" + + eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + ip = IP(src=self.pg0.remote_ip4, dst=self.ipv4_map_address) + icmp = ICMP(type="echo-reply", id=self.ipv6_udp_or_tcp_map_port) payload = "H" * 10 tx_pkt = eth / ip / icmp / payload @@ -326,11 +322,11 @@ class TestMAPBR(VppTestCase): rx_pkt = rx_pkts[0] self.assertEqual(rx_pkt[IPv6].nh, IPv6(nh="ICMPv6").nh) - self.assertEqual(rx_pkt[ICMPv6EchoReply].type, - ICMPv6EchoReply(type="Echo Reply").type) + self.assertEqual( + rx_pkt[ICMPv6EchoReply].type, ICMPv6EchoReply(type="Echo Reply").type + ) self.assertEqual(rx_pkt[ICMPv6EchoReply].code, 0) - self.assertEqual(rx_pkt[ICMPv6EchoReply].id, - self.ipv6_udp_or_tcp_map_port) + self.assertEqual(rx_pkt[ICMPv6EchoReply].id, self.ipv6_udp_or_tcp_map_port) # # Translation of ICMP Time Exceeded v4 -> v6 direction @@ -338,17 +334,16 @@ class TestMAPBR(VppTestCase): # def test_map_t_time_exceeded_ip4_to_ip6(self): - """ MAP-T time exceeded IPv4 -> IPv6 """ + """MAP-T time exceeded IPv4 -> IPv6""" - eth = Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) - ip = IP(src=self.pg0.remote_ip4, - dst=self.ipv4_map_address) + eth = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + ip = IP(src=self.pg0.remote_ip4, dst=self.ipv4_map_address) icmp = ICMP(type="time-exceeded", code="ttl-zero-during-transit") - ip_inner = IP(dst=self.pg0.remote_ip4, - src=self.ipv4_map_address, ttl=1) - udp_inner = UDP(sport=self.ipv4_udp_or_tcp_map_port, - dport=self.ipv4_udp_or_tcp_internet_port) + ip_inner = IP(dst=self.pg0.remote_ip4, src=self.ipv4_map_address, ttl=1) + udp_inner = UDP( + sport=self.ipv4_udp_or_tcp_map_port, + dport=self.ipv4_udp_or_tcp_internet_port, + ) payload = "H" * 10 tx_pkt = eth / ip / icmp / ip_inner / udp_inner / payload @@ -359,19 +354,18 @@ class TestMAPBR(VppTestCase): self.v6_address_check(rx_pkt) self.assertEqual(rx_pkt[IPv6].nh, IPv6(nh="ICMPv6").nh) - self.assertEqual(rx_pkt[ICMPv6TimeExceeded].type, - ICMPv6TimeExceeded().type) - self.assertEqual(rx_pkt[ICMPv6TimeExceeded].code, - ICMPv6TimeExceeded( - code="hop limit exceeded in transit").code) + self.assertEqual(rx_pkt[ICMPv6TimeExceeded].type, ICMPv6TimeExceeded().type) + self.assertEqual( + rx_pkt[ICMPv6TimeExceeded].code, + ICMPv6TimeExceeded(code="hop limit exceeded in transit").code, + ) self.assertEqual(rx_pkt[ICMPv6TimeExceeded].hlim, tx_pkt[IP][1].ttl) self.assertTrue(rx_pkt.haslayer(IPerror6)) self.assertTrue(rx_pkt.haslayer(UDPerror)) self.assertEqual(rx_pkt[IPv6].src, rx_pkt[IPerror6].dst) self.assertEqual(rx_pkt[IPv6].dst, rx_pkt[IPerror6].src) self.assertEqual(rx_pkt[UDPerror].sport, self.ipv6_udp_or_tcp_map_port) - self.assertEqual(rx_pkt[UDPerror].dport, - self.ipv6_udp_or_tcp_internet_port) + self.assertEqual(rx_pkt[UDPerror].dport, self.ipv6_udp_or_tcp_internet_port) # # Translation of ICMP Echo Request v6 -> v4 direction @@ -379,12 +373,10 @@ class TestMAPBR(VppTestCase): # def test_map_t_echo_request_ip6_to_ip4(self): - """ MAP-T echo request IPv6 -> IPv4 """ + """MAP-T echo request IPv6 -> IPv4""" - eth = Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) - ip = IPv6(src=self.ipv6_cpe_address, - dst=self.ipv6_map_address) + eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + ip = IPv6(src=self.ipv6_cpe_address, dst=self.ipv6_map_address) icmp = ICMPv6EchoRequest() icmp.id = self.ipv6_udp_or_tcp_map_port payload = "H" * 10 @@ -406,12 +398,10 @@ class TestMAPBR(VppTestCase): # def test_map_t_echo_reply_ip6_to_ip4(self): - """ MAP-T echo reply IPv6 -> IPv4 """ + """MAP-T echo reply IPv6 -> IPv4""" - eth = Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) - ip = IPv6(src=self.ipv6_cpe_address, - dst=self.ipv6_map_address) + eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + ip = IPv6(src=self.ipv6_cpe_address, dst=self.ipv6_map_address) icmp = ICMPv6EchoReply(id=self.ipv6_udp_or_tcp_map_port) payload = "H" * 10 tx_pkt = eth / ip / icmp / payload @@ -432,17 +422,16 @@ class TestMAPBR(VppTestCase): # def test_map_t_packet_too_big_ip6_to_ip4(self): - """ MAP-T packet too big IPv6 -> IPv4 """ + """MAP-T packet too big IPv6 -> IPv4""" - eth = Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) - ip = IPv6(src=self.ipv6_cpe_address, - dst=self.ipv6_map_address) + eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + ip = IPv6(src=self.ipv6_cpe_address, dst=self.ipv6_map_address) icmp = ICMPv6PacketTooBig(mtu=1280) - ip_inner = IPv6(src=self.ipv6_map_address, - dst=self.ipv6_cpe_address) - udp_inner = UDP(sport=self.ipv6_udp_or_tcp_internet_port, - dport=self.ipv6_udp_or_tcp_map_port) + ip_inner = IPv6(src=self.ipv6_map_address, dst=self.ipv6_cpe_address) + udp_inner = UDP( + sport=self.ipv6_udp_or_tcp_internet_port, + dport=self.ipv6_udp_or_tcp_map_port, + ) payload = "H" * 10 tx_pkt = eth / ip / icmp / ip_inner / udp_inner / payload @@ -454,16 +443,13 @@ class TestMAPBR(VppTestCase): self.v4_address_check(rx_pkt) self.assertEqual(rx_pkt[IP].proto, IP(proto="icmp").proto) self.assertEqual(rx_pkt[ICMP].type, ICMP(type="dest-unreach").type) - self.assertEqual(rx_pkt[ICMP].code, - ICMP(code="fragmentation-needed").code) - self.assertEqual(rx_pkt[ICMP].nexthopmtu, - tx_pkt[ICMPv6PacketTooBig].mtu - 20) + self.assertEqual(rx_pkt[ICMP].code, ICMP(code="fragmentation-needed").code) + self.assertEqual(rx_pkt[ICMP].nexthopmtu, tx_pkt[ICMPv6PacketTooBig].mtu - 20) self.assertTrue(rx_pkt.haslayer(IPerror)) self.assertTrue(rx_pkt.haslayer(UDPerror)) self.assertEqual(rx_pkt[IP].src, rx_pkt[IPerror].dst) self.assertEqual(rx_pkt[IP].dst, rx_pkt[IPerror].src) - self.assertEqual(rx_pkt[UDPerror].sport, - self.ipv4_udp_or_tcp_internet_port) + self.assertEqual(rx_pkt[UDPerror].sport, self.ipv4_udp_or_tcp_internet_port) self.assertEqual(rx_pkt[UDPerror].dport, self.ipv4_udp_or_tcp_map_port) # @@ -472,17 +458,16 @@ class TestMAPBR(VppTestCase): # def test_map_t_time_exceeded_ip6_to_ip4(self): - """ MAP-T time exceeded IPv6 -> IPv4 """ + """MAP-T time exceeded IPv6 -> IPv4""" - eth = Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) - ip = IPv6(src=self.ipv6_cpe_address, - dst=self.ipv6_map_address) + eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + ip = IPv6(src=self.ipv6_cpe_address, dst=self.ipv6_map_address) icmp = ICMPv6TimeExceeded() - ip_inner = IPv6(src=self.ipv6_map_address, - dst=self.ipv6_cpe_address, hlim=1) - udp_inner = UDP(sport=self.ipv6_udp_or_tcp_internet_port, - dport=self.ipv6_udp_or_tcp_map_port) + ip_inner = IPv6(src=self.ipv6_map_address, dst=self.ipv6_cpe_address, hlim=1) + udp_inner = UDP( + sport=self.ipv6_udp_or_tcp_internet_port, + dport=self.ipv6_udp_or_tcp_map_port, + ) payload = "H" * 10 tx_pkt = eth / ip / icmp / ip_inner / udp_inner / payload @@ -494,15 +479,13 @@ class TestMAPBR(VppTestCase): self.v4_address_check(rx_pkt) self.assertEqual(rx_pkt[IP].proto, IP(proto="icmp").proto) self.assertEqual(rx_pkt[ICMP].type, ICMP(type="time-exceeded").type) - self.assertEqual(rx_pkt[ICMP].code, - ICMP(code="ttl-zero-during-transit").code) + self.assertEqual(rx_pkt[ICMP].code, ICMP(code="ttl-zero-during-transit").code) self.assertEqual(rx_pkt[ICMP].ttl, tx_pkt[IPv6][1].hlim) self.assertTrue(rx_pkt.haslayer(IPerror)) self.assertTrue(rx_pkt.haslayer(UDPerror)) self.assertEqual(rx_pkt[IP].src, rx_pkt[IPerror].dst) self.assertEqual(rx_pkt[IP].dst, rx_pkt[IPerror].src) - self.assertEqual(rx_pkt[UDPerror].sport, - self.ipv4_udp_or_tcp_internet_port) + self.assertEqual(rx_pkt[UDPerror].sport, self.ipv4_udp_or_tcp_internet_port) self.assertEqual(rx_pkt[UDPerror].dport, self.ipv4_udp_or_tcp_map_port) # @@ -514,22 +497,21 @@ class TestMAPBR(VppTestCase): # def test_map_t_spoof_ipv4_src_addr_ip6_to_ip4(self): - """ MAP-T spoof ipv4 src addr IPv6 -> IPv4 """ - - eth = Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) - ip = IPv6(src=self.ipv6_spoof_address, - dst=self.ipv6_map_address) - udp = UDP(sport=self.ipv6_udp_or_tcp_map_port, - dport=self.ipv6_udp_or_tcp_internet_port) + """MAP-T spoof ipv4 src addr IPv6 -> IPv4""" + + eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + ip = IPv6(src=self.ipv6_spoof_address, dst=self.ipv6_map_address) + udp = UDP( + sport=self.ipv6_udp_or_tcp_map_port, + dport=self.ipv6_udp_or_tcp_internet_port, + ) payload = "a" * 82 tx_pkt = eth / ip / udp / payload self.pg_send(self.pg1, tx_pkt * 1) self.pg0.get_capture(0, timeout=1) - self.pg0.assert_nothing_captured( - remark="Should drop IPv4 spoof address") + self.pg0.assert_nothing_captured(remark="Should drop IPv4 spoof address") # # Spoofed IPv4 Source Prefix v6 -> v4 direction @@ -539,22 +521,21 @@ class TestMAPBR(VppTestCase): # def test_map_t_spoof_ipv4_src_prefix_ip6_to_ip4(self): - """ MAP-T spoof ipv4 src prefix IPv6 -> IPv4 """ - - eth = Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) - ip = IPv6(src=self.ipv6_spoof_prefix, - dst=self.ipv6_map_address) - udp = UDP(sport=self.ipv6_udp_or_tcp_map_port, - dport=self.ipv6_udp_or_tcp_internet_port) + """MAP-T spoof ipv4 src prefix IPv6 -> IPv4""" + + eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + ip = IPv6(src=self.ipv6_spoof_prefix, dst=self.ipv6_map_address) + udp = UDP( + sport=self.ipv6_udp_or_tcp_map_port, + dport=self.ipv6_udp_or_tcp_internet_port, + ) payload = "a" * 82 tx_pkt = eth / ip / udp / payload self.pg_send(self.pg1, tx_pkt * 1) self.pg0.get_capture(0, timeout=1) - self.pg0.assert_nothing_captured( - remark="Should drop IPv4 spoof prefix") + self.pg0.assert_nothing_captured(remark="Should drop IPv4 spoof prefix") # # Spoofed IPv6 PSID v6 -> v4 direction @@ -563,22 +544,21 @@ class TestMAPBR(VppTestCase): # def test_map_t_spoof_psid_ip6_to_ip4(self): - """ MAP-T spoof psid IPv6 -> IPv4 """ - - eth = Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) - ip = IPv6(src=self.ipv6_spoof_psid, - dst=self.ipv6_map_address) - udp = UDP(sport=self.ipv6_udp_or_tcp_map_port, - dport=self.ipv6_udp_or_tcp_internet_port) + """MAP-T spoof psid IPv6 -> IPv4""" + + eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + ip = IPv6(src=self.ipv6_spoof_psid, dst=self.ipv6_map_address) + udp = UDP( + sport=self.ipv6_udp_or_tcp_map_port, + dport=self.ipv6_udp_or_tcp_internet_port, + ) payload = "a" * 82 tx_pkt = eth / ip / udp / payload self.pg_send(self.pg1, tx_pkt * 1) self.pg0.get_capture(0, timeout=1) - self.pg0.assert_nothing_captured( - remark="Should drop IPv6 spoof PSID") + self.pg0.assert_nothing_captured(remark="Should drop IPv6 spoof PSID") # # Spoofed IPv6 subnet field v6 -> v4 direction @@ -587,22 +567,21 @@ class TestMAPBR(VppTestCase): # def test_map_t_spoof_subnet_ip6_to_ip4(self): - """ MAP-T spoof subnet IPv6 -> IPv4 """ - - eth = Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) - ip = IPv6(src=self.ipv6_spoof_subnet, - dst=self.ipv6_map_address) - udp = UDP(sport=self.ipv6_udp_or_tcp_map_port, - dport=self.ipv6_udp_or_tcp_internet_port) + """MAP-T spoof subnet IPv6 -> IPv4""" + + eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + ip = IPv6(src=self.ipv6_spoof_subnet, dst=self.ipv6_map_address) + udp = UDP( + sport=self.ipv6_udp_or_tcp_map_port, + dport=self.ipv6_udp_or_tcp_internet_port, + ) payload = "a" * 82 tx_pkt = eth / ip / udp / payload self.pg_send(self.pg1, tx_pkt * 1) self.pg0.get_capture(0, timeout=1) - self.pg0.assert_nothing_captured( - remark="Should drop IPv6 spoof subnet") + self.pg0.assert_nothing_captured(remark="Should drop IPv6 spoof subnet") # # Spoofed IPv6 port PSID v6 -> v4 direction @@ -611,22 +590,21 @@ class TestMAPBR(VppTestCase): # def test_map_t_spoof_port_psid_ip6_to_ip4(self): - """ MAP-T spoof port psid IPv6 -> IPv4 """ - - eth = Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) - ip = IPv6(src=self.ipv6_cpe_address, - dst=self.ipv6_map_address) - udp = UDP(sport=self.ipv6_udp_or_tcp_spoof_port, - dport=self.ipv6_udp_or_tcp_internet_port) + """MAP-T spoof port psid IPv6 -> IPv4""" + + eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + ip = IPv6(src=self.ipv6_cpe_address, dst=self.ipv6_map_address) + udp = UDP( + sport=self.ipv6_udp_or_tcp_spoof_port, + dport=self.ipv6_udp_or_tcp_internet_port, + ) payload = "a" * 82 tx_pkt = eth / ip / udp / payload self.pg_send(self.pg1, tx_pkt * 1) self.pg0.get_capture(0, timeout=1) - self.pg0.assert_nothing_captured( - remark="Should drop IPv6 spoof port PSID") + self.pg0.assert_nothing_captured(remark="Should drop IPv6 spoof port PSID") # # Spoofed IPv6 ICMP ID PSID v6 -> v4 direction @@ -635,12 +613,10 @@ class TestMAPBR(VppTestCase): # def test_map_t_spoof_icmp_id_psid_ip6_to_ip4(self): - """ MAP-T spoof ICMP id psid IPv6 -> IPv4 """ + """MAP-T spoof ICMP id psid IPv6 -> IPv4""" - eth = Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) - ip = IPv6(src=self.ipv6_cpe_address, - dst=self.ipv6_map_address) + eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + ip = IPv6(src=self.ipv6_cpe_address, dst=self.ipv6_map_address) icmp = ICMPv6EchoRequest() icmp.id = self.ipv6_udp_or_tcp_spoof_port payload = "H" * 10 @@ -649,8 +625,7 @@ class TestMAPBR(VppTestCase): self.pg_send(self.pg1, tx_pkt * 1) self.pg0.get_capture(0, timeout=1) - self.pg0.assert_nothing_captured( - remark="Should drop IPv6 spoof port PSID") + self.pg0.assert_nothing_captured(remark="Should drop IPv6 spoof port PSID") # # Map to Map - same rule, different address @@ -658,14 +633,11 @@ class TestMAPBR(VppTestCase): @unittest.skip("Fixme: correct behavior needs clarification") def test_map_t_same_rule_diff_addr_ip6_to_ip4(self): - """ MAP-T same rule, diff addr IPv6 -> IPv6 """ - - eth = Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) - ip = IPv6(src=self.ipv6_cpe_address, - dst=self.ipv6_map_same_rule_diff_addr) - udp = UDP(sport=self.ipv6_udp_or_tcp_map_port, - dport=1025) + """MAP-T same rule, diff addr IPv6 -> IPv6""" + + eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + ip = IPv6(src=self.ipv6_cpe_address, dst=self.ipv6_map_same_rule_diff_addr) + udp = UDP(sport=self.ipv6_udp_or_tcp_map_port, dport=1025) payload = "a" * 82 tx_pkt = eth / ip / udp / payload @@ -680,14 +652,11 @@ class TestMAPBR(VppTestCase): @unittest.skip("Fixme: correct behavior needs clarification") def test_map_t_same_rule_same_addr_ip6_to_ip4(self): - """ MAP-T same rule, same addr IPv6 -> IPv6 """ - - eth = Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) - ip = IPv6(src=self.ipv6_cpe_address, - dst=self.ipv6_map_same_rule_same_addr) - udp = UDP(sport=self.ipv6_udp_or_tcp_map_port, - dport=1025) + """MAP-T same rule, same addr IPv6 -> IPv6""" + + eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + ip = IPv6(src=self.ipv6_cpe_address, dst=self.ipv6_map_same_rule_same_addr) + udp = UDP(sport=self.ipv6_udp_or_tcp_map_port, dport=1025) payload = "a" * 82 tx_pkt = eth / ip / udp / payload @@ -697,5 +666,5 @@ class TestMAPBR(VppTestCase): rx_pkt = rx_pkts[0] -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_memif.py b/test/test_memif.py index 26e44f29485..9b15cd0005b 100644 --- a/test/test_memif.py +++ b/test/test_memif.py @@ -7,26 +7,25 @@ from scapy.layers.inet import IP, ICMP from framework import VppTestCase, VppTestRunner from framework import tag_run_solo from remote_test import RemoteClass, RemoteVppTestCase -from vpp_memif import remove_all_memif_vpp_config, \ - VppSocketFilename, VppMemif +from vpp_memif import remove_all_memif_vpp_config, VppSocketFilename, VppMemif from vpp_ip_route import VppIpRoute, VppRoutePath from vpp_papi import VppEnum @tag_run_solo class TestMemif(VppTestCase): - """ Memif Test Case """ + """Memif Test Case""" + remote_class = RemoteVppTestCase @classmethod def get_cpus_required(cls): - return (super().get_cpus_required() + - cls.remote_class.get_cpus_required()) + return super().get_cpus_required() + cls.remote_class.get_cpus_required() @classmethod def assign_cpus(cls, cpus): - remote_cpus = cpus[:cls.remote_class.get_cpus_required()] - my_cpus = cpus[cls.remote_class.get_cpus_required():] + remote_cpus = cpus[: cls.remote_class.get_cpus_required()] + my_cpus = cpus[cls.remote_class.get_cpus_required() :] cls.remote_class.assign_cpus(remote_cpus) super().assign_cpus(my_cpus) @@ -61,56 +60,47 @@ class TestMemif(VppTestCase): def _check_socket_filename(self, dump, socket_id, filename): for d in dump: - if (d.socket_id == socket_id) and ( - d.socket_filename == filename): + if (d.socket_id == socket_id) and (d.socket_filename == filename): return True return False def test_memif_socket_filename_add_del(self): - """ Memif socket filename add/del """ + """Memif socket filename add/del""" # dump default socket filename dump = self.vapi.memif_socket_filename_dump() self.assertTrue( - self._check_socket_filename( - dump, 0, "%s/memif.sock" % self.tempdir)) + self._check_socket_filename(dump, 0, "%s/memif.sock" % self.tempdir) + ) memif_sockets = [] # existing path memif_sockets.append( - VppSocketFilename( - self, 1, "%s/memif1.sock" % self.tempdir)) + VppSocketFilename(self, 1, "%s/memif1.sock" % self.tempdir) + ) # default path (test tempdir) memif_sockets.append( - VppSocketFilename( - self, - 2, - "memif2.sock", - add_default_folder=True)) + VppSocketFilename(self, 2, "memif2.sock", add_default_folder=True) + ) # create new folder in default folder memif_sockets.append( - VppSocketFilename( - self, - 3, - "sock/memif3.sock", - add_default_folder=True)) + VppSocketFilename(self, 3, "sock/memif3.sock", add_default_folder=True) + ) for sock in memif_sockets: sock.add_vpp_config() dump = sock.query_vpp_config() self.assertTrue( - self._check_socket_filename( - dump, - sock.socket_id, - sock.socket_filename)) + self._check_socket_filename(dump, sock.socket_id, sock.socket_filename) + ) for sock in memif_sockets: sock.remove_vpp_config() dump = self.vapi.memif_socket_filename_dump() self.assertTrue( - self._check_socket_filename( - dump, 0, "%s/memif.sock" % self.tempdir)) + self._check_socket_filename(dump, 0, "%s/memif.sock" % self.tempdir) + ) def _create_delete_test_one_interface(self, memif): memif.add_vpp_config() @@ -121,7 +111,7 @@ class TestMemif(VppTestCase): self.assertEqual(dump.sw_if_index, memif.sw_if_index) self.assertEqual(dump.role, memif.role) self.assertEqual(dump.mode, memif.mode) - if (memif.socket_id is not None): + if memif.socket_id is not None: self.assertEqual(dump.socket_id, memif.socket_id) memif.remove_vpp_config() @@ -155,43 +145,39 @@ class TestMemif(VppTestCase): memif1.remove_vpp_config() def test_memif_create_delete(self): - """ Memif create/delete interface """ + """Memif create/delete interface""" memif = VppMemif( self, VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_SLAVE, - VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET) + VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET, + ) self._create_delete_test_one_interface(memif) memif.role = VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_MASTER self._create_delete_test_one_interface(memif) def test_memif_create_custom_socket(self): - """ Memif create with non-default socket filename """ + """Memif create with non-default socket filename""" memif_sockets = [] # existing path memif_sockets.append( - VppSocketFilename( - self, 1, "%s/memif1.sock" % self.tempdir)) + VppSocketFilename(self, 1, "%s/memif1.sock" % self.tempdir) + ) # default path (test tempdir) memif_sockets.append( - VppSocketFilename( - self, - 2, - "memif2.sock", - add_default_folder=True)) + VppSocketFilename(self, 2, "memif2.sock", add_default_folder=True) + ) # create new folder in default folder memif_sockets.append( - VppSocketFilename( - self, - 3, - "sock/memif3.sock", - add_default_folder=True)) + VppSocketFilename(self, 3, "sock/memif3.sock", add_default_folder=True) + ) memif = VppMemif( self, VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_SLAVE, - VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET) + VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET, + ) for sock in memif_sockets: sock.add_vpp_config() @@ -202,17 +188,19 @@ class TestMemif(VppTestCase): self._create_delete_test_one_interface(memif) def test_memif_connect(self): - """ Memif connect """ + """Memif connect""" memif = VppMemif( self, VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_SLAVE, VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET, ring_size=1024, buffer_size=2048, - secret="abc") + secret="abc", + ) - remote_socket = VppSocketFilename(self.remote_test, 1, - "%s/memif.sock" % self.tempdir) + remote_socket = VppSocketFilename( + self.remote_test, 1, "%s/memif.sock" % self.tempdir + ) remote_socket.add_vpp_config() remote_memif = VppMemif( @@ -222,7 +210,8 @@ class TestMemif(VppTestCase): socket_id=1, ring_size=1024, buffer_size=2048, - secret="abc") + secret="abc", + ) self._connect_test_interface_pair(memif, remote_memif) @@ -234,10 +223,11 @@ class TestMemif(VppTestCase): def _create_icmp(self, pg, memif, num): pkts = [] for i in range(num): - pkt = (Ether(dst=pg.local_mac, src=pg.remote_mac) / - IP(src=pg.remote_ip4, - dst=str(memif.ip_prefix.network_address)) / - ICMP(id=memif.if_id, type='echo-request', seq=i)) + pkt = ( + Ether(dst=pg.local_mac, src=pg.remote_mac) + / IP(src=pg.remote_ip4, dst=str(memif.ip_prefix.network_address)) + / ICMP(id=memif.if_id, type="echo-request", seq=i) + ) pkts.append(pkt) return pkts @@ -252,22 +242,25 @@ class TestMemif(VppTestCase): self.assertEqual(icmp.seq, seq) def test_memif_ping(self): - """ Memif ping """ + """Memif ping""" memif = VppMemif( self, VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_SLAVE, - VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET) + VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET, + ) - remote_socket = VppSocketFilename(self.remote_test, 1, - "%s/memif.sock" % self.tempdir) + remote_socket = VppSocketFilename( + self.remote_test, 1, "%s/memif.sock" % self.tempdir + ) remote_socket.add_vpp_config() remote_memif = VppMemif( self.remote_test, VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_MASTER, VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET, - socket_id=1) + socket_id=1, + ) memif.add_vpp_config() memif.config_ip4() @@ -281,10 +274,13 @@ class TestMemif(VppTestCase): self.assertTrue(remote_memif.wait_for_link_up(5)) # add routing to remote vpp - route = VppIpRoute(self.remote_test, self.pg0._local_ip4_subnet, 24, - [VppRoutePath(memif.ip_prefix.network_address, - 0xffffffff)], - register=False) + route = VppIpRoute( + self.remote_test, + self.pg0._local_ip4_subnet, + 24, + [VppRoutePath(memif.ip_prefix.network_address, 0xFFFFFFFF)], + register=False, + ) route.add_vpp_config() @@ -304,17 +300,19 @@ class TestMemif(VppTestCase): route.remove_vpp_config() def test_memif_admin_up_down_up(self): - """ Memif admin up/down/up """ + """Memif admin up/down/up""" memif = VppMemif( self, VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_SLAVE, VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET, ring_size=1024, buffer_size=2048, - secret="abc") + secret="abc", + ) - remote_socket = VppSocketFilename(self.remote_test, 1, - "%s/memif.sock" % self.tempdir) + remote_socket = VppSocketFilename( + self.remote_test, 1, "%s/memif.sock" % self.tempdir + ) remote_socket.add_vpp_config() remote_memif = VppMemif( @@ -324,7 +322,8 @@ class TestMemif(VppTestCase): socket_id=1, ring_size=1024, buffer_size=2048, - secret="abc") + secret="abc", + ) memif.add_vpp_config() remote_memif.add_vpp_config() @@ -344,5 +343,5 @@ class TestMemif(VppTestCase): remote_socket.remove_vpp_config() -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_mpcap.py b/test/test_mpcap.py index bfa4385ed1a..e075214a202 100644 --- a/test/test_mpcap.py +++ b/test/test_mpcap.py @@ -8,7 +8,7 @@ import os class TestMpcap(VppTestCase): - """ Mpcap Unit Test Cases """ + """Mpcap Unit Test Cases""" @classmethod def setUpClass(cls): @@ -25,22 +25,24 @@ class TestMpcap(VppTestCase): super(TestMpcap, self).tearDown() def test_mpcap_unittest(self): - """ Mapped pcap file test """ - cmds = ["packet-generator new {\n" - " name mpcap\n" - " limit 15\n" - " size 128-128\n" - " interface local0\n" - " node mpcap-unittest\n" - " data {\n" - " IP6: 00:d0:2d:5e:86:85 -> 00:0d:ea:d0:00:00\n" - " ICMP: db00::1 -> db00::2\n" - " incrementing 30\n" - " }\n", - "trace add pg-input 15", - "pa en", - "show trace", - "show error"] + """Mapped pcap file test""" + cmds = [ + "packet-generator new {\n" + " name mpcap\n" + " limit 15\n" + " size 128-128\n" + " interface local0\n" + " node mpcap-unittest\n" + " data {\n" + " IP6: 00:d0:2d:5e:86:85 -> 00:0d:ea:d0:00:00\n" + " ICMP: db00::1 -> db00::2\n" + " incrementing 30\n" + " }\n", + "trace add pg-input 15", + "pa en", + "show trace", + "show error", + ] for cmd in cmds: self.logger.info(self.vapi.cli(cmd)) @@ -49,7 +51,8 @@ class TestMpcap(VppTestCase): os.remove("/tmp/mpcap_unittest.pcap") if size != 2184: self.logger.critical("BUG: file size %d not 2184" % size) - self.assertNotIn('WrongMPCAPFileSize', 'WrongMPCAPFileSize') + self.assertNotIn("WrongMPCAPFileSize", "WrongMPCAPFileSize") -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_mpls.py b/test/test_mpls.py index a568f849aed..6e01a03aea1 100644 --- a/test/test_mpls.py +++ b/test/test_mpls.py @@ -6,11 +6,24 @@ import socket from framework import tag_fixme_vpp_workers from framework import VppTestCase, VppTestRunner from vpp_ip import DpoProto, INVALID_INDEX -from vpp_ip_route import VppIpRoute, VppRoutePath, VppMplsRoute, \ - VppMplsIpBind, VppIpMRoute, VppMRoutePath, \ - VppIpTable, VppMplsTable, \ - VppMplsLabel, MplsLspMode, find_mpls_route, \ - FibPathProto, FibPathType, FibPathFlags, VppMplsLabel, MplsLspMode +from vpp_ip_route import ( + VppIpRoute, + VppRoutePath, + VppMplsRoute, + VppMplsIpBind, + VppIpMRoute, + VppMRoutePath, + VppIpTable, + VppMplsTable, + VppMplsLabel, + MplsLspMode, + find_mpls_route, + FibPathProto, + FibPathType, + FibPathFlags, + VppMplsLabel, + MplsLspMode, +) from vpp_mpls_tunnel_interface import VppMPLSTunnelInterface from vpp_papi import VppEnum @@ -18,8 +31,12 @@ import scapy.compat from scapy.packet import Raw from scapy.layers.l2 import Ether, ARP from scapy.layers.inet import IP, UDP, ICMP, icmptypes, icmpcodes -from scapy.layers.inet6 import IPv6, ICMPv6TimeExceeded, ICMPv6EchoRequest, \ - ICMPv6PacketTooBig +from scapy.layers.inet6 import ( + IPv6, + ICMPv6TimeExceeded, + ICMPv6EchoRequest, + ICMPv6PacketTooBig, +) from scapy.contrib.mpls import MPLS NUM_PKTS = 67 @@ -63,7 +80,7 @@ def verify_mpls_stack(tst, rx, mpls_labels): @tag_fixme_vpp_workers class TestMPLS(VppTestCase): - """ MPLS Test Case """ + """MPLS Test Case""" @classmethod def setUpClass(cls): @@ -120,15 +137,16 @@ class TestMPLS(VppTestCase): # the default of 64 matches the IP packet TTL default def create_stream_labelled_ip4( - self, - src_if, - mpls_labels, - ping=0, - ip_itf=None, - dst_ip=None, - chksum=None, - ip_ttl=64, - n=257): + self, + src_if, + mpls_labels, + ping=0, + ip_itf=None, + dst_ip=None, + chksum=None, + ip_ttl=64, + n=257, + ): self.reset_packet_infos() pkts = [] for i in range(0, n): @@ -137,25 +155,32 @@ class TestMPLS(VppTestCase): p = Ether(dst=src_if.local_mac, src=src_if.remote_mac) for ii in range(len(mpls_labels)): - p = p / MPLS(label=mpls_labels[ii].value, - ttl=mpls_labels[ii].ttl, - cos=mpls_labels[ii].exp) + p = p / MPLS( + label=mpls_labels[ii].value, + ttl=mpls_labels[ii].ttl, + cos=mpls_labels[ii].exp, + ) if not ping: if not dst_ip: - p = (p / IP(src=src_if.local_ip4, - dst=src_if.remote_ip4, - ttl=ip_ttl) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + p + / IP(src=src_if.local_ip4, dst=src_if.remote_ip4, ttl=ip_ttl) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) else: - p = (p / IP(src=src_if.local_ip4, dst=dst_ip, ttl=ip_ttl) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + p + / IP(src=src_if.local_ip4, dst=dst_ip, ttl=ip_ttl) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) else: - p = (p / IP(src=ip_itf.remote_ip4, - dst=ip_itf.local_ip4, - ttl=ip_ttl) / - ICMP()) + p = ( + p + / IP(src=ip_itf.remote_ip4, dst=ip_itf.local_ip4, ttl=ip_ttl) + / ICMP() + ) if chksum: p[IP].chksum = chksum @@ -163,18 +188,20 @@ class TestMPLS(VppTestCase): pkts.append(p) return pkts - def create_stream_ip4(self, src_if, dst_ip, ip_ttl=64, - ip_dscp=0, payload_size=None): + def create_stream_ip4( + self, src_if, dst_ip, ip_ttl=64, ip_dscp=0, payload_size=None + ): self.reset_packet_infos() pkts = [] for i in range(0, 257): info = self.create_packet_info(src_if, src_if) payload = self.info_to_payload(info) - p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - IP(src=src_if.remote_ip4, dst=dst_ip, - ttl=ip_ttl, tos=ip_dscp) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / IP(src=src_if.remote_ip4, dst=dst_ip, ttl=ip_ttl, tos=ip_dscp) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) info.data = p.copy() if payload_size: self.extend_packet(p, payload_size) @@ -187,18 +214,19 @@ class TestMPLS(VppTestCase): for i in range(0, 257): info = self.create_packet_info(src_if, src_if) payload = self.info_to_payload(info) - p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - IPv6(src=src_if.remote_ip6, dst=dst_ip, - hlim=ip_ttl, tc=ip_dscp) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / IPv6(src=src_if.remote_ip6, dst=dst_ip, hlim=ip_ttl, tc=ip_dscp) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) info.data = p.copy() pkts.append(p) return pkts - def create_stream_labelled_ip6(self, src_if, mpls_labels, - hlim=64, dst_ip=None, - ping=0, ip_itf=None): + def create_stream_labelled_ip6( + self, src_if, mpls_labels, hlim=64, dst_ip=None, ping=0, ip_itf=None + ): if dst_ip is None: dst_ip = src_if.remote_ip6 self.reset_packet_infos() @@ -211,19 +239,23 @@ class TestMPLS(VppTestCase): p = p / MPLS(label=l.value, ttl=l.ttl, cos=l.exp) if ping: - p = p / (IPv6(src=ip_itf.remote_ip6, - dst=ip_itf.local_ip6) / - ICMPv6EchoRequest()) + p = p / ( + IPv6(src=ip_itf.remote_ip6, dst=ip_itf.local_ip6) + / ICMPv6EchoRequest() + ) else: - p = p / (IPv6(src=src_if.remote_ip6, dst=dst_ip, hlim=hlim) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = p / ( + IPv6(src=src_if.remote_ip6, dst=dst_ip, hlim=hlim) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) info.data = p.copy() pkts.append(p) return pkts - def verify_capture_ip4(self, src_if, capture, sent, ping_resp=0, - ip_ttl=None, ip_dscp=0): + def verify_capture_ip4( + self, src_if, capture, sent, ping_resp=0, ip_ttl=None, ip_dscp=0 + ): try: capture = verify_filter(capture, sent) @@ -256,8 +288,9 @@ class TestMPLS(VppTestCase): except: raise - def verify_capture_labelled_ip4(self, src_if, capture, sent, - mpls_labels, ip_ttl=None): + def verify_capture_labelled_ip4( + self, src_if, capture, sent, mpls_labels, ip_ttl=None + ): try: capture = verify_filter(capture, sent) @@ -282,8 +315,9 @@ class TestMPLS(VppTestCase): except: raise - def verify_capture_labelled_ip6(self, src_if, capture, sent, - mpls_labels, ip_ttl=None): + def verify_capture_labelled_ip6( + self, src_if, capture, sent, mpls_labels, ip_ttl=None + ): try: capture = verify_filter(capture, sent) @@ -330,8 +364,7 @@ class TestMPLS(VppTestCase): except: raise - def verify_capture_labelled(self, src_if, capture, sent, - mpls_labels): + def verify_capture_labelled(self, src_if, capture, sent, mpls_labels): try: capture = verify_filter(capture, sent) @@ -343,9 +376,9 @@ class TestMPLS(VppTestCase): except: raise - def verify_capture_ip6(self, src_if, capture, sent, - ip_hlim=None, ip_dscp=0, - ping_resp=0): + def verify_capture_ip6( + self, src_if, capture, sent, ip_hlim=None, ip_dscp=0, ping_resp=0 + ): try: self.assertEqual(len(capture), len(sent)) @@ -363,7 +396,7 @@ class TestMPLS(VppTestCase): if not ping_resp: self.assertEqual(rx_ip.src, tx_ip.src) self.assertEqual(rx_ip.dst, tx_ip.dst) - self.assertEqual(rx_ip.tc, ip_dscp) + self.assertEqual(rx_ip.tc, ip_dscp) # IP processing post pop has decremented the TTL if not ip_hlim: self.assertEqual(rx_ip.hlim + 1, tx_ip.hlim) @@ -402,8 +435,9 @@ class TestMPLS(VppTestCase): except: raise - def verify_capture_fragmented_labelled_ip4(self, src_if, capture, sent, - mpls_labels, ip_ttl=None): + def verify_capture_fragmented_labelled_ip4( + self, src_if, capture, sent, mpls_labels, ip_ttl=None + ): try: capture = verify_filter(capture, sent) @@ -426,8 +460,9 @@ class TestMPLS(VppTestCase): except: raise - def verify_capture_fragmented_labelled_ip6(self, src_if, capture, sent, - mpls_labels, ip_ttl=None): + def verify_capture_fragmented_labelled_ip6( + self, src_if, capture, sent, mpls_labels, ip_ttl=None + ): try: capture = verify_filter(capture, sent) @@ -452,82 +487,115 @@ class TestMPLS(VppTestCase): raise def test_swap(self): - """ MPLS label swap tests """ + """MPLS label swap tests""" # # A simple MPLS xconnect - eos label in label out # - route_32_eos = VppMplsRoute(self, 32, 1, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index, - labels=[VppMplsLabel(33)])]) + route_32_eos = VppMplsRoute( + self, + 32, + 1, + [ + VppRoutePath( + self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[VppMplsLabel(33)] + ) + ], + ) route_32_eos.add_vpp_config() self.assertTrue( - find_mpls_route(self, 0, 32, 1, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index, - labels=[VppMplsLabel(33)])])) + find_mpls_route( + self, + 0, + 32, + 1, + [ + VppRoutePath( + self.pg0.remote_ip4, + self.pg0.sw_if_index, + labels=[VppMplsLabel(33)], + ) + ], + ) + ) # # a stream that matches the route for 10.0.0.1 # PG0 is in the default table # - tx = self.create_stream_labelled_ip4(self.pg0, - [VppMplsLabel(32, ttl=32, exp=1)]) + tx = self.create_stream_labelled_ip4( + self.pg0, [VppMplsLabel(32, ttl=32, exp=1)] + ) rx = self.send_and_expect(self.pg0, tx, self.pg0) - self.verify_capture_labelled(self.pg0, rx, tx, - [VppMplsLabel(33, ttl=31, exp=1)]) + self.verify_capture_labelled( + self.pg0, rx, tx, [VppMplsLabel(33, ttl=31, exp=1)] + ) - self.assertEqual(route_32_eos.get_stats_to()['packets'], 257) + self.assertEqual(route_32_eos.get_stats_to()["packets"], 257) # # A simple MPLS xconnect - non-eos label in label out # - route_32_neos = VppMplsRoute(self, 32, 0, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index, - labels=[VppMplsLabel(33)])]) + route_32_neos = VppMplsRoute( + self, + 32, + 0, + [ + VppRoutePath( + self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[VppMplsLabel(33)] + ) + ], + ) route_32_neos.add_vpp_config() # # a stream that matches the route for 10.0.0.1 # PG0 is in the default table # - tx = self.create_stream_labelled_ip4(self.pg0, - [VppMplsLabel(32, ttl=21, exp=7), - VppMplsLabel(99)]) + tx = self.create_stream_labelled_ip4( + self.pg0, [VppMplsLabel(32, ttl=21, exp=7), VppMplsLabel(99)] + ) rx = self.send_and_expect(self.pg0, tx, self.pg0) - self.verify_capture_labelled(self.pg0, rx, tx, - [VppMplsLabel(33, ttl=20, exp=7), - VppMplsLabel(99)]) - self.assertEqual(route_32_neos.get_stats_to()['packets'], 257) + self.verify_capture_labelled( + self.pg0, rx, tx, [VppMplsLabel(33, ttl=20, exp=7), VppMplsLabel(99)] + ) + self.assertEqual(route_32_neos.get_stats_to()["packets"], 257) # # A simple MPLS xconnect - non-eos label in label out, uniform mode # route_42_neos = VppMplsRoute( - self, 42, 0, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index, - labels=[VppMplsLabel(43, MplsLspMode.UNIFORM)])]) + self, + 42, + 0, + [ + VppRoutePath( + self.pg0.remote_ip4, + self.pg0.sw_if_index, + labels=[VppMplsLabel(43, MplsLspMode.UNIFORM)], + ) + ], + ) route_42_neos.add_vpp_config() - tx = self.create_stream_labelled_ip4(self.pg0, - [VppMplsLabel(42, ttl=21, exp=7), - VppMplsLabel(99)]) + tx = self.create_stream_labelled_ip4( + self.pg0, [VppMplsLabel(42, ttl=21, exp=7), VppMplsLabel(99)] + ) rx = self.send_and_expect(self.pg0, tx, self.pg0) - self.verify_capture_labelled(self.pg0, rx, tx, - [VppMplsLabel(43, ttl=20, exp=7), - VppMplsLabel(99)]) + self.verify_capture_labelled( + self.pg0, rx, tx, [VppMplsLabel(43, ttl=20, exp=7), VppMplsLabel(99)] + ) # # An MPLS xconnect - EOS label in IP out # - route_33_eos = VppMplsRoute(self, 33, 1, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index, - labels=[])]) + route_33_eos = VppMplsRoute( + self, + 33, + 1, + [VppRoutePath(self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[])], + ) route_33_eos.add_vpp_config() tx = self.create_stream_labelled_ip4(self.pg0, [VppMplsLabel(33)]) @@ -537,30 +605,36 @@ class TestMPLS(VppTestCase): # # disposed packets have an invalid IPv4 checksum # - tx = self.create_stream_labelled_ip4(self.pg0, [VppMplsLabel(33)], - dst_ip=self.pg0.remote_ip4, - n=65, - chksum=1) + tx = self.create_stream_labelled_ip4( + self.pg0, [VppMplsLabel(33)], dst_ip=self.pg0.remote_ip4, n=65, chksum=1 + ) self.send_and_assert_no_replies(self.pg0, tx, "Invalid Checksum") # # An MPLS xconnect - EOS label in IP out, uniform mode # route_3333_eos = VppMplsRoute( - self, 3333, 1, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index, - labels=[VppMplsLabel(3, MplsLspMode.UNIFORM)])]) + self, + 3333, + 1, + [ + VppRoutePath( + self.pg0.remote_ip4, + self.pg0.sw_if_index, + labels=[VppMplsLabel(3, MplsLspMode.UNIFORM)], + ) + ], + ) route_3333_eos.add_vpp_config() tx = self.create_stream_labelled_ip4( - self.pg0, - [VppMplsLabel(3333, ttl=55, exp=3)]) + self.pg0, [VppMplsLabel(3333, ttl=55, exp=3)] + ) rx = self.send_and_expect(self.pg0, tx, self.pg0) self.verify_capture_ip4(self.pg0, rx, tx, ip_ttl=54, ip_dscp=0x60) tx = self.create_stream_labelled_ip4( - self.pg0, - [VppMplsLabel(3333, ttl=66, exp=4)]) + self.pg0, [VppMplsLabel(3333, ttl=66, exp=4)] + ) rx = self.send_and_expect(self.pg0, tx, self.pg0) self.verify_capture_ip4(self.pg0, rx, tx, ip_ttl=65, ip_dscp=0x80) @@ -568,11 +642,12 @@ class TestMPLS(VppTestCase): # An MPLS xconnect - EOS label in IPv6 out # route_333_eos = VppMplsRoute( - self, 333, 1, - [VppRoutePath(self.pg0.remote_ip6, - self.pg0.sw_if_index, - labels=[])], - eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP6) + self, + 333, + 1, + [VppRoutePath(self.pg0.remote_ip6, self.pg0.sw_if_index, labels=[])], + eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ) route_333_eos.add_vpp_config() tx = self.create_stream_labelled_ip6(self.pg0, [VppMplsLabel(333)]) @@ -582,10 +657,9 @@ class TestMPLS(VppTestCase): # # disposed packets have an TTL expired # - tx = self.create_stream_labelled_ip6(self.pg0, - [VppMplsLabel(333, ttl=64)], - dst_ip=self.pg1.remote_ip6, - hlim=1) + tx = self.create_stream_labelled_ip6( + self.pg0, [VppMplsLabel(333, ttl=64)], dst_ip=self.pg1.remote_ip6, hlim=1 + ) rx = self.send_and_expect_some(self.pg0, tx, self.pg0) self.verify_capture_ip6_icmp(self.pg0, rx, tx) @@ -593,15 +667,19 @@ class TestMPLS(VppTestCase): # An MPLS xconnect - EOS label in IPv6 out w imp-null # route_334_eos = VppMplsRoute( - self, 334, 1, - [VppRoutePath(self.pg0.remote_ip6, - self.pg0.sw_if_index, - labels=[VppMplsLabel(3)])], - eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP6) + self, + 334, + 1, + [ + VppRoutePath( + self.pg0.remote_ip6, self.pg0.sw_if_index, labels=[VppMplsLabel(3)] + ) + ], + eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ) route_334_eos.add_vpp_config() - tx = self.create_stream_labelled_ip6(self.pg0, - [VppMplsLabel(334, ttl=64)]) + tx = self.create_stream_labelled_ip6(self.pg0, [VppMplsLabel(334, ttl=64)]) rx = self.send_and_expect(self.pg0, tx, self.pg0) self.verify_capture_ip6(self.pg0, rx, tx) @@ -609,25 +687,32 @@ class TestMPLS(VppTestCase): # An MPLS xconnect - EOS label in IPv6 out w imp-null in uniform mode # route_335_eos = VppMplsRoute( - self, 335, 1, - [VppRoutePath(self.pg0.remote_ip6, - self.pg0.sw_if_index, - labels=[VppMplsLabel(3, MplsLspMode.UNIFORM)])], - eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP6) + self, + 335, + 1, + [ + VppRoutePath( + self.pg0.remote_ip6, + self.pg0.sw_if_index, + labels=[VppMplsLabel(3, MplsLspMode.UNIFORM)], + ) + ], + eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ) route_335_eos.add_vpp_config() tx = self.create_stream_labelled_ip6( - self.pg0, - [VppMplsLabel(335, ttl=27, exp=4)]) + self.pg0, [VppMplsLabel(335, ttl=27, exp=4)] + ) rx = self.send_and_expect(self.pg0, tx, self.pg0) self.verify_capture_ip6(self.pg0, rx, tx, ip_hlim=26, ip_dscp=0x80) # # disposed packets have an TTL expired # - tx = self.create_stream_labelled_ip6(self.pg0, [VppMplsLabel(334)], - dst_ip=self.pg1.remote_ip6, - hlim=0) + tx = self.create_stream_labelled_ip6( + self.pg0, [VppMplsLabel(334)], dst_ip=self.pg1.remote_ip6, hlim=0 + ) rx = self.send_and_expect_some(self.pg0, tx, self.pg0) self.verify_capture_ip6_icmp(self.pg0, rx, tx) @@ -635,104 +720,136 @@ class TestMPLS(VppTestCase): # An MPLS xconnect - non-EOS label in IP out - an invalid configuration # so this traffic should be dropped. # - route_33_neos = VppMplsRoute(self, 33, 0, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index, - labels=[])]) + route_33_neos = VppMplsRoute( + self, + 33, + 0, + [VppRoutePath(self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[])], + ) route_33_neos.add_vpp_config() - tx = self.create_stream_labelled_ip4(self.pg0, - [VppMplsLabel(33), - VppMplsLabel(99)]) + tx = self.create_stream_labelled_ip4( + self.pg0, [VppMplsLabel(33), VppMplsLabel(99)] + ) self.send_and_assert_no_replies( - self.pg0, tx, - "MPLS non-EOS packets popped and forwarded") + self.pg0, tx, "MPLS non-EOS packets popped and forwarded" + ) # # A recursive EOS x-connect, which resolves through another x-connect # in pipe mode # - route_34_eos = VppMplsRoute(self, 34, 1, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_via_label=32, - labels=[VppMplsLabel(44), - VppMplsLabel(45)])]) + route_34_eos = VppMplsRoute( + self, + 34, + 1, + [ + VppRoutePath( + "0.0.0.0", + 0xFFFFFFFF, + nh_via_label=32, + labels=[VppMplsLabel(44), VppMplsLabel(45)], + ) + ], + ) route_34_eos.add_vpp_config() self.logger.info(self.vapi.cli("sh mpls fib 34")) - tx = self.create_stream_labelled_ip4(self.pg0, - [VppMplsLabel(34, ttl=3)]) + tx = self.create_stream_labelled_ip4(self.pg0, [VppMplsLabel(34, ttl=3)]) rx = self.send_and_expect(self.pg0, tx, self.pg0) - self.verify_capture_labelled(self.pg0, rx, tx, - [VppMplsLabel(33), - VppMplsLabel(44), - VppMplsLabel(45, ttl=2)]) + self.verify_capture_labelled( + self.pg0, + rx, + tx, + [VppMplsLabel(33), VppMplsLabel(44), VppMplsLabel(45, ttl=2)], + ) - self.assertEqual(route_34_eos.get_stats_to()['packets'], 257) - self.assertEqual(route_32_neos.get_stats_via()['packets'], 257) + self.assertEqual(route_34_eos.get_stats_to()["packets"], 257) + self.assertEqual(route_32_neos.get_stats_via()["packets"], 257) # # A recursive EOS x-connect, which resolves through another x-connect # in uniform mode # route_35_eos = VppMplsRoute( - self, 35, 1, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_via_label=42, - labels=[VppMplsLabel(44)])]) + self, + 35, + 1, + [ + VppRoutePath( + "0.0.0.0", 0xFFFFFFFF, nh_via_label=42, labels=[VppMplsLabel(44)] + ) + ], + ) route_35_eos.add_vpp_config() - tx = self.create_stream_labelled_ip4(self.pg0, - [VppMplsLabel(35, ttl=3)]) + tx = self.create_stream_labelled_ip4(self.pg0, [VppMplsLabel(35, ttl=3)]) rx = self.send_and_expect(self.pg0, tx, self.pg0) - self.verify_capture_labelled(self.pg0, rx, tx, - [VppMplsLabel(43, ttl=2), - VppMplsLabel(44, ttl=2)]) + self.verify_capture_labelled( + self.pg0, rx, tx, [VppMplsLabel(43, ttl=2), VppMplsLabel(44, ttl=2)] + ) # # A recursive non-EOS x-connect, which resolves through another # x-connect # - route_34_neos = VppMplsRoute(self, 34, 0, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_via_label=32, - labels=[VppMplsLabel(44), - VppMplsLabel(46)])]) + route_34_neos = VppMplsRoute( + self, + 34, + 0, + [ + VppRoutePath( + "0.0.0.0", + 0xFFFFFFFF, + nh_via_label=32, + labels=[VppMplsLabel(44), VppMplsLabel(46)], + ) + ], + ) route_34_neos.add_vpp_config() - tx = self.create_stream_labelled_ip4(self.pg0, - [VppMplsLabel(34, ttl=45), - VppMplsLabel(99)]) + tx = self.create_stream_labelled_ip4( + self.pg0, [VppMplsLabel(34, ttl=45), VppMplsLabel(99)] + ) rx = self.send_and_expect(self.pg0, tx, self.pg0) # it's the 2nd (counting from 0) label in the stack that is swapped - self.verify_capture_labelled(self.pg0, rx, tx, - [VppMplsLabel(33), - VppMplsLabel(44), - VppMplsLabel(46, ttl=44), - VppMplsLabel(99)]) + self.verify_capture_labelled( + self.pg0, + rx, + tx, + [ + VppMplsLabel(33), + VppMplsLabel(44), + VppMplsLabel(46, ttl=44), + VppMplsLabel(99), + ], + ) # # an recursive IP route that resolves through the recursive non-eos # x-connect # - ip_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_via_label=34, - labels=[VppMplsLabel(55)])]) + ip_10_0_0_1 = VppIpRoute( + self, + "10.0.0.1", + 32, + [ + VppRoutePath( + "0.0.0.0", 0xFFFFFFFF, nh_via_label=34, labels=[VppMplsLabel(55)] + ) + ], + ) ip_10_0_0_1.add_vpp_config() tx = self.create_stream_ip4(self.pg0, "10.0.0.1") rx = self.send_and_expect(self.pg0, tx, self.pg0) - self.verify_capture_labelled_ip4(self.pg0, rx, tx, - [VppMplsLabel(33), - VppMplsLabel(44), - VppMplsLabel(46), - VppMplsLabel(55)]) - self.assertEqual(ip_10_0_0_1.get_stats_to()['packets'], 257) + self.verify_capture_labelled_ip4( + self.pg0, + rx, + tx, + [VppMplsLabel(33), VppMplsLabel(44), VppMplsLabel(46), VppMplsLabel(55)], + ) + self.assertEqual(ip_10_0_0_1.get_stats_to()["packets"], 257) ip_10_0_0_1.remove_vpp_config() route_34_neos.remove_vpp_config() @@ -743,15 +860,21 @@ class TestMPLS(VppTestCase): route_32_eos.remove_vpp_config() def test_bind(self): - """ MPLS Local Label Binding test """ + """MPLS Local Label Binding test""" # # Add a non-recursive route with a single out label # - route_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index, - labels=[VppMplsLabel(45)])]) + route_10_0_0_1 = VppIpRoute( + self, + "10.0.0.1", + 32, + [ + VppRoutePath( + self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[VppMplsLabel(45)] + ) + ], + ) route_10_0_0_1.add_vpp_config() # bind a local label to the route @@ -759,19 +882,18 @@ class TestMPLS(VppTestCase): binding.add_vpp_config() # non-EOS stream - tx = self.create_stream_labelled_ip4(self.pg0, - [VppMplsLabel(44), - VppMplsLabel(99)]) + tx = self.create_stream_labelled_ip4( + self.pg0, [VppMplsLabel(44), VppMplsLabel(99)] + ) rx = self.send_and_expect(self.pg0, tx, self.pg0) - self.verify_capture_labelled(self.pg0, rx, tx, - [VppMplsLabel(45, ttl=63), - VppMplsLabel(99)]) + self.verify_capture_labelled( + self.pg0, rx, tx, [VppMplsLabel(45, ttl=63), VppMplsLabel(99)] + ) # EOS stream tx = self.create_stream_labelled_ip4(self.pg0, [VppMplsLabel(44)]) rx = self.send_and_expect(self.pg0, tx, self.pg0) - self.verify_capture_labelled(self.pg0, rx, tx, - [VppMplsLabel(45, ttl=63)]) + self.verify_capture_labelled(self.pg0, rx, tx, [VppMplsLabel(45, ttl=63)]) # IP stream tx = self.create_stream_ip4(self.pg0, "10.0.0.1") @@ -785,15 +907,21 @@ class TestMPLS(VppTestCase): route_10_0_0_1.remove_vpp_config() def test_imposition(self): - """ MPLS label imposition test """ + """MPLS label imposition test""" # # Add a non-recursive route with a single out label # - route_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index, - labels=[VppMplsLabel(32)])]) + route_10_0_0_1 = VppIpRoute( + self, + "10.0.0.1", + 32, + [ + VppRoutePath( + self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[VppMplsLabel(32)] + ) + ], + ) route_10_0_0_1.add_vpp_config() # @@ -807,65 +935,86 @@ class TestMPLS(VppTestCase): # # Add a non-recursive route with a 3 out labels # - route_10_0_0_2 = VppIpRoute(self, "10.0.0.2", 32, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index, - labels=[VppMplsLabel(32), - VppMplsLabel(33), - VppMplsLabel(34)])]) + route_10_0_0_2 = VppIpRoute( + self, + "10.0.0.2", + 32, + [ + VppRoutePath( + self.pg0.remote_ip4, + self.pg0.sw_if_index, + labels=[VppMplsLabel(32), VppMplsLabel(33), VppMplsLabel(34)], + ) + ], + ) route_10_0_0_2.add_vpp_config() - tx = self.create_stream_ip4(self.pg0, "10.0.0.2", - ip_ttl=44, ip_dscp=0xff) + tx = self.create_stream_ip4(self.pg0, "10.0.0.2", ip_ttl=44, ip_dscp=0xFF) rx = self.send_and_expect(self.pg0, tx, self.pg0) - self.verify_capture_labelled_ip4(self.pg0, rx, tx, - [VppMplsLabel(32), - VppMplsLabel(33), - VppMplsLabel(34)], - ip_ttl=43) + self.verify_capture_labelled_ip4( + self.pg0, + rx, + tx, + [VppMplsLabel(32), VppMplsLabel(33), VppMplsLabel(34)], + ip_ttl=43, + ) # # Add a non-recursive route with a single out label in uniform mode # route_10_0_0_3 = VppIpRoute( - self, "10.0.0.3", 32, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index, - labels=[VppMplsLabel(32, - mode=MplsLspMode.UNIFORM)])]) + self, + "10.0.0.3", + 32, + [ + VppRoutePath( + self.pg0.remote_ip4, + self.pg0.sw_if_index, + labels=[VppMplsLabel(32, mode=MplsLspMode.UNIFORM)], + ) + ], + ) route_10_0_0_3.add_vpp_config() - tx = self.create_stream_ip4(self.pg0, "10.0.0.3", - ip_ttl=54, ip_dscp=0xbe) + tx = self.create_stream_ip4(self.pg0, "10.0.0.3", ip_ttl=54, ip_dscp=0xBE) rx = self.send_and_expect(self.pg0, tx, self.pg0) - self.verify_capture_labelled_ip4(self.pg0, rx, tx, - [VppMplsLabel(32, ttl=53, exp=5)]) + self.verify_capture_labelled_ip4( + self.pg0, rx, tx, [VppMplsLabel(32, ttl=53, exp=5)] + ) # # Add a IPv6 non-recursive route with a single out label in # uniform mode # route_2001_3 = VppIpRoute( - self, "2001::3", 128, - [VppRoutePath(self.pg0.remote_ip6, - self.pg0.sw_if_index, - labels=[VppMplsLabel(32, - mode=MplsLspMode.UNIFORM)])]) + self, + "2001::3", + 128, + [ + VppRoutePath( + self.pg0.remote_ip6, + self.pg0.sw_if_index, + labels=[VppMplsLabel(32, mode=MplsLspMode.UNIFORM)], + ) + ], + ) route_2001_3.add_vpp_config() - tx = self.create_stream_ip6(self.pg0, "2001::3", - ip_ttl=54, ip_dscp=0xbe) + tx = self.create_stream_ip6(self.pg0, "2001::3", ip_ttl=54, ip_dscp=0xBE) rx = self.send_and_expect(self.pg0, tx, self.pg0) - self.verify_capture_labelled_ip6(self.pg0, rx, tx, - [VppMplsLabel(32, ttl=53, exp=5)]) + self.verify_capture_labelled_ip6( + self.pg0, rx, tx, [VppMplsLabel(32, ttl=53, exp=5)] + ) # # add a recursive path, with output label, via the 1 label route # - route_11_0_0_1 = VppIpRoute(self, "11.0.0.1", 32, - [VppRoutePath("10.0.0.1", - 0xffffffff, - labels=[VppMplsLabel(44)])]) + route_11_0_0_1 = VppIpRoute( + self, + "11.0.0.1", + 32, + [VppRoutePath("10.0.0.1", 0xFFFFFFFF, labels=[VppMplsLabel(44)])], + ) route_11_0_0_1.add_vpp_config() # @@ -874,20 +1023,25 @@ class TestMPLS(VppTestCase): # tx = self.create_stream_ip4(self.pg0, "11.0.0.1") rx = self.send_and_expect(self.pg0, tx, self.pg0) - self.verify_capture_labelled_ip4(self.pg0, rx, tx, - [VppMplsLabel(32), - VppMplsLabel(44)]) + self.verify_capture_labelled_ip4( + self.pg0, rx, tx, [VppMplsLabel(32), VppMplsLabel(44)] + ) - self.assertEqual(route_11_0_0_1.get_stats_to()['packets'], 257) + self.assertEqual(route_11_0_0_1.get_stats_to()["packets"], 257) # # add a recursive path, with 2 labels, via the 3 label route # - route_11_0_0_2 = VppIpRoute(self, "11.0.0.2", 32, - [VppRoutePath("10.0.0.2", - 0xffffffff, - labels=[VppMplsLabel(44), - VppMplsLabel(45)])]) + route_11_0_0_2 = VppIpRoute( + self, + "11.0.0.2", + 32, + [ + VppRoutePath( + "10.0.0.2", 0xFFFFFFFF, labels=[VppMplsLabel(44), VppMplsLabel(45)] + ) + ], + ) route_11_0_0_2.add_vpp_config() # @@ -896,24 +1050,36 @@ class TestMPLS(VppTestCase): # tx = self.create_stream_ip4(self.pg0, "11.0.0.2") rx = self.send_and_expect(self.pg0, tx, self.pg0) - self.verify_capture_labelled_ip4(self.pg0, rx, tx, - [VppMplsLabel(32), - VppMplsLabel(33), - VppMplsLabel(34), - VppMplsLabel(44), - VppMplsLabel(45)]) - - self.assertEqual(route_11_0_0_2.get_stats_to()['packets'], 257) + self.verify_capture_labelled_ip4( + self.pg0, + rx, + tx, + [ + VppMplsLabel(32), + VppMplsLabel(33), + VppMplsLabel(34), + VppMplsLabel(44), + VppMplsLabel(45), + ], + ) + + self.assertEqual(route_11_0_0_2.get_stats_to()["packets"], 257) rx = self.send_and_expect(self.pg0, tx, self.pg0) - self.verify_capture_labelled_ip4(self.pg0, rx, tx, - [VppMplsLabel(32), - VppMplsLabel(33), - VppMplsLabel(34), - VppMplsLabel(44), - VppMplsLabel(45)]) + self.verify_capture_labelled_ip4( + self.pg0, + rx, + tx, + [ + VppMplsLabel(32), + VppMplsLabel(33), + VppMplsLabel(34), + VppMplsLabel(44), + VppMplsLabel(45), + ], + ) - self.assertEqual(route_11_0_0_2.get_stats_to()['packets'], 514) + self.assertEqual(route_11_0_0_2.get_stats_to()["packets"], 514) # # cleanup @@ -924,20 +1090,32 @@ class TestMPLS(VppTestCase): route_10_0_0_1.remove_vpp_config() def test_imposition_fragmentation(self): - """ MPLS label imposition fragmentation test """ + """MPLS label imposition fragmentation test""" # # Add a ipv4 non-recursive route with a single out label # - route_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index, - labels=[VppMplsLabel(32)])]) + route_10_0_0_1 = VppIpRoute( + self, + "10.0.0.1", + 32, + [ + VppRoutePath( + self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[VppMplsLabel(32)] + ) + ], + ) route_10_0_0_1.add_vpp_config() - route_1000_1 = VppIpRoute(self, "1000::1", 128, - [VppRoutePath(self.pg0.remote_ip6, - self.pg0.sw_if_index, - labels=[VppMplsLabel(32)])]) + route_1000_1 = VppIpRoute( + self, + "1000::1", + 128, + [ + VppRoutePath( + self.pg0.remote_ip6, self.pg0.sw_if_index, labels=[VppMplsLabel(32)] + ) + ], + ) route_1000_1.add_vpp_config() # @@ -952,24 +1130,29 @@ class TestMPLS(VppTestCase): # 5 fragments per packet (257*5=1285) # rx = self.send_and_expect(self.pg0, tx, self.pg0, 1285) - self.verify_capture_fragmented_labelled_ip4(self.pg0, rx, tx, - [VppMplsLabel(32)]) + self.verify_capture_fragmented_labelled_ip4( + self.pg0, rx, tx, [VppMplsLabel(32)] + ) # packets with DF bit set generate ICMP for t in tx: - t[IP].flags = 'DF' + t[IP].flags = "DF" rxs = self.send_and_expect_some(self.pg0, tx, self.pg0) for rx in rxs: self.assertEqual(icmptypes[rx[ICMP].type], "dest-unreach") - self.assertEqual(icmpcodes[rx[ICMP].type][rx[ICMP].code], - "fragmentation-needed") + self.assertEqual( + icmpcodes[rx[ICMP].type][rx[ICMP].code], "fragmentation-needed" + ) # the link MTU is 9000, the MPLS over head is 4 bytes self.assertEqual(rx[ICMP].nexthopmtu, 9000 - 4) - self.assertEqual(self.statistics.get_err_counter( - "/err/mpls-frag/can't fragment this packet"), - len(tx)) + self.assertEqual( + self.statistics.get_err_counter( + "/err/mpls-frag/can't fragment this packet" + ), + len(tx), + ) # # a stream that matches the route for 1000::1/128 # PG0 is in the default table @@ -988,26 +1171,30 @@ class TestMPLS(VppTestCase): route_10_0_0_1.remove_vpp_config() def test_tunnel_pipe(self): - """ MPLS Tunnel Tests - Pipe """ + """MPLS Tunnel Tests - Pipe""" # # Create a tunnel with two out labels # mpls_tun = VppMPLSTunnelInterface( self, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index, - labels=[VppMplsLabel(44), - VppMplsLabel(46)])]) + [ + VppRoutePath( + self.pg0.remote_ip4, + self.pg0.sw_if_index, + labels=[VppMplsLabel(44), VppMplsLabel(46)], + ) + ], + ) mpls_tun.add_vpp_config() mpls_tun.admin_up() # # add an unlabelled route through the new tunnel # - route_10_0_0_3 = VppIpRoute(self, "10.0.0.3", 32, - [VppRoutePath("0.0.0.0", - mpls_tun._sw_if_index)]) + route_10_0_0_3 = VppIpRoute( + self, "10.0.0.3", 32, [VppRoutePath("0.0.0.0", mpls_tun._sw_if_index)] + ) route_10_0_0_3.add_vpp_config() self.vapi.cli("clear trace") @@ -1018,17 +1205,19 @@ class TestMPLS(VppTestCase): self.pg_start() rx = self.pg0.get_capture() - self.verify_capture_tunneled_ip4(self.pg0, rx, tx, - [VppMplsLabel(44), - VppMplsLabel(46)]) + self.verify_capture_tunneled_ip4( + self.pg0, rx, tx, [VppMplsLabel(44), VppMplsLabel(46)] + ) # # add a labelled route through the new tunnel # - route_10_0_0_4 = VppIpRoute(self, "10.0.0.4", 32, - [VppRoutePath("0.0.0.0", - mpls_tun._sw_if_index, - labels=[33])]) + route_10_0_0_4 = VppIpRoute( + self, + "10.0.0.4", + 32, + [VppRoutePath("0.0.0.0", mpls_tun._sw_if_index, labels=[33])], + ) route_10_0_0_4.add_vpp_config() self.vapi.cli("clear trace") @@ -1039,10 +1228,12 @@ class TestMPLS(VppTestCase): self.pg_start() rx = self.pg0.get_capture() - self.verify_capture_tunneled_ip4(self.pg0, rx, tx, - [VppMplsLabel(44), - VppMplsLabel(46), - VppMplsLabel(33, ttl=255)]) + self.verify_capture_tunneled_ip4( + self.pg0, + rx, + tx, + [VppMplsLabel(44), VppMplsLabel(46), VppMplsLabel(33, ttl=255)], + ) # # change tunnel's MTU to a low value @@ -1050,34 +1241,34 @@ class TestMPLS(VppTestCase): mpls_tun.set_l3_mtu(1200) # send IP into the tunnel to be fragmented - tx = self.create_stream_ip4(self.pg0, "10.0.0.3", - payload_size=1500) - rx = self.send_and_expect(self.pg0, tx, self.pg0, len(tx)*2) + tx = self.create_stream_ip4(self.pg0, "10.0.0.3", payload_size=1500) + rx = self.send_and_expect(self.pg0, tx, self.pg0, len(tx) * 2) fake_tx = [] for p in tx: fake_tx.append(p) fake_tx.append(p) - self.verify_capture_tunneled_ip4(self.pg0, rx, fake_tx, - [VppMplsLabel(44), - VppMplsLabel(46)]) + self.verify_capture_tunneled_ip4( + self.pg0, rx, fake_tx, [VppMplsLabel(44), VppMplsLabel(46)] + ) # send MPLS into the tunnel to be fragmented - tx = self.create_stream_ip4(self.pg0, "10.0.0.4", - payload_size=1500) - rx = self.send_and_expect(self.pg0, tx, self.pg0, len(tx)*2) + tx = self.create_stream_ip4(self.pg0, "10.0.0.4", payload_size=1500) + rx = self.send_and_expect(self.pg0, tx, self.pg0, len(tx) * 2) fake_tx = [] for p in tx: fake_tx.append(p) fake_tx.append(p) - self.verify_capture_tunneled_ip4(self.pg0, rx, fake_tx, - [VppMplsLabel(44), - VppMplsLabel(46), - VppMplsLabel(33, ttl=255)]) + self.verify_capture_tunneled_ip4( + self.pg0, + rx, + fake_tx, + [VppMplsLabel(44), VppMplsLabel(46), VppMplsLabel(33, ttl=255)], + ) def test_tunnel_uniform(self): - """ MPLS Tunnel Tests - Uniform """ + """MPLS Tunnel Tests - Uniform""" # # Create a tunnel with a single out label @@ -1085,19 +1276,26 @@ class TestMPLS(VppTestCase): # mpls_tun = VppMPLSTunnelInterface( self, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index, - labels=[VppMplsLabel(44, ttl=32), - VppMplsLabel(46, MplsLspMode.UNIFORM)])]) + [ + VppRoutePath( + self.pg0.remote_ip4, + self.pg0.sw_if_index, + labels=[ + VppMplsLabel(44, ttl=32), + VppMplsLabel(46, MplsLspMode.UNIFORM), + ], + ) + ], + ) mpls_tun.add_vpp_config() mpls_tun.admin_up() # # add an unlabelled route through the new tunnel # - route_10_0_0_3 = VppIpRoute(self, "10.0.0.3", 32, - [VppRoutePath("0.0.0.0", - mpls_tun._sw_if_index)]) + route_10_0_0_3 = VppIpRoute( + self, "10.0.0.3", 32, [VppRoutePath("0.0.0.0", mpls_tun._sw_if_index)] + ) route_10_0_0_3.add_vpp_config() self.vapi.cli("clear trace") @@ -1108,18 +1306,23 @@ class TestMPLS(VppTestCase): self.pg_start() rx = self.pg0.get_capture() - self.verify_capture_tunneled_ip4(self.pg0, rx, tx, - [VppMplsLabel(44, ttl=32), - VppMplsLabel(46, ttl=23)]) + self.verify_capture_tunneled_ip4( + self.pg0, rx, tx, [VppMplsLabel(44, ttl=32), VppMplsLabel(46, ttl=23)] + ) # # add a labelled route through the new tunnel # route_10_0_0_4 = VppIpRoute( - self, "10.0.0.4", 32, - [VppRoutePath("0.0.0.0", - mpls_tun._sw_if_index, - labels=[VppMplsLabel(33, ttl=47)])]) + self, + "10.0.0.4", + 32, + [ + VppRoutePath( + "0.0.0.0", mpls_tun._sw_if_index, labels=[VppMplsLabel(33, ttl=47)] + ) + ], + ) route_10_0_0_4.add_vpp_config() self.vapi.cli("clear trace") @@ -1130,45 +1333,63 @@ class TestMPLS(VppTestCase): self.pg_start() rx = self.pg0.get_capture() - self.verify_capture_tunneled_ip4(self.pg0, rx, tx, - [VppMplsLabel(44, ttl=32), - VppMplsLabel(46, ttl=47), - VppMplsLabel(33, ttl=47)]) + self.verify_capture_tunneled_ip4( + self.pg0, + rx, + tx, + [ + VppMplsLabel(44, ttl=32), + VppMplsLabel(46, ttl=47), + VppMplsLabel(33, ttl=47), + ], + ) def test_mpls_tunnel_many(self): - """ MPLS Multiple Tunnels """ + """MPLS Multiple Tunnels""" for ii in range(100): mpls_tun = VppMPLSTunnelInterface( self, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index, - labels=[VppMplsLabel(44, ttl=32), - VppMplsLabel(46, MplsLspMode.UNIFORM)])]) + [ + VppRoutePath( + self.pg0.remote_ip4, + self.pg0.sw_if_index, + labels=[ + VppMplsLabel(44, ttl=32), + VppMplsLabel(46, MplsLspMode.UNIFORM), + ], + ) + ], + ) mpls_tun.add_vpp_config() mpls_tun.admin_up() for ii in range(100): mpls_tun = VppMPLSTunnelInterface( self, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index, - labels=[VppMplsLabel(44, ttl=32), - VppMplsLabel(46, MplsLspMode.UNIFORM)])], - is_l2=1) + [ + VppRoutePath( + self.pg0.remote_ip4, + self.pg0.sw_if_index, + labels=[ + VppMplsLabel(44, ttl=32), + VppMplsLabel(46, MplsLspMode.UNIFORM), + ], + ) + ], + is_l2=1, + ) mpls_tun.add_vpp_config() mpls_tun.admin_up() def test_v4_exp_null(self): - """ MPLS V4 Explicit NULL test """ + """MPLS V4 Explicit NULL test""" # # The first test case has an MPLS TTL of 0 # all packet should be dropped # - tx = self.create_stream_labelled_ip4(self.pg0, - [VppMplsLabel(0, ttl=0)]) - self.send_and_assert_no_replies(self.pg0, tx, - "MPLS TTL=0 packets forwarded") + tx = self.create_stream_labelled_ip4(self.pg0, [VppMplsLabel(0, ttl=0)]) + self.send_and_assert_no_replies(self.pg0, tx, "MPLS TTL=0 packets forwarded") # # a stream with a non-zero MPLS TTL @@ -1188,7 +1409,7 @@ class TestMPLS(VppTestCase): self.verify_capture_ip4(self.pg1, rx, tx) def test_v6_exp_null(self): - """ MPLS V6 Explicit NULL test """ + """MPLS V6 Explicit NULL test""" # # a stream with a non-zero MPLS TTL @@ -1208,42 +1429,40 @@ class TestMPLS(VppTestCase): self.verify_capture_ip6(self.pg0, rx, tx) def test_deag(self): - """ MPLS Deagg """ + """MPLS Deagg""" # # A de-agg route - next-hop lookup in default table # - route_34_eos = VppMplsRoute(self, 34, 1, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_table_id=0)]) + route_34_eos = VppMplsRoute( + self, 34, 1, [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=0)] + ) route_34_eos.add_vpp_config() # # ping an interface in the default table # PG0 is in the default table # - tx = self.create_stream_labelled_ip4(self.pg0, - [VppMplsLabel(34)], - ping=1, - ip_itf=self.pg0) + tx = self.create_stream_labelled_ip4( + self.pg0, [VppMplsLabel(34)], ping=1, ip_itf=self.pg0 + ) rx = self.send_and_expect(self.pg0, tx, self.pg0) self.verify_capture_ip4(self.pg0, rx, tx, ping_resp=1) # # A de-agg route - next-hop lookup in non-default table # - route_35_eos = VppMplsRoute(self, 35, 1, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_table_id=1)]) + route_35_eos = VppMplsRoute( + self, 35, 1, [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=1)] + ) route_35_eos.add_vpp_config() route_356_eos = VppMplsRoute( - self, 356, 1, - [VppRoutePath("0::0", - 0xffffffff, - nh_table_id=1)], - eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP6) + self, + 356, + 1, + [VppRoutePath("0::0", 0xFFFFFFFF, nh_table_id=1)], + eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ) route_356_eos.add_vpp_config() # @@ -1252,26 +1471,25 @@ class TestMPLS(VppTestCase): # default table and egress unlabelled in the non-default # tx = self.create_stream_labelled_ip4( - self.pg0, [VppMplsLabel(35)], ping=1, ip_itf=self.pg1) + self.pg0, [VppMplsLabel(35)], ping=1, ip_itf=self.pg1 + ) rx = self.send_and_expect(self.pg0, tx, self.pg1) self.verify_capture_ip4(self.pg1, rx, tx, ping_resp=1) tx = self.create_stream_labelled_ip6( - self.pg0, [VppMplsLabel(356)], ping=1, ip_itf=self.pg1) + self.pg0, [VppMplsLabel(356)], ping=1, ip_itf=self.pg1 + ) rx = self.send_and_expect(self.pg0, tx, self.pg1) self.verify_capture_ip6(self.pg1, rx, tx, ping_resp=1) # # Double pop # - route_36_neos = VppMplsRoute(self, 36, 0, - [VppRoutePath("0.0.0.0", - 0xffffffff)]) + route_36_neos = VppMplsRoute(self, 36, 0, [VppRoutePath("0.0.0.0", 0xFFFFFFFF)]) route_36_neos.add_vpp_config() - tx = self.create_stream_labelled_ip4(self.pg0, - [VppMplsLabel(36), - VppMplsLabel(35)], - ping=1, ip_itf=self.pg1) + tx = self.create_stream_labelled_ip4( + self.pg0, [VppMplsLabel(36), VppMplsLabel(35)], ping=1, ip_itf=self.pg1 + ) rx = self.send_and_expect(self.pg0, tx, self.pg1) self.verify_capture_ip4(self.pg1, rx, tx, ping_resp=1) @@ -1280,16 +1498,19 @@ class TestMPLS(VppTestCase): route_34_eos.remove_vpp_config() def test_interface_rx(self): - """ MPLS Interface Receive """ + """MPLS Interface Receive""" # # Add a non-recursive route that will forward the traffic # post-interface-rx # - route_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32, - table_id=1, - paths=[VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index)]) + route_10_0_0_1 = VppIpRoute( + self, + "10.0.0.1", + 32, + table_id=1, + paths=[VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)], + ) route_10_0_0_1.add_vpp_config() # @@ -1301,33 +1522,43 @@ class TestMPLS(VppTestCase): # so as to have matched the route in table 1 # route_34_eos = VppMplsRoute( - self, 34, 1, - [VppRoutePath("0.0.0.0", - self.pg1.sw_if_index, - type=FibPathType.FIB_PATH_TYPE_INTERFACE_RX)]) + self, + 34, + 1, + [ + VppRoutePath( + "0.0.0.0", + self.pg1.sw_if_index, + type=FibPathType.FIB_PATH_TYPE_INTERFACE_RX, + ) + ], + ) route_34_eos.add_vpp_config() # # ping an interface in the default table # PG0 is in the default table # - tx = self.create_stream_labelled_ip4(self.pg0, - [VppMplsLabel(34)], - dst_ip="10.0.0.1") + tx = self.create_stream_labelled_ip4( + self.pg0, [VppMplsLabel(34)], dst_ip="10.0.0.1" + ) rx = self.send_and_expect(self.pg0, tx, self.pg1) self.verify_capture_ip4(self.pg1, rx, tx) def test_mcast_mid_point(self): - """ MPLS Multicast Mid Point """ + """MPLS Multicast Mid Point""" # # Add a non-recursive route that will forward the traffic # post-interface-rx # - route_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32, - table_id=1, - paths=[VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index)]) + route_10_0_0_1 = VppIpRoute( + self, + "10.0.0.1", + 32, + table_id=1, + paths=[VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)], + ) route_10_0_0_1.add_vpp_config() # @@ -1335,17 +1566,28 @@ class TestMPLS(VppTestCase): # and replicate to a interface-rx (like a bud node would) # route_3400_eos = VppMplsRoute( - self, 3400, 1, - [VppRoutePath(self.pg2.remote_ip4, - self.pg2.sw_if_index, - labels=[VppMplsLabel(3401)]), - VppRoutePath(self.pg3.remote_ip4, - self.pg3.sw_if_index, - labels=[VppMplsLabel(3402)]), - VppRoutePath("0.0.0.0", - self.pg1.sw_if_index, - type=FibPathType.FIB_PATH_TYPE_INTERFACE_RX)], - is_multicast=1) + self, + 3400, + 1, + [ + VppRoutePath( + self.pg2.remote_ip4, + self.pg2.sw_if_index, + labels=[VppMplsLabel(3401)], + ), + VppRoutePath( + self.pg3.remote_ip4, + self.pg3.sw_if_index, + labels=[VppMplsLabel(3402)], + ), + VppRoutePath( + "0.0.0.0", + self.pg1.sw_if_index, + type=FibPathType.FIB_PATH_TYPE_INTERFACE_RX, + ), + ], + is_multicast=1, + ) route_3400_eos.add_vpp_config() # @@ -1353,10 +1595,9 @@ class TestMPLS(VppTestCase): # PG0 is in the default table # self.vapi.cli("clear trace") - tx = self.create_stream_labelled_ip4(self.pg0, - [VppMplsLabel(3400, ttl=64)], - n=257, - dst_ip="10.0.0.1") + tx = self.create_stream_labelled_ip4( + self.pg0, [VppMplsLabel(3400, ttl=64)], n=257, dst_ip="10.0.0.1" + ) self.pg0.add_stream(tx) self.pg_enable_capture(self.pg_interfaces) @@ -1366,14 +1607,12 @@ class TestMPLS(VppTestCase): self.verify_capture_ip4(self.pg1, rx, tx) rx = self.pg2.get_capture(257) - self.verify_capture_labelled(self.pg2, rx, tx, - [VppMplsLabel(3401, ttl=63)]) + self.verify_capture_labelled(self.pg2, rx, tx, [VppMplsLabel(3401, ttl=63)]) rx = self.pg3.get_capture(257) - self.verify_capture_labelled(self.pg3, rx, tx, - [VppMplsLabel(3402, ttl=63)]) + self.verify_capture_labelled(self.pg3, rx, tx, [VppMplsLabel(3402, ttl=63)]) def test_mcast_head(self): - """ MPLS Multicast Head-end """ + """MPLS Multicast Head-end""" MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t @@ -1383,22 +1622,25 @@ class TestMPLS(VppTestCase): # mpls_tun = VppMPLSTunnelInterface( self, - [VppRoutePath(self.pg2.remote_ip4, - self.pg2.sw_if_index, - labels=[VppMplsLabel(42)]), - VppRoutePath(self.pg3.remote_ip4, - self.pg3.sw_if_index, - labels=[VppMplsLabel(43)])], - is_multicast=1) + [ + VppRoutePath( + self.pg2.remote_ip4, self.pg2.sw_if_index, labels=[VppMplsLabel(42)] + ), + VppRoutePath( + self.pg3.remote_ip4, self.pg3.sw_if_index, labels=[VppMplsLabel(43)] + ), + ], + is_multicast=1, + ) mpls_tun.add_vpp_config() mpls_tun.admin_up() # # add an unlabelled route through the new tunnel # - route_10_0_0_3 = VppIpRoute(self, "10.0.0.3", 32, - [VppRoutePath("0.0.0.0", - mpls_tun._sw_if_index)]) + route_10_0_0_3 = VppIpRoute( + self, "10.0.0.3", 32, [VppRoutePath("0.0.0.0", mpls_tun._sw_if_index)] + ) route_10_0_0_3.add_vpp_config() self.vapi.cli("clear trace") @@ -1421,12 +1663,18 @@ class TestMPLS(VppTestCase): route_232_1_1_1 = VppIpMRoute( self, "0.0.0.0", - "232.1.1.1", 32, + "232.1.1.1", + 32, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, - [VppMRoutePath(self.pg0.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT), - VppMRoutePath(mpls_tun._sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)]) + [ + VppMRoutePath( + self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT + ), + VppMRoutePath( + mpls_tun._sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ), + ], + ) route_232_1_1_1.add_vpp_config() self.logger.info(self.vapi.cli("sh ip mfib index 0")) @@ -1443,7 +1691,7 @@ class TestMPLS(VppTestCase): self.verify_capture_tunneled_ip4(self.pg0, rx, tx, [VppMplsLabel(43)]) def test_mcast_ip4_tail(self): - """ MPLS IPv4 Multicast Tail """ + """MPLS IPv4 Multicast Tail""" MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t @@ -1455,11 +1703,16 @@ class TestMPLS(VppTestCase): route_232_1_1_1 = VppIpMRoute( self, "0.0.0.0", - "232.1.1.1", 32, + "232.1.1.1", + 32, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, table_id=1, - paths=[VppMRoutePath(self.pg1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)]) + paths=[ + VppMRoutePath( + self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD + ) + ], + ) route_232_1_1_1.add_vpp_config() # @@ -1471,13 +1724,13 @@ class TestMPLS(VppTestCase): # table 1 # route_34_eos = VppMplsRoute( - self, 34, 1, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_table_id=1, - rpf_id=55)], + self, + 34, + 1, + [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=1, rpf_id=55)], is_multicast=1, - eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP4) + eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP4, + ) route_34_eos.add_vpp_config() @@ -1485,8 +1738,9 @@ class TestMPLS(VppTestCase): # Drop due to interface lookup miss # self.vapi.cli("clear trace") - tx = self.create_stream_labelled_ip4(self.pg0, [VppMplsLabel(34)], - dst_ip="232.1.1.1", n=1) + tx = self.create_stream_labelled_ip4( + self.pg0, [VppMplsLabel(34)], dst_ip="232.1.1.1", n=1 + ) self.send_and_assert_no_replies(self.pg0, tx, "RPF-ID drop none") # @@ -1495,29 +1749,31 @@ class TestMPLS(VppTestCase): route_232_1_1_1.update_rpf_id(55) self.logger.info(self.vapi.cli("sh ip mfib index 1 232.1.1.1")) - tx = self.create_stream_labelled_ip4(self.pg0, [VppMplsLabel(34)], - dst_ip="232.1.1.1") + tx = self.create_stream_labelled_ip4( + self.pg0, [VppMplsLabel(34)], dst_ip="232.1.1.1" + ) rx = self.send_and_expect(self.pg0, tx, self.pg1) self.verify_capture_ip4(self.pg1, rx, tx) # # disposed packets have an invalid IPv4 checksum # - tx = self.create_stream_labelled_ip4(self.pg0, [VppMplsLabel(34)], - dst_ip="232.1.1.1", n=65, - chksum=1) + tx = self.create_stream_labelled_ip4( + self.pg0, [VppMplsLabel(34)], dst_ip="232.1.1.1", n=65, chksum=1 + ) self.send_and_assert_no_replies(self.pg0, tx, "Invalid Checksum") # # set the RPF-ID of the entry to not match the input packet's # route_232_1_1_1.update_rpf_id(56) - tx = self.create_stream_labelled_ip4(self.pg0, [VppMplsLabel(34)], - dst_ip="232.1.1.1") + tx = self.create_stream_labelled_ip4( + self.pg0, [VppMplsLabel(34)], dst_ip="232.1.1.1" + ) self.send_and_assert_no_replies(self.pg0, tx, "RPF-ID drop 56") def test_mcast_ip6_tail(self): - """ MPLS IPv6 Multicast Tail """ + """MPLS IPv6 Multicast Tail""" MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t @@ -1529,12 +1785,18 @@ class TestMPLS(VppTestCase): route_ff = VppIpMRoute( self, "::", - "ff01::1", 32, + "ff01::1", + 32, MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE, table_id=1, - paths=[VppMRoutePath(self.pg1.sw_if_index, - MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)]) + paths=[ + VppMRoutePath( + self.pg1.sw_if_index, + MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ) + ], + ) route_ff.add_vpp_config() # @@ -1546,21 +1808,22 @@ class TestMPLS(VppTestCase): # table 1 # route_34_eos = VppMplsRoute( - self, 34, 1, - [VppRoutePath("::", - 0xffffffff, - nh_table_id=1, - rpf_id=55)], + self, + 34, + 1, + [VppRoutePath("::", 0xFFFFFFFF, nh_table_id=1, rpf_id=55)], is_multicast=1, - eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP6) + eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ) route_34_eos.add_vpp_config() # # Drop due to interface lookup miss # - tx = self.create_stream_labelled_ip6(self.pg0, [VppMplsLabel(34)], - dst_ip="ff01::1") + tx = self.create_stream_labelled_ip6( + self.pg0, [VppMplsLabel(34)], dst_ip="ff01::1" + ) self.send_and_assert_no_replies(self.pg0, tx, "RPF Miss") # @@ -1568,18 +1831,18 @@ class TestMPLS(VppTestCase): # route_ff.update_rpf_id(55) - tx = self.create_stream_labelled_ip6(self.pg0, [VppMplsLabel(34)], - dst_ip="ff01::1") + tx = self.create_stream_labelled_ip6( + self.pg0, [VppMplsLabel(34)], dst_ip="ff01::1" + ) rx = self.send_and_expect(self.pg0, tx, self.pg1) self.verify_capture_ip6(self.pg1, rx, tx) # # disposed packets have hop-limit = 1 # - tx = self.create_stream_labelled_ip6(self.pg0, - [VppMplsLabel(34)], - dst_ip="ff01::1", - hlim=1) + tx = self.create_stream_labelled_ip6( + self.pg0, [VppMplsLabel(34)], dst_ip="ff01::1", hlim=1 + ) rx = self.send_and_expect_some(self.pg0, tx, self.pg0) self.verify_capture_ip6_icmp(self.pg0, rx, tx) @@ -1587,21 +1850,27 @@ class TestMPLS(VppTestCase): # set the RPF-ID of the entry to not match the input packet's # route_ff.update_rpf_id(56) - tx = self.create_stream_labelled_ip6(self.pg0, - [VppMplsLabel(34)], - dst_ip="ff01::1") + tx = self.create_stream_labelled_ip6( + self.pg0, [VppMplsLabel(34)], dst_ip="ff01::1" + ) self.send_and_assert_no_replies(self.pg0, tx, "RPF-ID drop 56") def test_6pe(self): - """ MPLS 6PE """ + """MPLS 6PE""" # # Add a non-recursive route with a single out label # - route_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index, - labels=[VppMplsLabel(45)])]) + route_10_0_0_1 = VppIpRoute( + self, + "10.0.0.1", + 32, + [ + VppRoutePath( + self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[VppMplsLabel(45)] + ) + ], + ) route_10_0_0_1.add_vpp_config() # bind a local label to the route @@ -1612,55 +1881,57 @@ class TestMPLS(VppTestCase): # a labelled v6 route that resolves through the v4 # route_2001_3 = VppIpRoute( - self, "2001::3", 128, - [VppRoutePath("10.0.0.1", - INVALID_INDEX, - labels=[VppMplsLabel(32)])]) + self, + "2001::3", + 128, + [VppRoutePath("10.0.0.1", INVALID_INDEX, labels=[VppMplsLabel(32)])], + ) route_2001_3.add_vpp_config() tx = self.create_stream_ip6(self.pg0, "2001::3") rx = self.send_and_expect(self.pg0, tx, self.pg0) - self.verify_capture_labelled_ip6(self.pg0, rx, tx, - [VppMplsLabel(45), - VppMplsLabel(32)]) + self.verify_capture_labelled_ip6( + self.pg0, rx, tx, [VppMplsLabel(45), VppMplsLabel(32)] + ) # # and a v4 recursive via the v6 # route_20_3 = VppIpRoute( - self, "20.0.0.3", 32, - [VppRoutePath("2001::3", - INVALID_INDEX, - labels=[VppMplsLabel(99)])]) + self, + "20.0.0.3", + 32, + [VppRoutePath("2001::3", INVALID_INDEX, labels=[VppMplsLabel(99)])], + ) route_20_3.add_vpp_config() tx = self.create_stream_ip4(self.pg0, "20.0.0.3") rx = self.send_and_expect(self.pg0, tx, self.pg0) - self.verify_capture_labelled_ip4(self.pg0, rx, tx, - [VppMplsLabel(45), - VppMplsLabel(32), - VppMplsLabel(99)]) + self.verify_capture_labelled_ip4( + self.pg0, rx, tx, [VppMplsLabel(45), VppMplsLabel(32), VppMplsLabel(99)] + ) def test_attached(self): - """ Attach Routes with Local Label """ + """Attach Routes with Local Label""" # # test that if a local label is associated with an attached/connected # prefix, that we can reach hosts in the prefix. # - binding = VppMplsIpBind(self, 44, - self.pg0._local_ip4_subnet, - self.pg0.local_ip4_prefix_len) + binding = VppMplsIpBind( + self, 44, self.pg0._local_ip4_subnet, self.pg0.local_ip4_prefix_len + ) binding.add_vpp_config() - tx = (Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) / - MPLS(label=44, ttl=64) / - IP(src=self.pg0.remote_ip4, dst=self.pg0.remote_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + tx = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / MPLS(label=44, ttl=64) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.remote_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) rxs = self.send_and_expect(self.pg0, [tx], self.pg0) for rx in rxs: # if there's an ARP then the label is linked to the glean @@ -1672,7 +1943,7 @@ class TestMPLS(VppTestCase): class TestMPLSDisabled(VppTestCase): - """ MPLS disabled """ + """MPLS disabled""" @classmethod def setUpClass(cls): @@ -1709,26 +1980,29 @@ class TestMPLSDisabled(VppTestCase): super(TestMPLSDisabled, self).tearDown() def test_mpls_disabled(self): - """ MPLS Disabled """ + """MPLS Disabled""" self.logger.info(self.vapi.cli("show mpls interface")) self.logger.info(self.vapi.cli("show mpls interface pg1")) self.logger.info(self.vapi.cli("show mpls interface pg0")) - tx = (Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) / - MPLS(label=32, ttl=64) / - IPv6(src="2001::1", dst=self.pg0.remote_ip6) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + tx = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / MPLS(label=32, ttl=64) + / IPv6(src="2001::1", dst=self.pg0.remote_ip6) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) # # A simple MPLS xconnect - eos label in label out # - route_32_eos = VppMplsRoute(self, 32, 1, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index, - labels=[33])]) + route_32_eos = VppMplsRoute( + self, + 32, + 1, + [VppRoutePath(self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[33])], + ) route_32_eos.add_vpp_config() # @@ -1766,7 +2040,7 @@ class TestMPLSDisabled(VppTestCase): class TestMPLSPIC(VppTestCase): - """ MPLS Prefix-Independent Convergence (PIC) edge convergence """ + """MPLS Prefix-Independent Convergence (PIC) edge convergence""" @classmethod def setUpClass(cls): @@ -1829,7 +2103,7 @@ class TestMPLSPIC(VppTestCase): super(TestMPLSPIC, self).tearDown() def test_mpls_ibgp_pic(self): - """ MPLS iBGP Prefix-Independent Convergence (PIC) edge convergence + """MPLS iBGP Prefix-Independent Convergence (PIC) edge convergence 1) setup many iBGP VPN routes via a pair of iBGP peers. 2) Check EMCP forwarding to these peers @@ -1840,16 +2114,20 @@ class TestMPLSPIC(VppTestCase): # # IGP+LDP core routes # - core_10_0_0_45 = VppIpRoute(self, "10.0.0.45", 32, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index, - labels=[45])]) + core_10_0_0_45 = VppIpRoute( + self, + "10.0.0.45", + 32, + [VppRoutePath(self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[45])], + ) core_10_0_0_45.add_vpp_config() - core_10_0_0_46 = VppIpRoute(self, "10.0.0.46", 32, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index, - labels=[46])]) + core_10_0_0_46 = VppIpRoute( + self, + "10.0.0.46", + 32, + [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index, labels=[46])], + ) core_10_0_0_46.add_vpp_config() # @@ -1860,26 +2138,36 @@ class TestMPLSPIC(VppTestCase): pkts = [] for ii in range(NUM_PKTS): dst = "192.168.1.%d" % ii - vpn_routes.append(VppIpRoute( - self, dst, 32, - [VppRoutePath( - "10.0.0.45", - 0xffffffff, - labels=[145], - flags=FibPathFlags.FIB_PATH_FLAG_RESOLVE_VIA_HOST), - VppRoutePath( - "10.0.0.46", - 0xffffffff, - labels=[146], - flags=FibPathFlags.FIB_PATH_FLAG_RESOLVE_VIA_HOST)], - table_id=1)) + vpn_routes.append( + VppIpRoute( + self, + dst, + 32, + [ + VppRoutePath( + "10.0.0.45", + 0xFFFFFFFF, + labels=[145], + flags=FibPathFlags.FIB_PATH_FLAG_RESOLVE_VIA_HOST, + ), + VppRoutePath( + "10.0.0.46", + 0xFFFFFFFF, + labels=[146], + flags=FibPathFlags.FIB_PATH_FLAG_RESOLVE_VIA_HOST, + ), + ], + table_id=1, + ) + ) vpn_routes[ii].add_vpp_config() - pkts.append(Ether(dst=self.pg2.local_mac, - src=self.pg2.remote_mac) / - IP(src=self.pg2.remote_ip4, dst=dst) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + pkts.append( + Ether(dst=self.pg2.local_mac, src=self.pg2.remote_mac) + / IP(src=self.pg2.remote_ip4, dst=dst) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) # # Send the packet stream (one pkt to each VPN route) @@ -1896,9 +2184,12 @@ class TestMPLSPIC(VppTestCase): # with the split ratio, just as long as neither is 0 self.assertNotEqual(0, len(rx0)) self.assertNotEqual(0, len(rx1)) - self.assertEqual(len(pkts), len(rx0) + len(rx1), - "Expected all (%s) packets across both ECMP paths. " - "rx0: %s rx1: %s." % (len(pkts), len(rx0), len(rx1))) + self.assertEqual( + len(pkts), + len(rx0) + len(rx1), + "Expected all (%s) packets across both ECMP paths. " + "rx0: %s rx1: %s." % (len(pkts), len(rx0), len(rx1)), + ) # # use a test CLI command to stop the FIB walk process, this @@ -1921,9 +2212,12 @@ class TestMPLSPIC(VppTestCase): self.pg_start() rx0 = self.pg0.get_capture(NUM_PKTS) - self.assertEqual(len(pkts), len(rx0), - "Expected all (%s) packets across single path. " - "rx0: %s." % (len(pkts), len(rx0))) + self.assertEqual( + len(pkts), + len(rx0), + "Expected all (%s) packets across single path. " + "rx0: %s." % (len(pkts), len(rx0)), + ) # # enable the FIB walk process to converge the FIB @@ -1938,9 +2232,12 @@ class TestMPLSPIC(VppTestCase): self.pg_start() rx0 = self.pg0.get_capture(NUM_PKTS) - self.assertEqual(len(pkts), len(rx0), - "Expected all (%s) packets across single path. " - "rx0: %s." % (len(pkts), len(rx0))) + self.assertEqual( + len(pkts), + len(rx0), + "Expected all (%s) packets across single path. " + "rx0: %s." % (len(pkts), len(rx0)), + ) # # Add the IGP route back and we return to load-balancing @@ -1955,12 +2252,15 @@ class TestMPLSPIC(VppTestCase): rx1 = self.pg1._get_capture(NUM_PKTS) self.assertNotEqual(0, len(rx0)) self.assertNotEqual(0, len(rx1)) - self.assertEqual(len(pkts), len(rx0) + len(rx1), - "Expected all (%s) packets across both ECMP paths. " - "rx0: %s rx1: %s." % (len(pkts), len(rx0), len(rx1))) + self.assertEqual( + len(pkts), + len(rx0) + len(rx1), + "Expected all (%s) packets across both ECMP paths. " + "rx0: %s rx1: %s." % (len(pkts), len(rx0), len(rx1)), + ) def test_mpls_ebgp_pic(self): - """ MPLS eBGP Prefix-Independent Convergence (PIC) edge convergence + """MPLS eBGP Prefix-Independent Convergence (PIC) edge convergence 1) setup many eBGP VPN routes via a pair of eBGP peers. 2) Check EMCP forwarding to these peers @@ -1977,31 +2277,42 @@ class TestMPLSPIC(VppTestCase): for ii in range(NUM_PKTS): dst = "192.168.1.%d" % ii local_label = 1600 + ii - vpn_routes.append(VppIpRoute( - self, dst, 32, - [VppRoutePath( - self.pg2.remote_ip4, - 0xffffffff, - nh_table_id=1, - flags=FibPathFlags.FIB_PATH_FLAG_RESOLVE_VIA_ATTACHED), - VppRoutePath( - self.pg3.remote_ip4, - 0xffffffff, - nh_table_id=1, - flags=FibPathFlags.FIB_PATH_FLAG_RESOLVE_VIA_ATTACHED)], - table_id=1)) + vpn_routes.append( + VppIpRoute( + self, + dst, + 32, + [ + VppRoutePath( + self.pg2.remote_ip4, + 0xFFFFFFFF, + nh_table_id=1, + flags=FibPathFlags.FIB_PATH_FLAG_RESOLVE_VIA_ATTACHED, + ), + VppRoutePath( + self.pg3.remote_ip4, + 0xFFFFFFFF, + nh_table_id=1, + flags=FibPathFlags.FIB_PATH_FLAG_RESOLVE_VIA_ATTACHED, + ), + ], + table_id=1, + ) + ) vpn_routes[ii].add_vpp_config() - vpn_bindings.append(VppMplsIpBind(self, local_label, dst, 32, - ip_table_id=1)) + vpn_bindings.append( + VppMplsIpBind(self, local_label, dst, 32, ip_table_id=1) + ) vpn_bindings[ii].add_vpp_config() - pkts.append(Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - MPLS(label=local_label, ttl=64) / - IP(src=self.pg0.remote_ip4, dst=dst) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + pkts.append( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / MPLS(label=local_label, ttl=64) + / IP(src=self.pg0.remote_ip4, dst=dst) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) # # Send the packet stream (one pkt to each VPN route) @@ -2018,9 +2329,12 @@ class TestMPLSPIC(VppTestCase): # with the split ratio, just as long as neither is 0 self.assertNotEqual(0, len(rx0)) self.assertNotEqual(0, len(rx1)) - self.assertEqual(len(pkts), len(rx0) + len(rx1), - "Expected all (%s) packets across both ECMP paths. " - "rx0: %s rx1: %s." % (len(pkts), len(rx0), len(rx1))) + self.assertEqual( + len(pkts), + len(rx0) + len(rx1), + "Expected all (%s) packets across both ECMP paths. " + "rx0: %s rx1: %s." % (len(pkts), len(rx0), len(rx1)), + ) # # use a test CLI command to stop the FIB walk process, this @@ -2042,9 +2356,12 @@ class TestMPLSPIC(VppTestCase): self.pg_start() rx0 = self.pg3.get_capture(NUM_PKTS) - self.assertEqual(len(pkts), len(rx0), - "Expected all (%s) packets across single path. " - "rx0: %s." % (len(pkts), len(rx0))) + self.assertEqual( + len(pkts), + len(rx0), + "Expected all (%s) packets across single path. " + "rx0: %s." % (len(pkts), len(rx0)), + ) # # enable the FIB walk process to converge the FIB @@ -2059,9 +2376,12 @@ class TestMPLSPIC(VppTestCase): self.pg_start() rx0 = self.pg3.get_capture(NUM_PKTS) - self.assertEqual(len(pkts), len(rx0), - "Expected all (%s) packets across single path. " - "rx0: %s." % (len(pkts), len(rx0))) + self.assertEqual( + len(pkts), + len(rx0), + "Expected all (%s) packets across single path. " + "rx0: %s." % (len(pkts), len(rx0)), + ) # # put the connected routes back @@ -2077,12 +2397,15 @@ class TestMPLSPIC(VppTestCase): rx1 = self.pg3._get_capture(NUM_PKTS) self.assertNotEqual(0, len(rx0)) self.assertNotEqual(0, len(rx1)) - self.assertEqual(len(pkts), len(rx0) + len(rx1), - "Expected all (%s) packets across both ECMP paths. " - "rx0: %s rx1: %s." % (len(pkts), len(rx0), len(rx1))) + self.assertEqual( + len(pkts), + len(rx0) + len(rx1), + "Expected all (%s) packets across both ECMP paths. " + "rx0: %s rx1: %s." % (len(pkts), len(rx0), len(rx1)), + ) def test_mpls_v6_ebgp_pic(self): - """ MPLSv6 eBGP Prefix-Independent Convergence (PIC) edge convergence + """MPLSv6 eBGP Prefix-Independent Convergence (PIC) edge convergence 1) setup many eBGP VPNv6 routes via a pair of eBGP peers 2) Check EMCP forwarding to these peers @@ -2099,31 +2422,42 @@ class TestMPLSPIC(VppTestCase): for ii in range(NUM_PKTS): dst = "3000::%d" % ii local_label = 1600 + ii - vpn_routes.append(VppIpRoute( - self, dst, 128, - [VppRoutePath( - self.pg2.remote_ip6, - 0xffffffff, - nh_table_id=1, - flags=FibPathFlags.FIB_PATH_FLAG_RESOLVE_VIA_ATTACHED), - VppRoutePath( - self.pg3.remote_ip6, - 0xffffffff, - nh_table_id=1, - flags=FibPathFlags.FIB_PATH_FLAG_RESOLVE_VIA_ATTACHED)], - table_id=1)) + vpn_routes.append( + VppIpRoute( + self, + dst, + 128, + [ + VppRoutePath( + self.pg2.remote_ip6, + 0xFFFFFFFF, + nh_table_id=1, + flags=FibPathFlags.FIB_PATH_FLAG_RESOLVE_VIA_ATTACHED, + ), + VppRoutePath( + self.pg3.remote_ip6, + 0xFFFFFFFF, + nh_table_id=1, + flags=FibPathFlags.FIB_PATH_FLAG_RESOLVE_VIA_ATTACHED, + ), + ], + table_id=1, + ) + ) vpn_routes[ii].add_vpp_config() - vpn_bindings.append(VppMplsIpBind(self, local_label, dst, 128, - ip_table_id=1)) + vpn_bindings.append( + VppMplsIpBind(self, local_label, dst, 128, ip_table_id=1) + ) vpn_bindings[ii].add_vpp_config() - pkts.append(Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - MPLS(label=local_label, ttl=64) / - IPv6(src=self.pg0.remote_ip6, dst=dst) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + pkts.append( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / MPLS(label=local_label, ttl=64) + / IPv6(src=self.pg0.remote_ip6, dst=dst) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) self.logger.info(self.vapi.cli("sh ip6 fib %s" % dst)) self.pg0.add_stream(pkts) @@ -2134,9 +2468,12 @@ class TestMPLSPIC(VppTestCase): rx1 = self.pg3._get_capture(NUM_PKTS) self.assertNotEqual(0, len(rx0)) self.assertNotEqual(0, len(rx1)) - self.assertEqual(len(pkts), len(rx0) + len(rx1), - "Expected all (%s) packets across both ECMP paths. " - "rx0: %s rx1: %s." % (len(pkts), len(rx0), len(rx1))) + self.assertEqual( + len(pkts), + len(rx0) + len(rx1), + "Expected all (%s) packets across both ECMP paths. " + "rx0: %s rx1: %s." % (len(pkts), len(rx0), len(rx1)), + ) # # use a test CLI command to stop the FIB walk process, this @@ -2160,9 +2497,12 @@ class TestMPLSPIC(VppTestCase): self.pg_start() rx0 = self.pg3.get_capture(NUM_PKTS) - self.assertEqual(len(pkts), len(rx0), - "Expected all (%s) packets across single path. " - "rx0: %s." % (len(pkts), len(rx0))) + self.assertEqual( + len(pkts), + len(rx0), + "Expected all (%s) packets across single path. " + "rx0: %s." % (len(pkts), len(rx0)), + ) # # enable the FIB walk process to converge the FIB @@ -2173,9 +2513,12 @@ class TestMPLSPIC(VppTestCase): self.pg_start() rx0 = self.pg3.get_capture(NUM_PKTS) - self.assertEqual(len(pkts), len(rx0), - "Expected all (%s) packets across single path. " - "rx0: %s." % (len(pkts), len(rx0))) + self.assertEqual( + len(pkts), + len(rx0), + "Expected all (%s) packets across single path. " + "rx0: %s." % (len(pkts), len(rx0)), + ) # # put the connected routes back @@ -2193,13 +2536,16 @@ class TestMPLSPIC(VppTestCase): rx1 = self.pg3._get_capture(NUM_PKTS) self.assertNotEqual(0, len(rx0)) self.assertNotEqual(0, len(rx1)) - self.assertEqual(len(pkts), len(rx0) + len(rx1), - "Expected all (%s) packets across both ECMP paths. " - "rx0: %s rx1: %s." % (len(pkts), len(rx0), len(rx1))) + self.assertEqual( + len(pkts), + len(rx0) + len(rx1), + "Expected all (%s) packets across both ECMP paths. " + "rx0: %s rx1: %s." % (len(pkts), len(rx0), len(rx1)), + ) class TestMPLSL2(VppTestCase): - """ MPLS-L2 """ + """MPLS-L2""" @classmethod def setUpClass(cls): @@ -2274,7 +2620,7 @@ class TestMPLSL2(VppTestCase): self.assertEqual(arp.pdst, dip) def test_vpws(self): - """ Virtual Private Wire Service """ + """Virtual Private Wire Service""" # # Create an MPLS tunnel that pushes 1 label @@ -2283,10 +2629,15 @@ class TestMPLSL2(VppTestCase): # mpls_tun_1 = VppMPLSTunnelInterface( self, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index, - labels=[VppMplsLabel(42, MplsLspMode.UNIFORM)])], - is_l2=1) + [ + VppRoutePath( + self.pg0.remote_ip4, + self.pg0.sw_if_index, + labels=[VppMplsLabel(42, MplsLspMode.UNIFORM)], + ) + ], + is_l2=1, + ) mpls_tun_1.add_vpp_config() mpls_tun_1.admin_up() @@ -2294,35 +2645,42 @@ class TestMPLSL2(VppTestCase): # Create a label entry to for 55 that does L2 input to the tunnel # route_55_eos = VppMplsRoute( - self, 55, 1, - [VppRoutePath("0.0.0.0", - mpls_tun_1.sw_if_index, - type=FibPathType.FIB_PATH_TYPE_INTERFACE_RX, - proto=FibPathProto.FIB_PATH_NH_PROTO_ETHERNET)], - eos_proto=FibPathProto.FIB_PATH_NH_PROTO_ETHERNET) + self, + 55, + 1, + [ + VppRoutePath( + "0.0.0.0", + mpls_tun_1.sw_if_index, + type=FibPathType.FIB_PATH_TYPE_INTERFACE_RX, + proto=FibPathProto.FIB_PATH_NH_PROTO_ETHERNET, + ) + ], + eos_proto=FibPathProto.FIB_PATH_NH_PROTO_ETHERNET, + ) route_55_eos.add_vpp_config() # # Cross-connect the tunnel with one of the customers L2 interfaces # - self.vapi.sw_interface_set_l2_xconnect(self.pg1.sw_if_index, - mpls_tun_1.sw_if_index, - enable=1) - self.vapi.sw_interface_set_l2_xconnect(mpls_tun_1.sw_if_index, - self.pg1.sw_if_index, - enable=1) + self.vapi.sw_interface_set_l2_xconnect( + self.pg1.sw_if_index, mpls_tun_1.sw_if_index, enable=1 + ) + self.vapi.sw_interface_set_l2_xconnect( + mpls_tun_1.sw_if_index, self.pg1.sw_if_index, enable=1 + ) # # inject a packet from the core # - pcore = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - MPLS(label=55, ttl=64) / - Ether(dst="00:00:de:ad:ba:be", - src="00:00:de:ad:be:ef") / - IP(src="10.10.10.10", dst="11.11.11.11") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + pcore = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / MPLS(label=55, ttl=64) + / Ether(dst="00:00:de:ad:ba:be", src="00:00:de:ad:be:ef") + / IP(src="10.10.10.10", dst="11.11.11.11") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) tx0 = pcore * NUM_PKTS rx0 = self.send_and_expect(self.pg0, tx0, self.pg1) @@ -2339,10 +2697,9 @@ class TestMPLSL2(VppTestCase): tx1 = pcore[MPLS].payload rx1 = self.send_and_expect(self.pg1, [tx1], self.pg0) - self.verify_arp_req(rx1[0], - self.pg0.local_mac, - self.pg0.local_ip4, - self.pg0.remote_ip4) + self.verify_arp_req( + rx1[0], self.pg0.local_mac, self.pg0.local_ip4, self.pg0.remote_ip4 + ) # # resolve the ARP entries and send again @@ -2354,7 +2711,7 @@ class TestMPLSL2(VppTestCase): self.verify_capture_tunneled_ethernet(rx1, tx1, [VppMplsLabel(42)]) def test_vpls(self): - """ Virtual Private LAN Service """ + """Virtual Private LAN Service""" # we skipped this in the setup self.pg0.resolve_arp() @@ -2364,19 +2721,25 @@ class TestMPLSL2(VppTestCase): # mpls_tun1 = VppMPLSTunnelInterface( self, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index, - labels=[VppMplsLabel(42)])], - is_l2=1) + [ + VppRoutePath( + self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[VppMplsLabel(42)] + ) + ], + is_l2=1, + ) mpls_tun1.add_vpp_config() mpls_tun1.admin_up() mpls_tun2 = VppMPLSTunnelInterface( self, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index, - labels=[VppMplsLabel(43)])], - is_l2=1) + [ + VppRoutePath( + self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[VppMplsLabel(43)] + ) + ], + is_l2=1, + ) mpls_tun2.add_vpp_config() mpls_tun2.admin_up() @@ -2385,21 +2748,35 @@ class TestMPLSL2(VppTestCase): # the latter includes a Psuedo Wire Control Word # route_55_eos = VppMplsRoute( - self, 55, 1, - [VppRoutePath("0.0.0.0", - mpls_tun1.sw_if_index, - type=FibPathType.FIB_PATH_TYPE_INTERFACE_RX, - proto=FibPathProto.FIB_PATH_NH_PROTO_ETHERNET)], - eos_proto=FibPathProto.FIB_PATH_NH_PROTO_ETHERNET) + self, + 55, + 1, + [ + VppRoutePath( + "0.0.0.0", + mpls_tun1.sw_if_index, + type=FibPathType.FIB_PATH_TYPE_INTERFACE_RX, + proto=FibPathProto.FIB_PATH_NH_PROTO_ETHERNET, + ) + ], + eos_proto=FibPathProto.FIB_PATH_NH_PROTO_ETHERNET, + ) route_56_eos = VppMplsRoute( - self, 56, 1, - [VppRoutePath("0.0.0.0", - mpls_tun2.sw_if_index, - type=FibPathType.FIB_PATH_TYPE_INTERFACE_RX, - flags=FibPathFlags.FIB_PATH_FLAG_POP_PW_CW, - proto=FibPathProto.FIB_PATH_NH_PROTO_ETHERNET)], - eos_proto=FibPathProto.FIB_PATH_NH_PROTO_ETHERNET) + self, + 56, + 1, + [ + VppRoutePath( + "0.0.0.0", + mpls_tun2.sw_if_index, + type=FibPathType.FIB_PATH_TYPE_INTERFACE_RX, + flags=FibPathFlags.FIB_PATH_FLAG_POP_PW_CW, + proto=FibPathProto.FIB_PATH_NH_PROTO_ETHERNET, + ) + ], + eos_proto=FibPathProto.FIB_PATH_NH_PROTO_ETHERNET, + ) # move me route_56_eos.add_vpp_config() @@ -2411,43 +2788,48 @@ class TestMPLSL2(VppTestCase): # add to tunnel to the customers bridge-domain # self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=mpls_tun1.sw_if_index, bd_id=1) + rx_sw_if_index=mpls_tun1.sw_if_index, bd_id=1 + ) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=mpls_tun2.sw_if_index, bd_id=1) + rx_sw_if_index=mpls_tun2.sw_if_index, bd_id=1 + ) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg1.sw_if_index, bd_id=1) + rx_sw_if_index=self.pg1.sw_if_index, bd_id=1 + ) # # Packet from host on the customer interface to each host # reachable over the core, and vice-versa # - p_cust1 = (Ether(dst="00:00:de:ad:ba:b1", - src="00:00:de:ad:be:ef") / - IP(src="10.10.10.10", dst="11.11.11.11") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - p_cust2 = (Ether(dst="00:00:de:ad:ba:b2", - src="00:00:de:ad:be:ef") / - IP(src="10.10.10.10", dst="11.11.11.12") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - p_core1 = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - MPLS(label=55, ttl=64) / - Ether(src="00:00:de:ad:ba:b1", - dst="00:00:de:ad:be:ef") / - IP(dst="10.10.10.10", src="11.11.11.11") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - p_core2 = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - MPLS(label=56, ttl=64) / - Raw(b'\x01' * 4) / # PW CW - Ether(src="00:00:de:ad:ba:b2", - dst="00:00:de:ad:be:ef") / - IP(dst="10.10.10.10", src="11.11.11.12") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p_cust1 = ( + Ether(dst="00:00:de:ad:ba:b1", src="00:00:de:ad:be:ef") + / IP(src="10.10.10.10", dst="11.11.11.11") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + p_cust2 = ( + Ether(dst="00:00:de:ad:ba:b2", src="00:00:de:ad:be:ef") + / IP(src="10.10.10.10", dst="11.11.11.12") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + p_core1 = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / MPLS(label=55, ttl=64) + / Ether(src="00:00:de:ad:ba:b1", dst="00:00:de:ad:be:ef") + / IP(dst="10.10.10.10", src="11.11.11.11") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + p_core2 = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / MPLS(label=56, ttl=64) + / Raw(b"\x01" * 4) + / Ether(src="00:00:de:ad:ba:b2", dst="00:00:de:ad:be:ef") # PW CW + / IP(dst="10.10.10.10", src="11.11.11.12") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) # # The BD is learning, so send in one of each packet to learn @@ -2470,12 +2852,14 @@ class TestMPLSL2(VppTestCase): # now a stream in each direction from each host # rx = self.send_and_expect(self.pg1, p_cust1 * NUM_PKTS, self.pg0) - self.verify_capture_tunneled_ethernet(rx, p_cust1 * NUM_PKTS, - [VppMplsLabel(42)]) + self.verify_capture_tunneled_ethernet( + rx, p_cust1 * NUM_PKTS, [VppMplsLabel(42)] + ) rx = self.send_and_expect(self.pg1, p_cust2 * NUM_PKTS, self.pg0) - self.verify_capture_tunneled_ethernet(rx, p_cust2 * NUM_PKTS, - [VppMplsLabel(43)]) + self.verify_capture_tunneled_ethernet( + rx, p_cust2 * NUM_PKTS, [VppMplsLabel(43)] + ) rx = self.send_and_expect(self.pg0, p_core1 * NUM_PKTS, self.pg1) rx = self.send_and_expect(self.pg0, p_core2 * NUM_PKTS, self.pg1) @@ -2484,12 +2868,15 @@ class TestMPLSL2(VppTestCase): # remove interfaces from customers bridge-domain # self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=mpls_tun1.sw_if_index, bd_id=1, enable=0) + rx_sw_if_index=mpls_tun1.sw_if_index, bd_id=1, enable=0 + ) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=mpls_tun2.sw_if_index, bd_id=1, enable=0) + rx_sw_if_index=mpls_tun2.sw_if_index, bd_id=1, enable=0 + ) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg1.sw_if_index, bd_id=1, enable=0) + rx_sw_if_index=self.pg1.sw_if_index, bd_id=1, enable=0 + ) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_mss_clamp.py b/test/test_mss_clamp.py index 23495b6050b..663ecd37742 100644 --- a/test/test_mss_clamp.py +++ b/test/test_mss_clamp.py @@ -11,7 +11,7 @@ from scapy.packet import Raw class TestMSSClamp(VppTestCase): - """ TCP MSS Clamping Test Case """ + """TCP MSS Clamping Test Case""" def setUp(self): super(TestMSSClamp, self).setUp() @@ -40,31 +40,34 @@ class TestMSSClamp(VppTestCase): tcp_csum = tcp.chksum del tcp.chksum ip_csum = 0 - if (rx.haslayer(IP)): + if rx.haslayer(IP): ip_csum = rx[IP].chksum del rx[IP].chksum opt = tcp.options - self.assertEqual(opt[0][0], 'MSS') + self.assertEqual(opt[0][0], "MSS") self.assertEqual(opt[0][1], expected_mss) # recalculate checksums rx = rx.__class__(bytes(rx)) tcp = rx[TCP] self.assertEqual(tcp_csum, tcp.chksum) - if (rx.haslayer(IP)): + if rx.haslayer(IP): self.assertEqual(ip_csum, rx[IP].chksum) def send_and_verify_ip4(self, src_pg, dst_pg, mss, expected_mss): # IPv4 TCP packet with the requested MSS option. # from a host on src_pg to a host on dst_pg. - p = (Ether(dst=src_pg.local_mac, - src=src_pg.remote_mac) / - IP(src=src_pg.remote_ip4, - dst=dst_pg.remote_ip4) / - TCP(sport=1234, dport=1234, - flags="S", - options=[('MSS', (mss)), ('EOL', None)]) / - Raw('\xa5' * 100)) + p = ( + Ether(dst=src_pg.local_mac, src=src_pg.remote_mac) + / IP(src=src_pg.remote_ip4, dst=dst_pg.remote_ip4) + / TCP( + sport=1234, + dport=1234, + flags="S", + options=[("MSS", (mss)), ("EOL", None)], + ) + / Raw("\xa5" * 100) + ) rxs = self.send_and_expect(src_pg, p * 65, dst_pg) @@ -76,14 +79,17 @@ class TestMSSClamp(VppTestCase): # IPv6 TCP packet with the requested MSS option. # from a host on src_pg to a host on dst_pg. # - p = (Ether(dst=src_pg.local_mac, - src=src_pg.remote_mac) / - IPv6(src=src_pg.remote_ip6, - dst=dst_pg.remote_ip6) / - TCP(sport=1234, dport=1234, - flags="S", - options=[('MSS', (mss)), ('EOL', None)]) / - Raw('\xa5' * 100)) + p = ( + Ether(dst=src_pg.local_mac, src=src_pg.remote_mac) + / IPv6(src=src_pg.remote_ip6, dst=dst_pg.remote_ip6) + / TCP( + sport=1234, + dport=1234, + flags="S", + options=[("MSS", (mss)), ("EOL", None)], + ) + / Raw("\xa5" * 100) + ) rxs = self.send_and_expect(src_pg, p * 65, dst_pg) @@ -91,12 +97,16 @@ class TestMSSClamp(VppTestCase): self.verify_pkt(rx, expected_mss) def test_tcp_mss_clamping_ip4_tx(self): - """ IP4 TCP MSS Clamping TX """ + """IP4 TCP MSS Clamping TX""" # enable the TCP MSS clamping feature to lower the MSS to 1424. - self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index, - ipv4_mss=1424, ipv6_mss=0, - ipv4_direction=3, ipv6_direction=0) + self.vapi.mss_clamp_enable_disable( + self.pg1.sw_if_index, + ipv4_mss=1424, + ipv6_mss=0, + ipv4_direction=3, + ipv6_direction=0, + ) # Verify that the feature is enabled. rv, reply = self.vapi.mss_clamp_get(sw_if_index=self.pg1.sw_if_index) @@ -107,8 +117,7 @@ class TestMSSClamp(VppTestCase): self.send_and_verify_ip4(self.pg0, self.pg1, 1460, 1424) # check the stats - stats = self.statistics.get_counter( - '/err/tcp-mss-clamping-ip4-out/clamped') + stats = self.statistics.get_counter("/err/tcp-mss-clamping-ip4-out/clamped") self.assertEqual(sum(stats), 65) # Send syn packets with small enough MSS values and verify they are @@ -117,36 +126,52 @@ class TestMSSClamp(VppTestCase): # enable the the feature only in TX direction # and change the max MSS value - self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index, - ipv4_mss=1420, ipv6_mss=0, - ipv4_direction=2, ipv6_direction=0) + self.vapi.mss_clamp_enable_disable( + self.pg1.sw_if_index, + ipv4_mss=1420, + ipv6_mss=0, + ipv4_direction=2, + ipv6_direction=0, + ) # Send syn packets and verify that the MSS value is lowered. self.send_and_verify_ip4(self.pg0, self.pg1, 1460, 1420) # enable the the feature only in RX direction - self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index, - ipv4_mss=1424, ipv6_mss=0, - ipv4_direction=1, ipv6_direction=0) + self.vapi.mss_clamp_enable_disable( + self.pg1.sw_if_index, + ipv4_mss=1424, + ipv6_mss=0, + ipv4_direction=1, + ipv6_direction=0, + ) # Send the packets again and ensure they are unchanged. self.send_and_verify_ip4(self.pg0, self.pg1, 1460, 1460) # disable the feature - self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index, - ipv4_mss=0, ipv6_mss=0, - ipv4_direction=0, ipv6_direction=0) + self.vapi.mss_clamp_enable_disable( + self.pg1.sw_if_index, + ipv4_mss=0, + ipv6_mss=0, + ipv4_direction=0, + ipv6_direction=0, + ) # Send the packets again and ensure they are unchanged. self.send_and_verify_ip4(self.pg0, self.pg1, 1460, 1460) def test_tcp_mss_clamping_ip4_rx(self): - """ IP4 TCP MSS Clamping RX """ + """IP4 TCP MSS Clamping RX""" # enable the TCP MSS clamping feature to lower the MSS to 1424. - self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index, - ipv4_mss=1424, ipv6_mss=0, - ipv4_direction=3, ipv6_direction=0) + self.vapi.mss_clamp_enable_disable( + self.pg1.sw_if_index, + ipv4_mss=1424, + ipv6_mss=0, + ipv4_direction=3, + ipv6_direction=0, + ) # Verify that the feature is enabled. rv, reply = self.vapi.mss_clamp_get(sw_if_index=self.pg1.sw_if_index) @@ -157,8 +182,7 @@ class TestMSSClamp(VppTestCase): self.send_and_verify_ip4(self.pg1, self.pg0, 1460, 1424) # check the stats - stats = self.statistics.get_counter( - '/err/tcp-mss-clamping-ip4-in/clamped') + stats = self.statistics.get_counter("/err/tcp-mss-clamping-ip4-in/clamped") self.assertEqual(sum(stats), 65) # Send syn packets with small enough MSS values and verify they are @@ -167,36 +191,52 @@ class TestMSSClamp(VppTestCase): # enable the the feature only in RX direction # and change the max MSS value - self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index, - ipv4_mss=1420, ipv6_mss=0, - ipv4_direction=1, ipv6_direction=0) + self.vapi.mss_clamp_enable_disable( + self.pg1.sw_if_index, + ipv4_mss=1420, + ipv6_mss=0, + ipv4_direction=1, + ipv6_direction=0, + ) # Send syn packets and verify that the MSS value is lowered. self.send_and_verify_ip4(self.pg1, self.pg0, 1460, 1420) # enable the the feature only in TX direction - self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index, - ipv4_mss=1424, ipv6_mss=0, - ipv4_direction=2, ipv6_direction=0) + self.vapi.mss_clamp_enable_disable( + self.pg1.sw_if_index, + ipv4_mss=1424, + ipv6_mss=0, + ipv4_direction=2, + ipv6_direction=0, + ) # Send the packets again and ensure they are unchanged. self.send_and_verify_ip4(self.pg1, self.pg0, 1460, 1460) # disable the feature - self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index, - ipv4_mss=0, ipv6_mss=0, - ipv4_direction=0, ipv6_direction=0) + self.vapi.mss_clamp_enable_disable( + self.pg1.sw_if_index, + ipv4_mss=0, + ipv6_mss=0, + ipv4_direction=0, + ipv6_direction=0, + ) # Send the packets again and ensure they are unchanged. self.send_and_verify_ip4(self.pg1, self.pg0, 1460, 1460) def test_tcp_mss_clamping_ip6_tx(self): - """ IP6 TCP MSS Clamping TX """ + """IP6 TCP MSS Clamping TX""" # enable the TCP MSS clamping feature to lower the MSS to 1424. - self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index, - ipv4_mss=0, ipv6_mss=1424, - ipv4_direction=0, ipv6_direction=3) + self.vapi.mss_clamp_enable_disable( + self.pg1.sw_if_index, + ipv4_mss=0, + ipv6_mss=1424, + ipv4_direction=0, + ipv6_direction=3, + ) # Verify that the feature is enabled. rv, reply = self.vapi.mss_clamp_get(sw_if_index=self.pg1.sw_if_index) @@ -207,8 +247,7 @@ class TestMSSClamp(VppTestCase): self.send_and_verify_ip6(self.pg0, self.pg1, 1460, 1424) # check the stats - stats = self.statistics.get_counter( - '/err/tcp-mss-clamping-ip6-out/clamped') + stats = self.statistics.get_counter("/err/tcp-mss-clamping-ip6-out/clamped") self.assertEqual(sum(stats), 65) # Send syn packets with small enough MSS values and verify they are @@ -217,36 +256,52 @@ class TestMSSClamp(VppTestCase): # enable the the feature only in TX direction # and change the max MSS value - self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index, - ipv4_mss=0, ipv6_mss=1420, - ipv4_direction=0, ipv6_direction=2) + self.vapi.mss_clamp_enable_disable( + self.pg1.sw_if_index, + ipv4_mss=0, + ipv6_mss=1420, + ipv4_direction=0, + ipv6_direction=2, + ) # Send syn packets and verify that the MSS value is lowered. self.send_and_verify_ip6(self.pg0, self.pg1, 1460, 1420) # enable the the feature only in RX direction - self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index, - ipv4_mss=0, ipv6_mss=1424, - ipv4_direction=0, ipv6_direction=1) + self.vapi.mss_clamp_enable_disable( + self.pg1.sw_if_index, + ipv4_mss=0, + ipv6_mss=1424, + ipv4_direction=0, + ipv6_direction=1, + ) # Send the packets again and ensure they are unchanged. self.send_and_verify_ip6(self.pg0, self.pg1, 1460, 1460) # disable the feature - self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index, - ipv4_mss=0, ipv6_mss=0, - ipv4_direction=0, ipv6_direction=0) + self.vapi.mss_clamp_enable_disable( + self.pg1.sw_if_index, + ipv4_mss=0, + ipv6_mss=0, + ipv4_direction=0, + ipv6_direction=0, + ) # Send the packets again and ensure they are unchanged. self.send_and_verify_ip6(self.pg0, self.pg1, 1460, 1460) def test_tcp_mss_clamping_ip6_rx(self): - """ IP6 TCP MSS Clamping RX """ + """IP6 TCP MSS Clamping RX""" # enable the TCP MSS clamping feature to lower the MSS to 1424. - self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index, - ipv4_mss=0, ipv6_mss=1424, - ipv4_direction=0, ipv6_direction=3) + self.vapi.mss_clamp_enable_disable( + self.pg1.sw_if_index, + ipv4_mss=0, + ipv6_mss=1424, + ipv4_direction=0, + ipv6_direction=3, + ) # Verify that the feature is enabled. rv, reply = self.vapi.mss_clamp_get(sw_if_index=self.pg1.sw_if_index) @@ -257,8 +312,7 @@ class TestMSSClamp(VppTestCase): self.send_and_verify_ip6(self.pg1, self.pg0, 1460, 1424) # check the stats - stats = self.statistics.get_counter( - '/err/tcp-mss-clamping-ip6-in/clamped') + stats = self.statistics.get_counter("/err/tcp-mss-clamping-ip6-in/clamped") self.assertEqual(sum(stats), 65) # Send syn packets with small enough MSS values and verify they are @@ -267,29 +321,41 @@ class TestMSSClamp(VppTestCase): # enable the the feature only in RX direction # and change the max MSS value - self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index, - ipv4_mss=0, ipv6_mss=1420, - ipv4_direction=0, ipv6_direction=1) + self.vapi.mss_clamp_enable_disable( + self.pg1.sw_if_index, + ipv4_mss=0, + ipv6_mss=1420, + ipv4_direction=0, + ipv6_direction=1, + ) # Send syn packets and verify that the MSS value is lowered. self.send_and_verify_ip6(self.pg1, self.pg0, 1460, 1420) # enable the the feature only in TX direction - self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index, - ipv4_mss=0, ipv6_mss=1424, - ipv4_direction=0, ipv6_direction=2) + self.vapi.mss_clamp_enable_disable( + self.pg1.sw_if_index, + ipv4_mss=0, + ipv6_mss=1424, + ipv4_direction=0, + ipv6_direction=2, + ) # Send the packets again and ensure they are unchanged. self.send_and_verify_ip6(self.pg1, self.pg0, 1460, 1460) # disable the feature - self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index, - ipv4_mss=0, ipv6_mss=0, - ipv4_direction=0, ipv6_direction=0) + self.vapi.mss_clamp_enable_disable( + self.pg1.sw_if_index, + ipv4_mss=0, + ipv6_mss=0, + ipv4_direction=0, + ipv6_direction=0, + ) # Send the packets again and ensure they are unchanged. self.send_and_verify_ip6(self.pg1, self.pg0, 1460, 1460) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_mtu.py b/test/test_mtu.py index 27594e55727..922d83dc5ef 100644 --- a/test/test_mtu.py +++ b/test/test_mtu.py @@ -24,7 +24,8 @@ from util import reassemble4 class TestMTU(VppTestCase): - """ MTU Test Case """ + """MTU Test Case""" + maxDiff = None @classmethod @@ -62,7 +63,7 @@ class TestMTU(VppTestCase): self.assertEqual(rx, expected) def payload(self, len): - return 'x' * len + return "x" * len def get_mtu(self, sw_if_index): rv = self.vapi.sw_interface_dump(sw_if_index=sw_if_index) @@ -72,21 +73,19 @@ class TestMTU(VppTestCase): return 0 def test_ip4_mtu(self): - """ IP4 MTU test """ + """IP4 MTU test""" p_ether = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) - p_ip4 = IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, - flags='DF') + p_ip4 = IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, flags="DF") current_mtu = self.get_mtu(self.pg1.sw_if_index) - p_payload = UDP(sport=1234, dport=1234) / self.payload( - current_mtu - 20 - 8) + p_payload = UDP(sport=1234, dport=1234) / self.payload(current_mtu - 20 - 8) p4 = p_ether / p_ip4 / p_payload p4_reply = p_ip4 / p_payload p4_reply.ttl -= 1 - rx = self.send_and_expect(self.pg0, p4*11, self.pg1) + rx = self.send_and_expect(self.pg0, p4 * 11, self.pg1) for p in rx: self.validate(p[1], p4_reply) @@ -95,16 +94,22 @@ class TestMTU(VppTestCase): self.assertEqual(576, self.get_mtu(self.pg1.sw_if_index)) # Should fail. Too large MTU - p_icmp4 = ICMP(type='dest-unreach', code='fragmentation-needed', - nexthopmtu=576, chksum=0x2dbb) - icmp4_reply = (IP(src=self.pg0.local_ip4, - dst=self.pg0.remote_ip4, - ttl=254, len=576, id=0) / - p_icmp4 / p_ip4 / p_payload) + p_icmp4 = ICMP( + type="dest-unreach", + code="fragmentation-needed", + nexthopmtu=576, + chksum=0x2DBB, + ) + icmp4_reply = ( + IP(src=self.pg0.local_ip4, dst=self.pg0.remote_ip4, ttl=254, len=576, id=0) + / p_icmp4 + / p_ip4 + / p_payload + ) n = icmp4_reply.__class__(icmp4_reply) s = bytes(icmp4_reply) icmp4_reply = s[0:576] - rx = self.send_and_expect_some(self.pg0, p4*11, self.pg0) + rx = self.send_and_expect_some(self.pg0, p4 * 11, self.pg0) for p in rx: # p.show2() # n.show2() @@ -112,8 +117,7 @@ class TestMTU(VppTestCase): # Now with DF off. Expect fragments. # First go with 1500 byte packets. - p_payload = UDP(sport=1234, dport=1234) / self.payload( - 1500 - 20 - 8) + p_payload = UDP(sport=1234, dport=1234) / self.payload(1500 - 20 - 8) p4 = p_ether / p_ip4 / p_payload p4.flags = 0 p4_reply = p_ip4 / p_payload @@ -121,13 +125,13 @@ class TestMTU(VppTestCase): p4_reply.flags = 0 p4_reply.id = 256 self.pg_enable_capture() - self.pg0.add_stream(p4*1) + self.pg0.add_stream(p4 * 1) self.pg_start() rx = self.pg1.get_capture(3) reass_pkt = reassemble4(rx) self.validate(reass_pkt, p4_reply) - ''' + """ # Now what happens with a 9K frame p_payload = UDP(sport=1234, dport=1234) / self.payload( current_mtu - 20 - 8) @@ -146,27 +150,25 @@ class TestMTU(VppTestCase): reass_pkt.show2() p4_reply.show2() self.validate(reass_pkt, p4_reply) - ''' + """ # Reset MTU - self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, - [current_mtu, 0, 0, 0]) + self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [current_mtu, 0, 0, 0]) def test_ip6_mtu(self): - """ IP6 MTU test """ + """IP6 MTU test""" current_mtu = self.get_mtu(self.pg1.sw_if_index) p_ether = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) p_ip6 = IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6) - p_payload = UDP(sport=1234, dport=1234) / self.payload( - current_mtu - 40 - 8) + p_payload = UDP(sport=1234, dport=1234) / self.payload(current_mtu - 40 - 8) p6 = p_ether / p_ip6 / p_payload p6_reply = p_ip6 / p_payload p6_reply.hlim -= 1 - rx = self.send_and_expect(self.pg0, p6*9, self.pg1) + rx = self.send_and_expect(self.pg0, p6 * 9, self.pg1) for p in rx: self.validate(p[1], p6_reply) @@ -175,24 +177,25 @@ class TestMTU(VppTestCase): self.assertEqual(1280, self.get_mtu(self.pg1.sw_if_index)) # Should fail. Too large MTU - p_icmp6 = ICMPv6PacketTooBig(mtu=1280, cksum=0x4c7a) - icmp6_reply = (IPv6(src=self.pg0.local_ip6, - dst=self.pg0.remote_ip6, - hlim=255, plen=1240) / - p_icmp6 / p_ip6 / p_payload) + p_icmp6 = ICMPv6PacketTooBig(mtu=1280, cksum=0x4C7A) + icmp6_reply = ( + IPv6(src=self.pg0.local_ip6, dst=self.pg0.remote_ip6, hlim=255, plen=1240) + / p_icmp6 + / p_ip6 + / p_payload + ) icmp6_reply[2].hlim -= 1 n = icmp6_reply.__class__(icmp6_reply) s = bytes(icmp6_reply) icmp6_reply_str = s[0:1280] - rx = self.send_and_expect_some(self.pg0, p6*9, self.pg0) + rx = self.send_and_expect_some(self.pg0, p6 * 9, self.pg0) for p in rx: self.validate_bytes(bytes(p[1]), icmp6_reply_str) # Reset MTU - self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, - [current_mtu, 0, 0, 0]) + self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [current_mtu, 0, 0, 0]) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_nat44_ed.py b/test/test_nat44_ed.py index 21eebb22de4..77459874c09 100644 --- a/test/test_nat44_ed.py +++ b/test/test_nat44_ed.py @@ -21,9 +21,9 @@ from util import StatsDiff class TestNAT44ED(VppTestCase): - """ NAT44ED Test Case """ + """NAT44ED Test Case""" - nat_addr = '10.0.10.3' + nat_addr = "10.0.10.3" tcp_port_in = 6303 tcp_port_out = 6303 @@ -48,8 +48,7 @@ class TestNAT44ED(VppTestCase): self.plugin_disable() def plugin_enable(self): - self.vapi.nat44_ed_plugin_enable_disable( - sessions=self.max_sessions, enable=1) + self.vapi.nat44_ed_plugin_enable_disable(sessions=self.max_sessions, enable=1) def plugin_disable(self): self.vapi.nat44_ed_plugin_enable_disable(enable=0) @@ -87,7 +86,7 @@ class TestNAT44ED(VppTestCase): @classmethod def create_and_add_ip4_table(cls, i, table_id=0): - cls.vapi.ip_table_add_del(is_add=1, table={'table_id': table_id}) + cls.vapi.ip_table_add_del(is_add=1, table={"table_id": table_id}) i.set_table_ip4(table_id) @classmethod @@ -105,32 +104,41 @@ class TestNAT44ED(VppTestCase): @classmethod def nat_add_interface_address(cls, i): - cls.vapi.nat44_add_del_interface_addr( - sw_if_index=i.sw_if_index, is_add=1) + cls.vapi.nat44_add_del_interface_addr(sw_if_index=i.sw_if_index, is_add=1) def nat_add_inside_interface(self, i): self.vapi.nat44_interface_add_del_feature( - flags=self.config_flags.NAT_IS_INSIDE, - sw_if_index=i.sw_if_index, is_add=1) + flags=self.config_flags.NAT_IS_INSIDE, sw_if_index=i.sw_if_index, is_add=1 + ) def nat_add_outside_interface(self, i): self.vapi.nat44_interface_add_del_feature( - flags=self.config_flags.NAT_IS_OUTSIDE, - sw_if_index=i.sw_if_index, is_add=1) + flags=self.config_flags.NAT_IS_OUTSIDE, sw_if_index=i.sw_if_index, is_add=1 + ) - def nat_add_address(self, address, twice_nat=0, - vrf_id=0xFFFFFFFF, is_add=1): + def nat_add_address(self, address, twice_nat=0, vrf_id=0xFFFFFFFF, is_add=1): flags = self.config_flags.NAT_IS_TWICE_NAT if twice_nat else 0 - self.vapi.nat44_add_del_address_range(first_ip_address=address, - last_ip_address=address, - vrf_id=vrf_id, - is_add=is_add, - flags=flags) + self.vapi.nat44_add_del_address_range( + first_ip_address=address, + last_ip_address=address, + vrf_id=vrf_id, + is_add=is_add, + flags=flags, + ) - def nat_add_static_mapping(self, local_ip, external_ip='0.0.0.0', - local_port=0, external_port=0, vrf_id=0, - is_add=1, external_sw_if_index=0xFFFFFFFF, - proto=0, tag="", flags=0): + def nat_add_static_mapping( + self, + local_ip, + external_ip="0.0.0.0", + local_port=0, + external_port=0, + vrf_id=0, + is_add=1, + external_sw_if_index=0xFFFFFFFF, + proto=0, + tag="", + flags=0, + ): if not (local_port and external_port): flags |= self.config_flags.NAT_IS_ADDR_ONLY @@ -142,9 +150,11 @@ class TestNAT44ED(VppTestCase): external_sw_if_index=external_sw_if_index, local_port=local_port, external_port=external_port, - vrf_id=vrf_id, protocol=proto, + vrf_id=vrf_id, + protocol=proto, flags=flags, - tag=tag) + tag=tag, + ) @classmethod def setUpClass(cls): @@ -159,14 +169,14 @@ class TestNAT44ED(VppTestCase): cls.configure_ip4_interface(i, hosts=3) # test specific (test-multiple-vrf) - cls.vapi.ip_table_add_del(is_add=1, table={'table_id': 1}) + cls.vapi.ip_table_add_del(is_add=1, table={"table_id": 1}) # test specific (test-one-armed-nat44-static) cls.pg4.generate_remote_hosts(2) cls.pg4.config_ip4() cls.vapi.sw_interface_add_del_address( - sw_if_index=cls.pg4.sw_if_index, - prefix="10.0.0.1/24") + sw_if_index=cls.pg4.sw_if_index, prefix="10.0.0.1/24" + ) cls.pg4.admin_up() cls.pg4.resolve_arp() cls.pg4._remote_hosts[1]._ip4 = cls.pg4._remote_hosts[0]._ip4 @@ -190,58 +200,95 @@ class TestNAT44ED(VppTestCase): rl = list() - rl.append(VppIpRoute(cls, "0.0.0.0", 0, - [VppRoutePath("0.0.0.0", 0xffffffff, - nh_table_id=0)], - register=False, table_id=1)) - rl.append(VppIpRoute(cls, "0.0.0.0", 0, - [VppRoutePath(cls.pg1.local_ip4, - cls.pg1.sw_if_index)], - register=False)) - rl.append(VppIpRoute(cls, cls.pg5.remote_ip4, 32, - [VppRoutePath("0.0.0.0", - cls.pg5.sw_if_index)], - register=False, table_id=1)) - rl.append(VppIpRoute(cls, cls.pg6.remote_ip4, 32, - [VppRoutePath("0.0.0.0", - cls.pg6.sw_if_index)], - register=False, table_id=1)) - rl.append(VppIpRoute(cls, cls.pg6.remote_ip4, 16, - [VppRoutePath("0.0.0.0", 0xffffffff, - nh_table_id=1)], - register=False, table_id=0)) + rl.append( + VppIpRoute( + cls, + "0.0.0.0", + 0, + [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=0)], + register=False, + table_id=1, + ) + ) + rl.append( + VppIpRoute( + cls, + "0.0.0.0", + 0, + [VppRoutePath(cls.pg1.local_ip4, cls.pg1.sw_if_index)], + register=False, + ) + ) + rl.append( + VppIpRoute( + cls, + cls.pg5.remote_ip4, + 32, + [VppRoutePath("0.0.0.0", cls.pg5.sw_if_index)], + register=False, + table_id=1, + ) + ) + rl.append( + VppIpRoute( + cls, + cls.pg6.remote_ip4, + 32, + [VppRoutePath("0.0.0.0", cls.pg6.sw_if_index)], + register=False, + table_id=1, + ) + ) + rl.append( + VppIpRoute( + cls, + cls.pg6.remote_ip4, + 16, + [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=1)], + register=False, + table_id=0, + ) + ) for r in rl: r.add_vpp_config() - cls.no_diff = StatsDiff({ - pg.sw_if_index: { - '/nat44-ed/in2out/fastpath/tcp': 0, - '/nat44-ed/in2out/fastpath/udp': 0, - '/nat44-ed/in2out/fastpath/icmp': 0, - '/nat44-ed/in2out/fastpath/drops': 0, - '/nat44-ed/in2out/slowpath/tcp': 0, - '/nat44-ed/in2out/slowpath/udp': 0, - '/nat44-ed/in2out/slowpath/icmp': 0, - '/nat44-ed/in2out/slowpath/drops': 0, - '/nat44-ed/in2out/fastpath/tcp': 0, - '/nat44-ed/in2out/fastpath/udp': 0, - '/nat44-ed/in2out/fastpath/icmp': 0, - '/nat44-ed/in2out/fastpath/drops': 0, - '/nat44-ed/in2out/slowpath/tcp': 0, - '/nat44-ed/in2out/slowpath/udp': 0, - '/nat44-ed/in2out/slowpath/icmp': 0, - '/nat44-ed/in2out/slowpath/drops': 0, + cls.no_diff = StatsDiff( + { + pg.sw_if_index: { + "/nat44-ed/in2out/fastpath/tcp": 0, + "/nat44-ed/in2out/fastpath/udp": 0, + "/nat44-ed/in2out/fastpath/icmp": 0, + "/nat44-ed/in2out/fastpath/drops": 0, + "/nat44-ed/in2out/slowpath/tcp": 0, + "/nat44-ed/in2out/slowpath/udp": 0, + "/nat44-ed/in2out/slowpath/icmp": 0, + "/nat44-ed/in2out/slowpath/drops": 0, + "/nat44-ed/in2out/fastpath/tcp": 0, + "/nat44-ed/in2out/fastpath/udp": 0, + "/nat44-ed/in2out/fastpath/icmp": 0, + "/nat44-ed/in2out/fastpath/drops": 0, + "/nat44-ed/in2out/slowpath/tcp": 0, + "/nat44-ed/in2out/slowpath/udp": 0, + "/nat44-ed/in2out/slowpath/icmp": 0, + "/nat44-ed/in2out/slowpath/drops": 0, + } + for pg in cls.pg_interfaces } - for pg in cls.pg_interfaces - }) + ) def get_err_counter(self, path): return self.statistics.get_err_counter(path) - def reass_hairpinning(self, server_addr, server_in_port, server_out_port, - host_in_port, proto=IP_PROTOS.tcp, - ignore_port=False): + def reass_hairpinning( + self, + server_addr, + server_in_port, + server_out_port, + host_in_port, + proto=IP_PROTOS.tcp, + ignore_port=False, + ): layer = self.proto2layer(proto) if proto == IP_PROTOS.tcp: @@ -250,19 +297,14 @@ class TestNAT44ED(VppTestCase): data = b"A" * 16 + b"B" * 16 + b"C" * 3 # send packet from host to server - pkts = self.create_stream_frag(self.pg0, - self.nat_addr, - host_in_port, - server_out_port, - data, - proto) + pkts = self.create_stream_frag( + self.pg0, self.nat_addr, host_in_port, server_out_port, data, proto + ) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() frags = self.pg0.get_capture(len(pkts)) - p = self.reass_frags_and_verify(frags, - self.nat_addr, - server_addr) + p = self.reass_frags_and_verify(frags, self.nat_addr, server_addr) if proto != IP_PROTOS.icmp: if not ignore_port: self.assertNotEqual(p[layer].sport, host_in_port) @@ -272,8 +314,9 @@ class TestNAT44ED(VppTestCase): self.assertNotEqual(p[layer].id, host_in_port) self.assertEqual(data, p[Raw].load) - def frag_out_of_order(self, proto=IP_PROTOS.tcp, dont_translate=False, - ignore_port=False): + def frag_out_of_order( + self, proto=IP_PROTOS.tcp, dont_translate=False, ignore_port=False + ): layer = self.proto2layer(proto) if proto == IP_PROTOS.tcp: @@ -284,21 +327,22 @@ class TestNAT44ED(VppTestCase): for i in range(2): # in2out - pkts = self.create_stream_frag(self.pg0, self.pg1.remote_ip4, - self.port_in, 20, data, proto) + pkts = self.create_stream_frag( + self.pg0, self.pg1.remote_ip4, self.port_in, 20, data, proto + ) pkts.reverse() self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() frags = self.pg1.get_capture(len(pkts)) if not dont_translate: - p = self.reass_frags_and_verify(frags, - self.nat_addr, - self.pg1.remote_ip4) + p = self.reass_frags_and_verify( + frags, self.nat_addr, self.pg1.remote_ip4 + ) else: - p = self.reass_frags_and_verify(frags, - self.pg0.remote_ip4, - self.pg1.remote_ip4) + p = self.reass_frags_and_verify( + frags, self.pg0.remote_ip4, self.pg1.remote_ip4 + ) if proto != IP_PROTOS.icmp: if not dont_translate: self.assertEqual(p[layer].dport, 20) @@ -325,17 +369,18 @@ class TestNAT44ED(VppTestCase): else: sport = p[layer].id dport = 0 - pkts = self.create_stream_frag(self.pg1, dst_addr, sport, dport, - data, proto, echo_reply=True) + pkts = self.create_stream_frag( + self.pg1, dst_addr, sport, dport, data, proto, echo_reply=True + ) pkts.reverse() self.pg1.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.logger.info(self.vapi.cli("show trace")) self.pg_start() frags = self.pg0.get_capture(len(pkts)) - p = self.reass_frags_and_verify(frags, - self.pg1.remote_ip4, - self.pg0.remote_ip4) + p = self.reass_frags_and_verify( + frags, self.pg1.remote_ip4, self.pg0.remote_ip4 + ) if proto != IP_PROTOS.icmp: self.assertEqual(p[layer].sport, 20) self.assertEqual(p[layer].dport, self.port_in) @@ -351,21 +396,20 @@ class TestNAT44ED(VppTestCase): self.assert_ip_checksum_valid(p) buffer.seek(p[IP].frag * 8) buffer.write(bytes(p[IP].payload)) - ip = IP(src=frags[0][IP].src, dst=frags[0][IP].dst, - proto=frags[0][IP].proto) + ip = IP(src=frags[0][IP].src, dst=frags[0][IP].dst, proto=frags[0][IP].proto) if ip.proto == IP_PROTOS.tcp: - p = (ip / TCP(buffer.getvalue())) + p = ip / TCP(buffer.getvalue()) self.logger.debug(ppp("Reassembled:", p)) self.assert_tcp_checksum_valid(p) elif ip.proto == IP_PROTOS.udp: - p = (ip / UDP(buffer.getvalue()[:8]) / - Raw(buffer.getvalue()[8:])) + p = ip / UDP(buffer.getvalue()[:8]) / Raw(buffer.getvalue()[8:]) elif ip.proto == IP_PROTOS.icmp: - p = (ip / ICMP(buffer.getvalue())) + p = ip / ICMP(buffer.getvalue()) return p - def frag_in_order(self, proto=IP_PROTOS.tcp, dont_translate=False, - ignore_port=False): + def frag_in_order( + self, proto=IP_PROTOS.tcp, dont_translate=False, ignore_port=False + ): layer = self.proto2layer(proto) if proto == IP_PROTOS.tcp: @@ -375,20 +419,19 @@ class TestNAT44ED(VppTestCase): self.port_in = self.random_port() # in2out - pkts = self.create_stream_frag(self.pg0, self.pg1.remote_ip4, - self.port_in, 20, data, proto) + pkts = self.create_stream_frag( + self.pg0, self.pg1.remote_ip4, self.port_in, 20, data, proto + ) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() frags = self.pg1.get_capture(len(pkts)) if not dont_translate: - p = self.reass_frags_and_verify(frags, - self.nat_addr, - self.pg1.remote_ip4) + p = self.reass_frags_and_verify(frags, self.nat_addr, self.pg1.remote_ip4) else: - p = self.reass_frags_and_verify(frags, - self.pg0.remote_ip4, - self.pg1.remote_ip4) + p = self.reass_frags_and_verify( + frags, self.pg0.remote_ip4, self.pg1.remote_ip4 + ) if proto != IP_PROTOS.icmp: if not dont_translate: self.assertEqual(p[layer].dport, 20) @@ -415,15 +458,14 @@ class TestNAT44ED(VppTestCase): else: sport = p[layer].id dport = 0 - pkts = self.create_stream_frag(self.pg1, dst_addr, sport, dport, data, - proto, echo_reply=True) + pkts = self.create_stream_frag( + self.pg1, dst_addr, sport, dport, data, proto, echo_reply=True + ) self.pg1.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() frags = self.pg0.get_capture(len(pkts)) - p = self.reass_frags_and_verify(frags, - self.pg1.remote_ip4, - self.pg0.remote_ip4) + p = self.reass_frags_and_verify(frags, self.pg1.remote_ip4, self.pg0.remote_ip4) if proto != IP_PROTOS.icmp: self.assertEqual(p[layer].sport, 20) self.assertEqual(p[layer].dport, self.port_in) @@ -431,8 +473,9 @@ class TestNAT44ED(VppTestCase): self.assertEqual(p[layer].id, self.port_in) self.assertEqual(data, p[Raw].load) - def verify_capture_out(self, capture, nat_ip=None, same_port=False, - dst_ip=None, ignore_port=False): + def verify_capture_out( + self, capture, nat_ip=None, same_port=False, dst_ip=None, ignore_port=False + ): if nat_ip is None: nat_ip = self.nat_addr for packet in capture: @@ -444,35 +487,30 @@ class TestNAT44ED(VppTestCase): if packet.haslayer(TCP): if not ignore_port: if same_port: - self.assertEqual( - packet[TCP].sport, self.tcp_port_in) + self.assertEqual(packet[TCP].sport, self.tcp_port_in) else: - self.assertNotEqual( - packet[TCP].sport, self.tcp_port_in) + self.assertNotEqual(packet[TCP].sport, self.tcp_port_in) self.tcp_port_out = packet[TCP].sport self.assert_packet_checksums_valid(packet) elif packet.haslayer(UDP): if not ignore_port: if same_port: - self.assertEqual( - packet[UDP].sport, self.udp_port_in) + self.assertEqual(packet[UDP].sport, self.udp_port_in) else: - self.assertNotEqual( - packet[UDP].sport, self.udp_port_in) + self.assertNotEqual(packet[UDP].sport, self.udp_port_in) self.udp_port_out = packet[UDP].sport else: if not ignore_port: if same_port: - self.assertEqual( - packet[ICMP].id, self.icmp_id_in) + self.assertEqual(packet[ICMP].id, self.icmp_id_in) else: - self.assertNotEqual( - packet[ICMP].id, self.icmp_id_in) + self.assertNotEqual(packet[ICMP].id, self.icmp_id_in) self.icmp_id_out = packet[ICMP].id self.assert_packet_checksums_valid(packet) except: - self.logger.error(ppp("Unexpected or invalid packet " - "(outside network):", packet)) + self.logger.error( + ppp("Unexpected or invalid packet (outside network):", packet) + ) raise def verify_capture_in(self, capture, in_if): @@ -487,8 +525,9 @@ class TestNAT44ED(VppTestCase): else: self.assertEqual(packet[ICMP].id, self.icmp_id_in) except: - self.logger.error(ppp("Unexpected or invalid packet " - "(inside network):", packet)) + self.logger.error( + ppp("Unexpected or invalid packet (inside network):", packet) + ) raise def create_stream_in(self, in_if, out_if, dst_ip=None, ttl=64): @@ -497,27 +536,32 @@ class TestNAT44ED(VppTestCase): pkts = [] # TCP - p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) / - IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl) / - TCP(sport=self.tcp_port_in, dport=20)) + p = ( + Ether(dst=in_if.local_mac, src=in_if.remote_mac) + / IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl) + / TCP(sport=self.tcp_port_in, dport=20) + ) pkts.extend([p, p]) # UDP - p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) / - IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl) / - UDP(sport=self.udp_port_in, dport=20)) + p = ( + Ether(dst=in_if.local_mac, src=in_if.remote_mac) + / IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl) + / UDP(sport=self.udp_port_in, dport=20) + ) pkts.append(p) # ICMP - p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) / - IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl) / - ICMP(id=self.icmp_id_in, type='echo-request')) + p = ( + Ether(dst=in_if.local_mac, src=in_if.remote_mac) + / IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl) + / ICMP(id=self.icmp_id_in, type="echo-request") + ) pkts.append(p) return pkts - def create_stream_out(self, out_if, dst_ip=None, ttl=64, - use_inside_ports=False): + def create_stream_out(self, out_if, dst_ip=None, ttl=64, use_inside_ports=False): if dst_ip is None: dst_ip = self.nat_addr if not use_inside_ports: @@ -530,21 +574,27 @@ class TestNAT44ED(VppTestCase): icmp_id = self.icmp_id_in pkts = [] # TCP - p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) / - IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) / - TCP(dport=tcp_port, sport=20)) + p = ( + Ether(dst=out_if.local_mac, src=out_if.remote_mac) + / IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) + / TCP(dport=tcp_port, sport=20) + ) pkts.extend([p, p]) # UDP - p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) / - IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) / - UDP(dport=udp_port, sport=20)) + p = ( + Ether(dst=out_if.local_mac, src=out_if.remote_mac) + / IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) + / UDP(dport=udp_port, sport=20) + ) pkts.append(p) # ICMP - p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) / - IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) / - ICMP(id=icmp_id, type='echo-reply')) + p = ( + Ether(dst=out_if.local_mac, src=out_if.remote_mac) + / IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) + / ICMP(id=icmp_id, type="echo-reply") + ) pkts.append(p) return pkts @@ -554,19 +604,24 @@ class TestNAT44ED(VppTestCase): port = 6303 for i in range(count): - p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) / - IP(src=in_if.remote_ip4, dst=out_if.remote_ip4, ttl=64) / - TCP(sport=port + i, dport=20)) + p = ( + Ether(dst=in_if.local_mac, src=in_if.remote_mac) + / IP(src=in_if.remote_ip4, dst=out_if.remote_ip4, ttl=64) + / TCP(sport=port + i, dport=20) + ) pkts.append(p) return pkts - def create_stream_frag(self, src_if, dst, sport, dport, data, - proto=IP_PROTOS.tcp, echo_reply=False): + def create_stream_frag( + self, src_if, dst, sport, dport, data, proto=IP_PROTOS.tcp, echo_reply=False + ): if proto == IP_PROTOS.tcp: - p = (IP(src=src_if.remote_ip4, dst=dst) / - TCP(sport=sport, dport=dport) / - Raw(data)) + p = ( + IP(src=src_if.remote_ip4, dst=dst) + / TCP(sport=sport, dport=dport) + / Raw(data) + ) p = p.__class__(scapy.compat.raw(p)) chksum = p[TCP].chksum proto_header = TCP(sport=sport, dport=dport, chksum=chksum) @@ -574,9 +629,9 @@ class TestNAT44ED(VppTestCase): proto_header = UDP(sport=sport, dport=dport) elif proto == IP_PROTOS.icmp: if not echo_reply: - proto_header = ICMP(id=sport, type='echo-request') + proto_header = ICMP(id=sport, type="echo-request") else: - proto_header = ICMP(id=sport, type='echo-reply') + proto_header = ICMP(id=sport, type="echo-reply") else: raise Exception("Unsupported protocol") id = self.random_port() @@ -585,33 +640,38 @@ class TestNAT44ED(VppTestCase): raw = Raw(data[0:4]) else: raw = Raw(data[0:16]) - p = (Ether(src=src_if.remote_mac, dst=src_if.local_mac) / - IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=0, id=id) / - proto_header / - raw) + p = ( + Ether(src=src_if.remote_mac, dst=src_if.local_mac) + / IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=0, id=id) + / proto_header + / raw + ) pkts.append(p) if proto == IP_PROTOS.tcp: raw = Raw(data[4:20]) else: raw = Raw(data[16:32]) - p = (Ether(src=src_if.remote_mac, dst=src_if.local_mac) / - IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=3, id=id, - proto=proto) / - raw) + p = ( + Ether(src=src_if.remote_mac, dst=src_if.local_mac) + / IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=3, id=id, proto=proto) + / raw + ) pkts.append(p) if proto == IP_PROTOS.tcp: raw = Raw(data[20:]) else: raw = Raw(data[32:]) - p = (Ether(src=src_if.remote_mac, dst=src_if.local_mac) / - IP(src=src_if.remote_ip4, dst=dst, frag=5, proto=proto, - id=id) / - raw) + p = ( + Ether(src=src_if.remote_mac, dst=src_if.local_mac) + / IP(src=src_if.remote_ip4, dst=dst, frag=5, proto=proto, id=id) + / raw + ) pkts.append(p) return pkts - def frag_in_order_in_plus_out(self, in_addr, out_addr, in_port, out_port, - proto=IP_PROTOS.tcp): + def frag_in_order_in_plus_out( + self, in_addr, out_addr, in_port, out_port, proto=IP_PROTOS.tcp + ): layer = self.proto2layer(proto) @@ -623,16 +683,14 @@ class TestNAT44ED(VppTestCase): for i in range(2): # out2in - pkts = self.create_stream_frag(self.pg0, out_addr, - port_in, out_port, - data, proto) + pkts = self.create_stream_frag( + self.pg0, out_addr, port_in, out_port, data, proto + ) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() frags = self.pg1.get_capture(len(pkts)) - p = self.reass_frags_and_verify(frags, - self.pg0.remote_ip4, - in_addr) + p = self.reass_frags_and_verify(frags, self.pg0.remote_ip4, in_addr) if proto != IP_PROTOS.icmp: self.assertEqual(p[layer].sport, port_in) self.assertEqual(p[layer].dport, in_port) @@ -642,20 +700,24 @@ class TestNAT44ED(VppTestCase): # in2out if proto != IP_PROTOS.icmp: - pkts = self.create_stream_frag(self.pg1, self.pg0.remote_ip4, - in_port, - p[layer].sport, data, proto) + pkts = self.create_stream_frag( + self.pg1, self.pg0.remote_ip4, in_port, p[layer].sport, data, proto + ) else: - pkts = self.create_stream_frag(self.pg1, self.pg0.remote_ip4, - p[layer].id, 0, data, proto, - echo_reply=True) + pkts = self.create_stream_frag( + self.pg1, + self.pg0.remote_ip4, + p[layer].id, + 0, + data, + proto, + echo_reply=True, + ) self.pg1.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() frags = self.pg0.get_capture(len(pkts)) - p = self.reass_frags_and_verify(frags, - out_addr, - self.pg0.remote_ip4) + p = self.reass_frags_and_verify(frags, out_addr, self.pg0.remote_ip4) if proto != IP_PROTOS.icmp: self.assertEqual(p[layer].sport, out_port) self.assertEqual(p[layer].dport, port_in) @@ -663,8 +725,9 @@ class TestNAT44ED(VppTestCase): self.assertEqual(p[layer].id, port_in) self.assertEqual(data, p[Raw].load) - def frag_out_of_order_in_plus_out(self, in_addr, out_addr, in_port, - out_port, proto=IP_PROTOS.tcp): + def frag_out_of_order_in_plus_out( + self, in_addr, out_addr, in_port, out_port, proto=IP_PROTOS.tcp + ): layer = self.proto2layer(proto) @@ -676,17 +739,15 @@ class TestNAT44ED(VppTestCase): for i in range(2): # out2in - pkts = self.create_stream_frag(self.pg0, out_addr, - port_in, out_port, - data, proto) + pkts = self.create_stream_frag( + self.pg0, out_addr, port_in, out_port, data, proto + ) pkts.reverse() self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() frags = self.pg1.get_capture(len(pkts)) - p = self.reass_frags_and_verify(frags, - self.pg0.remote_ip4, - in_addr) + p = self.reass_frags_and_verify(frags, self.pg0.remote_ip4, in_addr) if proto != IP_PROTOS.icmp: self.assertEqual(p[layer].dport, in_port) self.assertEqual(p[layer].sport, port_in) @@ -697,21 +758,25 @@ class TestNAT44ED(VppTestCase): # in2out if proto != IP_PROTOS.icmp: - pkts = self.create_stream_frag(self.pg1, self.pg0.remote_ip4, - in_port, - p[layer].sport, data, proto) + pkts = self.create_stream_frag( + self.pg1, self.pg0.remote_ip4, in_port, p[layer].sport, data, proto + ) else: - pkts = self.create_stream_frag(self.pg1, self.pg0.remote_ip4, - p[layer].id, 0, data, proto, - echo_reply=True) + pkts = self.create_stream_frag( + self.pg1, + self.pg0.remote_ip4, + p[layer].id, + 0, + data, + proto, + echo_reply=True, + ) pkts.reverse() self.pg1.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() frags = self.pg0.get_capture(len(pkts)) - p = self.reass_frags_and_verify(frags, - out_addr, - self.pg0.remote_ip4) + p = self.reass_frags_and_verify(frags, out_addr, self.pg0.remote_ip4) if proto != IP_PROTOS.icmp: self.assertEqual(p[layer].sport, out_port) self.assertEqual(p[layer].dport, port_in) @@ -721,9 +786,11 @@ class TestNAT44ED(VppTestCase): def init_tcp_session(self, in_if, out_if, in_port, ext_port): # SYN packet in->out - p = (Ether(src=in_if.remote_mac, dst=in_if.local_mac) / - IP(src=in_if.remote_ip4, dst=out_if.remote_ip4) / - TCP(sport=in_port, dport=ext_port, flags="S")) + p = ( + Ether(src=in_if.remote_mac, dst=in_if.local_mac) + / IP(src=in_if.remote_ip4, dst=out_if.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="S") + ) in_if.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -732,18 +799,22 @@ class TestNAT44ED(VppTestCase): out_port = p[TCP].sport # SYN + ACK packet out->in - p = (Ether(src=out_if.remote_mac, dst=out_if.local_mac) / - IP(src=out_if.remote_ip4, dst=self.nat_addr) / - TCP(sport=ext_port, dport=out_port, flags="SA")) + p = ( + Ether(src=out_if.remote_mac, dst=out_if.local_mac) + / IP(src=out_if.remote_ip4, dst=self.nat_addr) + / TCP(sport=ext_port, dport=out_port, flags="SA") + ) out_if.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() in_if.get_capture(1) # ACK packet in->out - p = (Ether(src=in_if.remote_mac, dst=in_if.local_mac) / - IP(src=in_if.remote_ip4, dst=out_if.remote_ip4) / - TCP(sport=in_port, dport=ext_port, flags="A")) + p = ( + Ether(src=in_if.remote_mac, dst=in_if.local_mac) + / IP(src=in_if.remote_ip4, dst=out_if.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="A") + ) in_if.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -751,9 +822,10 @@ class TestNAT44ED(VppTestCase): return out_port - def twice_nat_common(self, self_twice_nat=False, same_pg=False, lb=False, - client_id=None): - twice_nat_addr = '10.0.1.3' + def twice_nat_common( + self, self_twice_nat=False, same_pg=False, lb=False, client_id=None + ): + twice_nat_addr = "10.0.1.3" port_in = 8080 if lb: @@ -780,8 +852,7 @@ class TestNAT44ED(VppTestCase): else: pg1 = self.pg1 - eh_translate = ((not self_twice_nat) or (not lb and same_pg) or - client_id == 1) + eh_translate = (not self_twice_nat) or (not lb and same_pg) or client_id == 1 self.nat_add_address(self.nat_addr) self.nat_add_address(twice_nat_addr, twice_nat=1) @@ -793,27 +864,30 @@ class TestNAT44ED(VppTestCase): flags |= self.config_flags.NAT_IS_TWICE_NAT if not lb: - self.nat_add_static_mapping(pg0.remote_ip4, self.nat_addr, - port_in, port_out, - proto=IP_PROTOS.tcp, - flags=flags) + self.nat_add_static_mapping( + pg0.remote_ip4, + self.nat_addr, + port_in, + port_out, + proto=IP_PROTOS.tcp, + flags=flags, + ) else: - locals = [{'addr': server1.ip4, - 'port': port_in1, - 'probability': 50, - 'vrf_id': 0}, - {'addr': server2.ip4, - 'port': port_in2, - 'probability': 50, - 'vrf_id': 0}] + locals = [ + {"addr": server1.ip4, "port": port_in1, "probability": 50, "vrf_id": 0}, + {"addr": server2.ip4, "port": port_in2, "probability": 50, "vrf_id": 0}, + ] out_addr = self.nat_addr - self.vapi.nat44_add_del_lb_static_mapping(is_add=1, flags=flags, - external_addr=out_addr, - external_port=port_out, - protocol=IP_PROTOS.tcp, - local_num=len(locals), - locals=locals) + self.vapi.nat44_add_del_lb_static_mapping( + is_add=1, + flags=flags, + external_addr=out_addr, + external_port=port_out, + protocol=IP_PROTOS.tcp, + local_num=len(locals), + locals=locals, + ) self.nat_add_inside_interface(pg0) self.nat_add_outside_interface(pg1) @@ -828,9 +902,11 @@ class TestNAT44ED(VppTestCase): client = self.pg0.remote_hosts[1] else: client = pg1.remote_hosts[0] - p = (Ether(src=pg1.remote_mac, dst=pg1.local_mac) / - IP(src=client.ip4, dst=self.nat_addr) / - TCP(sport=eh_port_out, dport=port_out)) + p = ( + Ether(src=pg1.remote_mac, dst=pg1.local_mac) + / IP(src=client.ip4, dst=self.nat_addr) + / TCP(sport=eh_port_out, dport=port_out) + ) pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -865,9 +941,11 @@ class TestNAT44ED(VppTestCase): self.logger.error(ppp("Unexpected or invalid packet:", p)) raise - p = (Ether(src=server.mac, dst=pg0.local_mac) / - IP(src=server.ip4, dst=eh_addr_in) / - TCP(sport=saved_port_in, dport=eh_port_in)) + p = ( + Ether(src=server.mac, dst=pg0.local_mac) + / IP(src=server.ip4, dst=eh_addr_in) + / TCP(sport=saved_port_in, dport=eh_port_in) + ) pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -888,24 +966,25 @@ class TestNAT44ED(VppTestCase): if eh_translate: sessions = self.vapi.nat44_user_session_dump(server.ip4, 0) self.assertEqual(len(sessions), 1) - self.assertTrue(sessions[0].flags & - self.config_flags.NAT_IS_EXT_HOST_VALID) - self.assertTrue(sessions[0].flags & - self.config_flags.NAT_IS_TWICE_NAT) + self.assertTrue(sessions[0].flags & self.config_flags.NAT_IS_EXT_HOST_VALID) + self.assertTrue(sessions[0].flags & self.config_flags.NAT_IS_TWICE_NAT) self.logger.info(self.vapi.cli("show nat44 sessions")) self.vapi.nat44_del_session( address=sessions[0].inside_ip_address, port=sessions[0].inside_port, protocol=sessions[0].protocol, - flags=(self.config_flags.NAT_IS_INSIDE | - self.config_flags.NAT_IS_EXT_HOST_VALID), + flags=( + self.config_flags.NAT_IS_INSIDE + | self.config_flags.NAT_IS_EXT_HOST_VALID + ), ext_host_address=sessions[0].ext_host_nat_address, - ext_host_port=sessions[0].ext_host_nat_port) + ext_host_port=sessions[0].ext_host_nat_port, + ) sessions = self.vapi.nat44_user_session_dump(server.ip4, 0) self.assertEqual(len(sessions), 0) def verify_syslog_sess(self, data, msgid, is_ip6=False): - message = data.decode('utf-8') + message = data.decode("utf-8") try: message = SyslogMessage.parse(message) except ParseError as e: @@ -913,29 +992,28 @@ class TestNAT44ED(VppTestCase): raise else: self.assertEqual(message.severity, SyslogSeverity.info) - self.assertEqual(message.appname, 'NAT') + self.assertEqual(message.appname, "NAT") self.assertEqual(message.msgid, msgid) - sd_params = message.sd.get('nsess') + sd_params = message.sd.get("nsess") self.assertTrue(sd_params is not None) if is_ip6: - self.assertEqual(sd_params.get('IATYP'), 'IPv6') - self.assertEqual(sd_params.get('ISADDR'), self.pg0.remote_ip6) + self.assertEqual(sd_params.get("IATYP"), "IPv6") + self.assertEqual(sd_params.get("ISADDR"), self.pg0.remote_ip6) else: - self.assertEqual(sd_params.get('IATYP'), 'IPv4') - self.assertEqual(sd_params.get('ISADDR'), self.pg0.remote_ip4) - self.assertTrue(sd_params.get('SSUBIX') is not None) - self.assertEqual(sd_params.get('ISPORT'), "%d" % self.tcp_port_in) - self.assertEqual(sd_params.get('XATYP'), 'IPv4') - self.assertEqual(sd_params.get('XSADDR'), self.nat_addr) - self.assertEqual(sd_params.get('XSPORT'), "%d" % self.tcp_port_out) - self.assertEqual(sd_params.get('PROTO'), "%d" % IP_PROTOS.tcp) - self.assertEqual(sd_params.get('SVLAN'), '0') - self.assertEqual(sd_params.get('XDADDR'), self.pg1.remote_ip4) - self.assertEqual(sd_params.get('XDPORT'), - "%d" % self.tcp_external_port) + self.assertEqual(sd_params.get("IATYP"), "IPv4") + self.assertEqual(sd_params.get("ISADDR"), self.pg0.remote_ip4) + self.assertTrue(sd_params.get("SSUBIX") is not None) + self.assertEqual(sd_params.get("ISPORT"), "%d" % self.tcp_port_in) + self.assertEqual(sd_params.get("XATYP"), "IPv4") + self.assertEqual(sd_params.get("XSADDR"), self.nat_addr) + self.assertEqual(sd_params.get("XSPORT"), "%d" % self.tcp_port_out) + self.assertEqual(sd_params.get("PROTO"), "%d" % IP_PROTOS.tcp) + self.assertEqual(sd_params.get("SVLAN"), "0") + self.assertEqual(sd_params.get("XDADDR"), self.pg1.remote_ip4) + self.assertEqual(sd_params.get("XDPORT"), "%d" % self.tcp_external_port) def test_icmp_error(self): - """ NAT44ED test ICMP error message with inner header""" + """NAT44ED test ICMP error message with inner header""" payload = "H" * 10 @@ -944,25 +1022,31 @@ class TestNAT44ED(VppTestCase): self.nat_add_outside_interface(self.pg1) # in2out (initiate connection) - p1 = [Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - UDP(sport=21, dport=20) / payload, - Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=21, dport=20, flags="S") / payload, - Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - ICMP(type='echo-request', id=7777) / payload, - ] + p1 = [ + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / UDP(sport=21, dport=20) + / payload, + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=21, dport=20, flags="S") + / payload, + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / ICMP(type="echo-request", id=7777) + / payload, + ] capture = self.send_and_expect(self.pg0, p1, self.pg1) # out2in (send error message) - p2 = [Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - ICMP(type='dest-unreach', code='port-unreachable') / - c[IP:] - for c in capture] + p2 = [ + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / ICMP(type="dest-unreach", code="port-unreachable") + / c[IP:] + for c in capture + ] capture = self.send_and_expect(self.pg1, p2, self.pg0) @@ -971,20 +1055,21 @@ class TestNAT44ED(VppTestCase): assert c[IP].dst == self.pg0.remote_ip4 assert c[IPerror].src == self.pg0.remote_ip4 except AssertionError as a: - raise AssertionError( - f"Packet {pr(c)} not translated properly") from a + raise AssertionError(f"Packet {pr(c)} not translated properly") from a def test_icmp_echo_reply_trailer(self): - """ ICMP echo reply with ethernet trailer""" + """ICMP echo reply with ethernet trailer""" self.nat_add_address(self.nat_addr) self.nat_add_inside_interface(self.pg0) self.nat_add_outside_interface(self.pg1) # in2out - p1 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - ICMP(type=8, id=0xabcd, seq=0)) + p1 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / ICMP(type=8, id=0xABCD, seq=0) + ) self.pg0.add_stream(p1) self.pg_enable_capture(self.pg_interfaces) @@ -994,9 +1079,11 @@ class TestNAT44ED(VppTestCase): self.logger.debug(self.vapi.cli("show trace")) # out2in - p2 = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr, id=0xee59) / - ICMP(type=0, id=c[ICMP].id, seq=0)) + p2 = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr, id=0xEE59) + / ICMP(type=0, id=c[ICMP].id, seq=0) + ) # force checksum calculation p2 = p2.__class__(bytes(p2)) @@ -1019,7 +1106,7 @@ class TestNAT44ED(VppTestCase): self.pg0.get_capture(1) def test_users_dump(self): - """ NAT44ED API test - nat44_user_dump """ + """NAT44ED API test - nat44_user_dump""" self.nat_add_address(self.nat_addr) self.nat_add_inside_interface(self.pg0) @@ -1061,9 +1148,9 @@ class TestNAT44ED(VppTestCase): host0 = self.pg0.remote_hosts[0] self.pg0.remote_hosts[0] = self.pg0.remote_hosts[1] try: - pkts = self.create_stream_out(self.pg1, - dst_ip=self.pg0.remote_ip4, - use_inside_ports=True) + pkts = self.create_stream_out( + self.pg1, dst_ip=self.pg0.remote_ip4, use_inside_ports=True + ) self.pg1.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1075,8 +1162,7 @@ class TestNAT44ED(VppTestCase): self.pg_enable_capture(self.pg_interfaces) self.pg_start() capture = self.pg1.get_capture(len(pkts)) - self.verify_capture_out(capture, nat_ip=self.pg0.remote_ip4, - same_port=True) + self.verify_capture_out(capture, nat_ip=self.pg0.remote_ip4, same_port=True) finally: self.pg0.remote_hosts[0] = host0 @@ -1107,14 +1193,14 @@ class TestNAT44ED(VppTestCase): self.assertEqual(non_static_user.nsessions, 3) def test_frag_out_of_order_do_not_translate(self): - """ NAT44ED don't translate fragments arriving out of order """ + """NAT44ED don't translate fragments arriving out of order""" self.nat_add_inside_interface(self.pg0) self.nat_add_outside_interface(self.pg1) self.vapi.nat44_forwarding_enable_disable(enable=True) self.frag_out_of_order(proto=IP_PROTOS.tcp, dont_translate=True) def test_forwarding(self): - """ NAT44ED forwarding test """ + """NAT44ED forwarding test""" self.nat_add_inside_interface(self.pg0) self.nat_add_outside_interface(self.pg1) @@ -1123,11 +1209,13 @@ class TestNAT44ED(VppTestCase): real_ip = self.pg0.remote_ip4 alias_ip = self.nat_addr flags = self.config_flags.NAT_IS_ADDR_ONLY - self.vapi.nat44_add_del_static_mapping(is_add=1, - local_ip_address=real_ip, - external_ip_address=alias_ip, - external_sw_if_index=0xFFFFFFFF, - flags=flags) + self.vapi.nat44_add_del_static_mapping( + is_add=1, + local_ip_address=real_ip, + external_ip_address=alias_ip, + external_sw_if_index=0xFFFFFFFF, + flags=flags, + ) try: # in2out - static mapping match @@ -1151,9 +1239,9 @@ class TestNAT44ED(VppTestCase): host0 = self.pg0.remote_hosts[0] self.pg0.remote_hosts[0] = self.pg0.remote_hosts[1] try: - pkts = self.create_stream_out(self.pg1, - dst_ip=self.pg0.remote_ip4, - use_inside_ports=True) + pkts = self.create_stream_out( + self.pg1, dst_ip=self.pg0.remote_ip4, use_inside_ports=True + ) self.pg1.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1165,24 +1253,27 @@ class TestNAT44ED(VppTestCase): self.pg_enable_capture(self.pg_interfaces) self.pg_start() capture = self.pg1.get_capture(len(pkts)) - self.verify_capture_out(capture, nat_ip=self.pg0.remote_ip4, - same_port=True) + self.verify_capture_out( + capture, nat_ip=self.pg0.remote_ip4, same_port=True + ) finally: self.pg0.remote_hosts[0] = host0 user = self.pg0.remote_hosts[1] sessions = self.vapi.nat44_user_session_dump(user.ip4, 0) self.assertEqual(len(sessions), 3) - self.assertTrue(sessions[0].flags & - self.config_flags.NAT_IS_EXT_HOST_VALID) + self.assertTrue(sessions[0].flags & self.config_flags.NAT_IS_EXT_HOST_VALID) self.vapi.nat44_del_session( address=sessions[0].inside_ip_address, port=sessions[0].inside_port, protocol=sessions[0].protocol, - flags=(self.config_flags.NAT_IS_INSIDE | - self.config_flags.NAT_IS_EXT_HOST_VALID), + flags=( + self.config_flags.NAT_IS_INSIDE + | self.config_flags.NAT_IS_EXT_HOST_VALID + ), ext_host_address=sessions[0].ext_host_address, - ext_host_port=sessions[0].ext_host_port) + ext_host_port=sessions[0].ext_host_port, + ) sessions = self.vapi.nat44_user_session_dump(user.ip4, 0) self.assertEqual(len(sessions), 2) @@ -1194,16 +1285,17 @@ class TestNAT44ED(VppTestCase): local_ip_address=real_ip, external_ip_address=alias_ip, external_sw_if_index=0xFFFFFFFF, - flags=flags) + flags=flags, + ) def test_output_feature_and_service2(self): - """ NAT44ED interface output feature and service host direct access """ + """NAT44ED interface output feature and service host direct access""" self.vapi.nat44_forwarding_enable_disable(enable=1) self.nat_add_address(self.nat_addr) self.vapi.nat44_ed_add_del_output_interface( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) # session initiated from service host - translate pkts = self.create_stream_in(self.pg0, self.pg1) @@ -1230,9 +1322,9 @@ class TestNAT44ED(VppTestCase): self.icmp_id_in = 60305 try: - pkts = self.create_stream_out(self.pg1, - self.pg0.remote_ip4, - use_inside_ports=True) + pkts = self.create_stream_out( + self.pg1, self.pg0.remote_ip4, use_inside_ports=True + ) self.pg1.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1244,40 +1336,37 @@ class TestNAT44ED(VppTestCase): self.pg_enable_capture(self.pg_interfaces) self.pg_start() capture = self.pg1.get_capture(len(pkts)) - self.verify_capture_out(capture, nat_ip=self.pg0.remote_ip4, - same_port=True) + self.verify_capture_out(capture, nat_ip=self.pg0.remote_ip4, same_port=True) finally: self.tcp_port_in = tcp_port_in self.udp_port_in = udp_port_in self.icmp_id_in = icmp_id_in def test_twice_nat(self): - """ NAT44ED Twice NAT """ + """NAT44ED Twice NAT""" self.twice_nat_common() def test_self_twice_nat_positive(self): - """ NAT44ED Self Twice NAT (positive test) """ + """NAT44ED Self Twice NAT (positive test)""" self.twice_nat_common(self_twice_nat=True, same_pg=True) def test_self_twice_nat_lb_positive(self): - """ NAT44ED Self Twice NAT local service load balancing (positive test) - """ - self.twice_nat_common(lb=True, self_twice_nat=True, same_pg=True, - client_id=1) + """NAT44ED Self Twice NAT local service load balancing (positive test)""" + self.twice_nat_common(lb=True, self_twice_nat=True, same_pg=True, client_id=1) def test_twice_nat_lb(self): - """ NAT44ED Twice NAT local service load balancing """ + """NAT44ED Twice NAT local service load balancing""" self.twice_nat_common(lb=True) def test_output_feature(self): - """ NAT44ED interface output feature (in2out postrouting) """ + """NAT44ED interface output feature (in2out postrouting)""" self.vapi.nat44_forwarding_enable_disable(enable=1) self.nat_add_address(self.nat_addr) self.nat_add_outside_interface(self.pg0) self.vapi.nat44_ed_add_del_output_interface( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) # in2out pkts = self.create_stream_in(self.pg0, self.pg1) @@ -1323,24 +1412,31 @@ class TestNAT44ED(VppTestCase): self.assertEqual(p[ICMP].type, 11) # 11 == time-exceeded def test_static_with_port_out2(self): - """ NAT44ED 1:1 NAPT asymmetrical rule """ + """NAT44ED 1:1 NAPT asymmetrical rule""" external_port = 80 local_port = 8080 self.vapi.nat44_forwarding_enable_disable(enable=1) flags = self.config_flags.NAT_IS_OUT2IN_ONLY - self.nat_add_static_mapping(self.pg0.remote_ip4, self.nat_addr, - local_port, external_port, - proto=IP_PROTOS.tcp, flags=flags) + self.nat_add_static_mapping( + self.pg0.remote_ip4, + self.nat_addr, + local_port, + external_port, + proto=IP_PROTOS.tcp, + flags=flags, + ) self.nat_add_inside_interface(self.pg0) self.nat_add_outside_interface(self.pg1) # from client to service - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=12345, dport=external_port)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=12345, dport=external_port) + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1357,9 +1453,12 @@ class TestNAT44ED(VppTestCase): raise # ICMP error - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - ICMP(type=11) / capture[0][IP]) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / ICMP(type=11) + / capture[0][IP] + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1375,9 +1474,11 @@ class TestNAT44ED(VppTestCase): raise # from service back to client - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=local_port, dport=12345)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=local_port, dport=12345) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1394,9 +1495,12 @@ class TestNAT44ED(VppTestCase): raise # ICMP error - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - ICMP(type=11) / capture[0][IP]) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / ICMP(type=11) + / capture[0][IP] + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1412,9 +1516,11 @@ class TestNAT44ED(VppTestCase): raise # from client to server (no translation) - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.pg0.remote_ip4) / - TCP(sport=12346, dport=local_port)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.pg0.remote_ip4) + / TCP(sport=12346, dport=local_port) + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1431,9 +1537,11 @@ class TestNAT44ED(VppTestCase): raise # from service back to client (no translation) - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=local_port, dport=12346)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=local_port, dport=12346) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1450,21 +1558,17 @@ class TestNAT44ED(VppTestCase): raise def test_static_lb(self): - """ NAT44ED local service load balancing """ + """NAT44ED local service load balancing""" external_addr_n = self.nat_addr external_port = 80 local_port = 8080 server1 = self.pg0.remote_hosts[0] server2 = self.pg0.remote_hosts[1] - locals = [{'addr': server1.ip4, - 'port': local_port, - 'probability': 70, - 'vrf_id': 0}, - {'addr': server2.ip4, - 'port': local_port, - 'probability': 30, - 'vrf_id': 0}] + locals = [ + {"addr": server1.ip4, "port": local_port, "probability": 70, "vrf_id": 0}, + {"addr": server2.ip4, "port": local_port, "probability": 30, "vrf_id": 0}, + ] self.nat_add_address(self.nat_addr) self.vapi.nat44_add_del_lb_static_mapping( @@ -1473,19 +1577,22 @@ class TestNAT44ED(VppTestCase): external_port=external_port, protocol=IP_PROTOS.tcp, local_num=len(locals), - locals=locals) + locals=locals, + ) flags = self.config_flags.NAT_IS_INSIDE self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) # from client to service - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=12345, dport=external_port)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=12345, dport=external_port) + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1507,9 +1614,11 @@ class TestNAT44ED(VppTestCase): raise # from service back to client - p = (Ether(src=server.mac, dst=self.pg0.local_mac) / - IP(src=server.ip4, dst=self.pg1.remote_ip4) / - TCP(sport=local_port, dport=12345)) + p = ( + Ether(src=server.mac, dst=self.pg0.local_mac) + / IP(src=server.ip4, dst=self.pg1.remote_ip4) + / TCP(sport=local_port, dport=12345) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1527,56 +1636,59 @@ class TestNAT44ED(VppTestCase): sessions = self.vapi.nat44_user_session_dump(server.ip4, 0) self.assertEqual(len(sessions), 1) - self.assertTrue(sessions[0].flags & - self.config_flags.NAT_IS_EXT_HOST_VALID) + self.assertTrue(sessions[0].flags & self.config_flags.NAT_IS_EXT_HOST_VALID) self.vapi.nat44_del_session( address=sessions[0].inside_ip_address, port=sessions[0].inside_port, protocol=sessions[0].protocol, - flags=(self.config_flags.NAT_IS_INSIDE | - self.config_flags.NAT_IS_EXT_HOST_VALID), + flags=( + self.config_flags.NAT_IS_INSIDE + | self.config_flags.NAT_IS_EXT_HOST_VALID + ), ext_host_address=sessions[0].ext_host_address, - ext_host_port=sessions[0].ext_host_port) + ext_host_port=sessions[0].ext_host_port, + ) sessions = self.vapi.nat44_user_session_dump(server.ip4, 0) self.assertEqual(len(sessions), 0) def test_static_lb_2(self): - """ NAT44ED local service load balancing (asymmetrical rule) """ + """NAT44ED local service load balancing (asymmetrical rule)""" external_addr = self.nat_addr external_port = 80 local_port = 8080 server1 = self.pg0.remote_hosts[0] server2 = self.pg0.remote_hosts[1] - locals = [{'addr': server1.ip4, - 'port': local_port, - 'probability': 70, - 'vrf_id': 0}, - {'addr': server2.ip4, - 'port': local_port, - 'probability': 30, - 'vrf_id': 0}] + locals = [ + {"addr": server1.ip4, "port": local_port, "probability": 70, "vrf_id": 0}, + {"addr": server2.ip4, "port": local_port, "probability": 30, "vrf_id": 0}, + ] self.vapi.nat44_forwarding_enable_disable(enable=1) flags = self.config_flags.NAT_IS_OUT2IN_ONLY - self.vapi.nat44_add_del_lb_static_mapping(is_add=1, flags=flags, - external_addr=external_addr, - external_port=external_port, - protocol=IP_PROTOS.tcp, - local_num=len(locals), - locals=locals) + self.vapi.nat44_add_del_lb_static_mapping( + is_add=1, + flags=flags, + external_addr=external_addr, + external_port=external_port, + protocol=IP_PROTOS.tcp, + local_num=len(locals), + locals=locals, + ) flags = self.config_flags.NAT_IS_INSIDE self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) # from client to service - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=12345, dport=external_port)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=12345, dport=external_port) + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1598,9 +1710,11 @@ class TestNAT44ED(VppTestCase): raise # from service back to client - p = (Ether(src=server.mac, dst=self.pg0.local_mac) / - IP(src=server.ip4, dst=self.pg1.remote_ip4) / - TCP(sport=local_port, dport=12345)) + p = ( + Ether(src=server.mac, dst=self.pg0.local_mac) + / IP(src=server.ip4, dst=self.pg1.remote_ip4) + / TCP(sport=local_port, dport=12345) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1617,9 +1731,11 @@ class TestNAT44ED(VppTestCase): raise # from client to server (no translation) - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=server1.ip4) / - TCP(sport=12346, dport=local_port)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=server1.ip4) + / TCP(sport=12346, dport=local_port) + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1637,9 +1753,11 @@ class TestNAT44ED(VppTestCase): raise # from service back to client (no translation) - p = (Ether(src=server1.mac, dst=self.pg0.local_mac) / - IP(src=server1.ip4, dst=self.pg1.remote_ip4) / - TCP(sport=local_port, dport=12346)) + p = ( + Ether(src=server1.mac, dst=self.pg0.local_mac) + / IP(src=server1.ip4, dst=self.pg1.remote_ip4) + / TCP(sport=local_port, dport=12346) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1656,41 +1774,41 @@ class TestNAT44ED(VppTestCase): raise def test_lb_affinity(self): - """ NAT44ED local service load balancing affinity """ + """NAT44ED local service load balancing affinity""" external_addr = self.nat_addr external_port = 80 local_port = 8080 server1 = self.pg0.remote_hosts[0] server2 = self.pg0.remote_hosts[1] - locals = [{'addr': server1.ip4, - 'port': local_port, - 'probability': 50, - 'vrf_id': 0}, - {'addr': server2.ip4, - 'port': local_port, - 'probability': 50, - 'vrf_id': 0}] + locals = [ + {"addr": server1.ip4, "port": local_port, "probability": 50, "vrf_id": 0}, + {"addr": server2.ip4, "port": local_port, "probability": 50, "vrf_id": 0}, + ] self.nat_add_address(self.nat_addr) - self.vapi.nat44_add_del_lb_static_mapping(is_add=1, - external_addr=external_addr, - external_port=external_port, - protocol=IP_PROTOS.tcp, - affinity=10800, - local_num=len(locals), - locals=locals) + self.vapi.nat44_add_del_lb_static_mapping( + is_add=1, + external_addr=external_addr, + external_port=external_port, + protocol=IP_PROTOS.tcp, + affinity=10800, + local_num=len(locals), + locals=locals, + ) flags = self.config_flags.NAT_IS_INSIDE self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=1025, dport=external_port)) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=1025, dport=external_port) + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1699,22 +1817,26 @@ class TestNAT44ED(VppTestCase): sessions = self.vapi.nat44_user_session_dump(backend, 0) self.assertEqual(len(sessions), 1) - self.assertTrue(sessions[0].flags & - self.config_flags.NAT_IS_EXT_HOST_VALID) + self.assertTrue(sessions[0].flags & self.config_flags.NAT_IS_EXT_HOST_VALID) self.vapi.nat44_del_session( address=sessions[0].inside_ip_address, port=sessions[0].inside_port, protocol=sessions[0].protocol, - flags=(self.config_flags.NAT_IS_INSIDE | - self.config_flags.NAT_IS_EXT_HOST_VALID), + flags=( + self.config_flags.NAT_IS_INSIDE + | self.config_flags.NAT_IS_EXT_HOST_VALID + ), ext_host_address=sessions[0].ext_host_address, - ext_host_port=sessions[0].ext_host_port) + ext_host_port=sessions[0].ext_host_port, + ) pkts = [] for port in range(1030, 1100): - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=port, dport=external_port)) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=port, dport=external_port) + ) pkts.append(p) self.pg1.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) @@ -1724,31 +1846,39 @@ class TestNAT44ED(VppTestCase): self.assertEqual(p[IP].dst, backend) def test_multiple_vrf_1(self): - """ Multiple VRF - both client & service in VRF1 """ + """Multiple VRF - both client & service in VRF1""" - external_addr = '1.2.3.4' + external_addr = "1.2.3.4" external_port = 80 local_port = 8080 port = 0 flags = self.config_flags.NAT_IS_INSIDE self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg5.sw_if_index, - is_add=1) + sw_if_index=self.pg5.sw_if_index, is_add=1 + ) self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg5.sw_if_index, - is_add=1, flags=flags) + sw_if_index=self.pg5.sw_if_index, is_add=1, flags=flags + ) self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg6.sw_if_index, - is_add=1) + sw_if_index=self.pg6.sw_if_index, is_add=1 + ) flags = self.config_flags.NAT_IS_OUT2IN_ONLY - self.nat_add_static_mapping(self.pg5.remote_ip4, external_addr, - local_port, external_port, vrf_id=1, - proto=IP_PROTOS.tcp, flags=flags) + self.nat_add_static_mapping( + self.pg5.remote_ip4, + external_addr, + local_port, + external_port, + vrf_id=1, + proto=IP_PROTOS.tcp, + flags=flags, + ) - p = (Ether(src=self.pg6.remote_mac, dst=self.pg6.local_mac) / - IP(src=self.pg6.remote_ip4, dst=external_addr) / - TCP(sport=12345, dport=external_port)) + p = ( + Ether(src=self.pg6.remote_mac, dst=self.pg6.local_mac) + / IP(src=self.pg6.remote_ip4, dst=external_addr) + / TCP(sport=12345, dport=external_port) + ) self.pg6.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1764,9 +1894,11 @@ class TestNAT44ED(VppTestCase): self.logger.error(ppp("Unexpected or invalid packet:", p)) raise - p = (Ether(src=self.pg5.remote_mac, dst=self.pg5.local_mac) / - IP(src=self.pg5.remote_ip4, dst=self.pg6.remote_ip4) / - TCP(sport=local_port, dport=12345)) + p = ( + Ether(src=self.pg5.remote_mac, dst=self.pg5.local_mac) + / IP(src=self.pg5.remote_ip4, dst=self.pg6.remote_ip4) + / TCP(sport=local_port, dport=12345) + ) self.pg5.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1783,9 +1915,9 @@ class TestNAT44ED(VppTestCase): raise def test_multiple_vrf_2(self): - """ Multiple VRF - dynamic NAT from VRF1 to VRF0 (output-feature) """ + """Multiple VRF - dynamic NAT from VRF1 to VRF0 (output-feature)""" - external_addr = '1.2.3.4' + external_addr = "1.2.3.4" external_port = 80 local_port = 8080 port = 0 @@ -1793,22 +1925,30 @@ class TestNAT44ED(VppTestCase): self.nat_add_address(self.nat_addr) flags = self.config_flags.NAT_IS_INSIDE self.vapi.nat44_ed_add_del_output_interface( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg5.sw_if_index, - is_add=1) + sw_if_index=self.pg5.sw_if_index, is_add=1 + ) self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg5.sw_if_index, - is_add=1, flags=flags) + sw_if_index=self.pg5.sw_if_index, is_add=1, flags=flags + ) flags = self.config_flags.NAT_IS_OUT2IN_ONLY - self.nat_add_static_mapping(self.pg5.remote_ip4, external_addr, - local_port, external_port, vrf_id=1, - proto=IP_PROTOS.tcp, flags=flags) + self.nat_add_static_mapping( + self.pg5.remote_ip4, + external_addr, + local_port, + external_port, + vrf_id=1, + proto=IP_PROTOS.tcp, + flags=flags, + ) - p = (Ether(src=self.pg5.remote_mac, dst=self.pg5.local_mac) / - IP(src=self.pg5.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=2345, dport=22)) + p = ( + Ether(src=self.pg5.remote_mac, dst=self.pg5.local_mac) + / IP(src=self.pg5.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=2345, dport=22) + ) self.pg5.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1824,9 +1964,11 @@ class TestNAT44ED(VppTestCase): self.logger.error(ppp("Unexpected or invalid packet:", p)) raise - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=22, dport=port)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=22, dport=port) + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1843,23 +1985,23 @@ class TestNAT44ED(VppTestCase): raise def test_multiple_vrf_3(self): - """ Multiple VRF - client in VRF1, service in VRF0 """ + """Multiple VRF - client in VRF1, service in VRF0""" - external_addr = '1.2.3.4' + external_addr = "1.2.3.4" external_port = 80 local_port = 8080 port = 0 flags = self.config_flags.NAT_IS_INSIDE self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - is_add=1) + sw_if_index=self.pg0.sw_if_index, is_add=1 + ) self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - is_add=1, flags=flags) + sw_if_index=self.pg0.sw_if_index, is_add=1, flags=flags + ) self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg6.sw_if_index, - is_add=1) + sw_if_index=self.pg6.sw_if_index, is_add=1 + ) flags = self.config_flags.NAT_IS_OUT2IN_ONLY self.nat_add_static_mapping( self.pg0.remote_ip4, @@ -1868,13 +2010,15 @@ class TestNAT44ED(VppTestCase): vrf_id=0, external_port=external_port, proto=IP_PROTOS.tcp, - flags=flags + flags=flags, ) # from client VRF1 to service VRF0 - p = (Ether(src=self.pg6.remote_mac, dst=self.pg6.local_mac) / - IP(src=self.pg6.remote_ip4, dst=self.pg0.local_ip4) / - TCP(sport=12346, dport=external_port)) + p = ( + Ether(src=self.pg6.remote_mac, dst=self.pg6.local_mac) + / IP(src=self.pg6.remote_ip4, dst=self.pg0.local_ip4) + / TCP(sport=12346, dport=external_port) + ) self.pg6.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1891,9 +2035,11 @@ class TestNAT44ED(VppTestCase): raise # from service VRF0 back to client VRF1 - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg6.remote_ip4) / - TCP(sport=local_port, dport=12346)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg6.remote_ip4) + / TCP(sport=local_port, dport=12346) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1910,35 +2056,43 @@ class TestNAT44ED(VppTestCase): raise def test_multiple_vrf_4(self): - """ Multiple VRF - client in VRF0, service in VRF1 """ + """Multiple VRF - client in VRF0, service in VRF1""" - external_addr = '1.2.3.4' + external_addr = "1.2.3.4" external_port = 80 local_port = 8080 port = 0 flags = self.config_flags.NAT_IS_INSIDE self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - is_add=1) + sw_if_index=self.pg0.sw_if_index, is_add=1 + ) self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - is_add=1, flags=flags) + sw_if_index=self.pg0.sw_if_index, is_add=1, flags=flags + ) self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg5.sw_if_index, - is_add=1) + sw_if_index=self.pg5.sw_if_index, is_add=1 + ) self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg5.sw_if_index, - is_add=1, flags=flags) + sw_if_index=self.pg5.sw_if_index, is_add=1, flags=flags + ) flags = self.config_flags.NAT_IS_OUT2IN_ONLY - self.nat_add_static_mapping(self.pg5.remote_ip4, external_addr, - local_port, external_port, vrf_id=1, - proto=IP_PROTOS.tcp, flags=flags) + self.nat_add_static_mapping( + self.pg5.remote_ip4, + external_addr, + local_port, + external_port, + vrf_id=1, + proto=IP_PROTOS.tcp, + flags=flags, + ) # from client VRF0 to service VRF1 - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=external_addr) / - TCP(sport=12347, dport=external_port)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=external_addr) + / TCP(sport=12347, dport=external_port) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1955,9 +2109,11 @@ class TestNAT44ED(VppTestCase): raise # from service VRF1 back to client VRF0 - p = (Ether(src=self.pg5.remote_mac, dst=self.pg5.local_mac) / - IP(src=self.pg5.remote_ip4, dst=self.pg0.remote_ip4) / - TCP(sport=local_port, dport=12347)) + p = ( + Ether(src=self.pg5.remote_mac, dst=self.pg5.local_mac) + / IP(src=self.pg5.remote_ip4, dst=self.pg0.remote_ip4) + / TCP(sport=local_port, dport=12347) + ) self.pg5.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1974,9 +2130,9 @@ class TestNAT44ED(VppTestCase): raise def test_multiple_vrf_5(self): - """ Multiple VRF - forwarding - no translation """ + """Multiple VRF - forwarding - no translation""" - external_addr = '1.2.3.4' + external_addr = "1.2.3.4" external_port = 80 local_port = 8080 port = 0 @@ -1984,24 +2140,30 @@ class TestNAT44ED(VppTestCase): self.vapi.nat44_forwarding_enable_disable(enable=1) flags = self.config_flags.NAT_IS_INSIDE self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - is_add=1) + sw_if_index=self.pg0.sw_if_index, is_add=1 + ) self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - is_add=1, flags=flags) + sw_if_index=self.pg0.sw_if_index, is_add=1, flags=flags + ) self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg5.sw_if_index, - is_add=1) + sw_if_index=self.pg5.sw_if_index, is_add=1 + ) self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg5.sw_if_index, - is_add=1, flags=flags) + sw_if_index=self.pg5.sw_if_index, is_add=1, flags=flags + ) self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg6.sw_if_index, - is_add=1) + sw_if_index=self.pg6.sw_if_index, is_add=1 + ) flags = self.config_flags.NAT_IS_OUT2IN_ONLY - self.nat_add_static_mapping(self.pg5.remote_ip4, external_addr, - local_port, external_port, vrf_id=1, - proto=IP_PROTOS.tcp, flags=flags) + self.nat_add_static_mapping( + self.pg5.remote_ip4, + external_addr, + local_port, + external_port, + vrf_id=1, + proto=IP_PROTOS.tcp, + flags=flags, + ) self.nat_add_static_mapping( self.pg0.remote_ip4, external_sw_if_index=self.pg0.sw_if_index, @@ -2009,13 +2171,15 @@ class TestNAT44ED(VppTestCase): vrf_id=0, external_port=external_port, proto=IP_PROTOS.tcp, - flags=flags + flags=flags, ) # from client to server (both VRF1, no translation) - p = (Ether(src=self.pg6.remote_mac, dst=self.pg6.local_mac) / - IP(src=self.pg6.remote_ip4, dst=self.pg5.remote_ip4) / - TCP(sport=12348, dport=local_port)) + p = ( + Ether(src=self.pg6.remote_mac, dst=self.pg6.local_mac) + / IP(src=self.pg6.remote_ip4, dst=self.pg5.remote_ip4) + / TCP(sport=12348, dport=local_port) + ) self.pg6.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2032,9 +2196,11 @@ class TestNAT44ED(VppTestCase): raise # from server back to client (both VRF1, no translation) - p = (Ether(src=self.pg5.remote_mac, dst=self.pg5.local_mac) / - IP(src=self.pg5.remote_ip4, dst=self.pg6.remote_ip4) / - TCP(sport=local_port, dport=12348)) + p = ( + Ether(src=self.pg5.remote_mac, dst=self.pg5.local_mac) + / IP(src=self.pg5.remote_ip4, dst=self.pg6.remote_ip4) + / TCP(sport=local_port, dport=12348) + ) self.pg5.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2051,9 +2217,11 @@ class TestNAT44ED(VppTestCase): raise # from client VRF1 to server VRF0 (no translation) - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg6.remote_ip4) / - TCP(sport=local_port, dport=12349)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg6.remote_ip4) + / TCP(sport=local_port, dport=12349) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2070,9 +2238,11 @@ class TestNAT44ED(VppTestCase): raise # from server VRF0 back to client VRF1 (no translation) - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg6.remote_ip4) / - TCP(sport=local_port, dport=12349)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg6.remote_ip4) + / TCP(sport=local_port, dport=12349) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2089,9 +2259,11 @@ class TestNAT44ED(VppTestCase): raise # from client VRF0 to server VRF1 (no translation) - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg5.remote_ip4) / - TCP(sport=12344, dport=local_port)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg5.remote_ip4) + / TCP(sport=12344, dport=local_port) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2108,9 +2280,11 @@ class TestNAT44ED(VppTestCase): raise # from server VRF1 back to client VRF0 (no translation) - p = (Ether(src=self.pg5.remote_mac, dst=self.pg5.local_mac) / - IP(src=self.pg5.remote_ip4, dst=self.pg0.remote_ip4) / - TCP(sport=local_port, dport=12344)) + p = ( + Ether(src=self.pg5.remote_mac, dst=self.pg5.local_mac) + / IP(src=self.pg5.remote_ip4, dst=self.pg0.remote_ip4) + / TCP(sport=local_port, dport=12344) + ) self.pg5.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2127,7 +2301,7 @@ class TestNAT44ED(VppTestCase): raise def test_outside_address_distribution(self): - """ Outside address distribution based on source address """ + """Outside address distribution based on source address""" x = 100 nat_addresses = [] @@ -2142,7 +2316,10 @@ class TestNAT44ED(VppTestCase): self.vapi.nat44_add_del_address_range( first_ip_address=nat_addresses[0], last_ip_address=nat_addresses[-1], - vrf_id=0xFFFFFFFF, is_add=1, flags=0) + vrf_id=0xFFFFFFFF, + is_add=1, + flags=0, + ) self.pg0.generate_remote_hosts(x) @@ -2150,11 +2327,12 @@ class TestNAT44ED(VppTestCase): for i in range(x): info = self.create_packet_info(self.pg0, self.pg1) payload = self.info_to_payload(info) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_hosts[i].ip4, - dst=self.pg1.remote_ip4) / - UDP(sport=7000+i, dport=8000+i) / - Raw(payload)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_hosts[i].ip4, dst=self.pg1.remote_ip4) + / UDP(sport=7000 + i, dport=8000 + i) + / Raw(payload) + ) info.data = p pkts.append(p) @@ -2172,20 +2350,23 @@ class TestNAT44ED(VppTestCase): packed = socket.inet_aton(p_sent[IP].src) numeric = struct.unpack("!L", packed)[0] numeric = socket.htonl(numeric) - a = nat_addresses[(numeric-1) % len(nat_addresses)] + a = nat_addresses[(numeric - 1) % len(nat_addresses)] self.assertEqual( - a, p_recvd[IP].src, + a, + p_recvd[IP].src, "Invalid packet (src IP %s translated to %s, but expected %s)" - % (p_sent[IP].src, p_recvd[IP].src, a)) + % (p_sent[IP].src, p_recvd[IP].src, a), + ) class TestNAT44EDMW(TestNAT44ED): - """ NAT44ED MW Test Case """ + """NAT44ED MW Test Case""" + vpp_worker_count = 4 max_sessions = 5000 def test_dynamic(self): - """ NAT44ED dynamic translation test """ + """NAT44ED dynamic translation test""" pkt_count = 1500 tcp_port_offset = 20 udp_port_offset = 20 @@ -2196,27 +2377,33 @@ class TestNAT44EDMW(TestNAT44ED): self.nat_add_outside_interface(self.pg1) # in2out - tc1 = self.statistics['/nat44-ed/in2out/slowpath/tcp'] - uc1 = self.statistics['/nat44-ed/in2out/slowpath/udp'] - ic1 = self.statistics['/nat44-ed/in2out/slowpath/icmp'] - dc1 = self.statistics['/nat44-ed/in2out/slowpath/drops'] + tc1 = self.statistics["/nat44-ed/in2out/slowpath/tcp"] + uc1 = self.statistics["/nat44-ed/in2out/slowpath/udp"] + ic1 = self.statistics["/nat44-ed/in2out/slowpath/icmp"] + dc1 = self.statistics["/nat44-ed/in2out/slowpath/drops"] i2o_pkts = [[] for x in range(0, self.vpp_worker_count)] for i in range(pkt_count): - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=tcp_port_offset + i, dport=20)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=tcp_port_offset + i, dport=20) + ) i2o_pkts[p[TCP].sport % self.vpp_worker_count].append(p) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - UDP(sport=udp_port_offset + i, dport=20)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / UDP(sport=udp_port_offset + i, dport=20) + ) i2o_pkts[p[UDP].sport % self.vpp_worker_count].append(p) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - ICMP(id=icmp_id_offset + i, type='echo-request')) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / ICMP(id=icmp_id_offset + i, type="echo-request") + ) i2o_pkts[p[ICMP].id % self.vpp_worker_count].append(p) for i in range(0, self.vpp_worker_count): @@ -2228,26 +2415,23 @@ class TestNAT44EDMW(TestNAT44ED): capture = self.pg1.get_capture(pkt_count * 3, timeout=5) if_idx = self.pg0.sw_if_index - tc2 = self.statistics['/nat44-ed/in2out/slowpath/tcp'] - uc2 = self.statistics['/nat44-ed/in2out/slowpath/udp'] - ic2 = self.statistics['/nat44-ed/in2out/slowpath/icmp'] - dc2 = self.statistics['/nat44-ed/in2out/slowpath/drops'] - - self.assertEqual( - tc2[:, if_idx].sum() - tc1[:, if_idx].sum(), pkt_count) - self.assertEqual( - uc2[:, if_idx].sum() - uc1[:, if_idx].sum(), pkt_count) - self.assertEqual( - ic2[:, if_idx].sum() - ic1[:, if_idx].sum(), pkt_count) + tc2 = self.statistics["/nat44-ed/in2out/slowpath/tcp"] + uc2 = self.statistics["/nat44-ed/in2out/slowpath/udp"] + ic2 = self.statistics["/nat44-ed/in2out/slowpath/icmp"] + dc2 = self.statistics["/nat44-ed/in2out/slowpath/drops"] + + self.assertEqual(tc2[:, if_idx].sum() - tc1[:, if_idx].sum(), pkt_count) + self.assertEqual(uc2[:, if_idx].sum() - uc1[:, if_idx].sum(), pkt_count) + self.assertEqual(ic2[:, if_idx].sum() - ic1[:, if_idx].sum(), pkt_count) self.assertEqual(dc2[:, if_idx].sum() - dc1[:, if_idx].sum(), 0) self.logger.info(self.vapi.cli("show trace")) # out2in - tc1 = self.statistics['/nat44-ed/out2in/fastpath/tcp'] - uc1 = self.statistics['/nat44-ed/out2in/fastpath/udp'] - ic1 = self.statistics['/nat44-ed/out2in/fastpath/icmp'] - dc1 = self.statistics['/nat44-ed/out2in/fastpath/drops'] + tc1 = self.statistics["/nat44-ed/out2in/fastpath/tcp"] + uc1 = self.statistics["/nat44-ed/out2in/fastpath/udp"] + ic1 = self.statistics["/nat44-ed/out2in/fastpath/icmp"] + dc1 = self.statistics["/nat44-ed/out2in/fastpath/drops"] recvd_tcp_ports = set() recvd_udp_ports = set() @@ -2267,19 +2451,25 @@ class TestNAT44EDMW(TestNAT44ED): o2i_pkts = [[] for x in range(0, self.vpp_worker_count)] for i in range(pkt_count): - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(dport=choice(recvd_tcp_ports), sport=20)) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(dport=choice(recvd_tcp_ports), sport=20) + ) o2i_pkts[p[TCP].dport % self.vpp_worker_count].append(p) - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - UDP(dport=choice(recvd_udp_ports), sport=20)) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / UDP(dport=choice(recvd_udp_ports), sport=20) + ) o2i_pkts[p[UDP].dport % self.vpp_worker_count].append(p) - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - ICMP(id=choice(recvd_icmp_ids), type='echo-reply')) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / ICMP(id=choice(recvd_icmp_ids), type="echo-reply") + ) o2i_pkts[p[ICMP].id % self.vpp_worker_count].append(p) for i in range(0, self.vpp_worker_count): @@ -2295,41 +2485,50 @@ class TestNAT44EDMW(TestNAT44ED): self.assertEqual(packet[IP].dst, self.pg0.remote_ip4) if packet.haslayer(TCP): self.assert_in_range( - packet[TCP].dport, tcp_port_offset, - tcp_port_offset + pkt_count, "dst TCP port") + packet[TCP].dport, + tcp_port_offset, + tcp_port_offset + pkt_count, + "dst TCP port", + ) elif packet.haslayer(UDP): self.assert_in_range( - packet[UDP].dport, udp_port_offset, - udp_port_offset + pkt_count, "dst UDP port") + packet[UDP].dport, + udp_port_offset, + udp_port_offset + pkt_count, + "dst UDP port", + ) else: self.assert_in_range( - packet[ICMP].id, icmp_id_offset, - icmp_id_offset + pkt_count, "ICMP id") + packet[ICMP].id, + icmp_id_offset, + icmp_id_offset + pkt_count, + "ICMP id", + ) except: - self.logger.error(ppp("Unexpected or invalid packet " - "(inside network):", packet)) + self.logger.error( + ppp("Unexpected or invalid packet (inside network):", packet) + ) raise if_idx = self.pg1.sw_if_index - tc2 = self.statistics['/nat44-ed/out2in/fastpath/tcp'] - uc2 = self.statistics['/nat44-ed/out2in/fastpath/udp'] - ic2 = self.statistics['/nat44-ed/out2in/fastpath/icmp'] - dc2 = self.statistics['/nat44-ed/out2in/fastpath/drops'] - - self.assertEqual( - tc2[:, if_idx].sum() - tc1[:, if_idx].sum(), pkt_count) - self.assertEqual( - uc2[:, if_idx].sum() - uc1[:, if_idx].sum(), pkt_count) - self.assertEqual( - ic2[:, if_idx].sum() - ic1[:, if_idx].sum(), pkt_count) + tc2 = self.statistics["/nat44-ed/out2in/fastpath/tcp"] + uc2 = self.statistics["/nat44-ed/out2in/fastpath/udp"] + ic2 = self.statistics["/nat44-ed/out2in/fastpath/icmp"] + dc2 = self.statistics["/nat44-ed/out2in/fastpath/drops"] + + self.assertEqual(tc2[:, if_idx].sum() - tc1[:, if_idx].sum(), pkt_count) + self.assertEqual(uc2[:, if_idx].sum() - uc1[:, if_idx].sum(), pkt_count) + self.assertEqual(ic2[:, if_idx].sum() - ic1[:, if_idx].sum(), pkt_count) self.assertEqual(dc2[:, if_idx].sum() - dc1[:, if_idx].sum(), 0) - sc = self.statistics['/nat44-ed/total-sessions'] - self.assertEqual(sc[:, 0].sum(), len(recvd_tcp_ports) + - len(recvd_udp_ports) + len(recvd_icmp_ids)) + sc = self.statistics["/nat44-ed/total-sessions"] + self.assertEqual( + sc[:, 0].sum(), + len(recvd_tcp_ports) + len(recvd_udp_ports) + len(recvd_icmp_ids), + ) def test_frag_in_order(self): - """ NAT44ED translate fragments arriving in order """ + """NAT44ED translate fragments arriving in order""" self.nat_add_address(self.nat_addr) self.nat_add_inside_interface(self.pg0) @@ -2340,7 +2539,7 @@ class TestNAT44EDMW(TestNAT44ED): self.frag_in_order(proto=IP_PROTOS.icmp, ignore_port=True) def test_frag_in_order_do_not_translate(self): - """ NAT44ED don't translate fragments arriving in order """ + """NAT44ED don't translate fragments arriving in order""" self.nat_add_address(self.nat_addr) self.nat_add_inside_interface(self.pg0) @@ -2350,7 +2549,7 @@ class TestNAT44EDMW(TestNAT44ED): self.frag_in_order(proto=IP_PROTOS.tcp, dont_translate=True) def test_frag_out_of_order(self): - """ NAT44ED translate fragments arriving out of order """ + """NAT44ED translate fragments arriving out of order""" self.nat_add_address(self.nat_addr) self.nat_add_inside_interface(self.pg0) @@ -2361,7 +2560,7 @@ class TestNAT44EDMW(TestNAT44ED): self.frag_out_of_order(proto=IP_PROTOS.icmp, ignore_port=True) def test_frag_in_order_in_plus_out(self): - """ NAT44ED in+out interface fragments in order """ + """NAT44ED in+out interface fragments in order""" in_port = self.random_port() out_port = self.random_port() @@ -2373,39 +2572,29 @@ class TestNAT44EDMW(TestNAT44ED): self.nat_add_outside_interface(self.pg1) # add static mappings for server - self.nat_add_static_mapping(self.server_addr, - self.nat_addr, - in_port, - out_port, - proto=IP_PROTOS.tcp) - self.nat_add_static_mapping(self.server_addr, - self.nat_addr, - in_port, - out_port, - proto=IP_PROTOS.udp) - self.nat_add_static_mapping(self.server_addr, - self.nat_addr, - proto=IP_PROTOS.icmp) + self.nat_add_static_mapping( + self.server_addr, self.nat_addr, in_port, out_port, proto=IP_PROTOS.tcp + ) + self.nat_add_static_mapping( + self.server_addr, self.nat_addr, in_port, out_port, proto=IP_PROTOS.udp + ) + self.nat_add_static_mapping( + self.server_addr, self.nat_addr, proto=IP_PROTOS.icmp + ) # run tests for each protocol - self.frag_in_order_in_plus_out(self.server_addr, - self.nat_addr, - in_port, - out_port, - IP_PROTOS.tcp) - self.frag_in_order_in_plus_out(self.server_addr, - self.nat_addr, - in_port, - out_port, - IP_PROTOS.udp) - self.frag_in_order_in_plus_out(self.server_addr, - self.nat_addr, - in_port, - out_port, - IP_PROTOS.icmp) + self.frag_in_order_in_plus_out( + self.server_addr, self.nat_addr, in_port, out_port, IP_PROTOS.tcp + ) + self.frag_in_order_in_plus_out( + self.server_addr, self.nat_addr, in_port, out_port, IP_PROTOS.udp + ) + self.frag_in_order_in_plus_out( + self.server_addr, self.nat_addr, in_port, out_port, IP_PROTOS.icmp + ) def test_frag_out_of_order_in_plus_out(self): - """ NAT44ED in+out interface fragments out of order """ + """NAT44ED in+out interface fragments out of order""" in_port = self.random_port() out_port = self.random_port() @@ -2417,39 +2606,29 @@ class TestNAT44EDMW(TestNAT44ED): self.nat_add_outside_interface(self.pg1) # add static mappings for server - self.nat_add_static_mapping(self.server_addr, - self.nat_addr, - in_port, - out_port, - proto=IP_PROTOS.tcp) - self.nat_add_static_mapping(self.server_addr, - self.nat_addr, - in_port, - out_port, - proto=IP_PROTOS.udp) - self.nat_add_static_mapping(self.server_addr, - self.nat_addr, - proto=IP_PROTOS.icmp) + self.nat_add_static_mapping( + self.server_addr, self.nat_addr, in_port, out_port, proto=IP_PROTOS.tcp + ) + self.nat_add_static_mapping( + self.server_addr, self.nat_addr, in_port, out_port, proto=IP_PROTOS.udp + ) + self.nat_add_static_mapping( + self.server_addr, self.nat_addr, proto=IP_PROTOS.icmp + ) # run tests for each protocol - self.frag_out_of_order_in_plus_out(self.server_addr, - self.nat_addr, - in_port, - out_port, - IP_PROTOS.tcp) - self.frag_out_of_order_in_plus_out(self.server_addr, - self.nat_addr, - in_port, - out_port, - IP_PROTOS.udp) - self.frag_out_of_order_in_plus_out(self.server_addr, - self.nat_addr, - in_port, - out_port, - IP_PROTOS.icmp) + self.frag_out_of_order_in_plus_out( + self.server_addr, self.nat_addr, in_port, out_port, IP_PROTOS.tcp + ) + self.frag_out_of_order_in_plus_out( + self.server_addr, self.nat_addr, in_port, out_port, IP_PROTOS.udp + ) + self.frag_out_of_order_in_plus_out( + self.server_addr, self.nat_addr, in_port, out_port, IP_PROTOS.icmp + ) def test_reass_hairpinning(self): - """ NAT44ED fragments hairpinning """ + """NAT44ED fragments hairpinning""" server_addr = self.pg0.remote_hosts[1].ip4 @@ -2462,26 +2641,49 @@ class TestNAT44EDMW(TestNAT44ED): self.nat_add_outside_interface(self.pg1) # add static mapping for server - self.nat_add_static_mapping(server_addr, self.nat_addr, - server_in_port, server_out_port, - proto=IP_PROTOS.tcp) - self.nat_add_static_mapping(server_addr, self.nat_addr, - server_in_port, server_out_port, - proto=IP_PROTOS.udp) + self.nat_add_static_mapping( + server_addr, + self.nat_addr, + server_in_port, + server_out_port, + proto=IP_PROTOS.tcp, + ) + self.nat_add_static_mapping( + server_addr, + self.nat_addr, + server_in_port, + server_out_port, + proto=IP_PROTOS.udp, + ) self.nat_add_static_mapping(server_addr, self.nat_addr) - self.reass_hairpinning(server_addr, server_in_port, server_out_port, - host_in_port, proto=IP_PROTOS.tcp, - ignore_port=True) - self.reass_hairpinning(server_addr, server_in_port, server_out_port, - host_in_port, proto=IP_PROTOS.udp, - ignore_port=True) - self.reass_hairpinning(server_addr, server_in_port, server_out_port, - host_in_port, proto=IP_PROTOS.icmp, - ignore_port=True) + self.reass_hairpinning( + server_addr, + server_in_port, + server_out_port, + host_in_port, + proto=IP_PROTOS.tcp, + ignore_port=True, + ) + self.reass_hairpinning( + server_addr, + server_in_port, + server_out_port, + host_in_port, + proto=IP_PROTOS.udp, + ignore_port=True, + ) + self.reass_hairpinning( + server_addr, + server_in_port, + server_out_port, + host_in_port, + proto=IP_PROTOS.icmp, + ignore_port=True, + ) def test_session_limit_per_vrf(self): - """ NAT44ED per vrf session limit """ + """NAT44ED per vrf session limit""" inside = self.pg0 inside_vrf10 = self.pg2 @@ -2520,27 +2722,29 @@ class TestNAT44EDMW(TestNAT44ED): capture = outside.get_capture(len(stream)) def test_show_max_translations(self): - """ NAT44ED API test - max translations per thread """ + """NAT44ED API test - max translations per thread""" config = self.vapi.nat44_show_running_config() - self.assertEqual(self.max_sessions, - config.sessions) + self.assertEqual(self.max_sessions, config.sessions) def test_lru_cleanup(self): - """ NAT44ED LRU cleanup algorithm """ + """NAT44ED LRU cleanup algorithm""" self.nat_add_address(self.nat_addr) self.nat_add_inside_interface(self.pg0) self.nat_add_outside_interface(self.pg1) self.vapi.nat_set_timeouts( - udp=1, tcp_established=7440, tcp_transitory=30, icmp=1) + udp=1, tcp_established=7440, tcp_transitory=30, icmp=1 + ) tcp_port_out = self.init_tcp_session(self.pg0, self.pg1, 2000, 80) pkts = [] for i in range(0, self.max_sessions - 1): - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, ttl=64) / - UDP(sport=7000+i, dport=80)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, ttl=64) + / UDP(sport=7000 + i, dport=80) + ) pkts.append(p) self.pg0.add_stream(pkts) @@ -2551,9 +2755,11 @@ class TestNAT44EDMW(TestNAT44ED): pkts = [] for i in range(0, self.max_sessions - 1): - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, ttl=64) / - ICMP(id=8000+i, type='echo-request')) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, ttl=64) + / ICMP(id=8000 + i, type="echo-request") + ) pkts.append(p) self.pg0.add_stream(pkts) @@ -2562,79 +2768,89 @@ class TestNAT44EDMW(TestNAT44ED): self.pg1.get_capture(len(pkts)) def test_session_rst_timeout(self): - """ NAT44ED session RST timeouts """ + """NAT44ED session RST timeouts""" self.nat_add_address(self.nat_addr) self.nat_add_inside_interface(self.pg0) self.nat_add_outside_interface(self.pg1) - self.vapi.nat_set_timeouts(udp=300, tcp_established=7440, - tcp_transitory=5, icmp=60) + self.vapi.nat_set_timeouts( + udp=300, tcp_established=7440, tcp_transitory=5, icmp=60 + ) - self.init_tcp_session(self.pg0, self.pg1, self.tcp_port_in, - self.tcp_external_port) - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, - flags="R")) + self.init_tcp_session( + self.pg0, self.pg1, self.tcp_port_in, self.tcp_external_port + ) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="R") + ) self.send_and_expect(self.pg0, p, self.pg1) self.virtual_sleep(6) # The session is already closed - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, - flags="P")) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="P") + ) self.send_and_assert_no_replies(self.pg0, p, self.pg1) # The session can be re-opened - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, - flags="S")) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="S") + ) self.send_and_expect(self.pg0, p, self.pg1) def test_session_rst_established_timeout(self): - """ NAT44ED session RST timeouts """ + """NAT44ED session RST timeouts""" self.nat_add_address(self.nat_addr) self.nat_add_inside_interface(self.pg0) self.nat_add_outside_interface(self.pg1) - self.vapi.nat_set_timeouts(udp=300, tcp_established=7440, - tcp_transitory=5, icmp=60) + self.vapi.nat_set_timeouts( + udp=300, tcp_established=7440, tcp_transitory=5, icmp=60 + ) - self.init_tcp_session(self.pg0, self.pg1, self.tcp_port_in, - self.tcp_external_port) + self.init_tcp_session( + self.pg0, self.pg1, self.tcp_port_in, self.tcp_external_port + ) # Wait at least the transitory time, the session is in established # state anyway. RST followed by a data packet should move it to # transitory state. self.virtual_sleep(6) - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, - flags="R")) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="R") + ) self.send_and_expect(self.pg0, p, self.pg1) - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, - flags="P")) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="P") + ) self.send_and_expect(self.pg0, p, self.pg1) # State is transitory, session should be closed after 6 seconds self.virtual_sleep(6) - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, - flags="P")) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="P") + ) self.send_and_assert_no_replies(self.pg0, p, self.pg1) def test_dynamic_out_of_ports(self): - """ NAT44ED dynamic translation test: out of ports """ + """NAT44ED dynamic translation test: out of ports""" self.nat_add_inside_interface(self.pg0) self.nat_add_outside_interface(self.pg1) @@ -2643,60 +2859,71 @@ class TestNAT44EDMW(TestNAT44ED): pkts = self.create_stream_in(self.pg0, self.pg1) self.send_and_assert_no_replies( - self.pg0, pkts, msg="i2o pkts", - stats_diff=self.no_diff | { + self.pg0, + pkts, + msg="i2o pkts", + stats_diff=self.no_diff + | { "err": { - '/err/nat44-ed-in2out-slowpath/out of ports': len(pkts), + "/err/nat44-ed-in2out-slowpath/out of ports": len(pkts), }, self.pg0.sw_if_index: { - '/nat44-ed/in2out/slowpath/drops': len(pkts), + "/nat44-ed/in2out/slowpath/drops": len(pkts), }, - } + }, ) # in2out after NAT addresses added self.nat_add_address(self.nat_addr) - tcpn, udpn, icmpn = (sum(x) for x in - zip(*((TCP in p, UDP in p, ICMP in p) - for p in pkts))) + tcpn, udpn, icmpn = ( + sum(x) for x in zip(*((TCP in p, UDP in p, ICMP in p) for p in pkts)) + ) self.send_and_expect( - self.pg0, pkts, self.pg1, msg="i2o pkts", - stats_diff=self.no_diff | { + self.pg0, + pkts, + self.pg1, + msg="i2o pkts", + stats_diff=self.no_diff + | { "err": { - '/err/nat44-ed-in2out-slowpath/out of ports': 0, + "/err/nat44-ed-in2out-slowpath/out of ports": 0, }, self.pg0.sw_if_index: { - '/nat44-ed/in2out/slowpath/drops': 0, - '/nat44-ed/in2out/slowpath/tcp': tcpn, - '/nat44-ed/in2out/slowpath/udp': udpn, - '/nat44-ed/in2out/slowpath/icmp': icmpn, + "/nat44-ed/in2out/slowpath/drops": 0, + "/nat44-ed/in2out/slowpath/tcp": tcpn, + "/nat44-ed/in2out/slowpath/udp": udpn, + "/nat44-ed/in2out/slowpath/icmp": icmpn, }, - } + }, ) def test_unknown_proto(self): - """ NAT44ED translate packet with unknown protocol """ + """NAT44ED translate packet with unknown protocol""" self.nat_add_address(self.nat_addr) self.nat_add_inside_interface(self.pg0) self.nat_add_outside_interface(self.pg1) # in2out - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=self.tcp_port_in, dport=20)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=self.tcp_port_in, dport=20) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() p = self.pg1.get_capture(1) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - GRE() / - IP(src=self.pg2.remote_ip4, dst=self.pg2.remote_ip4) / - TCP(sport=1234, dport=1234)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / GRE() + / IP(src=self.pg2.remote_ip4, dst=self.pg2.remote_ip4) + / TCP(sport=1234, dport=1234) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2712,11 +2939,13 @@ class TestNAT44EDMW(TestNAT44ED): raise # out2in - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - GRE() / - IP(src=self.pg2.remote_ip4, dst=self.pg2.remote_ip4) / - TCP(sport=1234, dport=1234)) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / GRE() + / IP(src=self.pg2.remote_ip4, dst=self.pg2.remote_ip4) + / TCP(sport=1234, dport=1234) + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2732,7 +2961,7 @@ class TestNAT44EDMW(TestNAT44ED): raise def test_hairpinning_unknown_proto(self): - """ NAT44ED translate packet with unknown protocol - hairpinning """ + """NAT44ED translate packet with unknown protocol - hairpinning""" host = self.pg0.remote_hosts[0] server = self.pg0.remote_hosts[1] host_in_port = 1234 @@ -2747,19 +2976,23 @@ class TestNAT44EDMW(TestNAT44ED): self.nat_add_static_mapping(server.ip4, server_nat_ip) # host to server - p = (Ether(src=host.mac, dst=self.pg0.local_mac) / - IP(src=host.ip4, dst=server_nat_ip) / - TCP(sport=host_in_port, dport=server_out_port)) + p = ( + Ether(src=host.mac, dst=self.pg0.local_mac) + / IP(src=host.ip4, dst=server_nat_ip) + / TCP(sport=host_in_port, dport=server_out_port) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() self.pg0.get_capture(1) - p = (Ether(dst=self.pg0.local_mac, src=host.mac) / - IP(src=host.ip4, dst=server_nat_ip) / - GRE() / - IP(src=self.pg2.remote_ip4, dst=self.pg2.remote_ip4) / - TCP(sport=1234, dport=1234)) + p = ( + Ether(dst=self.pg0.local_mac, src=host.mac) + / IP(src=host.ip4, dst=server_nat_ip) + / GRE() + / IP(src=self.pg2.remote_ip4, dst=self.pg2.remote_ip4) + / TCP(sport=1234, dport=1234) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2775,11 +3008,13 @@ class TestNAT44EDMW(TestNAT44ED): raise # server to host - p = (Ether(dst=self.pg0.local_mac, src=server.mac) / - IP(src=server.ip4, dst=self.nat_addr) / - GRE() / - IP(src=self.pg2.remote_ip4, dst=self.pg2.remote_ip4) / - TCP(sport=1234, dport=1234)) + p = ( + Ether(dst=self.pg0.local_mac, src=server.mac) + / IP(src=server.ip4, dst=self.nat_addr) + / GRE() + / IP(src=self.pg2.remote_ip4, dst=self.pg2.remote_ip4) + / TCP(sport=1234, dport=1234) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2795,8 +3030,8 @@ class TestNAT44EDMW(TestNAT44ED): raise def test_output_feature_and_service(self): - """ NAT44ED interface output feature and services """ - external_addr = '1.2.3.4' + """NAT44ED interface output feature and services""" + external_addr = "1.2.3.4" external_port = 80 local_port = 8080 @@ -2804,22 +3039,33 @@ class TestNAT44EDMW(TestNAT44ED): self.nat_add_address(self.nat_addr) flags = self.config_flags.NAT_IS_ADDR_ONLY self.vapi.nat44_add_del_identity_mapping( - ip_address=self.pg1.remote_ip4, sw_if_index=0xFFFFFFFF, - flags=flags, is_add=1) + ip_address=self.pg1.remote_ip4, + sw_if_index=0xFFFFFFFF, + flags=flags, + is_add=1, + ) flags = self.config_flags.NAT_IS_OUT2IN_ONLY - self.nat_add_static_mapping(self.pg0.remote_ip4, external_addr, - local_port, external_port, - proto=IP_PROTOS.tcp, flags=flags) + self.nat_add_static_mapping( + self.pg0.remote_ip4, + external_addr, + local_port, + external_port, + proto=IP_PROTOS.tcp, + flags=flags, + ) self.nat_add_inside_interface(self.pg0) self.nat_add_outside_interface(self.pg0) self.vapi.nat44_ed_add_del_output_interface( - sw_if_index=self.pg1.sw_if_index, is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) # from client to service - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=external_addr) / - TCP(sport=12345, dport=external_port)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=external_addr) + / TCP(sport=12345, dport=external_port) + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2836,9 +3082,11 @@ class TestNAT44EDMW(TestNAT44ED): raise # from service back to client - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=local_port, dport=12345)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=local_port, dport=12345) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2877,26 +3125,34 @@ class TestNAT44EDMW(TestNAT44ED): self.verify_capture_in(capture, self.pg0) def test_output_feature_and_service3(self): - """ NAT44ED interface output feature and DST NAT """ - external_addr = '1.2.3.4' + """NAT44ED interface output feature and DST NAT""" + external_addr = "1.2.3.4" external_port = 80 local_port = 8080 self.vapi.nat44_forwarding_enable_disable(enable=1) self.nat_add_address(self.nat_addr) flags = self.config_flags.NAT_IS_OUT2IN_ONLY - self.nat_add_static_mapping(self.pg1.remote_ip4, external_addr, - local_port, external_port, - proto=IP_PROTOS.tcp, flags=flags) + self.nat_add_static_mapping( + self.pg1.remote_ip4, + external_addr, + local_port, + external_port, + proto=IP_PROTOS.tcp, + flags=flags, + ) self.nat_add_inside_interface(self.pg0) self.nat_add_outside_interface(self.pg0) self.vapi.nat44_ed_add_del_output_interface( - sw_if_index=self.pg1.sw_if_index, is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=external_addr) / - TCP(sport=12345, dport=external_port)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=external_addr) + / TCP(sport=12345, dport=external_port) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2914,9 +3170,11 @@ class TestNAT44EDMW(TestNAT44ED): self.logger.error(ppp("Unexpected or invalid packet:", p)) raise - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.pg0.remote_ip4) / - TCP(sport=local_port, dport=12345)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.pg0.remote_ip4) + / TCP(sport=local_port, dport=12345) + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2935,17 +3193,15 @@ class TestNAT44EDMW(TestNAT44ED): raise def test_self_twice_nat_lb_negative(self): - """ NAT44ED Self Twice NAT local service load balancing (negative test) - """ - self.twice_nat_common(lb=True, self_twice_nat=True, same_pg=True, - client_id=2) + """NAT44ED Self Twice NAT local service load balancing (negative test)""" + self.twice_nat_common(lb=True, self_twice_nat=True, same_pg=True, client_id=2) def test_self_twice_nat_negative(self): - """ NAT44ED Self Twice NAT (negative test) """ + """NAT44ED Self Twice NAT (negative test)""" self.twice_nat_common(self_twice_nat=True) def test_static_lb_multi_clients(self): - """ NAT44ED local service load balancing - multiple clients""" + """NAT44ED local service load balancing - multiple clients""" external_addr = self.nat_addr external_port = 80 @@ -2954,39 +3210,39 @@ class TestNAT44EDMW(TestNAT44ED): server2 = self.pg0.remote_hosts[1] server3 = self.pg0.remote_hosts[2] - locals = [{'addr': server1.ip4, - 'port': local_port, - 'probability': 90, - 'vrf_id': 0}, - {'addr': server2.ip4, - 'port': local_port, - 'probability': 10, - 'vrf_id': 0}] + locals = [ + {"addr": server1.ip4, "port": local_port, "probability": 90, "vrf_id": 0}, + {"addr": server2.ip4, "port": local_port, "probability": 10, "vrf_id": 0}, + ] flags = self.config_flags.NAT_IS_INSIDE self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) self.nat_add_address(self.nat_addr) - self.vapi.nat44_add_del_lb_static_mapping(is_add=1, - external_addr=external_addr, - external_port=external_port, - protocol=IP_PROTOS.tcp, - local_num=len(locals), - locals=locals) + self.vapi.nat44_add_del_lb_static_mapping( + is_add=1, + external_addr=external_addr, + external_port=external_port, + protocol=IP_PROTOS.tcp, + local_num=len(locals), + locals=locals, + ) server1_n = 0 server2_n = 0 clients = ip4_range(self.pg1.remote_ip4, 10, 50) pkts = [] for client in clients: - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=client, dst=self.nat_addr) / - TCP(sport=12345, dport=external_port)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=client, dst=self.nat_addr) + / TCP(sport=12345, dport=external_port) + ) pkts.append(p) self.pg1.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) @@ -3000,10 +3256,10 @@ class TestNAT44EDMW(TestNAT44ED): self.assertGreaterEqual(server1_n, server2_n) local = { - 'addr': server3.ip4, - 'port': local_port, - 'probability': 20, - 'vrf_id': 0 + "addr": server3.ip4, + "port": local_port, + "probability": 20, + "vrf_id": 0, } # add new back-end @@ -3012,16 +3268,19 @@ class TestNAT44EDMW(TestNAT44ED): external_addr=external_addr, external_port=external_port, local=local, - protocol=IP_PROTOS.tcp) + protocol=IP_PROTOS.tcp, + ) server1_n = 0 server2_n = 0 server3_n = 0 clients = ip4_range(self.pg1.remote_ip4, 60, 110) pkts = [] for client in clients: - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=client, dst=self.nat_addr) / - TCP(sport=12346, dport=external_port)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=client, dst=self.nat_addr) + / TCP(sport=12346, dport=external_port) + ) pkts.append(p) self.assertGreater(len(pkts), 0) self.pg1.add_stream(pkts) @@ -3040,10 +3299,10 @@ class TestNAT44EDMW(TestNAT44ED): self.assertGreater(server3_n, 0) local = { - 'addr': server2.ip4, - 'port': local_port, - 'probability': 10, - 'vrf_id': 0 + "addr": server2.ip4, + "port": local_port, + "probability": 10, + "vrf_id": 0, } # remove one back-end @@ -3052,7 +3311,8 @@ class TestNAT44EDMW(TestNAT44ED): external_addr=external_addr, external_port=external_port, local=local, - protocol=IP_PROTOS.tcp) + protocol=IP_PROTOS.tcp, + ) server1_n = 0 server2_n = 0 server3_n = 0 @@ -3075,39 +3335,39 @@ class TestNAT44EDMW(TestNAT44ED): # setting syslog sender cannot be undone and if it is set, it messes # with self.send_and_assert_no_replies functionality def test_zzz_syslog_sess(self): - """ NAT44ED Test syslog session creation and deletion """ - self.vapi.syslog_set_filter( - self.syslog_severity.SYSLOG_API_SEVERITY_INFO) + """NAT44ED Test syslog session creation and deletion""" + self.vapi.syslog_set_filter(self.syslog_severity.SYSLOG_API_SEVERITY_INFO) self.vapi.syslog_set_sender(self.pg3.local_ip4, self.pg3.remote_ip4) self.nat_add_address(self.nat_addr) self.nat_add_inside_interface(self.pg0) self.nat_add_outside_interface(self.pg1) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=self.tcp_port_in, dport=self.tcp_external_port)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() capture = self.pg1.get_capture(1) self.tcp_port_out = capture[0][TCP].sport capture = self.pg3.get_capture(1) - self.verify_syslog_sess(capture[0][Raw].load, 'SADD') + self.verify_syslog_sess(capture[0][Raw].load, "SADD") self.pg_enable_capture(self.pg_interfaces) self.pg_start() self.nat_add_address(self.nat_addr, is_add=0) capture = self.pg3.get_capture(1) - self.verify_syslog_sess(capture[0][Raw].load, 'SDEL') + self.verify_syslog_sess(capture[0][Raw].load, "SDEL") # put zzz in front of syslog test name so that it runs as a last test # setting syslog sender cannot be undone and if it is set, it messes # with self.send_and_assert_no_replies functionality def test_zzz_syslog_sess_reopen(self): - """ Syslog events for session reopen """ - self.vapi.syslog_set_filter( - self.syslog_severity.SYSLOG_API_SEVERITY_INFO) + """Syslog events for session reopen""" + self.vapi.syslog_set_filter(self.syslog_severity.SYSLOG_API_SEVERITY_INFO) self.vapi.syslog_set_sender(self.pg3.local_ip4, self.pg3.remote_ip4) self.nat_add_address(self.nat_addr) @@ -3115,55 +3375,62 @@ class TestNAT44EDMW(TestNAT44ED): self.nat_add_outside_interface(self.pg1) # SYN in2out - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=self.tcp_port_in, dport=self.tcp_external_port)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port) + ) capture = self.send_and_expect(self.pg0, p, self.pg1)[0] self.tcp_port_out = capture[0][TCP].sport capture = self.pg3.get_capture(1) - self.verify_syslog_sess(capture[0][Raw].load, 'SADD') + self.verify_syslog_sess(capture[0][Raw].load, "SADD") # SYN out2in - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=self.tcp_external_port, dport=self.tcp_port_out, - flags='SA')) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=self.tcp_external_port, dport=self.tcp_port_out, flags="SA") + ) self.send_and_expect(self.pg1, p, self.pg0) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, - flags="A")) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="A") + ) self.send_and_expect(self.pg0, p, self.pg1) # FIN in2out - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, - flags="F")) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="F") + ) self.send_and_expect(self.pg0, p, self.pg1) # FIN out2in - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=self.tcp_external_port, dport=self.tcp_port_out, - flags="F")) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=self.tcp_external_port, dport=self.tcp_port_out, flags="F") + ) self.send_and_expect(self.pg1, p, self.pg0) - self.init_tcp_session(self.pg0, self.pg1, self.tcp_port_in, - self.tcp_external_port) + self.init_tcp_session( + self.pg0, self.pg1, self.tcp_port_in, self.tcp_external_port + ) # 2 records should be produced - first one del & add capture = self.pg3.get_capture(2) - self.verify_syslog_sess(capture[0][Raw].load, 'SDEL') - self.verify_syslog_sess(capture[1][Raw].load, 'SADD') + self.verify_syslog_sess(capture[0][Raw].load, "SDEL") + self.verify_syslog_sess(capture[1][Raw].load, "SADD") def test_twice_nat_interface_addr(self): - """ NAT44ED Acquire twice NAT addresses from interface """ + """NAT44ED Acquire twice NAT addresses from interface""" flags = self.config_flags.NAT_IS_TWICE_NAT self.vapi.nat44_add_del_interface_addr( - sw_if_index=self.pg11.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg11.sw_if_index, flags=flags, is_add=1 + ) # no address in NAT pool adresses = self.vapi.nat44_address_dump() @@ -3173,8 +3440,7 @@ class TestNAT44EDMW(TestNAT44ED): self.pg11.config_ip4() adresses = self.vapi.nat44_address_dump() self.assertEqual(1, len(adresses)) - self.assertEqual(str(adresses[0].ip_address), - self.pg11.local_ip4) + self.assertEqual(str(adresses[0].ip_address), self.pg11.local_ip4) self.assertEqual(adresses[0].flags, flags) # remove interface address and check NAT address pool @@ -3183,11 +3449,12 @@ class TestNAT44EDMW(TestNAT44ED): self.assertEqual(0, len(adresses)) def test_output_feature_stateful_acl(self): - """ NAT44ED output feature works with stateful ACL """ + """NAT44ED output feature works with stateful ACL""" self.nat_add_address(self.nat_addr) self.vapi.nat44_ed_add_del_output_interface( - sw_if_index=self.pg1.sw_if_index, is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) # First ensure that the NAT is working sans ACL @@ -3197,14 +3464,16 @@ class TestNAT44EDMW(TestNAT44ED): # send packets into inside intf, ensure received via outside intf pkts_in2out = self.create_stream_in(self.pg0, self.pg1) - capture = self.send_and_expect(self.pg0, pkts_in2out, self.pg1, - len(pkts_in2out)) + capture = self.send_and_expect( + self.pg0, pkts_in2out, self.pg1, len(pkts_in2out) + ) self.verify_capture_out(capture, ignore_port=True) # send out2in again, with sessions created it should work now pkts_out2in = self.create_stream_out(self.pg1) - capture = self.send_and_expect(self.pg1, pkts_out2in, self.pg0, - len(pkts_out2in)) + capture = self.send_and_expect( + self.pg1, pkts_out2in, self.pg0, len(pkts_out2in) + ) self.verify_capture_in(capture, self.pg0) # Create an ACL blocking everything @@ -3218,8 +3487,9 @@ class TestNAT44EDMW(TestNAT44ED): in2out_acl.add_vpp_config() # apply as input acl on interface and confirm it blocks everything - acl_if = VppAclInterface(self, sw_if_index=self.pg1.sw_if_index, - n_input=1, acls=[out2in_acl]) + acl_if = VppAclInterface( + self, sw_if_index=self.pg1.sw_if_index, n_input=1, acls=[out2in_acl] + ) acl_if.add_vpp_config() self.send_and_assert_no_replies(self.pg1, pkts_out2in) @@ -3227,8 +3497,9 @@ class TestNAT44EDMW(TestNAT44ED): acl_if.acls = [out2in_acl, in2out_acl] acl_if.add_vpp_config() # send in2out to generate ACL state (NAT state was created earlier) - capture = self.send_and_expect(self.pg0, pkts_in2out, self.pg1, - len(pkts_in2out)) + capture = self.send_and_expect( + self.pg0, pkts_in2out, self.pg1, len(pkts_in2out) + ) self.verify_capture_out(capture, ignore_port=True) # send out2in again. ACL state exists so it should work now. @@ -3236,13 +3507,14 @@ class TestNAT44EDMW(TestNAT44ED): for p in pkts_out2in: if p.haslayer(TCP) and p[TCP].flags & 0x02: p[TCP].flags |= 0x10 - capture = self.send_and_expect(self.pg1, pkts_out2in, self.pg0, - len(pkts_out2in)) + capture = self.send_and_expect( + self.pg1, pkts_out2in, self.pg0, len(pkts_out2in) + ) self.verify_capture_in(capture, self.pg0) self.logger.info(self.vapi.cli("show trace")) def test_tcp_close(self): - """ NAT44ED Close TCP session from inside network - output feature """ + """NAT44ED Close TCP session from inside network - output feature""" config = self.vapi.nat44_show_running_config() old_timeouts = config.timeouts new_transitory = 2 @@ -3250,77 +3522,92 @@ class TestNAT44EDMW(TestNAT44ED): udp=old_timeouts.udp, tcp_established=old_timeouts.tcp_established, icmp=old_timeouts.icmp, - tcp_transitory=new_transitory) + tcp_transitory=new_transitory, + ) self.vapi.nat44_forwarding_enable_disable(enable=1) self.nat_add_address(self.pg1.local_ip4) - twice_nat_addr = '10.0.1.3' - service_ip = '192.168.16.150' + twice_nat_addr = "10.0.1.3" + service_ip = "192.168.16.150" self.nat_add_address(twice_nat_addr, twice_nat=1) flags = self.config_flags.NAT_IS_INSIDE self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - is_add=1) + sw_if_index=self.pg0.sw_if_index, is_add=1 + ) self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ed_add_del_output_interface( - is_add=1, - sw_if_index=self.pg1.sw_if_index) - - flags = (self.config_flags.NAT_IS_OUT2IN_ONLY | - self.config_flags.NAT_IS_TWICE_NAT) - self.nat_add_static_mapping(self.pg0.remote_ip4, - service_ip, 80, 80, - proto=IP_PROTOS.tcp, - flags=flags) + is_add=1, sw_if_index=self.pg1.sw_if_index + ) + + flags = ( + self.config_flags.NAT_IS_OUT2IN_ONLY | self.config_flags.NAT_IS_TWICE_NAT + ) + self.nat_add_static_mapping( + self.pg0.remote_ip4, service_ip, 80, 80, proto=IP_PROTOS.tcp, flags=flags + ) sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0) start_sessnum = len(sessions) # SYN packet out->in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=service_ip) / - TCP(sport=33898, dport=80, flags="S")) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=service_ip) + / TCP(sport=33898, dport=80, flags="S") + ) capture = self.send_and_expect(self.pg1, p, self.pg0, n_rx=1) p = capture[0] tcp_port = p[TCP].sport # SYN + ACK packet in->out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=twice_nat_addr) / - TCP(sport=80, dport=tcp_port, flags="SA")) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=twice_nat_addr) + / TCP(sport=80, dport=tcp_port, flags="SA") + ) self.send_and_expect(self.pg0, p, self.pg1, n_rx=1) # ACK packet out->in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=service_ip) / - TCP(sport=33898, dport=80, flags="A")) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=service_ip) + / TCP(sport=33898, dport=80, flags="A") + ) self.send_and_expect(self.pg1, p, self.pg0, n_rx=1) # FIN packet in -> out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=twice_nat_addr) / - TCP(sport=80, dport=tcp_port, flags="FA", seq=100, ack=300)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=twice_nat_addr) + / TCP(sport=80, dport=tcp_port, flags="FA", seq=100, ack=300) + ) self.send_and_expect(self.pg0, p, self.pg1, n_rx=1) # FIN+ACK packet out -> in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=service_ip) / - TCP(sport=33898, dport=80, flags="FA", seq=300, ack=101)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=service_ip) + / TCP(sport=33898, dport=80, flags="FA", seq=300, ack=101) + ) self.send_and_expect(self.pg1, p, self.pg0, n_rx=1) # ACK packet in -> out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=twice_nat_addr) / - TCP(sport=80, dport=tcp_port, flags="A", seq=101, ack=301)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=twice_nat_addr) + / TCP(sport=80, dport=tcp_port, flags="A", seq=101, ack=301) + ) self.send_and_expect(self.pg0, p, self.pg1, n_rx=1) # session now in transitory timeout, but traffic still flows # try FIN packet out->in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=service_ip) / - TCP(sport=33898, dport=80, flags="F")) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=service_ip) + / TCP(sport=33898, dport=80, flags="F") + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -3334,15 +3621,17 @@ class TestNAT44EDMW(TestNAT44ED): # send FIN+ACK packet out -> in - will cause session to be wiped # but won't create a new session - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=service_ip) / - TCP(sport=33898, dport=80, flags="FA", seq=300, ack=101)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=service_ip) + / TCP(sport=33898, dport=80, flags="FA", seq=300, ack=101) + ) self.send_and_assert_no_replies(self.pg1, p) sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0) self.assertEqual(len(sessions) - start_sessnum, 0) def test_tcp_session_close_in(self): - """ NAT44ED Close TCP session from inside network """ + """NAT44ED Close TCP session from inside network""" in_port = self.tcp_port_in out_port = 10505 @@ -3351,79 +3640,92 @@ class TestNAT44EDMW(TestNAT44ED): self.nat_add_address(self.nat_addr) self.nat_add_inside_interface(self.pg0) self.nat_add_outside_interface(self.pg1) - self.nat_add_static_mapping(self.pg0.remote_ip4, self.nat_addr, - in_port, out_port, proto=IP_PROTOS.tcp, - flags=self.config_flags.NAT_IS_TWICE_NAT) + self.nat_add_static_mapping( + self.pg0.remote_ip4, + self.nat_addr, + in_port, + out_port, + proto=IP_PROTOS.tcp, + flags=self.config_flags.NAT_IS_TWICE_NAT, + ) sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0) session_n = len(sessions) - self.vapi.nat_set_timeouts(udp=300, tcp_established=7440, - tcp_transitory=2, icmp=5) + self.vapi.nat_set_timeouts( + udp=300, tcp_established=7440, tcp_transitory=2, icmp=5 + ) self.init_tcp_session(self.pg0, self.pg1, in_port, ext_port) # FIN packet in -> out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, - flags="FA", seq=100, ack=300)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="FA", seq=100, ack=300) + ) self.send_and_expect(self.pg0, p, self.pg1) pkts = [] # ACK packet out -> in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=ext_port, dport=out_port, - flags="A", seq=300, ack=101)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=ext_port, dport=out_port, flags="A", seq=300, ack=101) + ) pkts.append(p) # FIN packet out -> in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=ext_port, dport=out_port, - flags="FA", seq=300, ack=101)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=ext_port, dport=out_port, flags="FA", seq=300, ack=101) + ) pkts.append(p) self.send_and_expect(self.pg1, pkts, self.pg0) # ACK packet in -> out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, - flags="A", seq=101, ack=301)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="A", seq=101, ack=301) + ) self.send_and_expect(self.pg0, p, self.pg1) sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0) self.assertEqual(len(sessions) - session_n, 1) # retransmit FIN packet out -> in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=ext_port, dport=out_port, - flags="FA", seq=300, ack=101)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=ext_port, dport=out_port, flags="FA", seq=300, ack=101) + ) self.send_and_expect(self.pg1, p, self.pg0) # retransmit ACK packet in -> out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, - flags="A", seq=101, ack=301)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="A", seq=101, ack=301) + ) self.send_and_expect(self.pg0, p, self.pg1) self.virtual_sleep(3) # retransmit ACK packet in -> out - this will cause session to be wiped - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, - flags="A", seq=101, ack=301)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="A", seq=101, ack=301) + ) self.send_and_assert_no_replies(self.pg0, p) sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0) self.assertEqual(len(sessions) - session_n, 0) def test_tcp_session_close_out(self): - """ NAT44ED Close TCP session from outside network """ + """NAT44ED Close TCP session from outside network""" in_port = self.tcp_port_in out_port = 10505 @@ -3432,33 +3734,41 @@ class TestNAT44EDMW(TestNAT44ED): self.nat_add_address(self.nat_addr) self.nat_add_inside_interface(self.pg0) self.nat_add_outside_interface(self.pg1) - self.nat_add_static_mapping(self.pg0.remote_ip4, self.nat_addr, - in_port, out_port, proto=IP_PROTOS.tcp, - flags=self.config_flags.NAT_IS_TWICE_NAT) + self.nat_add_static_mapping( + self.pg0.remote_ip4, + self.nat_addr, + in_port, + out_port, + proto=IP_PROTOS.tcp, + flags=self.config_flags.NAT_IS_TWICE_NAT, + ) sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0) session_n = len(sessions) - self.vapi.nat_set_timeouts(udp=300, tcp_established=7440, - tcp_transitory=2, icmp=5) + self.vapi.nat_set_timeouts( + udp=300, tcp_established=7440, tcp_transitory=2, icmp=5 + ) _ = self.init_tcp_session(self.pg0, self.pg1, in_port, ext_port) # FIN packet out -> in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=ext_port, dport=out_port, - flags="FA", seq=100, ack=300)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=ext_port, dport=out_port, flags="FA", seq=100, ack=300) + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() self.pg0.get_capture(1) # FIN+ACK packet in -> out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, - flags="FA", seq=300, ack=101)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="FA", seq=300, ack=101) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) @@ -3466,10 +3776,11 @@ class TestNAT44EDMW(TestNAT44ED): self.pg1.get_capture(1) # ACK packet out -> in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=ext_port, dport=out_port, - flags="A", seq=101, ack=301)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=ext_port, dport=out_port, flags="A", seq=101, ack=301) + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -3479,31 +3790,34 @@ class TestNAT44EDMW(TestNAT44ED): self.assertEqual(len(sessions) - session_n, 1) # retransmit FIN packet out -> in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=ext_port, dport=out_port, - flags="FA", seq=300, ack=101)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=ext_port, dport=out_port, flags="FA", seq=300, ack=101) + ) self.send_and_expect(self.pg1, p, self.pg0) # retransmit ACK packet in -> out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, - flags="A", seq=101, ack=301)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="A", seq=101, ack=301) + ) self.send_and_expect(self.pg0, p, self.pg1) self.virtual_sleep(3) # retransmit ACK packet in -> out - this will cause session to be wiped - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, - flags="A", seq=101, ack=301)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="A", seq=101, ack=301) + ) self.send_and_assert_no_replies(self.pg0, p) sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0) self.assertEqual(len(sessions) - session_n, 0) def test_tcp_session_close_simultaneous(self): - """ Simultaneous TCP close from both sides """ + """Simultaneous TCP close from both sides""" in_port = self.tcp_port_in ext_port = 10505 @@ -3511,252 +3825,297 @@ class TestNAT44EDMW(TestNAT44ED): self.nat_add_address(self.nat_addr) self.nat_add_inside_interface(self.pg0) self.nat_add_outside_interface(self.pg1) - self.nat_add_static_mapping(self.pg0.remote_ip4, self.nat_addr, - in_port, ext_port, proto=IP_PROTOS.tcp, - flags=self.config_flags.NAT_IS_TWICE_NAT) + self.nat_add_static_mapping( + self.pg0.remote_ip4, + self.nat_addr, + in_port, + ext_port, + proto=IP_PROTOS.tcp, + flags=self.config_flags.NAT_IS_TWICE_NAT, + ) sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0) session_n = len(sessions) - self.vapi.nat_set_timeouts(udp=300, tcp_established=7440, - tcp_transitory=2, icmp=5) + self.vapi.nat_set_timeouts( + udp=300, tcp_established=7440, tcp_transitory=2, icmp=5 + ) out_port = self.init_tcp_session(self.pg0, self.pg1, in_port, ext_port) # FIN packet in -> out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, - flags="FA", seq=100, ack=300)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="FA", seq=100, ack=300) + ) self.send_and_expect(self.pg0, p, self.pg1) # FIN packet out -> in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=ext_port, dport=out_port, - flags="FA", seq=300, ack=100)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=ext_port, dport=out_port, flags="FA", seq=300, ack=100) + ) self.send_and_expect(self.pg1, p, self.pg0) # ACK packet in -> out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, - flags="A", seq=101, ack=301)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="A", seq=101, ack=301) + ) self.send_and_expect(self.pg0, p, self.pg1) # ACK packet out -> in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=ext_port, dport=out_port, - flags="A", seq=301, ack=101)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=ext_port, dport=out_port, flags="A", seq=301, ack=101) + ) self.send_and_expect(self.pg1, p, self.pg0) sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0) self.assertEqual(len(sessions) - session_n, 1) # retransmit FIN packet out -> in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=ext_port, dport=out_port, - flags="FA", seq=300, ack=101)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=ext_port, dport=out_port, flags="FA", seq=300, ack=101) + ) self.send_and_expect(self.pg1, p, self.pg0) # retransmit ACK packet in -> out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, - flags="A", seq=101, ack=301)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="A", seq=101, ack=301) + ) self.send_and_expect(self.pg0, p, self.pg1) self.virtual_sleep(3) # retransmit ACK packet in -> out - this will cause session to be wiped - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, - flags="A", seq=101, ack=301)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="A", seq=101, ack=301) + ) self.pg_send(self.pg0, p) self.send_and_assert_no_replies(self.pg0, p) sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0) self.assertEqual(len(sessions) - session_n, 0) def test_tcp_session_half_reopen_inside(self): - """ TCP session in FIN/FIN state not reopened by in2out SYN only """ + """TCP session in FIN/FIN state not reopened by in2out SYN only""" in_port = self.tcp_port_in ext_port = 10505 self.nat_add_address(self.nat_addr) self.nat_add_inside_interface(self.pg0) self.nat_add_outside_interface(self.pg1) - self.nat_add_static_mapping(self.pg0.remote_ip4, self.nat_addr, - in_port, ext_port, proto=IP_PROTOS.tcp, - flags=self.config_flags.NAT_IS_TWICE_NAT) + self.nat_add_static_mapping( + self.pg0.remote_ip4, + self.nat_addr, + in_port, + ext_port, + proto=IP_PROTOS.tcp, + flags=self.config_flags.NAT_IS_TWICE_NAT, + ) sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0) session_n = len(sessions) - self.vapi.nat_set_timeouts(udp=300, tcp_established=7440, - tcp_transitory=2, icmp=5) + self.vapi.nat_set_timeouts( + udp=300, tcp_established=7440, tcp_transitory=2, icmp=5 + ) out_port = self.init_tcp_session(self.pg0, self.pg1, in_port, ext_port) # FIN packet in -> out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, - flags="FA", seq=100, ack=300)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="FA", seq=100, ack=300) + ) self.send_and_expect(self.pg0, p, self.pg1) # FIN packet out -> in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=ext_port, dport=out_port, - flags="FA", seq=300, ack=100)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=ext_port, dport=out_port, flags="FA", seq=300, ack=100) + ) self.send_and_expect(self.pg1, p, self.pg0) sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0) self.assertEqual(len(sessions) - session_n, 1) # send SYN packet in -> out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, - flags="S", seq=101, ack=301)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="S", seq=101, ack=301) + ) self.send_and_expect(self.pg0, p, self.pg1) self.virtual_sleep(3) # send ACK packet in -> out - session should be wiped - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, - flags="A", seq=101, ack=301)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="A", seq=101, ack=301) + ) self.send_and_assert_no_replies(self.pg0, p, self.pg1) sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0) self.assertEqual(len(sessions) - session_n, 0) def test_tcp_session_half_reopen_outside(self): - """ TCP session in FIN/FIN state not reopened by out2in SYN only """ + """TCP session in FIN/FIN state not reopened by out2in SYN only""" in_port = self.tcp_port_in ext_port = 10505 self.nat_add_address(self.nat_addr) self.nat_add_inside_interface(self.pg0) self.nat_add_outside_interface(self.pg1) - self.nat_add_static_mapping(self.pg0.remote_ip4, self.nat_addr, - in_port, ext_port, proto=IP_PROTOS.tcp, - flags=self.config_flags.NAT_IS_TWICE_NAT) + self.nat_add_static_mapping( + self.pg0.remote_ip4, + self.nat_addr, + in_port, + ext_port, + proto=IP_PROTOS.tcp, + flags=self.config_flags.NAT_IS_TWICE_NAT, + ) sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0) session_n = len(sessions) - self.vapi.nat_set_timeouts(udp=300, tcp_established=7440, - tcp_transitory=2, icmp=5) + self.vapi.nat_set_timeouts( + udp=300, tcp_established=7440, tcp_transitory=2, icmp=5 + ) out_port = self.init_tcp_session(self.pg0, self.pg1, in_port, ext_port) # FIN packet in -> out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, - flags="FA", seq=100, ack=300)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="FA", seq=100, ack=300) + ) self.send_and_expect(self.pg0, p, self.pg1) # FIN packet out -> in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=ext_port, dport=out_port, - flags="FA", seq=300, ack=100)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=ext_port, dport=out_port, flags="FA", seq=300, ack=100) + ) self.send_and_expect(self.pg1, p, self.pg0) sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0) self.assertEqual(len(sessions) - session_n, 1) # send SYN packet out -> in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=ext_port, dport=out_port, - flags="S", seq=300, ack=101)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=ext_port, dport=out_port, flags="S", seq=300, ack=101) + ) self.send_and_expect(self.pg1, p, self.pg0) self.virtual_sleep(3) # send ACK packet in -> out - session should be wiped - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, - flags="A", seq=101, ack=301)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="A", seq=101, ack=301) + ) self.send_and_assert_no_replies(self.pg0, p, self.pg1) sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0) self.assertEqual(len(sessions) - session_n, 0) def test_tcp_session_reopen(self): - """ TCP session in FIN/FIN state reopened by SYN from both sides """ + """TCP session in FIN/FIN state reopened by SYN from both sides""" in_port = self.tcp_port_in ext_port = 10505 self.nat_add_address(self.nat_addr) self.nat_add_inside_interface(self.pg0) self.nat_add_outside_interface(self.pg1) - self.nat_add_static_mapping(self.pg0.remote_ip4, self.nat_addr, - in_port, ext_port, proto=IP_PROTOS.tcp, - flags=self.config_flags.NAT_IS_TWICE_NAT) + self.nat_add_static_mapping( + self.pg0.remote_ip4, + self.nat_addr, + in_port, + ext_port, + proto=IP_PROTOS.tcp, + flags=self.config_flags.NAT_IS_TWICE_NAT, + ) sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0) session_n = len(sessions) - self.vapi.nat_set_timeouts(udp=300, tcp_established=7440, - tcp_transitory=2, icmp=5) + self.vapi.nat_set_timeouts( + udp=300, tcp_established=7440, tcp_transitory=2, icmp=5 + ) out_port = self.init_tcp_session(self.pg0, self.pg1, in_port, ext_port) # FIN packet in -> out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, - flags="FA", seq=100, ack=300)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="FA", seq=100, ack=300) + ) self.send_and_expect(self.pg0, p, self.pg1) # FIN packet out -> in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=ext_port, dport=out_port, - flags="FA", seq=300, ack=100)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=ext_port, dport=out_port, flags="FA", seq=300, ack=100) + ) self.send_and_expect(self.pg1, p, self.pg0) sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0) self.assertEqual(len(sessions) - session_n, 1) # send SYN packet out -> in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=ext_port, dport=out_port, - flags="S", seq=300, ack=101)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=ext_port, dport=out_port, flags="S", seq=300, ack=101) + ) self.send_and_expect(self.pg1, p, self.pg0) # send SYN packet in -> out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, - flags="SA", seq=101, ack=301)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="SA", seq=101, ack=301) + ) self.send_and_expect(self.pg0, p, self.pg1) # send ACK packet out -> in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=ext_port, dport=out_port, - flags="A", seq=300, ack=101)) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=ext_port, dport=out_port, flags="A", seq=300, ack=101) + ) self.send_and_expect(self.pg1, p, self.pg0) self.virtual_sleep(3) # send ACK packet in -> out - should be forwarded and session alive - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, - flags="A", seq=101, ack=301)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="A", seq=101, ack=301) + ) self.send_and_expect(self.pg0, p, self.pg1) sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0) self.assertEqual(len(sessions) - session_n, 1) def test_dynamic_vrf(self): - """ NAT44ED dynamic translation test: different VRF""" + """NAT44ED dynamic translation test: different VRF""" vrf_id_in = 33 vrf_id_out = 34 @@ -3789,30 +4148,28 @@ class TestNAT44EDMW(TestNAT44ED): self.pg7.unconfig() self.pg8.unconfig() - self.vapi.ip_table_add_del(is_add=0, - table={'table_id': vrf_id_in}) - self.vapi.ip_table_add_del(is_add=0, - table={'table_id': vrf_id_out}) + self.vapi.ip_table_add_del(is_add=0, table={"table_id": vrf_id_in}) + self.vapi.ip_table_add_del(is_add=0, table={"table_id": vrf_id_out}) def test_dynamic_output_feature_vrf(self): - """ NAT44ED dynamic translation test: output-feature, VRF""" + """NAT44ED dynamic translation test: output-feature, VRF""" # other then default (0) new_vrf_id = 22 self.nat_add_address(self.nat_addr) self.vapi.nat44_ed_add_del_output_interface( - sw_if_index=self.pg8.sw_if_index, - is_add=1) + sw_if_index=self.pg8.sw_if_index, is_add=1 + ) try: self.configure_ip4_interface(self.pg7, table_id=new_vrf_id) self.configure_ip4_interface(self.pg8, table_id=new_vrf_id) # in2out - tcpn = self.statistics['/nat44-ed/in2out/slowpath/tcp'] - udpn = self.statistics['/nat44-ed/in2out/slowpath/udp'] - icmpn = self.statistics['/nat44-ed/in2out/slowpath/icmp'] - drops = self.statistics['/nat44-ed/in2out/slowpath/drops'] + tcpn = self.statistics["/nat44-ed/in2out/slowpath/tcp"] + udpn = self.statistics["/nat44-ed/in2out/slowpath/udp"] + icmpn = self.statistics["/nat44-ed/in2out/slowpath/icmp"] + drops = self.statistics["/nat44-ed/in2out/slowpath/drops"] pkts = self.create_stream_in(self.pg7, self.pg8) self.pg7.add_stream(pkts) @@ -3822,20 +4179,20 @@ class TestNAT44EDMW(TestNAT44ED): self.verify_capture_out(capture, ignore_port=True) if_idx = self.pg8.sw_if_index - cnt = self.statistics['/nat44-ed/in2out/slowpath/tcp'] + cnt = self.statistics["/nat44-ed/in2out/slowpath/tcp"] self.assertEqual(cnt[:, if_idx].sum() - tcpn[:, if_idx].sum(), 2) - cnt = self.statistics['/nat44-ed/in2out/slowpath/udp'] + cnt = self.statistics["/nat44-ed/in2out/slowpath/udp"] self.assertEqual(cnt[:, if_idx].sum() - udpn[:, if_idx].sum(), 1) - cnt = self.statistics['/nat44-ed/in2out/slowpath/icmp'] + cnt = self.statistics["/nat44-ed/in2out/slowpath/icmp"] self.assertEqual(cnt[:, if_idx].sum() - icmpn[:, if_idx].sum(), 1) - cnt = self.statistics['/nat44-ed/in2out/slowpath/drops'] + cnt = self.statistics["/nat44-ed/in2out/slowpath/drops"] self.assertEqual(cnt[:, if_idx].sum() - drops[:, if_idx].sum(), 0) # out2in - tcpn = self.statistics['/nat44-ed/out2in/fastpath/tcp'] - udpn = self.statistics['/nat44-ed/out2in/fastpath/udp'] - icmpn = self.statistics['/nat44-ed/out2in/fastpath/icmp'] - drops = self.statistics['/nat44-ed/out2in/fastpath/drops'] + tcpn = self.statistics["/nat44-ed/out2in/fastpath/tcp"] + udpn = self.statistics["/nat44-ed/out2in/fastpath/udp"] + icmpn = self.statistics["/nat44-ed/out2in/fastpath/icmp"] + drops = self.statistics["/nat44-ed/out2in/fastpath/drops"] pkts = self.create_stream_out(self.pg8) self.pg8.add_stream(pkts) @@ -3845,48 +4202,56 @@ class TestNAT44EDMW(TestNAT44ED): self.verify_capture_in(capture, self.pg7) if_idx = self.pg8.sw_if_index - cnt = self.statistics['/nat44-ed/out2in/fastpath/tcp'] + cnt = self.statistics["/nat44-ed/out2in/fastpath/tcp"] self.assertEqual(cnt[:, if_idx].sum() - tcpn[:, if_idx].sum(), 2) - cnt = self.statistics['/nat44-ed/out2in/fastpath/udp'] + cnt = self.statistics["/nat44-ed/out2in/fastpath/udp"] self.assertEqual(cnt[:, if_idx].sum() - udpn[:, if_idx].sum(), 1) - cnt = self.statistics['/nat44-ed/out2in/fastpath/icmp'] + cnt = self.statistics["/nat44-ed/out2in/fastpath/icmp"] self.assertEqual(cnt[:, if_idx].sum() - icmpn[:, if_idx].sum(), 1) - cnt = self.statistics['/nat44-ed/out2in/fastpath/drops'] + cnt = self.statistics["/nat44-ed/out2in/fastpath/drops"] self.assertEqual(cnt[:, if_idx].sum() - drops[:, if_idx].sum(), 0) - sessions = self.statistics['/nat44-ed/total-sessions'] + sessions = self.statistics["/nat44-ed/total-sessions"] self.assertEqual(sessions[:, 0].sum(), 3) finally: self.pg7.unconfig() self.pg8.unconfig() - self.vapi.ip_table_add_del(is_add=0, - table={'table_id': new_vrf_id}) + self.vapi.ip_table_add_del(is_add=0, table={"table_id": new_vrf_id}) def test_next_src_nat(self): - """ NAT44ED On way back forward packet to nat44-in2out node. """ + """NAT44ED On way back forward packet to nat44-in2out node.""" - twice_nat_addr = '10.0.1.3' + twice_nat_addr = "10.0.1.3" external_port = 80 local_port = 8080 post_twice_nat_port = 0 self.vapi.nat44_forwarding_enable_disable(enable=1) self.nat_add_address(twice_nat_addr, twice_nat=1) - flags = (self.config_flags.NAT_IS_OUT2IN_ONLY | - self.config_flags.NAT_IS_SELF_TWICE_NAT) - self.nat_add_static_mapping(self.pg6.remote_ip4, self.pg1.remote_ip4, - local_port, external_port, - proto=IP_PROTOS.tcp, vrf_id=1, - flags=flags) + flags = ( + self.config_flags.NAT_IS_OUT2IN_ONLY + | self.config_flags.NAT_IS_SELF_TWICE_NAT + ) + self.nat_add_static_mapping( + self.pg6.remote_ip4, + self.pg1.remote_ip4, + local_port, + external_port, + proto=IP_PROTOS.tcp, + vrf_id=1, + flags=flags, + ) self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg6.sw_if_index, - is_add=1) + sw_if_index=self.pg6.sw_if_index, is_add=1 + ) - p = (Ether(src=self.pg6.remote_mac, dst=self.pg6.local_mac) / - IP(src=self.pg6.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=12345, dport=external_port)) + p = ( + Ether(src=self.pg6.remote_mac, dst=self.pg6.local_mac) + / IP(src=self.pg6.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=12345, dport=external_port) + ) self.pg6.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -3905,9 +4270,11 @@ class TestNAT44EDMW(TestNAT44ED): self.logger.error(ppp("Unexpected or invalid packet:", p)) raise - p = (Ether(src=self.pg6.remote_mac, dst=self.pg6.local_mac) / - IP(src=self.pg6.remote_ip4, dst=twice_nat_addr) / - TCP(sport=local_port, dport=post_twice_nat_port)) + p = ( + Ether(src=self.pg6.remote_mac, dst=self.pg6.local_mac) + / IP(src=self.pg6.remote_ip4, dst=twice_nat_addr) + / TCP(sport=local_port, dport=post_twice_nat_port) + ) self.pg6.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -3926,7 +4293,7 @@ class TestNAT44EDMW(TestNAT44ED): raise def test_one_armed_nat44_static(self): - """ NAT44ED One armed NAT and 1:1 NAPT asymmetrical rule """ + """NAT44ED One armed NAT and 1:1 NAPT asymmetrical rule""" remote_host = self.pg4.remote_hosts[0] local_host = self.pg4.remote_hosts[1] @@ -3936,23 +4303,31 @@ class TestNAT44EDMW(TestNAT44ED): self.vapi.nat44_forwarding_enable_disable(enable=1) self.nat_add_address(self.nat_addr, twice_nat=1) - flags = (self.config_flags.NAT_IS_OUT2IN_ONLY | - self.config_flags.NAT_IS_TWICE_NAT) - self.nat_add_static_mapping(local_host.ip4, self.nat_addr, - local_port, external_port, - proto=IP_PROTOS.tcp, flags=flags) + flags = ( + self.config_flags.NAT_IS_OUT2IN_ONLY | self.config_flags.NAT_IS_TWICE_NAT + ) + self.nat_add_static_mapping( + local_host.ip4, + self.nat_addr, + local_port, + external_port, + proto=IP_PROTOS.tcp, + flags=flags, + ) flags = self.config_flags.NAT_IS_INSIDE self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg4.sw_if_index, - is_add=1) + sw_if_index=self.pg4.sw_if_index, is_add=1 + ) self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg4.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg4.sw_if_index, flags=flags, is_add=1 + ) # from client to service - p = (Ether(src=self.pg4.remote_mac, dst=self.pg4.local_mac) / - IP(src=remote_host.ip4, dst=self.nat_addr) / - TCP(sport=12345, dport=external_port)) + p = ( + Ether(src=self.pg4.remote_mac, dst=self.pg4.local_mac) + / IP(src=remote_host.ip4, dst=self.nat_addr) + / TCP(sport=12345, dport=external_port) + ) self.pg4.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -3972,9 +4347,11 @@ class TestNAT44EDMW(TestNAT44ED): raise # from service back to client - p = (Ether(src=self.pg4.remote_mac, dst=self.pg4.local_mac) / - IP(src=local_host.ip4, dst=self.nat_addr) / - TCP(sport=local_port, dport=eh_port_in)) + p = ( + Ether(src=self.pg4.remote_mac, dst=self.pg4.local_mac) + / IP(src=local_host.ip4, dst=self.nat_addr) + / TCP(sport=local_port, dport=eh_port_in) + ) self.pg4.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -3993,7 +4370,7 @@ class TestNAT44EDMW(TestNAT44ED): raise def test_icmp_error_fwd_outbound(self): - """ NAT44ED ICMP error outbound with forwarding enabled """ + """NAT44ED ICMP error outbound with forwarding enabled""" # Ensure that an outbound ICMP error message is properly associated # with the inbound forward bypass session it is related to. @@ -4005,9 +4382,12 @@ class TestNAT44EDMW(TestNAT44ED): # enable forwarding and initiate connection out2in self.vapi.nat44_forwarding_enable_disable(enable=1) - p1 = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.pg0.remote_ip4) / - UDP(sport=21, dport=20) / payload) + p1 = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.pg0.remote_ip4) + / UDP(sport=21, dport=20) + / payload + ) self.pg1.add_stream(p1) self.pg_enable_capture(self.pg_interfaces) @@ -4021,10 +4401,12 @@ class TestNAT44EDMW(TestNAT44ED): # session dumps for a user will only look on the worker that the # user is supposed to be mapped to in2out. The forward bypass session # is not necessarily created on that worker. - p2 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - ICMP(type='dest-unreach', code='port-unreachable') / - capture[IP:]) + p2 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / ICMP(type="dest-unreach", code="port-unreachable") + / capture[IP:] + ) self.pg0.add_stream(p2) self.pg_enable_capture(self.pg_interfaces) @@ -4038,11 +4420,11 @@ class TestNAT44EDMW(TestNAT44ED): self.logger.info(ppp("capture packet:", capture)) def test_tcp_session_open_retransmit1(self): - """ NAT44ED Open TCP session with SYN,ACK retransmit 1 + """NAT44ED Open TCP session with SYN,ACK retransmit 1 - The client does not receive the [SYN,ACK] or the - ACK from the client is lost. Therefore, the [SYN, ACK] - is retransmitted by the server. + The client does not receive the [SYN,ACK] or the + ACK from the client is lost. Therefore, the [SYN, ACK] + is retransmitted by the server. """ in_port = self.tcp_port_in @@ -4053,50 +4435,61 @@ class TestNAT44EDMW(TestNAT44ED): self.nat_add_inside_interface(self.pg0) self.nat_add_outside_interface(self.pg1) - self.vapi.nat_set_timeouts(udp=300, tcp_established=7440, - tcp_transitory=5, icmp=60) + self.vapi.nat_set_timeouts( + udp=300, tcp_established=7440, tcp_transitory=5, icmp=60 + ) # SYN packet in->out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, flags="S")) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="S") + ) p = self.send_and_expect(self.pg0, p, self.pg1)[0] out_port = p[TCP].sport # SYN + ACK packet out->in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=ext_port, dport=out_port, flags="SA")) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=ext_port, dport=out_port, flags="SA") + ) self.send_and_expect(self.pg1, p, self.pg0) # ACK in->out does not arrive # resent SYN + ACK packet out->in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=ext_port, dport=out_port, flags="SA")) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=ext_port, dport=out_port, flags="SA") + ) self.send_and_expect(self.pg1, p, self.pg0) # ACK packet in->out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, flags="A")) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="A") + ) self.send_and_expect(self.pg0, p, self.pg1) # Verify that the data can be transmitted after the transitory time self.virtual_sleep(6) - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, flags="PA") / - Raw(payload)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="PA") + / Raw(payload) + ) self.send_and_expect(self.pg0, p, self.pg1) def test_tcp_session_open_retransmit2(self): - """ NAT44ED Open TCP session with SYN,ACK retransmit 2 + """NAT44ED Open TCP session with SYN,ACK retransmit 2 - The ACK is lost to the server after the TCP session is opened. - Data is sent by the client, then the [SYN,ACK] is - retransmitted by the server. + The ACK is lost to the server after the TCP session is opened. + Data is sent by the client, then the [SYN,ACK] is + retransmitted by the server. """ in_port = self.tcp_port_in @@ -4107,68 +4500,87 @@ class TestNAT44EDMW(TestNAT44ED): self.nat_add_inside_interface(self.pg0) self.nat_add_outside_interface(self.pg1) - self.vapi.nat_set_timeouts(udp=300, tcp_established=7440, - tcp_transitory=5, icmp=60) + self.vapi.nat_set_timeouts( + udp=300, tcp_established=7440, tcp_transitory=5, icmp=60 + ) # SYN packet in->out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, flags="S")) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="S") + ) p = self.send_and_expect(self.pg0, p, self.pg1)[0] out_port = p[TCP].sport # SYN + ACK packet out->in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=ext_port, dport=out_port, flags="SA")) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=ext_port, dport=out_port, flags="SA") + ) self.send_and_expect(self.pg1, p, self.pg0) # ACK packet in->out -- not received by the server - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, flags="A")) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="A") + ) self.send_and_expect(self.pg0, p, self.pg1) # PUSH + ACK packet in->out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, flags="PA") / - Raw(payload)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="PA") + / Raw(payload) + ) self.send_and_expect(self.pg0, p, self.pg1) # resent SYN + ACK packet out->in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=ext_port, dport=out_port, flags="SA")) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=ext_port, dport=out_port, flags="SA") + ) self.send_and_expect(self.pg1, p, self.pg0) # resent ACK packet in->out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, flags="A")) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="A") + ) self.send_and_expect(self.pg0, p, self.pg1) # resent PUSH + ACK packet in->out - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, flags="PA") / - Raw(payload)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="PA") + / Raw(payload) + ) self.send_and_expect(self.pg0, p, self.pg1) # ACK packet out->in - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=ext_port, dport=out_port, flags="A")) + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=ext_port, dport=out_port, flags="A") + ) self.send_and_expect(self.pg1, p, self.pg0) # Verify that the data can be transmitted after the transitory time self.virtual_sleep(6) - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=in_port, dport=ext_port, flags="PA") / - Raw(payload)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=in_port, dport=ext_port, flags="PA") + / Raw(payload) + ) self.send_and_expect(self.pg0, p, self.pg1) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_nat44_ed_output.py b/test/test_nat44_ed_output.py index 4ea8a5b5eda..4d75241c321 100644 --- a/test/test_nat44_ed_output.py +++ b/test/test_nat44_ed_output.py @@ -21,7 +21,8 @@ def get_nat44_ed_in2out_worker_index(ip, vpp_worker_count): class TestNAT44EDOutput(VppTestCase): - """ NAT44 ED output feature Test Case """ + """NAT44 ED output feature Test Case""" + max_sessions = 1024 @classmethod @@ -40,8 +41,7 @@ class TestNAT44EDOutput(VppTestCase): i.admin_up() i.config_ip4() i.resolve_arp() - self.vapi.nat44_ed_plugin_enable_disable(sessions=self.max_sessions, - enable=1) + self.vapi.nat44_ed_plugin_enable_disable(sessions=self.max_sessions, enable=1) def tearDown(self): if not self.vpp_dead: @@ -54,7 +54,7 @@ class TestNAT44EDOutput(VppTestCase): self.vapi.nat44_ed_plugin_enable_disable(enable=0) def test_static_dynamic(self): - """ Create static mapping which matches existing dynamic mapping """ + """Create static mapping which matches existing dynamic mapping""" config = self.vapi.nat44_show_running_config() old_timeouts = config.timeouts @@ -63,31 +63,37 @@ class TestNAT44EDOutput(VppTestCase): udp=old_timeouts.udp, tcp_established=old_timeouts.tcp_established, icmp=old_timeouts.icmp, - tcp_transitory=new_transitory) + tcp_transitory=new_transitory, + ) local_host = self.pg0.remote_ip4 remote_host = self.pg1.remote_ip4 nat_intf = self.pg1 outside_addr = nat_intf.local_ip4 - self.vapi.nat44_add_del_address_range(first_ip_address=outside_addr, - last_ip_address=outside_addr, - vrf_id=0xffffffff, - is_add=1, - flags=0) + self.vapi.nat44_add_del_address_range( + first_ip_address=outside_addr, + last_ip_address=outside_addr, + vrf_id=0xFFFFFFFF, + is_add=1, + flags=0, + ) self.vapi.nat44_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - is_add=1) + sw_if_index=self.pg0.sw_if_index, is_add=1 + ) self.vapi.nat44_interface_add_del_feature( sw_if_index=self.pg0.sw_if_index, - flags=VppEnum.vl_api_nat_config_flags_t.NAT_IS_INSIDE, is_add=1) + flags=VppEnum.vl_api_nat_config_flags_t.NAT_IS_INSIDE, + is_add=1, + ) self.vapi.nat44_ed_add_del_output_interface( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) thread_index = get_nat44_ed_in2out_worker_index( - local_host, self.vpp_worker_count) - port_per_thread = int((0xffff-1024) / max(1, self.vpp_worker_count)) + local_host, self.vpp_worker_count + ) + port_per_thread = int((0xFFFF - 1024) / max(1, self.vpp_worker_count)) local_sport = 1024 + random.randint(1, port_per_thread) if self.vpp_worker_count > 0: local_sport += port_per_thread * (thread_index - 1) @@ -100,9 +106,11 @@ class TestNAT44EDOutput(VppTestCase): # first setup a dynamic TCP session # SYN packet in->out - p = (Ether(src=pg0.remote_mac, dst=pg0.local_mac) / - IP(src=local_host, dst=remote_host) / - TCP(sport=local_sport, dport=remote_dport, flags="S")) + p = ( + Ether(src=pg0.remote_mac, dst=pg0.local_mac) + / IP(src=local_host, dst=remote_host) + / TCP(sport=local_sport, dport=remote_dport, flags="S") + ) p = self.send_and_expect(pg0, [p], pg1)[0] self.assertEqual(p[IP].src, outside_addr) @@ -110,15 +118,19 @@ class TestNAT44EDOutput(VppTestCase): outside_port = p[TCP].sport # SYN+ACK packet out->in - p = (Ether(src=pg1.remote_mac, dst=pg1.local_mac) / - IP(src=remote_host, dst=outside_addr) / - TCP(sport=remote_dport, dport=outside_port, flags="SA")) + p = ( + Ether(src=pg1.remote_mac, dst=pg1.local_mac) + / IP(src=remote_host, dst=outside_addr) + / TCP(sport=remote_dport, dport=outside_port, flags="SA") + ) self.send_and_expect(pg1, [p], pg0) # ACK packet in->out - p = (Ether(src=pg0.remote_mac, dst=pg0.local_mac) / - IP(src=local_host, dst=remote_host) / - TCP(sport=local_sport, dport=remote_dport, flags="A")) + p = ( + Ether(src=pg0.remote_mac, dst=pg0.local_mac) + / IP(src=local_host, dst=remote_host) + / TCP(sport=local_sport, dport=remote_dport, flags="A") + ) self.send_and_expect(pg0, [p], pg1) # now we have a session up, create a conflicting static mapping @@ -126,11 +138,12 @@ class TestNAT44EDOutput(VppTestCase): is_add=1, local_ip_address=local_host, external_ip_address=outside_addr, - external_sw_if_index=0xffffffff, + external_sw_if_index=0xFFFFFFFF, local_port=local_sport, external_port=outside_port, protocol=IP_PROTOS.tcp, - flags=VppEnum.vl_api_nat_config_flags_t.NAT_IS_OUT2IN_ONLY) + flags=VppEnum.vl_api_nat_config_flags_t.NAT_IS_OUT2IN_ONLY, + ) sessions = self.vapi.nat44_user_session_dump(local_host, 0) self.assertEqual(1, len(sessions)) @@ -138,47 +151,56 @@ class TestNAT44EDOutput(VppTestCase): # now send some more data over existing session - it should pass # in->out - p = (Ether(src=pg0.remote_mac, dst=pg0.local_mac) / - IP(src=local_host, dst=remote_host) / - TCP(sport=local_sport, dport=remote_dport) / - Raw("zippity zap")) + p = ( + Ether(src=pg0.remote_mac, dst=pg0.local_mac) + / IP(src=local_host, dst=remote_host) + / TCP(sport=local_sport, dport=remote_dport) + / Raw("zippity zap") + ) self.send_and_expect(pg0, [p], pg1) # out->in - p = (Ether(src=pg1.remote_mac, dst=pg1.local_mac) / - IP(src=remote_host, dst=outside_addr) / - TCP(sport=remote_dport, dport=outside_port) / - Raw("flippity flop")) + p = ( + Ether(src=pg1.remote_mac, dst=pg1.local_mac) + / IP(src=remote_host, dst=outside_addr) + / TCP(sport=remote_dport, dport=outside_port) + / Raw("flippity flop") + ) self.send_and_expect(pg1, [p], pg0) # now close the session # FIN packet in -> out - p = (Ether(src=pg0.remote_mac, dst=pg0.local_mac) / - IP(src=local_host, dst=remote_host) / - TCP(sport=local_sport, dport=remote_dport, flags="FA", seq=100, - ack=300)) + p = ( + Ether(src=pg0.remote_mac, dst=pg0.local_mac) + / IP(src=local_host, dst=remote_host) + / TCP(sport=local_sport, dport=remote_dport, flags="FA", seq=100, ack=300) + ) self.send_and_expect(pg0, [p], pg1) # FIN+ACK packet out -> in - p = (Ether(src=pg1.remote_mac, dst=pg1.local_mac) / - IP(src=remote_host, dst=outside_addr) / - TCP(sport=remote_dport, dport=outside_port, flags="FA", seq=300, - ack=101)) + p = ( + Ether(src=pg1.remote_mac, dst=pg1.local_mac) + / IP(src=remote_host, dst=outside_addr) + / TCP(sport=remote_dport, dport=outside_port, flags="FA", seq=300, ack=101) + ) self.send_and_expect(pg1, [p], pg0) # ACK packet in -> out - p = (Ether(src=pg0.remote_mac, dst=pg0.local_mac) / - IP(src=local_host, dst=remote_host) / - TCP(sport=local_sport, dport=remote_dport, flags="A", seq=101, - ack=301)) + p = ( + Ether(src=pg0.remote_mac, dst=pg0.local_mac) + / IP(src=local_host, dst=remote_host) + / TCP(sport=local_sport, dport=remote_dport, flags="A", seq=101, ack=301) + ) self.send_and_expect(pg0, [p], pg1) # session now in transitory timeout # try SYN packet in->out - should be dropped - p = (Ether(src=pg0.remote_mac, dst=pg0.local_mac) / - IP(src=local_host, dst=remote_host) / - TCP(sport=local_sport, dport=remote_dport, flags="S")) + p = ( + Ether(src=pg0.remote_mac, dst=pg0.local_mac) + / IP(src=local_host, dst=remote_host) + / TCP(sport=local_sport, dport=remote_dport, flags="S") + ) pg0.add_stream(p) self.pg_enable_capture() self.pg_start() @@ -192,10 +214,11 @@ class TestNAT44EDOutput(VppTestCase): # send FIN+ACK packet in->out - will cause session to be wiped # but won't create a new session - p = (Ether(src=pg0.remote_mac, dst=pg0.local_mac) / - IP(src=local_host, dst=remote_host) / - TCP(sport=local_sport, dport=remote_dport, flags="FA", seq=300, - ack=101)) + p = ( + Ether(src=pg0.remote_mac, dst=pg0.local_mac) + / IP(src=local_host, dst=remote_host) + / TCP(sport=local_sport, dport=remote_dport, flags="FA", seq=300, ack=101) + ) pg1.add_stream(p) self.pg_enable_capture() self.pg_start() @@ -207,9 +230,11 @@ class TestNAT44EDOutput(VppTestCase): # create a new session and make sure the outside port is remapped # SYN packet in->out - p = (Ether(src=pg0.remote_mac, dst=pg0.local_mac) / - IP(src=local_host, dst=remote_host) / - TCP(sport=local_sport, dport=remote_dport, flags="S")) + p = ( + Ether(src=pg0.remote_mac, dst=pg0.local_mac) + / IP(src=local_host, dst=remote_host) + / TCP(sport=local_sport, dport=remote_dport, flags="S") + ) p = self.send_and_expect(pg0, [p], pg1)[0] self.assertEqual(p[IP].src, outside_addr) @@ -217,14 +242,16 @@ class TestNAT44EDOutput(VppTestCase): # make sure static mapping works and creates a new session # SYN packet out->in - p = (Ether(src=pg1.remote_mac, dst=pg1.local_mac) / - IP(src=remote_host, dst=outside_addr) / - TCP(sport=remote_dport, dport=outside_port, flags="S")) + p = ( + Ether(src=pg1.remote_mac, dst=pg1.local_mac) + / IP(src=remote_host, dst=outside_addr) + / TCP(sport=remote_dport, dport=outside_port, flags="S") + ) self.send_and_expect(pg1, [p], pg0) sessions = self.vapi.nat44_user_session_dump(pg0.remote_ip4, 0) self.assertEqual(2, len(sessions)) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_nat44_ei.py b/test/test_nat44_ei.py index aafd345f43f..9eb127aaf0b 100644 --- a/test/test_nat44_ei.py +++ b/test/test_nat44_ei.py @@ -10,9 +10,19 @@ from io import BytesIO import scapy.compat from framework import VppTestCase, VppTestRunner from ipfix import IPFIX, Set, Template, Data, IPFIXDecoder -from scapy.all import bind_layers, Packet, ByteEnumField, ShortField, \ - IPField, IntField, LongField, XByteField, FlagsField, FieldLenField, \ - PacketListField +from scapy.all import ( + bind_layers, + Packet, + ByteEnumField, + ShortField, + IPField, + IntField, + LongField, + XByteField, + FlagsField, + FieldLenField, + PacketListField, +) from scapy.data import IP_PROTOS from scapy.layers.inet import IP, TCP, UDP, ICMP from scapy.layers.inet import IPerror, TCPerror, UDPerror, ICMPerror @@ -30,22 +40,22 @@ from vpp_papi import VppEnum # NAT HA protocol event data class Event(Packet): name = "Event" - fields_desc = [ByteEnumField("event_type", None, - {1: "add", 2: "del", 3: "refresh"}), - ByteEnumField("protocol", None, - {0: "other", 1: "udp", 2: "tcp", 3: "icmp"}), - ShortField("flags", 0), - IPField("in_addr", None), - IPField("out_addr", None), - ShortField("in_port", None), - ShortField("out_port", None), - IPField("eh_addr", None), - IPField("ehn_addr", None), - ShortField("eh_port", None), - ShortField("ehn_port", None), - IntField("fib_index", None), - IntField("total_pkts", 0), - LongField("total_bytes", 0)] + fields_desc = [ + ByteEnumField("event_type", None, {1: "add", 2: "del", 3: "refresh"}), + ByteEnumField("protocol", None, {0: "other", 1: "udp", 2: "tcp", 3: "icmp"}), + ShortField("flags", 0), + IPField("in_addr", None), + IPField("out_addr", None), + ShortField("in_port", None), + ShortField("out_port", None), + IPField("eh_addr", None), + IPField("ehn_addr", None), + ShortField("eh_port", None), + ShortField("ehn_port", None), + IntField("fib_index", None), + IntField("total_pkts", 0), + LongField("total_bytes", 0), + ] def extract_padding(self, s): return "", s @@ -54,17 +64,18 @@ class Event(Packet): # NAT HA protocol header class HANATStateSync(Packet): name = "HA NAT state sync" - fields_desc = [XByteField("version", 1), - FlagsField("flags", 0, 8, ['ACK']), - FieldLenField("count", None, count_of="events"), - IntField("sequence_number", 1), - IntField("thread_index", 0), - PacketListField("events", [], Event, - count_from=lambda pkt: pkt.count)] + fields_desc = [ + XByteField("version", 1), + FlagsField("flags", 0, 8, ["ACK"]), + FieldLenField("count", None, count_of="events"), + IntField("sequence_number", 1), + IntField("thread_index", 0), + PacketListField("events", [], Event, count_from=lambda pkt: pkt.count), + ] class MethodHolder(VppTestCase): - """ NAT create capture and verify method holder """ + """NAT create capture and verify method holder""" @property def config_flags(self): @@ -74,10 +85,19 @@ class MethodHolder(VppTestCase): def SYSLOG_SEVERITY(self): return VppEnum.vl_api_syslog_severity_t - def nat44_add_static_mapping(self, local_ip, external_ip='0.0.0.0', - local_port=0, external_port=0, vrf_id=0, - is_add=1, external_sw_if_index=0xFFFFFFFF, - proto=0, tag="", flags=0): + def nat44_add_static_mapping( + self, + local_ip, + external_ip="0.0.0.0", + local_port=0, + external_port=0, + vrf_id=0, + is_add=1, + external_sw_if_index=0xFFFFFFFF, + proto=0, + tag="", + flags=0, + ): """ Add/delete NAT44EI static mapping @@ -103,9 +123,11 @@ class MethodHolder(VppTestCase): external_sw_if_index=external_sw_if_index, local_port=local_port, external_port=external_port, - vrf_id=vrf_id, protocol=proto, + vrf_id=vrf_id, + protocol=proto, flags=flags, - tag=tag) + tag=tag, + ) def nat44_add_address(self, ip, is_add=1, vrf_id=0xFFFFFFFF): """ @@ -114,31 +136,40 @@ class MethodHolder(VppTestCase): :param ip: IP address :param is_add: 1 if add, 0 if delete (Default add) """ - self.vapi.nat44_ei_add_del_address_range(first_ip_address=ip, - last_ip_address=ip, - vrf_id=vrf_id, - is_add=is_add) + self.vapi.nat44_ei_add_del_address_range( + first_ip_address=ip, last_ip_address=ip, vrf_id=vrf_id, is_add=is_add + ) def create_routes_and_neigbors(self): - r1 = VppIpRoute(self, self.pg7.remote_ip4, 32, - [VppRoutePath(self.pg7.remote_ip4, - self.pg7.sw_if_index)]) - r2 = VppIpRoute(self, self.pg8.remote_ip4, 32, - [VppRoutePath(self.pg8.remote_ip4, - self.pg8.sw_if_index)]) + r1 = VppIpRoute( + self, + self.pg7.remote_ip4, + 32, + [VppRoutePath(self.pg7.remote_ip4, self.pg7.sw_if_index)], + ) + r2 = VppIpRoute( + self, + self.pg8.remote_ip4, + 32, + [VppRoutePath(self.pg8.remote_ip4, self.pg8.sw_if_index)], + ) r1.add_vpp_config() r2.add_vpp_config() - n1 = VppNeighbor(self, - self.pg7.sw_if_index, - self.pg7.remote_mac, - self.pg7.remote_ip4, - is_static=1) - n2 = VppNeighbor(self, - self.pg8.sw_if_index, - self.pg8.remote_mac, - self.pg8.remote_ip4, - is_static=1) + n1 = VppNeighbor( + self, + self.pg7.sw_if_index, + self.pg7.remote_mac, + self.pg7.remote_ip4, + is_static=1, + ) + n2 = VppNeighbor( + self, + self.pg8.sw_if_index, + self.pg8.remote_mac, + self.pg8.remote_ip4, + is_static=1, + ) n1.add_vpp_config() n2.add_vpp_config() @@ -156,21 +187,27 @@ class MethodHolder(VppTestCase): pkts = [] # TCP - p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) / - IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl) / - TCP(sport=self.tcp_port_in, dport=20)) + p = ( + Ether(dst=in_if.local_mac, src=in_if.remote_mac) + / IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl) + / TCP(sport=self.tcp_port_in, dport=20) + ) pkts.extend([p, p]) # UDP - p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) / - IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl) / - UDP(sport=self.udp_port_in, dport=20)) + p = ( + Ether(dst=in_if.local_mac, src=in_if.remote_mac) + / IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl) + / UDP(sport=self.udp_port_in, dport=20) + ) pkts.append(p) # ICMP - p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) / - IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl) / - ICMP(id=self.icmp_id_in, type='echo-request')) + p = ( + Ether(dst=in_if.local_mac, src=in_if.remote_mac) + / IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl) + / ICMP(id=self.icmp_id_in, type="echo-request") + ) pkts.append(p) return pkts @@ -216,11 +253,10 @@ class MethodHolder(VppTestCase): pref_n[13] = ip4_n[1] pref_n[14] = ip4_n[2] pref_n[15] = ip4_n[3] - packed_pref_n = b''.join([scapy.compat.chb(x) for x in pref_n]) + packed_pref_n = b"".join([scapy.compat.chb(x) for x in pref_n]) return socket.inet_ntop(socket.AF_INET6, packed_pref_n) - def create_stream_out(self, out_if, dst_ip=None, ttl=64, - use_inside_ports=False): + def create_stream_out(self, out_if, dst_ip=None, ttl=64, use_inside_ports=False): """ Create packet stream for outside network @@ -242,21 +278,27 @@ class MethodHolder(VppTestCase): icmp_id = self.icmp_id_in pkts = [] # TCP - p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) / - IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) / - TCP(dport=tcp_port, sport=20)) + p = ( + Ether(dst=out_if.local_mac, src=out_if.remote_mac) + / IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) + / TCP(dport=tcp_port, sport=20) + ) pkts.extend([p, p]) # UDP - p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) / - IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) / - UDP(dport=udp_port, sport=20)) + p = ( + Ether(dst=out_if.local_mac, src=out_if.remote_mac) + / IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) + / UDP(dport=udp_port, sport=20) + ) pkts.append(p) # ICMP - p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) / - IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) / - ICMP(id=icmp_id, type='echo-reply')) + p = ( + Ether(dst=out_if.local_mac, src=out_if.remote_mac) + / IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) + / ICMP(id=icmp_id, type="echo-reply") + ) pkts.append(p) return pkts @@ -271,27 +313,40 @@ class MethodHolder(VppTestCase): """ pkts = [] # TCP - p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) / - IPv6(src=src_ip, dst=dst_ip, hlim=hl) / - TCP(dport=self.tcp_port_out, sport=20)) + p = ( + Ether(dst=out_if.local_mac, src=out_if.remote_mac) + / IPv6(src=src_ip, dst=dst_ip, hlim=hl) + / TCP(dport=self.tcp_port_out, sport=20) + ) pkts.append(p) # UDP - p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) / - IPv6(src=src_ip, dst=dst_ip, hlim=hl) / - UDP(dport=self.udp_port_out, sport=20)) + p = ( + Ether(dst=out_if.local_mac, src=out_if.remote_mac) + / IPv6(src=src_ip, dst=dst_ip, hlim=hl) + / UDP(dport=self.udp_port_out, sport=20) + ) pkts.append(p) # ICMP - p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) / - IPv6(src=src_ip, dst=dst_ip, hlim=hl) / - ICMPv6EchoReply(id=self.icmp_id_out)) + p = ( + Ether(dst=out_if.local_mac, src=out_if.remote_mac) + / IPv6(src=src_ip, dst=dst_ip, hlim=hl) + / ICMPv6EchoReply(id=self.icmp_id_out) + ) pkts.append(p) return pkts - def verify_capture_out(self, capture, nat_ip=None, same_port=False, - dst_ip=None, is_ip6=False, ignore_port=False): + def verify_capture_out( + self, + capture, + nat_ip=None, + same_port=False, + dst_ip=None, + is_ip6=False, + ignore_port=False, + ): """ Verify captured packets on outside network @@ -319,39 +374,33 @@ class MethodHolder(VppTestCase): if packet.haslayer(TCP): if not ignore_port: if same_port: - self.assertEqual( - packet[TCP].sport, self.tcp_port_in) + self.assertEqual(packet[TCP].sport, self.tcp_port_in) else: - self.assertNotEqual( - packet[TCP].sport, self.tcp_port_in) + self.assertNotEqual(packet[TCP].sport, self.tcp_port_in) self.tcp_port_out = packet[TCP].sport self.assert_packet_checksums_valid(packet) elif packet.haslayer(UDP): if not ignore_port: if same_port: - self.assertEqual( - packet[UDP].sport, self.udp_port_in) + self.assertEqual(packet[UDP].sport, self.udp_port_in) else: - self.assertNotEqual( - packet[UDP].sport, self.udp_port_in) + self.assertNotEqual(packet[UDP].sport, self.udp_port_in) self.udp_port_out = packet[UDP].sport else: if not ignore_port: if same_port: - self.assertEqual( - packet[ICMP46].id, self.icmp_id_in) + self.assertEqual(packet[ICMP46].id, self.icmp_id_in) else: - self.assertNotEqual( - packet[ICMP46].id, self.icmp_id_in) + self.assertNotEqual(packet[ICMP46].id, self.icmp_id_in) self.icmp_id_out = packet[ICMP46].id self.assert_packet_checksums_valid(packet) except: - self.logger.error(ppp("Unexpected or invalid packet " - "(outside network):", packet)) + self.logger.error( + ppp("Unexpected or invalid packet (outside network):", packet) + ) raise - def verify_capture_out_ip6(self, capture, nat_ip, same_port=False, - dst_ip=None): + def verify_capture_out_ip6(self, capture, nat_ip, same_port=False, dst_ip=None): """ Verify captured packets on outside network @@ -360,8 +409,7 @@ class MethodHolder(VppTestCase): :param same_port: Source port number is not translated (Default False) :param dst_ip: Destination IP address (Default do not verify) """ - return self.verify_capture_out(capture, nat_ip, same_port, dst_ip, - True) + return self.verify_capture_out(capture, nat_ip, same_port, dst_ip, True) def verify_capture_in(self, capture, in_if): """ @@ -381,8 +429,9 @@ class MethodHolder(VppTestCase): else: self.assertEqual(packet[ICMP].id, self.icmp_id_in) except: - self.logger.error(ppp("Unexpected or invalid packet " - "(inside network):", packet)) + self.logger.error( + ppp("Unexpected or invalid packet (inside network):", packet) + ) raise def verify_capture_no_translation(self, capture, ingress_if, egress_if): @@ -404,12 +453,12 @@ class MethodHolder(VppTestCase): else: self.assertEqual(packet[ICMP].id, self.icmp_id_in) except: - self.logger.error(ppp("Unexpected or invalid packet " - "(inside network):", packet)) + self.logger.error( + ppp("Unexpected or invalid packet (inside network):", packet) + ) raise - def verify_capture_out_with_icmp_errors(self, capture, src_ip=None, - icmp_type=11): + def verify_capture_out_with_icmp_errors(self, capture, src_ip=None, icmp_type=11): """ Verify captured packets with ICMP errors on outside network @@ -430,16 +479,15 @@ class MethodHolder(VppTestCase): self.assertTrue(icmp.haslayer(IPerror)) inner_ip = icmp[IPerror] if inner_ip.haslayer(TCPerror): - self.assertEqual(inner_ip[TCPerror].dport, - self.tcp_port_out) + self.assertEqual(inner_ip[TCPerror].dport, self.tcp_port_out) elif inner_ip.haslayer(UDPerror): - self.assertEqual(inner_ip[UDPerror].dport, - self.udp_port_out) + self.assertEqual(inner_ip[UDPerror].dport, self.udp_port_out) else: self.assertEqual(inner_ip[ICMPerror].id, self.icmp_id_out) except: - self.logger.error(ppp("Unexpected or invalid packet " - "(outside network):", packet)) + self.logger.error( + ppp("Unexpected or invalid packet (outside network):", packet) + ) raise def verify_capture_in_with_icmp_errors(self, capture, in_if, icmp_type=11): @@ -460,20 +508,20 @@ class MethodHolder(VppTestCase): self.assertTrue(icmp.haslayer(IPerror)) inner_ip = icmp[IPerror] if inner_ip.haslayer(TCPerror): - self.assertEqual(inner_ip[TCPerror].sport, - self.tcp_port_in) + self.assertEqual(inner_ip[TCPerror].sport, self.tcp_port_in) elif inner_ip.haslayer(UDPerror): - self.assertEqual(inner_ip[UDPerror].sport, - self.udp_port_in) + self.assertEqual(inner_ip[UDPerror].sport, self.udp_port_in) else: self.assertEqual(inner_ip[ICMPerror].id, self.icmp_id_in) except: - self.logger.error(ppp("Unexpected or invalid packet " - "(inside network):", packet)) + self.logger.error( + ppp("Unexpected or invalid packet (inside network):", packet) + ) raise - def create_stream_frag(self, src_if, dst, sport, dport, data, - proto=IP_PROTOS.tcp, echo_reply=False): + def create_stream_frag( + self, src_if, dst, sport, dport, data, proto=IP_PROTOS.tcp, echo_reply=False + ): """ Create fragmented packet stream @@ -487,9 +535,11 @@ class MethodHolder(VppTestCase): :returns: Fragments """ if proto == IP_PROTOS.tcp: - p = (IP(src=src_if.remote_ip4, dst=dst) / - TCP(sport=sport, dport=dport) / - Raw(data)) + p = ( + IP(src=src_if.remote_ip4, dst=dst) + / TCP(sport=sport, dport=dport) + / Raw(data) + ) p = p.__class__(scapy.compat.raw(p)) chksum = p[TCP].chksum proto_header = TCP(sport=sport, dport=dport, chksum=chksum) @@ -497,9 +547,9 @@ class MethodHolder(VppTestCase): proto_header = UDP(sport=sport, dport=dport) elif proto == IP_PROTOS.icmp: if not echo_reply: - proto_header = ICMP(id=sport, type='echo-request') + proto_header = ICMP(id=sport, type="echo-request") else: - proto_header = ICMP(id=sport, type='echo-reply') + proto_header = ICMP(id=sport, type="echo-reply") else: raise Exception("Unsupported protocol") id = random.randint(0, 65535) @@ -508,28 +558,32 @@ class MethodHolder(VppTestCase): raw = Raw(data[0:4]) else: raw = Raw(data[0:16]) - p = (Ether(src=src_if.remote_mac, dst=src_if.local_mac) / - IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=0, id=id) / - proto_header / - raw) + p = ( + Ether(src=src_if.remote_mac, dst=src_if.local_mac) + / IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=0, id=id) + / proto_header + / raw + ) pkts.append(p) if proto == IP_PROTOS.tcp: raw = Raw(data[4:20]) else: raw = Raw(data[16:32]) - p = (Ether(src=src_if.remote_mac, dst=src_if.local_mac) / - IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=3, id=id, - proto=proto) / - raw) + p = ( + Ether(src=src_if.remote_mac, dst=src_if.local_mac) + / IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=3, id=id, proto=proto) + / raw + ) pkts.append(p) if proto == IP_PROTOS.tcp: raw = Raw(data[20:]) else: raw = Raw(data[32:]) - p = (Ether(src=src_if.remote_mac, dst=src_if.local_mac) / - IP(src=src_if.remote_ip4, dst=dst, frag=5, proto=proto, - id=id) / - raw) + p = ( + Ether(src=src_if.remote_mac, dst=src_if.local_mac) + / IP(src=src_if.remote_ip4, dst=dst, frag=5, proto=proto, id=id) + / raw + ) pkts.append(p) return pkts @@ -550,17 +604,15 @@ class MethodHolder(VppTestCase): self.assert_ip_checksum_valid(p) buffer.seek(p[IP].frag * 8) buffer.write(bytes(p[IP].payload)) - ip = IP(src=frags[0][IP].src, dst=frags[0][IP].dst, - proto=frags[0][IP].proto) + ip = IP(src=frags[0][IP].src, dst=frags[0][IP].dst, proto=frags[0][IP].proto) if ip.proto == IP_PROTOS.tcp: - p = (ip / TCP(buffer.getvalue())) + p = ip / TCP(buffer.getvalue()) self.logger.debug(ppp("Reassembled:", p)) self.assert_tcp_checksum_valid(p) elif ip.proto == IP_PROTOS.udp: - p = (ip / UDP(buffer.getvalue()[:8]) / - Raw(buffer.getvalue()[8:])) + p = ip / UDP(buffer.getvalue()[:8]) / Raw(buffer.getvalue()[8:]) elif ip.proto == IP_PROTOS.icmp: - p = (ip / ICMP(buffer.getvalue())) + p = ip / ICMP(buffer.getvalue()) return p def verify_ipfix_nat44_ses(self, data): @@ -580,29 +632,24 @@ class MethodHolder(VppTestCase): else: nat44_ses_delete_num += 1 # sourceIPv4Address - self.assertEqual(self.pg0.remote_ip4, - str(ipaddress.IPv4Address(record[8]))) + self.assertEqual(self.pg0.remote_ip4, str(ipaddress.IPv4Address(record[8]))) # postNATSourceIPv4Address - self.assertEqual(socket.inet_pton(socket.AF_INET, self.nat_addr), - record[225]) + self.assertEqual( + socket.inet_pton(socket.AF_INET, self.nat_addr), record[225] + ) # ingressVRFID self.assertEqual(struct.pack("!I", 0), record[234]) # protocolIdentifier/sourceTransportPort # /postNAPTSourceTransportPort if IP_PROTOS.icmp == scapy.compat.orb(record[4]): self.assertEqual(struct.pack("!H", self.icmp_id_in), record[7]) - self.assertEqual(struct.pack("!H", self.icmp_id_out), - record[227]) + self.assertEqual(struct.pack("!H", self.icmp_id_out), record[227]) elif IP_PROTOS.tcp == scapy.compat.orb(record[4]): - self.assertEqual(struct.pack("!H", self.tcp_port_in), - record[7]) - self.assertEqual(struct.pack("!H", self.tcp_port_out), - record[227]) + self.assertEqual(struct.pack("!H", self.tcp_port_in), record[7]) + self.assertEqual(struct.pack("!H", self.tcp_port_out), record[227]) elif IP_PROTOS.udp == scapy.compat.orb(record[4]): - self.assertEqual(struct.pack("!H", self.udp_port_in), - record[7]) - self.assertEqual(struct.pack("!H", self.udp_port_out), - record[227]) + self.assertEqual(struct.pack("!H", self.udp_port_in), record[7]) + self.assertEqual(struct.pack("!H", self.udp_port_out), record[227]) else: self.fail(f"Invalid protocol {scapy.compat.orb(record[4])}") self.assertEqual(3, nat44_ses_create_num) @@ -627,16 +674,16 @@ class MethodHolder(VppTestCase): self.assertEqual(struct.pack("!I", limit), record[471]) def verify_no_nat44_user(self): - """ Verify that there is no NAT44EI user """ + """Verify that there is no NAT44EI user""" users = self.vapi.nat44_ei_user_dump() self.assertEqual(len(users), 0) - users = self.statistics['/nat44-ei/total-users'] + users = self.statistics["/nat44-ei/total-users"] self.assertEqual(users[0][0], 0) - sessions = self.statistics['/nat44-ei/total-sessions'] + sessions = self.statistics["/nat44-ei/total-sessions"] self.assertEqual(sessions[0][0], 0) def verify_syslog_apmap(self, data, is_add=True): - message = data.decode('utf-8') + message = data.decode("utf-8") try: message = SyslogMessage.parse(message) except ParseError as e: @@ -644,26 +691,26 @@ class MethodHolder(VppTestCase): raise else: self.assertEqual(message.severity, SyslogSeverity.info) - self.assertEqual(message.appname, 'NAT') - self.assertEqual(message.msgid, 'APMADD' if is_add else 'APMDEL') - sd_params = message.sd.get('napmap') + self.assertEqual(message.appname, "NAT") + self.assertEqual(message.msgid, "APMADD" if is_add else "APMDEL") + sd_params = message.sd.get("napmap") self.assertTrue(sd_params is not None) - self.assertEqual(sd_params.get('IATYP'), 'IPv4') - self.assertEqual(sd_params.get('ISADDR'), self.pg0.remote_ip4) - self.assertEqual(sd_params.get('ISPORT'), "%d" % self.tcp_port_in) - self.assertEqual(sd_params.get('XATYP'), 'IPv4') - self.assertEqual(sd_params.get('XSADDR'), self.nat_addr) - self.assertEqual(sd_params.get('XSPORT'), "%d" % self.tcp_port_out) - self.assertEqual(sd_params.get('PROTO'), "%d" % IP_PROTOS.tcp) - self.assertTrue(sd_params.get('SSUBIX') is not None) - self.assertEqual(sd_params.get('SVLAN'), '0') + self.assertEqual(sd_params.get("IATYP"), "IPv4") + self.assertEqual(sd_params.get("ISADDR"), self.pg0.remote_ip4) + self.assertEqual(sd_params.get("ISPORT"), "%d" % self.tcp_port_in) + self.assertEqual(sd_params.get("XATYP"), "IPv4") + self.assertEqual(sd_params.get("XSADDR"), self.nat_addr) + self.assertEqual(sd_params.get("XSPORT"), "%d" % self.tcp_port_out) + self.assertEqual(sd_params.get("PROTO"), "%d" % IP_PROTOS.tcp) + self.assertTrue(sd_params.get("SSUBIX") is not None) + self.assertEqual(sd_params.get("SVLAN"), "0") def verify_mss_value(self, pkt, mss): if not pkt.haslayer(IP) or not pkt.haslayer(TCP): raise TypeError("Not a TCP/IP packet") for option in pkt[TCP].options: - if option[0] == 'MSS': + if option[0] == "MSS": self.assertEqual(option[1], mss) self.assert_tcp_checksum_valid(pkt) @@ -678,8 +725,9 @@ class MethodHolder(VppTestCase): else: raise Exception("Unsupported protocol") - def frag_in_order(self, proto=IP_PROTOS.tcp, dont_translate=False, - ignore_port=False): + def frag_in_order( + self, proto=IP_PROTOS.tcp, dont_translate=False, ignore_port=False + ): layer = self.proto2layer(proto) if proto == IP_PROTOS.tcp: @@ -689,20 +737,19 @@ class MethodHolder(VppTestCase): self.port_in = random.randint(1025, 65535) # in2out - pkts = self.create_stream_frag(self.pg0, self.pg1.remote_ip4, - self.port_in, 20, data, proto) + pkts = self.create_stream_frag( + self.pg0, self.pg1.remote_ip4, self.port_in, 20, data, proto + ) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() frags = self.pg1.get_capture(len(pkts)) if not dont_translate: - p = self.reass_frags_and_verify(frags, - self.nat_addr, - self.pg1.remote_ip4) + p = self.reass_frags_and_verify(frags, self.nat_addr, self.pg1.remote_ip4) else: - p = self.reass_frags_and_verify(frags, - self.pg0.remote_ip4, - self.pg1.remote_ip4) + p = self.reass_frags_and_verify( + frags, self.pg0.remote_ip4, self.pg1.remote_ip4 + ) if proto != IP_PROTOS.icmp: if not dont_translate: self.assertEqual(p[layer].dport, 20) @@ -729,15 +776,14 @@ class MethodHolder(VppTestCase): else: sport = p[layer].id dport = 0 - pkts = self.create_stream_frag(self.pg1, dst_addr, sport, dport, data, - proto, echo_reply=True) + pkts = self.create_stream_frag( + self.pg1, dst_addr, sport, dport, data, proto, echo_reply=True + ) self.pg1.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() frags = self.pg0.get_capture(len(pkts)) - p = self.reass_frags_and_verify(frags, - self.pg1.remote_ip4, - self.pg0.remote_ip4) + p = self.reass_frags_and_verify(frags, self.pg1.remote_ip4, self.pg0.remote_ip4) if proto != IP_PROTOS.icmp: self.assertEqual(p[layer].sport, 20) self.assertEqual(p[layer].dport, self.port_in) @@ -745,9 +791,15 @@ class MethodHolder(VppTestCase): self.assertEqual(p[layer].id, self.port_in) self.assertEqual(data, p[Raw].load) - def reass_hairpinning(self, server_addr, server_in_port, server_out_port, - host_in_port, proto=IP_PROTOS.tcp, - ignore_port=False): + def reass_hairpinning( + self, + server_addr, + server_in_port, + server_out_port, + host_in_port, + proto=IP_PROTOS.tcp, + ignore_port=False, + ): layer = self.proto2layer(proto) @@ -757,19 +809,14 @@ class MethodHolder(VppTestCase): data = b"A" * 16 + b"B" * 16 + b"C" * 3 # send packet from host to server - pkts = self.create_stream_frag(self.pg0, - self.nat_addr, - host_in_port, - server_out_port, - data, - proto) + pkts = self.create_stream_frag( + self.pg0, self.nat_addr, host_in_port, server_out_port, data, proto + ) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() frags = self.pg0.get_capture(len(pkts)) - p = self.reass_frags_and_verify(frags, - self.nat_addr, - server_addr) + p = self.reass_frags_and_verify(frags, self.nat_addr, server_addr) if proto != IP_PROTOS.icmp: if not ignore_port: self.assertNotEqual(p[layer].sport, host_in_port) @@ -779,8 +826,9 @@ class MethodHolder(VppTestCase): self.assertNotEqual(p[layer].id, host_in_port) self.assertEqual(data, p[Raw].load) - def frag_out_of_order(self, proto=IP_PROTOS.tcp, dont_translate=False, - ignore_port=False): + def frag_out_of_order( + self, proto=IP_PROTOS.tcp, dont_translate=False, ignore_port=False + ): layer = self.proto2layer(proto) if proto == IP_PROTOS.tcp: @@ -791,21 +839,22 @@ class MethodHolder(VppTestCase): for i in range(2): # in2out - pkts = self.create_stream_frag(self.pg0, self.pg1.remote_ip4, - self.port_in, 20, data, proto) + pkts = self.create_stream_frag( + self.pg0, self.pg1.remote_ip4, self.port_in, 20, data, proto + ) pkts.reverse() self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() frags = self.pg1.get_capture(len(pkts)) if not dont_translate: - p = self.reass_frags_and_verify(frags, - self.nat_addr, - self.pg1.remote_ip4) + p = self.reass_frags_and_verify( + frags, self.nat_addr, self.pg1.remote_ip4 + ) else: - p = self.reass_frags_and_verify(frags, - self.pg0.remote_ip4, - self.pg1.remote_ip4) + p = self.reass_frags_and_verify( + frags, self.pg0.remote_ip4, self.pg1.remote_ip4 + ) if proto != IP_PROTOS.icmp: if not dont_translate: self.assertEqual(p[layer].dport, 20) @@ -832,16 +881,17 @@ class MethodHolder(VppTestCase): else: sport = p[layer].id dport = 0 - pkts = self.create_stream_frag(self.pg1, dst_addr, sport, dport, - data, proto, echo_reply=True) + pkts = self.create_stream_frag( + self.pg1, dst_addr, sport, dport, data, proto, echo_reply=True + ) pkts.reverse() self.pg1.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() frags = self.pg0.get_capture(len(pkts)) - p = self.reass_frags_and_verify(frags, - self.pg1.remote_ip4, - self.pg0.remote_ip4) + p = self.reass_frags_and_verify( + frags, self.pg1.remote_ip4, self.pg0.remote_ip4 + ) if proto != IP_PROTOS.icmp: self.assertEqual(p[layer].sport, 20) self.assertEqual(p[layer].dport, self.port_in) @@ -861,7 +911,7 @@ def get_nat44_ei_in2out_worker_index(ip, vpp_worker_count): class TestNAT44EI(MethodHolder): - """ NAT44EI Test Cases """ + """NAT44EI Test Cases""" max_translations = 10240 max_users = 10240 @@ -877,7 +927,7 @@ class TestNAT44EI(MethodHolder): cls.udp_port_out = 6304 cls.icmp_id_in = 6305 cls.icmp_id_out = 6305 - cls.nat_addr = '10.0.0.3' + cls.nat_addr = "10.0.0.3" cls.ipfix_src_port = 4739 cls.ipfix_domain_id = 1 cls.tcp_external_port = 80 @@ -898,8 +948,8 @@ class TestNAT44EI(MethodHolder): cls.pg1.configure_ipv4_neighbors() cls.overlapping_interfaces = list(list(cls.pg_interfaces[4:7])) - cls.vapi.ip_table_add_del(is_add=1, table={'table_id': 10}) - cls.vapi.ip_table_add_del(is_add=1, table={'table_id': 20}) + cls.vapi.ip_table_add_del(is_add=1, table={"table_id": 10}) + cls.vapi.ip_table_add_del(is_add=1, table={"table_id": 20}) cls.pg4._local_ip4 = "172.16.255.1" cls.pg4._remote_hosts[0]._ip4 = "172.16.255.2" @@ -921,8 +971,8 @@ class TestNAT44EI(MethodHolder): cls.pg9.generate_remote_hosts(2) cls.pg9.config_ip4() cls.vapi.sw_interface_add_del_address( - sw_if_index=cls.pg9.sw_if_index, - prefix="10.0.0.1/24") + sw_if_index=cls.pg9.sw_if_index, prefix="10.0.0.1/24" + ) cls.pg9.admin_up() cls.pg9.resolve_arp() @@ -932,8 +982,8 @@ class TestNAT44EI(MethodHolder): def plugin_enable(self): self.vapi.nat44_ei_plugin_enable_disable( - sessions=self.max_translations, - users=self.max_users, enable=1) + sessions=self.max_translations, users=self.max_users, enable=1 + ) def setUp(self): super(TestNAT44EI, self).setUp() @@ -943,8 +993,8 @@ class TestNAT44EI(MethodHolder): super(TestNAT44EI, self).tearDown() if not self.vpp_dead: self.vapi.nat44_ei_ipfix_enable_disable( - domain_id=self.ipfix_domain_id, src_port=self.ipfix_src_port, - enable=0) + domain_id=self.ipfix_domain_id, src_port=self.ipfix_src_port, enable=0 + ) self.ipfix_src_port = 4739 self.ipfix_domain_id = 1 @@ -952,16 +1002,16 @@ class TestNAT44EI(MethodHolder): self.vapi.cli("clear logging") def test_clear_sessions(self): - """ NAT44EI session clearing test """ + """NAT44EI session clearing test""" self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) pkts = self.create_stream_in(self.pg0, self.pg1) self.pg0.add_stream(pkts) @@ -970,32 +1020,32 @@ class TestNAT44EI(MethodHolder): capture = self.pg1.get_capture(len(pkts)) self.verify_capture_out(capture) - sessions = self.statistics['/nat44-ei/total-sessions'] + sessions = self.statistics["/nat44-ei/total-sessions"] self.assertGreater(sessions[:, 0].sum(), 0, "Session count invalid") self.logger.info("sessions before clearing: %s" % sessions[0][0]) self.vapi.cli("clear nat44 ei sessions") - sessions = self.statistics['/nat44-ei/total-sessions'] + sessions = self.statistics["/nat44-ei/total-sessions"] self.assertEqual(sessions[:, 0].sum(), 0, "Session count invalid") self.logger.info("sessions after clearing: %s" % sessions[0][0]) def test_dynamic(self): - """ NAT44EI dynamic translation test """ + """NAT44EI dynamic translation test""" self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) # in2out - tcpn = self.statistics['/nat44-ei/in2out/slowpath/tcp'] - udpn = self.statistics['/nat44-ei/in2out/slowpath/udp'] - icmpn = self.statistics['/nat44-ei/in2out/slowpath/icmp'] - drops = self.statistics['/nat44-ei/in2out/slowpath/drops'] + tcpn = self.statistics["/nat44-ei/in2out/slowpath/tcp"] + udpn = self.statistics["/nat44-ei/in2out/slowpath/udp"] + icmpn = self.statistics["/nat44-ei/in2out/slowpath/icmp"] + drops = self.statistics["/nat44-ei/in2out/slowpath/drops"] pkts = self.create_stream_in(self.pg0, self.pg1) self.pg0.add_stream(pkts) @@ -1005,20 +1055,20 @@ class TestNAT44EI(MethodHolder): self.verify_capture_out(capture) if_idx = self.pg0.sw_if_index - cnt = self.statistics['/nat44-ei/in2out/slowpath/tcp'] + cnt = self.statistics["/nat44-ei/in2out/slowpath/tcp"] self.assertEqual(cnt[:, if_idx].sum() - tcpn[:, if_idx].sum(), 2) - cnt = self.statistics['/nat44-ei/in2out/slowpath/udp'] + cnt = self.statistics["/nat44-ei/in2out/slowpath/udp"] self.assertEqual(cnt[:, if_idx].sum() - udpn[:, if_idx].sum(), 1) - cnt = self.statistics['/nat44-ei/in2out/slowpath/icmp'] + cnt = self.statistics["/nat44-ei/in2out/slowpath/icmp"] self.assertEqual(cnt[:, if_idx].sum() - icmpn[:, if_idx].sum(), 1) - cnt = self.statistics['/nat44-ei/in2out/slowpath/drops'] + cnt = self.statistics["/nat44-ei/in2out/slowpath/drops"] self.assertEqual(cnt[:, if_idx].sum() - drops[:, if_idx].sum(), 0) # out2in - tcpn = self.statistics['/nat44-ei/out2in/slowpath/tcp'] - udpn = self.statistics['/nat44-ei/out2in/slowpath/udp'] - icmpn = self.statistics['/nat44-ei/out2in/slowpath/icmp'] - drops = self.statistics['/nat44-ei/out2in/slowpath/drops'] + tcpn = self.statistics["/nat44-ei/out2in/slowpath/tcp"] + udpn = self.statistics["/nat44-ei/out2in/slowpath/udp"] + icmpn = self.statistics["/nat44-ei/out2in/slowpath/icmp"] + drops = self.statistics["/nat44-ei/out2in/slowpath/drops"] pkts = self.create_stream_out(self.pg1) self.pg1.add_stream(pkts) @@ -1028,31 +1078,31 @@ class TestNAT44EI(MethodHolder): self.verify_capture_in(capture, self.pg0) if_idx = self.pg1.sw_if_index - cnt = self.statistics['/nat44-ei/out2in/slowpath/tcp'] + cnt = self.statistics["/nat44-ei/out2in/slowpath/tcp"] self.assertEqual(cnt[:, if_idx].sum() - tcpn[:, if_idx].sum(), 2) - cnt = self.statistics['/nat44-ei/out2in/slowpath/udp'] + cnt = self.statistics["/nat44-ei/out2in/slowpath/udp"] self.assertEqual(cnt[:, if_idx].sum() - udpn[:, if_idx].sum(), 1) - cnt = self.statistics['/nat44-ei/out2in/slowpath/icmp'] + cnt = self.statistics["/nat44-ei/out2in/slowpath/icmp"] self.assertEqual(cnt[:, if_idx].sum() - icmpn[:, if_idx].sum(), 1) - cnt = self.statistics['/nat44-ei/out2in/slowpath/drops'] + cnt = self.statistics["/nat44-ei/out2in/slowpath/drops"] self.assertEqual(cnt[:, if_idx].sum() - drops[:, if_idx].sum(), 0) - users = self.statistics['/nat44-ei/total-users'] + users = self.statistics["/nat44-ei/total-users"] self.assertEqual(users[:, 0].sum(), 1) - sessions = self.statistics['/nat44-ei/total-sessions'] + sessions = self.statistics["/nat44-ei/total-sessions"] self.assertEqual(sessions[:, 0].sum(), 3) def test_dynamic_icmp_errors_in2out_ttl_1(self): - """ NAT44EI handling of client packets with TTL=1 """ + """NAT44EI handling of client packets with TTL=1""" self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) # Client side - generate traffic pkts = self.create_stream_in(self.pg0, self.pg1, ttl=1) @@ -1062,16 +1112,16 @@ class TestNAT44EI(MethodHolder): self.verify_capture_in_with_icmp_errors(capture, self.pg0) def test_dynamic_icmp_errors_out2in_ttl_1(self): - """ NAT44EI handling of server packets with TTL=1 """ + """NAT44EI handling of server packets with TTL=1""" self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) # Client side - create sessions pkts = self.create_stream_in(self.pg0, self.pg1) @@ -1086,21 +1136,19 @@ class TestNAT44EI(MethodHolder): capture = self.send_and_expect_some(self.pg1, pkts, self.pg1) # Server side - verify ICMP type 11 packets - self.verify_capture_out_with_icmp_errors(capture, - src_ip=self.pg1.local_ip4) + self.verify_capture_out_with_icmp_errors(capture, src_ip=self.pg1.local_ip4) def test_dynamic_icmp_errors_in2out_ttl_2(self): - """ NAT44EI handling of error responses to client packets with TTL=2 - """ + """NAT44EI handling of error responses to client packets with TTL=2""" self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) # Client side - generate traffic pkts = self.create_stream_in(self.pg0, self.pg1, ttl=2) @@ -1110,9 +1158,13 @@ class TestNAT44EI(MethodHolder): # Server side - simulate ICMP type 11 response capture = self.pg1.get_capture(len(pkts)) - pkts = [Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - ICMP(type=11) / packet[IP] for packet in capture] + pkts = [ + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / ICMP(type=11) + / packet[IP] + for packet in capture + ] self.pg1.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1122,17 +1174,16 @@ class TestNAT44EI(MethodHolder): self.verify_capture_in_with_icmp_errors(capture, self.pg0) def test_dynamic_icmp_errors_out2in_ttl_2(self): - """ NAT44EI handling of error responses to server packets with TTL=2 - """ + """NAT44EI handling of error responses to server packets with TTL=2""" self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) # Client side - create sessions pkts = self.create_stream_in(self.pg0, self.pg1) @@ -1150,9 +1201,13 @@ class TestNAT44EI(MethodHolder): # Client side - simulate ICMP type 11 response capture = self.pg0.get_capture(len(pkts)) - pkts = [Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - ICMP(type=11) / packet[IP] for packet in capture] + pkts = [ + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / ICMP(type=11) + / packet[IP] + for packet in capture + ] self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1162,20 +1217,22 @@ class TestNAT44EI(MethodHolder): self.verify_capture_out_with_icmp_errors(capture) def test_ping_out_interface_from_outside(self): - """ NAT44EI ping out interface from outside network """ + """NAT44EI ping out interface from outside network""" self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) - - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IP(src=self.pg1.remote_ip4, dst=self.pg1.local_ip4) / - ICMP(id=self.icmp_id_out, type='echo-request')) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) + + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src=self.pg1.remote_ip4, dst=self.pg1.local_ip4) + / ICMP(id=self.icmp_id_out, type="echo-request") + ) pkts = [p] self.pg1.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) @@ -1188,26 +1245,29 @@ class TestNAT44EI(MethodHolder): self.assertEqual(packet[ICMP].id, self.icmp_id_in) self.assertEqual(packet[ICMP].type, 0) # echo reply except: - self.logger.error(ppp("Unexpected or invalid packet " - "(outside network):", packet)) + self.logger.error( + ppp("Unexpected or invalid packet (outside network):", packet) + ) raise def test_ping_internal_host_from_outside(self): - """ NAT44EI ping internal host from outside network """ + """NAT44EI ping internal host from outside network""" self.nat44_add_static_mapping(self.pg0.remote_ip4, self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) # out2in - pkt = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr, ttl=64) / - ICMP(id=self.icmp_id_out, type='echo-request')) + pkt = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr, ttl=64) + / ICMP(id=self.icmp_id_out, type="echo-request") + ) self.pg1.add_stream(pkt) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1216,9 +1276,11 @@ class TestNAT44EI(MethodHolder): self.assert_equal(capture[0][IP].proto, IP_PROTOS.icmp) # in2out - pkt = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, ttl=64) / - ICMP(id=self.icmp_id_in, type='echo-reply')) + pkt = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, ttl=64) + / ICMP(id=self.icmp_id_in, type="echo-reply") + ) self.pg0.add_stream(pkt) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1227,25 +1289,27 @@ class TestNAT44EI(MethodHolder): self.assert_equal(capture[0][IP].proto, IP_PROTOS.icmp) def test_forwarding(self): - """ NAT44EI forwarding test """ + """NAT44EI forwarding test""" flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) self.vapi.nat44_ei_forwarding_enable_disable(enable=1) real_ip = self.pg0.remote_ip4 alias_ip = self.nat_addr flags = self.config_flags.NAT44_EI_ADDR_ONLY_MAPPING self.vapi.nat44_ei_add_del_static_mapping( - is_add=1, local_ip_address=real_ip, + is_add=1, + local_ip_address=real_ip, external_ip_address=alias_ip, external_sw_if_index=0xFFFFFFFF, - flags=flags) + flags=flags, + ) try: # static mapping match @@ -1269,9 +1333,9 @@ class TestNAT44EI(MethodHolder): host0 = self.pg0.remote_hosts[0] self.pg0.remote_hosts[0] = self.pg0.remote_hosts[1] try: - pkts = self.create_stream_out(self.pg1, - dst_ip=self.pg0.remote_ip4, - use_inside_ports=True) + pkts = self.create_stream_out( + self.pg1, dst_ip=self.pg0.remote_ip4, use_inside_ports=True + ) self.pg1.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1283,8 +1347,9 @@ class TestNAT44EI(MethodHolder): self.pg_enable_capture(self.pg_interfaces) self.pg_start() capture = self.pg1.get_capture(len(pkts)) - self.verify_capture_out(capture, nat_ip=self.pg0.remote_ip4, - same_port=True) + self.verify_capture_out( + capture, nat_ip=self.pg0.remote_ip4, same_port=True + ) finally: self.pg0.remote_hosts[0] = host0 @@ -1296,10 +1361,11 @@ class TestNAT44EI(MethodHolder): local_ip_address=real_ip, external_ip_address=alias_ip, external_sw_if_index=0xFFFFFFFF, - flags=flags) + flags=flags, + ) def test_static_in(self): - """ NAT44EI 1:1 NAT initialized from inside network """ + """NAT44EI 1:1 NAT initialized from inside network""" nat_ip = "10.0.0.10" self.tcp_port_out = 6303 @@ -1309,14 +1375,14 @@ class TestNAT44EI(MethodHolder): self.nat44_add_static_mapping(self.pg0.remote_ip4, nat_ip) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) sm = self.vapi.nat44_ei_static_mapping_dump() self.assertEqual(len(sm), 1) - self.assertEqual(sm[0].tag, '') + self.assertEqual(sm[0].tag, "") self.assertEqual(sm[0].protocol, 0) self.assertEqual(sm[0].local_port, 0) self.assertEqual(sm[0].external_port, 0) @@ -1338,7 +1404,7 @@ class TestNAT44EI(MethodHolder): self.verify_capture_in(capture, self.pg0) def test_static_out(self): - """ NAT44EI 1:1 NAT initialized from outside network """ + """NAT44EI 1:1 NAT initialized from outside network""" nat_ip = "10.0.0.20" self.tcp_port_out = 6303 @@ -1349,11 +1415,11 @@ class TestNAT44EI(MethodHolder): self.nat44_add_static_mapping(self.pg0.remote_ip4, nat_ip, tag=tag) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) sm = self.vapi.nat44_ei_static_mapping_dump() self.assertEqual(len(sm), 1) self.assertEqual(sm[0].tag, tag) @@ -1375,29 +1441,41 @@ class TestNAT44EI(MethodHolder): self.verify_capture_out(capture, nat_ip, True) def test_static_with_port_in(self): - """ NAT44EI 1:1 NAPT initialized from inside network """ + """NAT44EI 1:1 NAPT initialized from inside network""" self.tcp_port_out = 3606 self.udp_port_out = 3607 self.icmp_id_out = 3608 self.nat44_add_address(self.nat_addr) - self.nat44_add_static_mapping(self.pg0.remote_ip4, self.nat_addr, - self.tcp_port_in, self.tcp_port_out, - proto=IP_PROTOS.tcp) - self.nat44_add_static_mapping(self.pg0.remote_ip4, self.nat_addr, - self.udp_port_in, self.udp_port_out, - proto=IP_PROTOS.udp) - self.nat44_add_static_mapping(self.pg0.remote_ip4, self.nat_addr, - self.icmp_id_in, self.icmp_id_out, - proto=IP_PROTOS.icmp) + self.nat44_add_static_mapping( + self.pg0.remote_ip4, + self.nat_addr, + self.tcp_port_in, + self.tcp_port_out, + proto=IP_PROTOS.tcp, + ) + self.nat44_add_static_mapping( + self.pg0.remote_ip4, + self.nat_addr, + self.udp_port_in, + self.udp_port_out, + proto=IP_PROTOS.udp, + ) + self.nat44_add_static_mapping( + self.pg0.remote_ip4, + self.nat_addr, + self.icmp_id_in, + self.icmp_id_out, + proto=IP_PROTOS.icmp, + ) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) # in2out pkts = self.create_stream_in(self.pg0, self.pg1) @@ -1416,29 +1494,41 @@ class TestNAT44EI(MethodHolder): self.verify_capture_in(capture, self.pg0) def test_static_with_port_out(self): - """ NAT44EI 1:1 NAPT initialized from outside network """ + """NAT44EI 1:1 NAPT initialized from outside network""" self.tcp_port_out = 30606 self.udp_port_out = 30607 self.icmp_id_out = 30608 self.nat44_add_address(self.nat_addr) - self.nat44_add_static_mapping(self.pg0.remote_ip4, self.nat_addr, - self.tcp_port_in, self.tcp_port_out, - proto=IP_PROTOS.tcp) - self.nat44_add_static_mapping(self.pg0.remote_ip4, self.nat_addr, - self.udp_port_in, self.udp_port_out, - proto=IP_PROTOS.udp) - self.nat44_add_static_mapping(self.pg0.remote_ip4, self.nat_addr, - self.icmp_id_in, self.icmp_id_out, - proto=IP_PROTOS.icmp) + self.nat44_add_static_mapping( + self.pg0.remote_ip4, + self.nat_addr, + self.tcp_port_in, + self.tcp_port_out, + proto=IP_PROTOS.tcp, + ) + self.nat44_add_static_mapping( + self.pg0.remote_ip4, + self.nat_addr, + self.udp_port_in, + self.udp_port_out, + proto=IP_PROTOS.udp, + ) + self.nat44_add_static_mapping( + self.pg0.remote_ip4, + self.nat_addr, + self.icmp_id_in, + self.icmp_id_out, + proto=IP_PROTOS.icmp, + ) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) # out2in pkts = self.create_stream_out(self.pg1) @@ -1457,7 +1547,7 @@ class TestNAT44EI(MethodHolder): self.verify_capture_out(capture) def test_static_vrf_aware(self): - """ NAT44EI 1:1 NAT VRF awareness """ + """NAT44EI 1:1 NAT VRF awareness""" nat_ip1 = "10.0.0.30" nat_ip2 = "10.0.0.40" @@ -1465,20 +1555,18 @@ class TestNAT44EI(MethodHolder): self.udp_port_out = 6304 self.icmp_id_out = 6305 - self.nat44_add_static_mapping(self.pg4.remote_ip4, nat_ip1, - vrf_id=10) - self.nat44_add_static_mapping(self.pg0.remote_ip4, nat_ip2, - vrf_id=10) + self.nat44_add_static_mapping(self.pg4.remote_ip4, nat_ip1, vrf_id=10) + self.nat44_add_static_mapping(self.pg0.remote_ip4, nat_ip2, vrf_id=10) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg3.sw_if_index, - is_add=1) + sw_if_index=self.pg3.sw_if_index, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg4.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg4.sw_if_index, flags=flags, is_add=1 + ) # inside interface VRF match NAT44EI static mapping VRF pkts = self.create_stream_in(self.pg4, self.pg3) @@ -1497,7 +1585,7 @@ class TestNAT44EI(MethodHolder): self.pg3.assert_nothing_captured() def test_dynamic_to_static(self): - """ NAT44EI Switch from dynamic translation to 1:1NAT """ + """NAT44EI Switch from dynamic translation to 1:1NAT""" nat_ip = "10.0.0.10" self.tcp_port_out = 6303 self.udp_port_out = 6304 @@ -1506,11 +1594,11 @@ class TestNAT44EI(MethodHolder): self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) # dynamic pkts = self.create_stream_in(self.pg0, self.pg1) @@ -1532,22 +1620,27 @@ class TestNAT44EI(MethodHolder): self.verify_capture_out(capture, nat_ip, True) def test_identity_nat(self): - """ NAT44EI Identity NAT """ + """NAT44EI Identity NAT""" flags = self.config_flags.NAT44_EI_ADDR_ONLY_MAPPING self.vapi.nat44_ei_add_del_identity_mapping( - ip_address=self.pg0.remote_ip4, sw_if_index=0xFFFFFFFF, - flags=flags, is_add=1) + ip_address=self.pg0.remote_ip4, + sw_if_index=0xFFFFFFFF, + flags=flags, + is_add=1, + ) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) - - p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.pg0.remote_ip4) / - TCP(sport=12345, dport=56789)) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) + + p = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.pg0.remote_ip4) + / TCP(sport=12345, dport=56789) + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1569,26 +1662,29 @@ class TestNAT44EI(MethodHolder): self.assertEqual(len(sessions), 0) flags = self.config_flags.NAT44_EI_ADDR_ONLY_MAPPING self.vapi.nat44_ei_add_del_identity_mapping( - ip_address=self.pg0.remote_ip4, sw_if_index=0xFFFFFFFF, - flags=flags, vrf_id=1, is_add=1) + ip_address=self.pg0.remote_ip4, + sw_if_index=0xFFFFFFFF, + flags=flags, + vrf_id=1, + is_add=1, + ) identity_mappings = self.vapi.nat44_ei_identity_mapping_dump() self.assertEqual(len(identity_mappings), 2) def test_multiple_inside_interfaces(self): - """ NAT44EI multiple non-overlapping address space inside interfaces - """ + """NAT44EI multiple non-overlapping address space inside interfaces""" self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg1.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg3.sw_if_index, - is_add=1) + sw_if_index=self.pg3.sw_if_index, is_add=1 + ) # between two NAT44EI inside interfaces (no translation) pkts = self.create_stream_in(self.pg0, self.pg1) @@ -1639,26 +1735,24 @@ class TestNAT44EI(MethodHolder): self.verify_capture_in(capture, self.pg1) def test_inside_overlapping_interfaces(self): - """ NAT44EI multiple inside interfaces with overlapping address space - """ + """NAT44EI multiple inside interfaces with overlapping address space""" static_nat_ip = "10.0.0.10" self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg3.sw_if_index, - is_add=1) + sw_if_index=self.pg3.sw_if_index, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg4.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg4.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg5.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg5.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg6.sw_if_index, - flags=flags, is_add=1) - self.nat44_add_static_mapping(self.pg6.remote_ip4, static_nat_ip, - vrf_id=20) + sw_if_index=self.pg6.sw_if_index, flags=flags, is_add=1 + ) + self.nat44_add_static_mapping(self.pg6.remote_ip4, static_nat_ip, vrf_id=20) # between NAT44EI inside interfaces with same VRF (no translation) pkts = self.create_stream_in(self.pg4, self.pg5) @@ -1669,9 +1763,11 @@ class TestNAT44EI(MethodHolder): self.verify_capture_no_translation(capture, self.pg4, self.pg5) # between NAT44EI inside interfaces with different VRF (hairpinning) - p = (Ether(src=self.pg4.remote_mac, dst=self.pg4.local_mac) / - IP(src=self.pg4.remote_ip4, dst=static_nat_ip) / - TCP(sport=1234, dport=5678)) + p = ( + Ether(src=self.pg4.remote_mac, dst=self.pg4.local_mac) + / IP(src=self.pg4.remote_ip4, dst=static_nat_ip) + / TCP(sport=1234, dport=5678) + ) self.pg4.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1723,16 +1819,12 @@ class TestNAT44EI(MethodHolder): # pg5 session dump addresses = self.vapi.nat44_ei_address_dump() self.assertEqual(len(addresses), 1) - sessions = self.vapi.nat44_ei_user_session_dump( - self.pg5.remote_ip4, 10) + sessions = self.vapi.nat44_ei_user_session_dump(self.pg5.remote_ip4, 10) self.assertEqual(len(sessions), 3) for session in sessions: - self.assertFalse(session.flags & - self.config_flags.NAT44_EI_STATIC_MAPPING) - self.assertEqual(str(session.inside_ip_address), - self.pg5.remote_ip4) - self.assertEqual(session.outside_ip_address, - addresses[0].ip_address) + self.assertFalse(session.flags & self.config_flags.NAT44_EI_STATIC_MAPPING) + self.assertEqual(str(session.inside_ip_address), self.pg5.remote_ip4) + self.assertEqual(session.outside_ip_address, addresses[0].ip_address) self.assertEqual(sessions[0].protocol, IP_PROTOS.tcp) self.assertEqual(sessions[1].protocol, IP_PROTOS.udp) self.assertEqual(sessions[2].protocol, IP_PROTOS.icmp) @@ -1765,44 +1857,38 @@ class TestNAT44EI(MethodHolder): addresses = self.vapi.nat44_ei_address_dump() self.assertEqual(len(addresses), 1) for user in users: - sessions = self.vapi.nat44_ei_user_session_dump(user.ip_address, - user.vrf_id) + sessions = self.vapi.nat44_ei_user_session_dump( + user.ip_address, user.vrf_id + ) for session in sessions: self.assertEqual(user.ip_address, session.inside_ip_address) self.assertTrue(session.total_bytes > session.total_pkts > 0) - self.assertTrue(session.protocol in - [IP_PROTOS.tcp, IP_PROTOS.udp, - IP_PROTOS.icmp]) + self.assertTrue( + session.protocol in [IP_PROTOS.tcp, IP_PROTOS.udp, IP_PROTOS.icmp] + ) # pg4 session dump - sessions = self.vapi.nat44_ei_user_session_dump( - self.pg4.remote_ip4, 10) + sessions = self.vapi.nat44_ei_user_session_dump(self.pg4.remote_ip4, 10) self.assertGreaterEqual(len(sessions), 4) for session in sessions: - self.assertFalse( - session.flags & self.config_flags.NAT44_EI_STATIC_MAPPING) - self.assertEqual(str(session.inside_ip_address), - self.pg4.remote_ip4) - self.assertEqual(session.outside_ip_address, - addresses[0].ip_address) + self.assertFalse(session.flags & self.config_flags.NAT44_EI_STATIC_MAPPING) + self.assertEqual(str(session.inside_ip_address), self.pg4.remote_ip4) + self.assertEqual(session.outside_ip_address, addresses[0].ip_address) # pg6 session dump - sessions = self.vapi.nat44_ei_user_session_dump( - self.pg6.remote_ip4, 20) + sessions = self.vapi.nat44_ei_user_session_dump(self.pg6.remote_ip4, 20) self.assertGreaterEqual(len(sessions), 3) for session in sessions: + self.assertTrue(session.flags & self.config_flags.NAT44_EI_STATIC_MAPPING) + self.assertEqual(str(session.inside_ip_address), self.pg6.remote_ip4) + self.assertEqual(str(session.outside_ip_address), static_nat_ip) self.assertTrue( - session.flags & self.config_flags.NAT44_EI_STATIC_MAPPING) - self.assertEqual(str(session.inside_ip_address), - self.pg6.remote_ip4) - self.assertEqual(str(session.outside_ip_address), - static_nat_ip) - self.assertTrue(session.inside_port in - [self.tcp_port_in, self.udp_port_in, - self.icmp_id_in]) + session.inside_port + in [self.tcp_port_in, self.udp_port_in, self.icmp_id_in] + ) def test_hairpinning(self): - """ NAT44EI hairpinning - 1:1 NAPT """ + """NAT44EI hairpinning - 1:1 NAPT""" host = self.pg0.remote_hosts[0] server = self.pg0.remote_hosts[1] @@ -1814,22 +1900,28 @@ class TestNAT44EI(MethodHolder): self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) # add static mapping for server - self.nat44_add_static_mapping(server.ip4, self.nat_addr, - server_in_port, server_out_port, - proto=IP_PROTOS.tcp) - - cnt = self.statistics['/nat44-ei/hairpinning'] + self.nat44_add_static_mapping( + server.ip4, + self.nat_addr, + server_in_port, + server_out_port, + proto=IP_PROTOS.tcp, + ) + + cnt = self.statistics["/nat44-ei/hairpinning"] # send packet from host to server - p = (Ether(src=host.mac, dst=self.pg0.local_mac) / - IP(src=host.ip4, dst=self.nat_addr) / - TCP(sport=host_in_port, dport=server_out_port)) + p = ( + Ether(src=host.mac, dst=self.pg0.local_mac) + / IP(src=host.ip4, dst=self.nat_addr) + / TCP(sport=host_in_port, dport=server_out_port) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1848,14 +1940,16 @@ class TestNAT44EI(MethodHolder): self.logger.error(ppp("Unexpected or invalid packet:", p)) raise - after = self.statistics['/nat44-ei/hairpinning'] + after = self.statistics["/nat44-ei/hairpinning"] if_idx = self.pg0.sw_if_index self.assertEqual(after[:, if_idx].sum() - cnt[:, if_idx].sum(), 1) # send reply from server to host - p = (Ether(src=server.mac, dst=self.pg0.local_mac) / - IP(src=server.ip4, dst=self.nat_addr) / - TCP(sport=server_in_port, dport=host_out_port)) + p = ( + Ether(src=server.mac, dst=self.pg0.local_mac) + / IP(src=server.ip4, dst=self.nat_addr) + / TCP(sport=server_in_port, dport=host_out_port) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1873,13 +1967,15 @@ class TestNAT44EI(MethodHolder): self.logger.error(ppp("Unexpected or invalid packet:", p)) raise - after = self.statistics['/nat44-ei/hairpinning'] + after = self.statistics["/nat44-ei/hairpinning"] if_idx = self.pg0.sw_if_index - self.assertEqual(after[:, if_idx].sum() - cnt[:, if_idx].sum(), - 2+(1 if self.vpp_worker_count > 0 else 0)) + self.assertEqual( + after[:, if_idx].sum() - cnt[:, if_idx].sum(), + 2 + (1 if self.vpp_worker_count > 0 else 0), + ) def test_hairpinning2(self): - """ NAT44EI hairpinning - 1:1 NAT""" + """NAT44EI hairpinning - 1:1 NAT""" server1_nat_ip = "10.0.0.10" server2_nat_ip = "10.0.0.11" @@ -1892,11 +1988,11 @@ class TestNAT44EI(MethodHolder): self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) # add static mapping for servers self.nat44_add_static_mapping(server1.ip4, server1_nat_ip) @@ -1904,17 +2000,23 @@ class TestNAT44EI(MethodHolder): # host to server1 pkts = [] - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=host.ip4, dst=server1_nat_ip) / - TCP(sport=self.tcp_port_in, dport=server_tcp_port)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=host.ip4, dst=server1_nat_ip) + / TCP(sport=self.tcp_port_in, dport=server_tcp_port) + ) pkts.append(p) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=host.ip4, dst=server1_nat_ip) / - UDP(sport=self.udp_port_in, dport=server_udp_port)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=host.ip4, dst=server1_nat_ip) + / UDP(sport=self.udp_port_in, dport=server_udp_port) + ) pkts.append(p) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=host.ip4, dst=server1_nat_ip) / - ICMP(id=self.icmp_id_in, type='echo-request')) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=host.ip4, dst=server1_nat_ip) + / ICMP(id=self.icmp_id_in, type="echo-request") + ) pkts.append(p) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) @@ -1942,17 +2044,23 @@ class TestNAT44EI(MethodHolder): # server1 to host pkts = [] - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=server1.ip4, dst=self.nat_addr) / - TCP(sport=server_tcp_port, dport=self.tcp_port_out)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=server1.ip4, dst=self.nat_addr) + / TCP(sport=server_tcp_port, dport=self.tcp_port_out) + ) pkts.append(p) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=server1.ip4, dst=self.nat_addr) / - UDP(sport=server_udp_port, dport=self.udp_port_out)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=server1.ip4, dst=self.nat_addr) + / UDP(sport=server_udp_port, dport=self.udp_port_out) + ) pkts.append(p) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=server1.ip4, dst=self.nat_addr) / - ICMP(id=self.icmp_id_out, type='echo-reply')) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=server1.ip4, dst=self.nat_addr) + / ICMP(id=self.icmp_id_out, type="echo-reply") + ) pkts.append(p) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) @@ -1977,17 +2085,23 @@ class TestNAT44EI(MethodHolder): # server2 to server1 pkts = [] - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=server2.ip4, dst=server1_nat_ip) / - TCP(sport=self.tcp_port_in, dport=server_tcp_port)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=server2.ip4, dst=server1_nat_ip) + / TCP(sport=self.tcp_port_in, dport=server_tcp_port) + ) pkts.append(p) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=server2.ip4, dst=server1_nat_ip) / - UDP(sport=self.udp_port_in, dport=server_udp_port)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=server2.ip4, dst=server1_nat_ip) + / UDP(sport=self.udp_port_in, dport=server_udp_port) + ) pkts.append(p) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=server2.ip4, dst=server1_nat_ip) / - ICMP(id=self.icmp_id_in, type='echo-request')) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=server2.ip4, dst=server1_nat_ip) + / ICMP(id=self.icmp_id_in, type="echo-request") + ) pkts.append(p) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) @@ -2015,17 +2129,23 @@ class TestNAT44EI(MethodHolder): # server1 to server2 pkts = [] - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=server1.ip4, dst=server2_nat_ip) / - TCP(sport=server_tcp_port, dport=self.tcp_port_out)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=server1.ip4, dst=server2_nat_ip) + / TCP(sport=server_tcp_port, dport=self.tcp_port_out) + ) pkts.append(p) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=server1.ip4, dst=server2_nat_ip) / - UDP(sport=server_udp_port, dport=self.udp_port_out)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=server1.ip4, dst=server2_nat_ip) + / UDP(sport=server_udp_port, dport=self.udp_port_out) + ) pkts.append(p) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=server1.ip4, dst=server2_nat_ip) / - ICMP(id=self.icmp_id_out, type='echo-reply')) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=server1.ip4, dst=server2_nat_ip) + / ICMP(id=self.icmp_id_out, type="echo-reply") + ) pkts.append(p) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) @@ -2049,7 +2169,7 @@ class TestNAT44EI(MethodHolder): raise def test_hairpinning_avoid_inf_loop(self): - """ NAT44EI hairpinning - 1:1 NAPT avoid infinite loop """ + """NAT44EI hairpinning - 1:1 NAPT avoid infinite loop""" host = self.pg0.remote_hosts[0] server = self.pg0.remote_hosts[1] @@ -2061,34 +2181,42 @@ class TestNAT44EI(MethodHolder): self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) # add static mapping for server - self.nat44_add_static_mapping(server.ip4, self.nat_addr, - server_in_port, server_out_port, - proto=IP_PROTOS.tcp) + self.nat44_add_static_mapping( + server.ip4, + self.nat_addr, + server_in_port, + server_out_port, + proto=IP_PROTOS.tcp, + ) # add another static mapping that maps pg0.local_ip4 address to itself self.nat44_add_static_mapping(self.pg0.local_ip4, self.pg0.local_ip4) # send packet from host to VPP (the packet should get dropped) - p = (Ether(src=host.mac, dst=self.pg0.local_mac) / - IP(src=host.ip4, dst=self.pg0.local_ip4) / - TCP(sport=host_in_port, dport=server_out_port)) + p = ( + Ether(src=host.mac, dst=self.pg0.local_mac) + / IP(src=host.ip4, dst=self.pg0.local_ip4) + / TCP(sport=host_in_port, dport=server_out_port) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() # Here VPP used to crash due to an infinite loop - cnt = self.statistics['/nat44-ei/hairpinning'] + cnt = self.statistics["/nat44-ei/hairpinning"] # send packet from host to server - p = (Ether(src=host.mac, dst=self.pg0.local_mac) / - IP(src=host.ip4, dst=self.nat_addr) / - TCP(sport=host_in_port, dport=server_out_port)) + p = ( + Ether(src=host.mac, dst=self.pg0.local_mac) + / IP(src=host.ip4, dst=self.nat_addr) + / TCP(sport=host_in_port, dport=server_out_port) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2107,14 +2235,16 @@ class TestNAT44EI(MethodHolder): self.logger.error(ppp("Unexpected or invalid packet:", p)) raise - after = self.statistics['/nat44-ei/hairpinning'] + after = self.statistics["/nat44-ei/hairpinning"] if_idx = self.pg0.sw_if_index self.assertEqual(after[:, if_idx].sum() - cnt[:, if_idx].sum(), 1) # send reply from server to host - p = (Ether(src=server.mac, dst=self.pg0.local_mac) / - IP(src=server.ip4, dst=self.nat_addr) / - TCP(sport=server_in_port, dport=host_out_port)) + p = ( + Ether(src=server.mac, dst=self.pg0.local_mac) + / IP(src=server.ip4, dst=self.nat_addr) + / TCP(sport=server_in_port, dport=host_out_port) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2132,16 +2262,18 @@ class TestNAT44EI(MethodHolder): self.logger.error(ppp("Unexpected or invalid packet:", p)) raise - after = self.statistics['/nat44-ei/hairpinning'] + after = self.statistics["/nat44-ei/hairpinning"] if_idx = self.pg0.sw_if_index - self.assertEqual(after[:, if_idx].sum() - cnt[:, if_idx].sum(), - 2+(1 if self.vpp_worker_count > 0 else 0)) + self.assertEqual( + after[:, if_idx].sum() - cnt[:, if_idx].sum(), + 2 + (1 if self.vpp_worker_count > 0 else 0), + ) def test_interface_addr(self): - """ NAT44EI acquire addresses from interface """ + """NAT44EI acquire addresses from interface""" self.vapi.nat44_ei_add_del_interface_addr( - is_add=1, - sw_if_index=self.pg7.sw_if_index) + is_add=1, sw_if_index=self.pg7.sw_if_index + ) # no address in NAT pool addresses = self.vapi.nat44_ei_address_dump() @@ -2159,22 +2291,20 @@ class TestNAT44EI(MethodHolder): self.assertEqual(0, len(addresses)) def test_interface_addr_static_mapping(self): - """ NAT44EI Static mapping with addresses from interface """ + """NAT44EI Static mapping with addresses from interface""" tag = "testTAG" self.vapi.nat44_ei_add_del_interface_addr( - is_add=1, - sw_if_index=self.pg7.sw_if_index) + is_add=1, sw_if_index=self.pg7.sw_if_index + ) self.nat44_add_static_mapping( - '1.2.3.4', - external_sw_if_index=self.pg7.sw_if_index, - tag=tag) + "1.2.3.4", external_sw_if_index=self.pg7.sw_if_index, tag=tag + ) # static mappings with external interface static_mappings = self.vapi.nat44_ei_static_mapping_dump() self.assertEqual(1, len(static_mappings)) - self.assertEqual(self.pg7.sw_if_index, - static_mappings[0].external_sw_if_index) + self.assertEqual(self.pg7.sw_if_index, static_mappings[0].external_sw_if_index) self.assertEqual(static_mappings[0].tag, tag) # configure interface address and check static mappings @@ -2184,8 +2314,7 @@ class TestNAT44EI(MethodHolder): resolved = False for sm in static_mappings: if sm.external_sw_if_index == 0xFFFFFFFF: - self.assertEqual(str(sm.external_ip_address), - self.pg7.local_ip4) + self.assertEqual(str(sm.external_ip_address), self.pg7.local_ip4) self.assertEqual(sm.tag, tag) resolved = True self.assertTrue(resolved) @@ -2194,8 +2323,7 @@ class TestNAT44EI(MethodHolder): self.pg7.unconfig_ip4() static_mappings = self.vapi.nat44_ei_static_mapping_dump() self.assertEqual(1, len(static_mappings)) - self.assertEqual(self.pg7.sw_if_index, - static_mappings[0].external_sw_if_index) + self.assertEqual(self.pg7.sw_if_index, static_mappings[0].external_sw_if_index) self.assertEqual(static_mappings[0].tag, tag) # configure interface address again and check static mappings @@ -2205,40 +2333,37 @@ class TestNAT44EI(MethodHolder): resolved = False for sm in static_mappings: if sm.external_sw_if_index == 0xFFFFFFFF: - self.assertEqual(str(sm.external_ip_address), - self.pg7.local_ip4) + self.assertEqual(str(sm.external_ip_address), self.pg7.local_ip4) self.assertEqual(sm.tag, tag) resolved = True self.assertTrue(resolved) # remove static mapping self.nat44_add_static_mapping( - '1.2.3.4', - external_sw_if_index=self.pg7.sw_if_index, - tag=tag, - is_add=0) + "1.2.3.4", external_sw_if_index=self.pg7.sw_if_index, tag=tag, is_add=0 + ) static_mappings = self.vapi.nat44_ei_static_mapping_dump() self.assertEqual(0, len(static_mappings)) def test_interface_addr_identity_nat(self): - """ NAT44EI Identity NAT with addresses from interface """ + """NAT44EI Identity NAT with addresses from interface""" port = 53053 self.vapi.nat44_ei_add_del_interface_addr( - is_add=1, - sw_if_index=self.pg7.sw_if_index) + is_add=1, sw_if_index=self.pg7.sw_if_index + ) self.vapi.nat44_ei_add_del_identity_mapping( - ip_address=b'0', + ip_address=b"0", sw_if_index=self.pg7.sw_if_index, port=port, protocol=IP_PROTOS.tcp, - is_add=1) + is_add=1, + ) # identity mappings with external interface identity_mappings = self.vapi.nat44_ei_identity_mapping_dump() self.assertEqual(1, len(identity_mappings)) - self.assertEqual(self.pg7.sw_if_index, - identity_mappings[0].sw_if_index) + self.assertEqual(self.pg7.sw_if_index, identity_mappings[0].sw_if_index) # configure interface address and check identity mappings self.pg7.config_ip4() @@ -2247,8 +2372,9 @@ class TestNAT44EI(MethodHolder): self.assertEqual(2, len(identity_mappings)) for sm in identity_mappings: if sm.sw_if_index == 0xFFFFFFFF: - self.assertEqual(str(identity_mappings[0].ip_address), - self.pg7.local_ip4) + self.assertEqual( + str(identity_mappings[0].ip_address), self.pg7.local_ip4 + ) self.assertEqual(port, identity_mappings[0].port) self.assertEqual(IP_PROTOS.tcp, identity_mappings[0].protocol) resolved = True @@ -2258,11 +2384,10 @@ class TestNAT44EI(MethodHolder): self.pg7.unconfig_ip4() identity_mappings = self.vapi.nat44_ei_identity_mapping_dump() self.assertEqual(1, len(identity_mappings)) - self.assertEqual(self.pg7.sw_if_index, - identity_mappings[0].sw_if_index) + self.assertEqual(self.pg7.sw_if_index, identity_mappings[0].sw_if_index) def test_ipfix_nat44_sess(self): - """ NAT44EI IPFIX logging NAT44EI session created/deleted """ + """NAT44EI IPFIX logging NAT44EI session created/deleted""" self.ipfix_domain_id = 10 self.ipfix_src_port = 20202 collector_port = 30303 @@ -2270,19 +2395,21 @@ class TestNAT44EI(MethodHolder): self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) - self.vapi.set_ipfix_exporter(collector_address=self.pg3.remote_ip4, - src_address=self.pg3.local_ip4, - path_mtu=512, - template_interval=10, - collector_port=collector_port) - self.vapi.nat44_ei_ipfix_enable_disable(domain_id=self.ipfix_domain_id, - src_port=self.ipfix_src_port, - enable=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) + self.vapi.set_ipfix_exporter( + collector_address=self.pg3.remote_ip4, + src_address=self.pg3.local_ip4, + path_mtu=512, + template_interval=10, + collector_port=collector_port, + ) + self.vapi.nat44_ei_ipfix_enable_disable( + domain_id=self.ipfix_domain_id, src_port=self.ipfix_src_port, enable=1 + ) pkts = self.create_stream_in(self.pg0, self.pg1) self.pg0.add_stream(pkts) @@ -2301,8 +2428,7 @@ class TestNAT44EI(MethodHolder): self.assertEqual(p[IP].dst, self.pg3.remote_ip4) self.assertEqual(p[UDP].sport, self.ipfix_src_port) self.assertEqual(p[UDP].dport, collector_port) - self.assertEqual(p[IPFIX].observationDomainID, - self.ipfix_domain_id) + self.assertEqual(p[IPFIX].observationDomainID, self.ipfix_domain_id) if p.haslayer(Template): ipfix.add_template(p.getlayer(Template)) # verify events in data set @@ -2312,25 +2438,29 @@ class TestNAT44EI(MethodHolder): self.verify_ipfix_nat44_ses(data) def test_ipfix_addr_exhausted(self): - """ NAT44EI IPFIX logging NAT addresses exhausted """ + """NAT44EI IPFIX logging NAT addresses exhausted""" flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) - self.vapi.set_ipfix_exporter(collector_address=self.pg3.remote_ip4, - src_address=self.pg3.local_ip4, - path_mtu=512, - template_interval=10) - self.vapi.nat44_ei_ipfix_enable_disable(domain_id=self.ipfix_domain_id, - src_port=self.ipfix_src_port, - enable=1) - - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=3025)) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) + self.vapi.set_ipfix_exporter( + collector_address=self.pg3.remote_ip4, + src_address=self.pg3.local_ip4, + path_mtu=512, + template_interval=10, + ) + self.vapi.nat44_ei_ipfix_enable_disable( + domain_id=self.ipfix_domain_id, src_port=self.ipfix_src_port, enable=1 + ) + + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=3025) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2345,8 +2475,7 @@ class TestNAT44EI(MethodHolder): self.assertEqual(p[IP].dst, self.pg3.remote_ip4) self.assertEqual(p[UDP].sport, self.ipfix_src_port) self.assertEqual(p[UDP].dport, 4739) - self.assertEqual(p[IPFIX].observationDomainID, - self.ipfix_domain_id) + self.assertEqual(p[IPFIX].observationDomainID, self.ipfix_domain_id) if p.haslayer(Template): ipfix.add_template(p.getlayer(Template)) # verify events in data set @@ -2356,15 +2485,15 @@ class TestNAT44EI(MethodHolder): self.verify_ipfix_addr_exhausted(data) def test_ipfix_max_sessions(self): - """ NAT44EI IPFIX logging maximum session entries exceeded """ + """NAT44EI IPFIX logging maximum session entries exceeded""" self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) max_sessions_per_thread = self.max_translations max_sessions = max(1, self.vpp_worker_count) * max_sessions_per_thread @@ -2372,26 +2501,32 @@ class TestNAT44EI(MethodHolder): pkts = [] for i in range(0, max_sessions): src = "10.10.%u.%u" % ((i & 0xFF00) >> 8, i & 0xFF) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=src, dst=self.pg1.remote_ip4) / - TCP(sport=1025)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=src, dst=self.pg1.remote_ip4) + / TCP(sport=1025) + ) pkts.append(p) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() self.pg1.get_capture(max_sessions) - self.vapi.set_ipfix_exporter(collector_address=self.pg3.remote_ip4, - src_address=self.pg3.local_ip4, - path_mtu=512, - template_interval=10) - self.vapi.nat44_ei_ipfix_enable_disable(domain_id=self.ipfix_domain_id, - src_port=self.ipfix_src_port, - enable=1) - - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=1025)) + self.vapi.set_ipfix_exporter( + collector_address=self.pg3.remote_ip4, + src_address=self.pg3.local_ip4, + path_mtu=512, + template_interval=10, + ) + self.vapi.nat44_ei_ipfix_enable_disable( + domain_id=self.ipfix_domain_id, src_port=self.ipfix_src_port, enable=1 + ) + + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=1025) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2406,8 +2541,7 @@ class TestNAT44EI(MethodHolder): self.assertEqual(p[IP].dst, self.pg3.remote_ip4) self.assertEqual(p[UDP].sport, self.ipfix_src_port) self.assertEqual(p[UDP].dport, 4739) - self.assertEqual(p[IPFIX].observationDomainID, - self.ipfix_domain_id) + self.assertEqual(p[IPFIX].observationDomainID, self.ipfix_domain_id) if p.haslayer(Template): ipfix.add_template(p.getlayer(Template)) # verify events in data set @@ -2417,22 +2551,23 @@ class TestNAT44EI(MethodHolder): self.verify_ipfix_max_sessions(data, max_sessions_per_thread) def test_syslog_apmap(self): - """ NAT44EI syslog address and port mapping creation and deletion """ - self.vapi.syslog_set_filter( - self.SYSLOG_SEVERITY.SYSLOG_API_SEVERITY_INFO) + """NAT44EI syslog address and port mapping creation and deletion""" + self.vapi.syslog_set_filter(self.SYSLOG_SEVERITY.SYSLOG_API_SEVERITY_INFO) self.vapi.syslog_set_sender(self.pg3.local_ip4, self.pg3.remote_ip4) self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) - - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=self.tcp_port_in, dport=20)) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) + + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=self.tcp_port_in, dport=20) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2448,22 +2583,25 @@ class TestNAT44EI(MethodHolder): self.verify_syslog_apmap(capture[0][Raw].load, False) def test_pool_addr_fib(self): - """ NAT44EI add pool addresses to FIB """ - static_addr = '10.0.0.10' + """NAT44EI add pool addresses to FIB""" + static_addr = "10.0.0.10" self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) self.nat44_add_static_mapping(self.pg0.remote_ip4, static_addr) # NAT44EI address - p = (Ether(src=self.pg1.remote_mac, dst='ff:ff:ff:ff:ff:ff') / - ARP(op=ARP.who_has, pdst=self.nat_addr, - psrc=self.pg1.remote_ip4, hwsrc=self.pg1.remote_mac)) + p = Ether(src=self.pg1.remote_mac, dst="ff:ff:ff:ff:ff:ff") / ARP( + op=ARP.who_has, + pdst=self.nat_addr, + psrc=self.pg1.remote_ip4, + hwsrc=self.pg1.remote_mac, + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2472,9 +2610,12 @@ class TestNAT44EI(MethodHolder): self.assertTrue(capture[0][ARP].op, ARP.is_at) # 1:1 NAT address - p = (Ether(src=self.pg1.remote_mac, dst='ff:ff:ff:ff:ff:ff') / - ARP(op=ARP.who_has, pdst=static_addr, - psrc=self.pg1.remote_ip4, hwsrc=self.pg1.remote_mac)) + p = Ether(src=self.pg1.remote_mac, dst="ff:ff:ff:ff:ff:ff") / ARP( + op=ARP.who_has, + pdst=static_addr, + psrc=self.pg1.remote_ip4, + hwsrc=self.pg1.remote_mac, + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2483,9 +2624,12 @@ class TestNAT44EI(MethodHolder): self.assertTrue(capture[0][ARP].op, ARP.is_at) # send ARP to non-NAT44EI interface - p = (Ether(src=self.pg2.remote_mac, dst='ff:ff:ff:ff:ff:ff') / - ARP(op=ARP.who_has, pdst=self.nat_addr, - psrc=self.pg2.remote_ip4, hwsrc=self.pg2.remote_mac)) + p = Ether(src=self.pg2.remote_mac, dst="ff:ff:ff:ff:ff:ff") / ARP( + op=ARP.who_has, + pdst=self.nat_addr, + psrc=self.pg2.remote_ip4, + hwsrc=self.pg2.remote_mac, + ) self.pg2.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2493,27 +2637,32 @@ class TestNAT44EI(MethodHolder): # remove addresses and verify self.nat44_add_address(self.nat_addr, is_add=0) - self.nat44_add_static_mapping(self.pg0.remote_ip4, static_addr, - is_add=0) - - p = (Ether(src=self.pg1.remote_mac, dst='ff:ff:ff:ff:ff:ff') / - ARP(op=ARP.who_has, pdst=self.nat_addr, - psrc=self.pg1.remote_ip4, hwsrc=self.pg1.remote_mac)) + self.nat44_add_static_mapping(self.pg0.remote_ip4, static_addr, is_add=0) + + p = Ether(src=self.pg1.remote_mac, dst="ff:ff:ff:ff:ff:ff") / ARP( + op=ARP.who_has, + pdst=self.nat_addr, + psrc=self.pg1.remote_ip4, + hwsrc=self.pg1.remote_mac, + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() self.pg1.assert_nothing_captured() - p = (Ether(src=self.pg1.remote_mac, dst='ff:ff:ff:ff:ff:ff') / - ARP(op=ARP.who_has, pdst=static_addr, - psrc=self.pg1.remote_ip4, hwsrc=self.pg1.remote_mac)) + p = Ether(src=self.pg1.remote_mac, dst="ff:ff:ff:ff:ff:ff") / ARP( + op=ARP.who_has, + pdst=static_addr, + psrc=self.pg1.remote_ip4, + hwsrc=self.pg1.remote_mac, + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() self.pg1.assert_nothing_captured() def test_vrf_mode(self): - """ NAT44EI tenant VRF aware address pool mode """ + """NAT44EI tenant VRF aware address pool mode""" vrf_id1 = 1 vrf_id2 = 2 @@ -2522,8 +2671,8 @@ class TestNAT44EI(MethodHolder): self.pg0.unconfig_ip4() self.pg1.unconfig_ip4() - self.vapi.ip_table_add_del(is_add=1, table={'table_id': vrf_id1}) - self.vapi.ip_table_add_del(is_add=1, table={'table_id': vrf_id2}) + self.vapi.ip_table_add_del(is_add=1, table={"table_id": vrf_id1}) + self.vapi.ip_table_add_del(is_add=1, table={"table_id": vrf_id2}) self.pg0.set_table_ip4(vrf_id1) self.pg1.set_table_ip4(vrf_id2) self.pg0.config_ip4() @@ -2535,14 +2684,14 @@ class TestNAT44EI(MethodHolder): self.nat44_add_address(nat_ip2, vrf_id=vrf_id2) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg1.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg2.sw_if_index, - is_add=1) + sw_if_index=self.pg2.sw_if_index, is_add=1 + ) try: # first VRF @@ -2570,11 +2719,11 @@ class TestNAT44EI(MethodHolder): self.pg1.config_ip4() self.pg0.resolve_arp() self.pg1.resolve_arp() - self.vapi.ip_table_add_del(is_add=0, table={'table_id': vrf_id1}) - self.vapi.ip_table_add_del(is_add=0, table={'table_id': vrf_id2}) + self.vapi.ip_table_add_del(is_add=0, table={"table_id": vrf_id1}) + self.vapi.ip_table_add_del(is_add=0, table={"table_id": vrf_id2}) def test_vrf_feature_independent(self): - """ NAT44EI tenant VRF independent address pool mode """ + """NAT44EI tenant VRF independent address pool mode""" nat_ip1 = "10.0.0.10" nat_ip2 = "10.0.0.11" @@ -2583,14 +2732,14 @@ class TestNAT44EI(MethodHolder): self.nat44_add_address(nat_ip2, vrf_id=99) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg1.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg2.sw_if_index, - is_add=1) + sw_if_index=self.pg2.sw_if_index, is_add=1 + ) # first VRF pkts = self.create_stream_in(self.pg0, self.pg2) @@ -2609,16 +2758,16 @@ class TestNAT44EI(MethodHolder): self.verify_capture_out(capture, nat_ip1) def test_dynamic_ipless_interfaces(self): - """ NAT44EI interfaces without configured IP address """ + """NAT44EI interfaces without configured IP address""" self.create_routes_and_neigbors() self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg7.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg7.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg8.sw_if_index, - is_add=1) + sw_if_index=self.pg8.sw_if_index, is_add=1 + ) # in2out pkts = self.create_stream_in(self.pg7, self.pg8) @@ -2637,17 +2786,17 @@ class TestNAT44EI(MethodHolder): self.verify_capture_in(capture, self.pg7) def test_static_ipless_interfaces(self): - """ NAT44EI interfaces without configured IP address - 1:1 NAT """ + """NAT44EI interfaces without configured IP address - 1:1 NAT""" self.create_routes_and_neigbors() self.nat44_add_static_mapping(self.pg7.remote_ip4, self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg7.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg7.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg8.sw_if_index, - is_add=1) + sw_if_index=self.pg8.sw_if_index, is_add=1 + ) # out2in pkts = self.create_stream_out(self.pg8) @@ -2666,7 +2815,7 @@ class TestNAT44EI(MethodHolder): self.verify_capture_out(capture, self.nat_addr, True) def test_static_with_port_ipless_interfaces(self): - """ NAT44EI interfaces without configured IP address - 1:1 NAPT """ + """NAT44EI interfaces without configured IP address - 1:1 NAPT""" self.tcp_port_out = 30606 self.udp_port_out = 30607 @@ -2674,22 +2823,34 @@ class TestNAT44EI(MethodHolder): self.create_routes_and_neigbors() self.nat44_add_address(self.nat_addr) - self.nat44_add_static_mapping(self.pg7.remote_ip4, self.nat_addr, - self.tcp_port_in, self.tcp_port_out, - proto=IP_PROTOS.tcp) - self.nat44_add_static_mapping(self.pg7.remote_ip4, self.nat_addr, - self.udp_port_in, self.udp_port_out, - proto=IP_PROTOS.udp) - self.nat44_add_static_mapping(self.pg7.remote_ip4, self.nat_addr, - self.icmp_id_in, self.icmp_id_out, - proto=IP_PROTOS.icmp) + self.nat44_add_static_mapping( + self.pg7.remote_ip4, + self.nat_addr, + self.tcp_port_in, + self.tcp_port_out, + proto=IP_PROTOS.tcp, + ) + self.nat44_add_static_mapping( + self.pg7.remote_ip4, + self.nat_addr, + self.udp_port_in, + self.udp_port_out, + proto=IP_PROTOS.udp, + ) + self.nat44_add_static_mapping( + self.pg7.remote_ip4, + self.nat_addr, + self.icmp_id_in, + self.icmp_id_out, + proto=IP_PROTOS.icmp, + ) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg7.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg7.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg8.sw_if_index, - is_add=1) + sw_if_index=self.pg8.sw_if_index, is_add=1 + ) # out2in pkts = self.create_stream_out(self.pg8) @@ -2708,23 +2869,25 @@ class TestNAT44EI(MethodHolder): self.verify_capture_out(capture) def test_static_unknown_proto(self): - """ NAT44EI 1:1 translate packet with unknown protocol """ + """NAT44EI 1:1 translate packet with unknown protocol""" nat_ip = "10.0.0.10" self.nat44_add_static_mapping(self.pg0.remote_ip4, nat_ip) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) # in2out - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - GRE() / - IP(src=self.pg2.remote_ip4, dst=self.pg3.remote_ip4) / - TCP(sport=1234, dport=1234)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / GRE() + / IP(src=self.pg2.remote_ip4, dst=self.pg3.remote_ip4) + / TCP(sport=1234, dport=1234) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2740,11 +2903,13 @@ class TestNAT44EI(MethodHolder): raise # out2in - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IP(src=self.pg1.remote_ip4, dst=nat_ip) / - GRE() / - IP(src=self.pg3.remote_ip4, dst=self.pg2.remote_ip4) / - TCP(sport=1234, dport=1234)) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src=self.pg1.remote_ip4, dst=nat_ip) + / GRE() + / IP(src=self.pg3.remote_ip4, dst=self.pg2.remote_ip4) + / TCP(sport=1234, dport=1234) + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2760,8 +2925,7 @@ class TestNAT44EI(MethodHolder): raise def test_hairpinning_static_unknown_proto(self): - """ NAT44EI 1:1 translate packet with unknown protocol - hairpinning - """ + """NAT44EI 1:1 translate packet with unknown protocol - hairpinning""" host = self.pg0.remote_hosts[0] server = self.pg0.remote_hosts[1] @@ -2773,18 +2937,20 @@ class TestNAT44EI(MethodHolder): self.nat44_add_static_mapping(server.ip4, server_nat_ip) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) # host to server - p = (Ether(dst=self.pg0.local_mac, src=host.mac) / - IP(src=host.ip4, dst=server_nat_ip) / - GRE() / - IP(src=self.pg2.remote_ip4, dst=self.pg3.remote_ip4) / - TCP(sport=1234, dport=1234)) + p = ( + Ether(dst=self.pg0.local_mac, src=host.mac) + / IP(src=host.ip4, dst=server_nat_ip) + / GRE() + / IP(src=self.pg2.remote_ip4, dst=self.pg3.remote_ip4) + / TCP(sport=1234, dport=1234) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2800,11 +2966,13 @@ class TestNAT44EI(MethodHolder): raise # server to host - p = (Ether(dst=self.pg0.local_mac, src=server.mac) / - IP(src=server.ip4, dst=host_nat_ip) / - GRE() / - IP(src=self.pg3.remote_ip4, dst=self.pg2.remote_ip4) / - TCP(sport=1234, dport=1234)) + p = ( + Ether(dst=self.pg0.local_mac, src=server.mac) + / IP(src=server.ip4, dst=host_nat_ip) + / GRE() + / IP(src=self.pg3.remote_ip4, dst=self.pg2.remote_ip4) + / TCP(sport=1234, dport=1234) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2820,10 +2988,11 @@ class TestNAT44EI(MethodHolder): raise def test_output_feature(self): - """ NAT44EI output feature (in2out postrouting) """ + """NAT44EI output feature (in2out postrouting)""" self.nat44_add_address(self.nat_addr) self.vapi.nat44_ei_add_del_output_interface( - sw_if_index=self.pg3.sw_if_index, is_add=1) + sw_if_index=self.pg3.sw_if_index, is_add=1 + ) # in2out pkts = self.create_stream_in(self.pg0, self.pg3) @@ -2850,25 +3019,32 @@ class TestNAT44EI(MethodHolder): self.verify_capture_no_translation(capture, self.pg2, self.pg0) def test_output_feature_vrf_aware(self): - """ NAT44EI output feature VRF aware (in2out postrouting) """ + """NAT44EI output feature VRF aware (in2out postrouting)""" nat_ip_vrf10 = "10.0.0.10" nat_ip_vrf20 = "10.0.0.20" - r1 = VppIpRoute(self, self.pg3.remote_ip4, 32, - [VppRoutePath(self.pg3.remote_ip4, - self.pg3.sw_if_index)], - table_id=10) - r2 = VppIpRoute(self, self.pg3.remote_ip4, 32, - [VppRoutePath(self.pg3.remote_ip4, - self.pg3.sw_if_index)], - table_id=20) + r1 = VppIpRoute( + self, + self.pg3.remote_ip4, + 32, + [VppRoutePath(self.pg3.remote_ip4, self.pg3.sw_if_index)], + table_id=10, + ) + r2 = VppIpRoute( + self, + self.pg3.remote_ip4, + 32, + [VppRoutePath(self.pg3.remote_ip4, self.pg3.sw_if_index)], + table_id=20, + ) r1.add_vpp_config() r2.add_vpp_config() self.nat44_add_address(nat_ip_vrf10, vrf_id=10) self.nat44_add_address(nat_ip_vrf20, vrf_id=20) self.vapi.nat44_ei_add_del_output_interface( - sw_if_index=self.pg3.sw_if_index, is_add=1) + sw_if_index=self.pg3.sw_if_index, is_add=1 + ) # in2out VRF 10 pkts = self.create_stream_in(self.pg4, self.pg3) @@ -2903,7 +3079,7 @@ class TestNAT44EI(MethodHolder): self.verify_capture_in(capture, self.pg6) def test_output_feature_hairpinning(self): - """ NAT44EI output feature hairpinning (in2out postrouting) """ + """NAT44EI output feature hairpinning (in2out postrouting)""" host = self.pg0.remote_hosts[0] server = self.pg0.remote_hosts[1] host_in_port = 1234 @@ -2913,19 +3089,27 @@ class TestNAT44EI(MethodHolder): self.nat44_add_address(self.nat_addr) self.vapi.nat44_ei_add_del_output_interface( - sw_if_index=self.pg0.sw_if_index, is_add=1) + sw_if_index=self.pg0.sw_if_index, is_add=1 + ) self.vapi.nat44_ei_add_del_output_interface( - sw_if_index=self.pg1.sw_if_index, is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) # add static mapping for server - self.nat44_add_static_mapping(server.ip4, self.nat_addr, - server_in_port, server_out_port, - proto=IP_PROTOS.tcp) + self.nat44_add_static_mapping( + server.ip4, + self.nat_addr, + server_in_port, + server_out_port, + proto=IP_PROTOS.tcp, + ) # send packet from host to server - p = (Ether(src=host.mac, dst=self.pg0.local_mac) / - IP(src=host.ip4, dst=self.nat_addr) / - TCP(sport=host_in_port, dport=server_out_port)) + p = ( + Ether(src=host.mac, dst=self.pg0.local_mac) + / IP(src=host.ip4, dst=self.nat_addr) + / TCP(sport=host_in_port, dport=server_out_port) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2945,9 +3129,11 @@ class TestNAT44EI(MethodHolder): raise # send reply from server to host - p = (Ether(src=server.mac, dst=self.pg0.local_mac) / - IP(src=server.ip4, dst=self.nat_addr) / - TCP(sport=server_in_port, dport=host_out_port)) + p = ( + Ether(src=server.mac, dst=self.pg0.local_mac) + / IP(src=server.ip4, dst=self.nat_addr) + / TCP(sport=server_in_port, dport=host_out_port) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -2966,7 +3152,7 @@ class TestNAT44EI(MethodHolder): raise def test_one_armed_nat44(self): - """ NAT44EI One armed NAT """ + """NAT44EI One armed NAT""" remote_host = self.pg9.remote_hosts[0] local_host = self.pg9.remote_hosts[1] external_port = 0 @@ -2974,16 +3160,18 @@ class TestNAT44EI(MethodHolder): self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg9.sw_if_index, - is_add=1) + sw_if_index=self.pg9.sw_if_index, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg9.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg9.sw_if_index, flags=flags, is_add=1 + ) # in2out - p = (Ether(src=self.pg9.remote_mac, dst=self.pg9.local_mac) / - IP(src=local_host.ip4, dst=remote_host.ip4) / - TCP(sport=12345, dport=80)) + p = ( + Ether(src=self.pg9.remote_mac, dst=self.pg9.local_mac) + / IP(src=local_host.ip4, dst=remote_host.ip4) + / TCP(sport=12345, dport=80) + ) self.pg9.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -3003,9 +3191,11 @@ class TestNAT44EI(MethodHolder): raise # out2in - p = (Ether(src=self.pg9.remote_mac, dst=self.pg9.local_mac) / - IP(src=remote_host.ip4, dst=self.nat_addr) / - TCP(sport=80, dport=external_port)) + p = ( + Ether(src=self.pg9.remote_mac, dst=self.pg9.local_mac) + / IP(src=remote_host.ip4, dst=self.nat_addr) + / TCP(sport=80, dport=external_port) + ) self.pg9.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -3028,21 +3218,21 @@ class TestNAT44EI(MethodHolder): else: node = "nat44-ei-classify" - err = self.statistics.get_err_counter('/err/%s/next in2out' % node) + err = self.statistics.get_err_counter("/err/%s/next in2out" % node) self.assertEqual(err, 1) - err = self.statistics.get_err_counter('/err/%s/next out2in' % node) + err = self.statistics.get_err_counter("/err/%s/next out2in" % node) self.assertEqual(err, 1) def test_del_session(self): - """ NAT44EI delete session """ + """NAT44EI delete session""" self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) pkts = self.create_stream_in(self.pg0, self.pg1) self.pg0.add_stream(pkts) @@ -3057,12 +3247,14 @@ class TestNAT44EI(MethodHolder): address=sessions[0].inside_ip_address, port=sessions[0].inside_port, protocol=sessions[0].protocol, - flags=self.config_flags.NAT44_EI_IF_INSIDE) + flags=self.config_flags.NAT44_EI_IF_INSIDE, + ) self.vapi.nat44_ei_del_session( address=sessions[1].outside_ip_address, port=sessions[1].outside_port, - protocol=sessions[1].protocol) + protocol=sessions[1].protocol, + ) sessions = self.vapi.nat44_ei_user_session_dump(self.pg0.remote_ip4, 0) self.assertEqual(nsessions - len(sessions), 2) @@ -3071,60 +3263,56 @@ class TestNAT44EI(MethodHolder): address=sessions[0].inside_ip_address, port=sessions[0].inside_port, protocol=sessions[0].protocol, - flags=self.config_flags.NAT44_EI_IF_INSIDE) + flags=self.config_flags.NAT44_EI_IF_INSIDE, + ) self.verify_no_nat44_user() def test_frag_in_order(self): - """ NAT44EI translate fragments arriving in order """ + """NAT44EI translate fragments arriving in order""" self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) self.frag_in_order(proto=IP_PROTOS.tcp) self.frag_in_order(proto=IP_PROTOS.udp) self.frag_in_order(proto=IP_PROTOS.icmp) def test_frag_forwarding(self): - """ NAT44EI forwarding fragment test """ + """NAT44EI forwarding fragment test""" self.vapi.nat44_ei_add_del_interface_addr( - is_add=1, - sw_if_index=self.pg1.sw_if_index) + is_add=1, sw_if_index=self.pg1.sw_if_index + ) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) self.vapi.nat44_ei_forwarding_enable_disable(enable=1) data = b"A" * 16 + b"B" * 16 + b"C" * 3 - pkts = self.create_stream_frag(self.pg1, - self.pg0.remote_ip4, - 4789, - 4789, - data, - proto=IP_PROTOS.udp) + pkts = self.create_stream_frag( + self.pg1, self.pg0.remote_ip4, 4789, 4789, data, proto=IP_PROTOS.udp + ) self.pg1.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() frags = self.pg0.get_capture(len(pkts)) - p = self.reass_frags_and_verify(frags, - self.pg1.remote_ip4, - self.pg0.remote_ip4) + p = self.reass_frags_and_verify(frags, self.pg1.remote_ip4, self.pg0.remote_ip4) self.assertEqual(p[UDP].sport, 4789) self.assertEqual(p[UDP].dport, 4789) self.assertEqual(data, p[Raw].load) def test_reass_hairpinning(self): - """ NAT44EI fragments hairpinning """ + """NAT44EI fragments hairpinning""" server_addr = self.pg0.remote_hosts[1].ip4 host_in_port = random.randint(1025, 65535) @@ -3134,63 +3322,85 @@ class TestNAT44EI(MethodHolder): self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) # add static mapping for server - self.nat44_add_static_mapping(server_addr, self.nat_addr, - server_in_port, - server_out_port, - proto=IP_PROTOS.tcp) - self.nat44_add_static_mapping(server_addr, self.nat_addr, - server_in_port, - server_out_port, - proto=IP_PROTOS.udp) + self.nat44_add_static_mapping( + server_addr, + self.nat_addr, + server_in_port, + server_out_port, + proto=IP_PROTOS.tcp, + ) + self.nat44_add_static_mapping( + server_addr, + self.nat_addr, + server_in_port, + server_out_port, + proto=IP_PROTOS.udp, + ) self.nat44_add_static_mapping(server_addr, self.nat_addr) - self.reass_hairpinning(server_addr, server_in_port, server_out_port, - host_in_port, proto=IP_PROTOS.tcp) - self.reass_hairpinning(server_addr, server_in_port, server_out_port, - host_in_port, proto=IP_PROTOS.udp) - self.reass_hairpinning(server_addr, server_in_port, server_out_port, - host_in_port, proto=IP_PROTOS.icmp) + self.reass_hairpinning( + server_addr, + server_in_port, + server_out_port, + host_in_port, + proto=IP_PROTOS.tcp, + ) + self.reass_hairpinning( + server_addr, + server_in_port, + server_out_port, + host_in_port, + proto=IP_PROTOS.udp, + ) + self.reass_hairpinning( + server_addr, + server_in_port, + server_out_port, + host_in_port, + proto=IP_PROTOS.icmp, + ) def test_frag_out_of_order(self): - """ NAT44EI translate fragments arriving out of order """ + """NAT44EI translate fragments arriving out of order""" self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) self.frag_out_of_order(proto=IP_PROTOS.tcp) self.frag_out_of_order(proto=IP_PROTOS.udp) self.frag_out_of_order(proto=IP_PROTOS.icmp) def test_port_restricted(self): - """ NAT44EI Port restricted NAT44EI (MAP-E CE) """ + """NAT44EI Port restricted NAT44EI (MAP-E CE)""" self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) - self.vapi.nat44_ei_set_addr_and_port_alloc_alg(alg=1, - psid_offset=6, - psid_length=6, - psid=10) - - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=4567, dport=22)) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) + self.vapi.nat44_ei_set_addr_and_port_alloc_alg( + alg=1, psid_offset=6, psid_length=6, psid=10 + ) + + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=4567, dport=22) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -3210,24 +3420,26 @@ class TestNAT44EI(MethodHolder): raise def test_port_range(self): - """ NAT44EI External address port range """ + """NAT44EI External address port range""" self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) - self.vapi.nat44_ei_set_addr_and_port_alloc_alg(alg=2, - start_port=1025, - end_port=1027) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) + self.vapi.nat44_ei_set_addr_and_port_alloc_alg( + alg=2, start_port=1025, end_port=1027 + ) pkts = [] for port in range(0, 5): - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=1125 + port)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP(sport=1125 + port) + ) pkts.append(p) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) @@ -3239,14 +3451,14 @@ class TestNAT44EI(MethodHolder): self.assertLessEqual(tcp.sport, 1027) def test_multiple_outside_vrf(self): - """ NAT44EI Multiple outside VRF """ + """NAT44EI Multiple outside VRF""" vrf_id1 = 1 vrf_id2 = 2 self.pg1.unconfig_ip4() self.pg2.unconfig_ip4() - self.vapi.ip_table_add_del(is_add=1, table={'table_id': vrf_id1}) - self.vapi.ip_table_add_del(is_add=1, table={'table_id': vrf_id2}) + self.vapi.ip_table_add_del(is_add=1, table={"table_id": vrf_id1}) + self.vapi.ip_table_add_del(is_add=1, table={"table_id": vrf_id2}) self.pg1.set_table_ip4(vrf_id1) self.pg2.set_table_ip4(vrf_id2) self.pg1.config_ip4() @@ -3257,14 +3469,14 @@ class TestNAT44EI(MethodHolder): self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg2.sw_if_index, - is_add=1) + sw_if_index=self.pg2.sw_if_index, is_add=1 + ) try: # first VRF @@ -3313,20 +3525,26 @@ class TestNAT44EI(MethodHolder): self.pg2.resolve_arp() def test_mss_clamping(self): - """ NAT44EI TCP MSS clamping """ + """NAT44EI TCP MSS clamping""" self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) - - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, - flags="S", options=[('MSS', 1400)])) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) + + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / TCP( + sport=self.tcp_port_in, + dport=self.tcp_external_port, + flags="S", + options=[("MSS", 1400)], + ) + ) self.vapi.nat44_ei_set_mss_clamping(enable=1, mss_value=1000) self.pg0.add_stream(p) @@ -3353,21 +3571,22 @@ class TestNAT44EI(MethodHolder): self.verify_mss_value(capture[0], 1400) def test_ha_send(self): - """ NAT44EI Send HA session synchronization events (active) """ + """NAT44EI Send HA session synchronization events (active)""" flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) self.nat44_add_address(self.nat_addr) self.vapi.nat44_ei_ha_set_listener( - ip_address=self.pg3.local_ip4, port=12345, path_mtu=512) + ip_address=self.pg3.local_ip4, port=12345, path_mtu=512 + ) self.vapi.nat44_ei_ha_set_failover( - ip_address=self.pg3.remote_ip4, port=12346, - session_refresh_interval=10) + ip_address=self.pg3.remote_ip4, port=12346, session_refresh_interval=10 + ) bind_layers(UDP, HANATStateSync, sport=12345) # create sessions @@ -3379,7 +3598,7 @@ class TestNAT44EI(MethodHolder): self.verify_capture_out(capture) # active send HA events self.vapi.nat44_ei_ha_flush() - stats = self.statistics['/nat44-ei/ha/add-event-send'] + stats = self.statistics["/nat44-ei/ha/add-event-send"] self.assertEqual(stats[:, 0].sum(), 3) capture = self.pg3.get_capture(1) p = capture[0] @@ -3407,23 +3626,29 @@ class TestNAT44EI(MethodHolder): self.assertEqual(event.fib_index, 0) # ACK received events - ack = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) / - IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) / - UDP(sport=12346, dport=12345) / - HANATStateSync(sequence_number=seq, flags='ACK', - thread_index=hanat.thread_index)) + ack = ( + Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) + / IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) + / UDP(sport=12346, dport=12345) + / HANATStateSync( + sequence_number=seq, flags="ACK", thread_index=hanat.thread_index + ) + ) self.pg3.add_stream(ack) self.pg_start() - stats = self.statistics['/nat44-ei/ha/ack-recv'] + stats = self.statistics["/nat44-ei/ha/ack-recv"] self.assertEqual(stats[:, 0].sum(), 1) # delete one session self.pg_enable_capture(self.pg_interfaces) self.vapi.nat44_ei_del_session( - address=self.pg0.remote_ip4, port=self.tcp_port_in, - protocol=IP_PROTOS.tcp, flags=self.config_flags.NAT44_EI_IF_INSIDE) + address=self.pg0.remote_ip4, + port=self.tcp_port_in, + protocol=IP_PROTOS.tcp, + flags=self.config_flags.NAT44_EI_IF_INSIDE, + ) self.vapi.nat44_ei_ha_flush() - stats = self.statistics['/nat44-ei/ha/del-event-send'] + stats = self.statistics["/nat44-ei/ha/del-event-send"] self.assertEqual(stats[:, 0].sum(), 1) capture = self.pg3.get_capture(1) p = capture[0] @@ -3438,9 +3663,9 @@ class TestNAT44EI(MethodHolder): # do not send ACK, active retry send HA event again self.pg_enable_capture(self.pg_interfaces) self.virtual_sleep(12) - stats = self.statistics['/nat44-ei/ha/retry-count'] + stats = self.statistics["/nat44-ei/ha/retry-count"] self.assertEqual(stats[:, 0].sum(), 3) - stats = self.statistics['/nat44-ei/ha/missed-count'] + stats = self.statistics["/nat44-ei/ha/missed-count"] self.assertEqual(stats[:, 0].sum(), 1) capture = self.pg3.get_capture(3) for packet in capture: @@ -3453,7 +3678,7 @@ class TestNAT44EI(MethodHolder): self.pg_start() self.pg0.get_capture(2) self.vapi.nat44_ei_ha_flush() - stats = self.statistics['/nat44-ei/ha/refresh-event-send'] + stats = self.statistics["/nat44-ei/ha/refresh-event-send"] self.assertEqual(stats[:, 0].sum(), 2) capture = self.pg3.get_capture(1) p = capture[0] @@ -3480,29 +3705,33 @@ class TestNAT44EI(MethodHolder): self.assertEqual(event.total_pkts, 2) self.assertGreater(event.total_bytes, 0) - stats = self.statistics['/nat44-ei/ha/ack-recv'] - ack = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) / - IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) / - UDP(sport=12346, dport=12345) / - HANATStateSync(sequence_number=seq, flags='ACK', - thread_index=hanat.thread_index)) + stats = self.statistics["/nat44-ei/ha/ack-recv"] + ack = ( + Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) + / IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) + / UDP(sport=12346, dport=12345) + / HANATStateSync( + sequence_number=seq, flags="ACK", thread_index=hanat.thread_index + ) + ) self.pg3.add_stream(ack) self.pg_start() - stats = self.statistics['/nat44-ei/ha/ack-recv'] + stats = self.statistics["/nat44-ei/ha/ack-recv"] self.assertEqual(stats[:, 0].sum(), 2) def test_ha_recv(self): - """ NAT44EI Receive HA session synchronization events (passive) """ + """NAT44EI Receive HA session synchronization events (passive)""" self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) - self.vapi.nat44_ei_ha_set_listener(ip_address=self.pg3.local_ip4, - port=12345, path_mtu=512) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) + self.vapi.nat44_ei_ha_set_listener( + ip_address=self.pg3.local_ip4, port=12345, path_mtu=512 + ) bind_layers(UDP, HANATStateSync, sport=12345) # this is a bit tricky - HA dictates thread index due to how it's @@ -3512,11 +3741,12 @@ class TestNAT44EI(MethodHolder): # IP address) and out2in (based on outside port) # first choose a thread index which is correct for IP - thread_index = get_nat44_ei_in2out_worker_index(self.pg0.remote_ip4, - self.vpp_worker_count) + thread_index = get_nat44_ei_in2out_worker_index( + self.pg0.remote_ip4, self.vpp_worker_count + ) # now pick a port which is correct for given thread - port_per_thread = int((0xffff-1024) / max(1, self.vpp_worker_count)) + port_per_thread = int((0xFFFF - 1024) / max(1, self.vpp_worker_count)) self.tcp_port_out = 1024 + random.randint(1, port_per_thread) self.udp_port_out = 1024 + random.randint(1, port_per_thread) if self.vpp_worker_count > 0: @@ -3524,25 +3754,43 @@ class TestNAT44EI(MethodHolder): self.udp_port_out += port_per_thread * (thread_index - 1) # send HA session add events to failover/passive - p = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) / - IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) / - UDP(sport=12346, dport=12345) / - HANATStateSync(sequence_number=1, events=[ - Event(event_type='add', protocol='tcp', - in_addr=self.pg0.remote_ip4, out_addr=self.nat_addr, - in_port=self.tcp_port_in, out_port=self.tcp_port_out, - eh_addr=self.pg1.remote_ip4, - ehn_addr=self.pg1.remote_ip4, - eh_port=self.tcp_external_port, - ehn_port=self.tcp_external_port, fib_index=0), - Event(event_type='add', protocol='udp', - in_addr=self.pg0.remote_ip4, out_addr=self.nat_addr, - in_port=self.udp_port_in, out_port=self.udp_port_out, - eh_addr=self.pg1.remote_ip4, - ehn_addr=self.pg1.remote_ip4, - eh_port=self.udp_external_port, - ehn_port=self.udp_external_port, fib_index=0)], - thread_index=thread_index)) + p = ( + Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) + / IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) + / UDP(sport=12346, dport=12345) + / HANATStateSync( + sequence_number=1, + events=[ + Event( + event_type="add", + protocol="tcp", + in_addr=self.pg0.remote_ip4, + out_addr=self.nat_addr, + in_port=self.tcp_port_in, + out_port=self.tcp_port_out, + eh_addr=self.pg1.remote_ip4, + ehn_addr=self.pg1.remote_ip4, + eh_port=self.tcp_external_port, + ehn_port=self.tcp_external_port, + fib_index=0, + ), + Event( + event_type="add", + protocol="udp", + in_addr=self.pg0.remote_ip4, + out_addr=self.nat_addr, + in_port=self.udp_port_in, + out_port=self.udp_port_out, + eh_addr=self.pg1.remote_ip4, + ehn_addr=self.pg1.remote_ip4, + eh_port=self.udp_external_port, + ehn_port=self.udp_external_port, + fib_index=0, + ), + ], + thread_index=thread_index, + ) + ) self.pg3.add_stream(p) self.pg_enable_capture(self.pg_interfaces) @@ -3557,49 +3805,57 @@ class TestNAT44EI(MethodHolder): raise else: self.assertEqual(hanat.sequence_number, 1) - self.assertEqual(hanat.flags, 'ACK') + self.assertEqual(hanat.flags, "ACK") self.assertEqual(hanat.version, 1) self.assertEqual(hanat.thread_index, thread_index) - stats = self.statistics['/nat44-ei/ha/ack-send'] + stats = self.statistics["/nat44-ei/ha/ack-send"] self.assertEqual(stats[:, 0].sum(), 1) - stats = self.statistics['/nat44-ei/ha/add-event-recv'] + stats = self.statistics["/nat44-ei/ha/add-event-recv"] self.assertEqual(stats[:, 0].sum(), 2) - users = self.statistics['/nat44-ei/total-users'] + users = self.statistics["/nat44-ei/total-users"] self.assertEqual(users[:, 0].sum(), 1) - sessions = self.statistics['/nat44-ei/total-sessions'] + sessions = self.statistics["/nat44-ei/total-sessions"] self.assertEqual(sessions[:, 0].sum(), 2) users = self.vapi.nat44_ei_user_dump() self.assertEqual(len(users), 1) - self.assertEqual(str(users[0].ip_address), - self.pg0.remote_ip4) + self.assertEqual(str(users[0].ip_address), self.pg0.remote_ip4) # there should be 2 sessions created by HA sessions = self.vapi.nat44_ei_user_session_dump( - users[0].ip_address, users[0].vrf_id) + users[0].ip_address, users[0].vrf_id + ) self.assertEqual(len(sessions), 2) for session in sessions: - self.assertEqual(str(session.inside_ip_address), - self.pg0.remote_ip4) - self.assertEqual(str(session.outside_ip_address), - self.nat_addr) - self.assertIn(session.inside_port, - [self.tcp_port_in, self.udp_port_in]) - self.assertIn(session.outside_port, - [self.tcp_port_out, self.udp_port_out]) + self.assertEqual(str(session.inside_ip_address), self.pg0.remote_ip4) + self.assertEqual(str(session.outside_ip_address), self.nat_addr) + self.assertIn(session.inside_port, [self.tcp_port_in, self.udp_port_in]) + self.assertIn(session.outside_port, [self.tcp_port_out, self.udp_port_out]) self.assertIn(session.protocol, [IP_PROTOS.tcp, IP_PROTOS.udp]) # send HA session delete event to failover/passive - p = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) / - IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) / - UDP(sport=12346, dport=12345) / - HANATStateSync(sequence_number=2, events=[ - Event(event_type='del', protocol='udp', - in_addr=self.pg0.remote_ip4, out_addr=self.nat_addr, - in_port=self.udp_port_in, out_port=self.udp_port_out, - eh_addr=self.pg1.remote_ip4, - ehn_addr=self.pg1.remote_ip4, - eh_port=self.udp_external_port, - ehn_port=self.udp_external_port, fib_index=0)], - thread_index=thread_index)) + p = ( + Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) + / IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) + / UDP(sport=12346, dport=12345) + / HANATStateSync( + sequence_number=2, + events=[ + Event( + event_type="del", + protocol="udp", + in_addr=self.pg0.remote_ip4, + out_addr=self.nat_addr, + in_port=self.udp_port_in, + out_port=self.udp_port_out, + eh_addr=self.pg1.remote_ip4, + ehn_addr=self.pg1.remote_ip4, + eh_port=self.udp_external_port, + ehn_port=self.udp_external_port, + fib_index=0, + ) + ], + thread_index=thread_index, + ) + ) self.pg3.add_stream(p) self.pg_enable_capture(self.pg_interfaces) @@ -3614,37 +3870,49 @@ class TestNAT44EI(MethodHolder): raise else: self.assertEqual(hanat.sequence_number, 2) - self.assertEqual(hanat.flags, 'ACK') + self.assertEqual(hanat.flags, "ACK") self.assertEqual(hanat.version, 1) users = self.vapi.nat44_ei_user_dump() self.assertEqual(len(users), 1) - self.assertEqual(str(users[0].ip_address), - self.pg0.remote_ip4) + self.assertEqual(str(users[0].ip_address), self.pg0.remote_ip4) # now we should have only 1 session, 1 deleted by HA - sessions = self.vapi.nat44_ei_user_session_dump(users[0].ip_address, - users[0].vrf_id) + sessions = self.vapi.nat44_ei_user_session_dump( + users[0].ip_address, users[0].vrf_id + ) self.assertEqual(len(sessions), 1) - stats = self.statistics['/nat44-ei/ha/del-event-recv'] + stats = self.statistics["/nat44-ei/ha/del-event-recv"] self.assertEqual(stats[:, 0].sum(), 1) - stats = self.statistics.get_err_counter( - '/err/nat44-ei-ha/pkts-processed') + stats = self.statistics.get_err_counter("/err/nat44-ei-ha/pkts-processed") self.assertEqual(stats, 2) # send HA session refresh event to failover/passive - p = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) / - IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) / - UDP(sport=12346, dport=12345) / - HANATStateSync(sequence_number=3, events=[ - Event(event_type='refresh', protocol='tcp', - in_addr=self.pg0.remote_ip4, out_addr=self.nat_addr, - in_port=self.tcp_port_in, out_port=self.tcp_port_out, - eh_addr=self.pg1.remote_ip4, - ehn_addr=self.pg1.remote_ip4, - eh_port=self.tcp_external_port, - ehn_port=self.tcp_external_port, fib_index=0, - total_bytes=1024, total_pkts=2)], - thread_index=thread_index)) + p = ( + Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) + / IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) + / UDP(sport=12346, dport=12345) + / HANATStateSync( + sequence_number=3, + events=[ + Event( + event_type="refresh", + protocol="tcp", + in_addr=self.pg0.remote_ip4, + out_addr=self.nat_addr, + in_port=self.tcp_port_in, + out_port=self.tcp_port_out, + eh_addr=self.pg1.remote_ip4, + ehn_addr=self.pg1.remote_ip4, + eh_port=self.tcp_external_port, + ehn_port=self.tcp_external_port, + fib_index=0, + total_bytes=1024, + total_pkts=2, + ) + ], + thread_index=thread_index, + ) + ) self.pg3.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -3658,29 +3926,30 @@ class TestNAT44EI(MethodHolder): raise else: self.assertEqual(hanat.sequence_number, 3) - self.assertEqual(hanat.flags, 'ACK') + self.assertEqual(hanat.flags, "ACK") self.assertEqual(hanat.version, 1) users = self.vapi.nat44_ei_user_dump() self.assertEqual(len(users), 1) - self.assertEqual(str(users[0].ip_address), - self.pg0.remote_ip4) + self.assertEqual(str(users[0].ip_address), self.pg0.remote_ip4) sessions = self.vapi.nat44_ei_user_session_dump( - users[0].ip_address, users[0].vrf_id) + users[0].ip_address, users[0].vrf_id + ) self.assertEqual(len(sessions), 1) session = sessions[0] self.assertEqual(session.total_bytes, 1024) self.assertEqual(session.total_pkts, 2) - stats = self.statistics['/nat44-ei/ha/refresh-event-recv'] + stats = self.statistics["/nat44-ei/ha/refresh-event-recv"] self.assertEqual(stats[:, 0].sum(), 1) - stats = self.statistics.get_err_counter( - '/err/nat44-ei-ha/pkts-processed') + stats = self.statistics.get_err_counter("/err/nat44-ei-ha/pkts-processed") self.assertEqual(stats, 3) # send packet to test session created by HA - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - TCP(sport=self.tcp_external_port, dport=self.tcp_port_out)) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / TCP(sport=self.tcp_external_port, dport=self.tcp_port_out) + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -3706,7 +3975,7 @@ class TestNAT44EI(MethodHolder): return self.vapi.nat44_ei_show_fq_options().frame_queue_nelts def test_set_frame_queue_nelts(self): - """ NAT44EI API test - worker handoff frame queue elements """ + """NAT44EI API test - worker handoff frame queue elements""" self.assertEqual(self.reconfigure_frame_queue_nelts(512), 512) def show_commands_at_teardown(self): @@ -3718,11 +3987,10 @@ class TestNAT44EI(MethodHolder): self.logger.info(self.vapi.cli("show nat44 ei sessions detail")) self.logger.info(self.vapi.cli("show nat44 ei hash tables detail")) self.logger.info(self.vapi.cli("show nat44 ei ha")) - self.logger.info( - self.vapi.cli("show nat44 ei addr-port-assignment-alg")) + self.logger.info(self.vapi.cli("show nat44 ei addr-port-assignment-alg")) def test_outside_address_distribution(self): - """ Outside address distribution based on source address """ + """Outside address distribution based on source address""" x = 100 nat_addresses = [] @@ -3733,16 +4001,18 @@ class TestNAT44EI(MethodHolder): flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) self.vapi.nat44_ei_add_del_address_range( first_ip_address=nat_addresses[0], last_ip_address=nat_addresses[-1], - vrf_id=0xFFFFFFFF, is_add=1) + vrf_id=0xFFFFFFFF, + is_add=1, + ) self.pg0.generate_remote_hosts(x) @@ -3750,11 +4020,12 @@ class TestNAT44EI(MethodHolder): for i in range(x): info = self.create_packet_info(self.pg0, self.pg1) payload = self.info_to_payload(info) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_hosts[i].ip4, - dst=self.pg1.remote_ip4) / - UDP(sport=7000+i, dport=8000+i) / - Raw(payload)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_hosts[i].ip4, dst=self.pg1.remote_ip4) + / UDP(sport=7000 + i, dport=8000 + i) + / Raw(payload) + ) info.data = p pkts.append(p) @@ -3772,21 +4043,23 @@ class TestNAT44EI(MethodHolder): packed = socket.inet_aton(p_sent[IP].src) numeric = struct.unpack("!L", packed)[0] numeric = socket.htonl(numeric) - a = nat_addresses[(numeric-1) % len(nat_addresses)] + a = nat_addresses[(numeric - 1) % len(nat_addresses)] self.assertEqual( - a, p_recvd[IP].src, + a, + p_recvd[IP].src, "Invalid packet (src IP %s translated to %s, but expected %s)" - % (p_sent[IP].src, p_recvd[IP].src, a)) + % (p_sent[IP].src, p_recvd[IP].src, a), + ) def test_default_user_sessions(self): - """ NAT44EI default per-user session limit is used and reported """ + """NAT44EI default per-user session limit is used and reported""" nat44_ei_config = self.vapi.nat44_ei_show_running_config() # a nonzero default should be reported for user_sessions self.assertNotEqual(nat44_ei_config.user_sessions, 0) class TestNAT44Out2InDPO(MethodHolder): - """ NAT44EI Test Cases using out2in DPO """ + """NAT44EI Test Cases using out2in DPO""" @classmethod def setUpClass(cls): @@ -3799,8 +4072,8 @@ class TestNAT44Out2InDPO(MethodHolder): cls.udp_port_out = 6304 cls.icmp_id_in = 6305 cls.icmp_id_out = 6305 - cls.nat_addr = '10.0.0.3' - cls.dst_ip4 = '192.168.70.1' + cls.nat_addr = "10.0.0.3" + cls.dst_ip4 = "192.168.70.1" cls.create_pg_interfaces(range(2)) @@ -3812,10 +4085,13 @@ class TestNAT44Out2InDPO(MethodHolder): cls.pg1.config_ip6() cls.pg1.resolve_ndp() - r1 = VppIpRoute(cls, "::", 0, - [VppRoutePath(cls.pg1.remote_ip6, - cls.pg1.sw_if_index)], - register=False) + r1 = VppIpRoute( + cls, + "::", + 0, + [VppRoutePath(cls.pg1.remote_ip6, cls.pg1.sw_if_index)], + register=False, + ) r1.add_vpp_config() def setUp(self): @@ -3830,37 +4106,44 @@ class TestNAT44Out2InDPO(MethodHolder): self.vapi.cli("clear logging") def configure_xlat(self): - self.dst_ip6_pfx = '1:2:3::' - self.dst_ip6_pfx_n = socket.inet_pton(socket.AF_INET6, - self.dst_ip6_pfx) + self.dst_ip6_pfx = "1:2:3::" + self.dst_ip6_pfx_n = socket.inet_pton(socket.AF_INET6, self.dst_ip6_pfx) self.dst_ip6_pfx_len = 96 - self.src_ip6_pfx = '4:5:6::' - self.src_ip6_pfx_n = socket.inet_pton(socket.AF_INET6, - self.src_ip6_pfx) + self.src_ip6_pfx = "4:5:6::" + self.src_ip6_pfx_n = socket.inet_pton(socket.AF_INET6, self.src_ip6_pfx) self.src_ip6_pfx_len = 96 - self.vapi.map_add_domain(self.dst_ip6_pfx_n, self.dst_ip6_pfx_len, - self.src_ip6_pfx_n, self.src_ip6_pfx_len, - '\x00\x00\x00\x00', 0) - - @unittest.skip('Temporary disabled') + self.vapi.map_add_domain( + self.dst_ip6_pfx_n, + self.dst_ip6_pfx_len, + self.src_ip6_pfx_n, + self.src_ip6_pfx_len, + "\x00\x00\x00\x00", + 0, + ) + + @unittest.skip("Temporary disabled") def test_464xlat_ce(self): - """ Test 464XLAT CE with NAT44EI """ + """Test 464XLAT CE with NAT44EI""" self.configure_xlat() flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_add_del_address_range( first_ip_address=self.nat_addr_n, last_ip_address=self.nat_addr_n, - vrf_id=0xFFFFFFFF, is_add=1) + vrf_id=0xFFFFFFFF, + is_add=1, + ) - out_src_ip6 = self.compose_ip6(self.dst_ip4, self.dst_ip6_pfx, - self.dst_ip6_pfx_len) - out_dst_ip6 = self.compose_ip6(self.nat_addr, self.src_ip6_pfx, - self.src_ip6_pfx_len) + out_src_ip6 = self.compose_ip6( + self.dst_ip4, self.dst_ip6_pfx, self.dst_ip6_pfx_len + ) + out_dst_ip6 = self.compose_ip6( + self.nat_addr, self.src_ip6_pfx, self.src_ip6_pfx_len + ) try: pkts = self.create_stream_in(self.pg0, self.pg1, self.dst_ip4) @@ -3868,11 +4151,9 @@ class TestNAT44Out2InDPO(MethodHolder): self.pg_enable_capture(self.pg_interfaces) self.pg_start() capture = self.pg1.get_capture(len(pkts)) - self.verify_capture_out_ip6(capture, nat_ip=out_dst_ip6, - dst_ip=out_src_ip6) + self.verify_capture_out_ip6(capture, nat_ip=out_dst_ip6, dst_ip=out_src_ip6) - pkts = self.create_stream_out_ip6(self.pg1, out_src_ip6, - out_dst_ip6) + pkts = self.create_stream_out_ip6(self.pg1, out_src_ip6, out_dst_ip6) self.pg1.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -3880,31 +4161,35 @@ class TestNAT44Out2InDPO(MethodHolder): self.verify_capture_in(capture, self.pg0) finally: self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags) + sw_if_index=self.pg0.sw_if_index, flags=flags + ) self.vapi.nat44_ei_add_del_address_range( first_ip_address=self.nat_addr_n, last_ip_address=self.nat_addr_n, - vrf_id=0xFFFFFFFF) + vrf_id=0xFFFFFFFF, + ) - @unittest.skip('Temporary disabled') + @unittest.skip("Temporary disabled") def test_464xlat_ce_no_nat(self): - """ Test 464XLAT CE without NAT44EI """ + """Test 464XLAT CE without NAT44EI""" self.configure_xlat() - out_src_ip6 = self.compose_ip6(self.dst_ip4, self.dst_ip6_pfx, - self.dst_ip6_pfx_len) - out_dst_ip6 = self.compose_ip6(self.pg0.remote_ip4, self.src_ip6_pfx, - self.src_ip6_pfx_len) + out_src_ip6 = self.compose_ip6( + self.dst_ip4, self.dst_ip6_pfx, self.dst_ip6_pfx_len + ) + out_dst_ip6 = self.compose_ip6( + self.pg0.remote_ip4, self.src_ip6_pfx, self.src_ip6_pfx_len + ) pkts = self.create_stream_in(self.pg0, self.pg1, self.dst_ip4) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() capture = self.pg1.get_capture(len(pkts)) - self.verify_capture_out_ip6(capture, dst_ip=out_src_ip6, - nat_ip=out_dst_ip6, same_port=True) + self.verify_capture_out_ip6( + capture, dst_ip=out_src_ip6, nat_ip=out_dst_ip6, same_port=True + ) pkts = self.create_stream_out_ip6(self.pg1, out_src_ip6, out_dst_ip6) self.pg1.add_stream(pkts) @@ -3915,7 +4200,8 @@ class TestNAT44Out2InDPO(MethodHolder): class TestNAT44EIMW(MethodHolder): - """ NAT44EI Test Cases (multiple workers) """ + """NAT44EI Test Cases (multiple workers)""" + vpp_worker_count = 2 max_translations = 10240 max_users = 10240 @@ -3931,7 +4217,7 @@ class TestNAT44EIMW(MethodHolder): cls.udp_port_out = 6304 cls.icmp_id_in = 6305 cls.icmp_id_out = 6305 - cls.nat_addr = '10.0.0.3' + cls.nat_addr = "10.0.0.3" cls.ipfix_src_port = 4739 cls.ipfix_domain_id = 1 cls.tcp_external_port = 80 @@ -3952,8 +4238,8 @@ class TestNAT44EIMW(MethodHolder): cls.pg1.configure_ipv4_neighbors() cls.overlapping_interfaces = list(list(cls.pg_interfaces[4:7])) - cls.vapi.ip_table_add_del(is_add=1, table={'table_id': 10}) - cls.vapi.ip_table_add_del(is_add=1, table={'table_id': 20}) + cls.vapi.ip_table_add_del(is_add=1, table={"table_id": 10}) + cls.vapi.ip_table_add_del(is_add=1, table={"table_id": 20}) cls.pg4._local_ip4 = "172.16.255.1" cls.pg4._remote_hosts[0]._ip4 = "172.16.255.2" @@ -3975,8 +4261,8 @@ class TestNAT44EIMW(MethodHolder): cls.pg9.generate_remote_hosts(2) cls.pg9.config_ip4() cls.vapi.sw_interface_add_del_address( - sw_if_index=cls.pg9.sw_if_index, - prefix="10.0.0.1/24") + sw_if_index=cls.pg9.sw_if_index, prefix="10.0.0.1/24" + ) cls.pg9.admin_up() cls.pg9.resolve_arp() @@ -3987,16 +4273,15 @@ class TestNAT44EIMW(MethodHolder): def setUp(self): super(TestNAT44EIMW, self).setUp() self.vapi.nat44_ei_plugin_enable_disable( - sessions=self.max_translations, - users=self.max_users, enable=1) + sessions=self.max_translations, users=self.max_users, enable=1 + ) def tearDown(self): super(TestNAT44EIMW, self).tearDown() if not self.vpp_dead: self.vapi.nat44_ei_ipfix_enable_disable( - domain_id=self.ipfix_domain_id, - src_port=self.ipfix_src_port, - enable=0) + domain_id=self.ipfix_domain_id, src_port=self.ipfix_src_port, enable=0 + ) self.ipfix_src_port = 4739 self.ipfix_domain_id = 1 @@ -4004,7 +4289,7 @@ class TestNAT44EIMW(MethodHolder): self.vapi.cli("clear logging") def test_hairpinning(self): - """ NAT44EI hairpinning - 1:1 NAPT """ + """NAT44EI hairpinning - 1:1 NAPT""" host = self.pg0.remote_hosts[0] server = self.pg0.remote_hosts[1] @@ -4018,22 +4303,28 @@ class TestNAT44EIMW(MethodHolder): self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) # add static mapping for server - self.nat44_add_static_mapping(server.ip4, self.nat_addr, - server_in_port, server_out_port, - proto=IP_PROTOS.tcp) - - cnt = self.statistics['/nat44-ei/hairpinning'] + self.nat44_add_static_mapping( + server.ip4, + self.nat_addr, + server_in_port, + server_out_port, + proto=IP_PROTOS.tcp, + ) + + cnt = self.statistics["/nat44-ei/hairpinning"] # send packet from host to server - p = (Ether(src=host.mac, dst=self.pg0.local_mac) / - IP(src=host.ip4, dst=self.nat_addr) / - TCP(sport=host_in_port, dport=server_out_port)) + p = ( + Ether(src=host.mac, dst=self.pg0.local_mac) + / IP(src=host.ip4, dst=self.nat_addr) + / TCP(sport=host_in_port, dport=server_out_port) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -4052,15 +4343,17 @@ class TestNAT44EIMW(MethodHolder): self.logger.error(ppp("Unexpected or invalid packet:", p)) raise - after = self.statistics['/nat44-ei/hairpinning'] + after = self.statistics["/nat44-ei/hairpinning"] if_idx = self.pg0.sw_if_index self.assertEqual(after[worker_2][if_idx] - cnt[worker_1][if_idx], 1) # send reply from server to host - p = (Ether(src=server.mac, dst=self.pg0.local_mac) / - IP(src=server.ip4, dst=self.nat_addr) / - TCP(sport=server_in_port, dport=host_out_port)) + p = ( + Ether(src=server.mac, dst=self.pg0.local_mac) + / IP(src=server.ip4, dst=self.nat_addr) + / TCP(sport=server_in_port, dport=host_out_port) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -4078,13 +4371,13 @@ class TestNAT44EIMW(MethodHolder): self.logger.error(ppp("Unexpected or invalid packet:", p)) raise - after = self.statistics['/nat44-ei/hairpinning'] + after = self.statistics["/nat44-ei/hairpinning"] if_idx = self.pg0.sw_if_index self.assertEqual(after[worker_1][if_idx] - cnt[worker_1][if_idx], 1) self.assertEqual(after[worker_2][if_idx] - cnt[worker_2][if_idx], 2) def test_hairpinning2(self): - """ NAT44EI hairpinning - 1:1 NAT""" + """NAT44EI hairpinning - 1:1 NAT""" server1_nat_ip = "10.0.0.10" server2_nat_ip = "10.0.0.11" @@ -4097,11 +4390,11 @@ class TestNAT44EIMW(MethodHolder): self.nat44_add_address(self.nat_addr) flags = self.config_flags.NAT44_EI_IF_INSIDE self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg0.sw_if_index, - flags=flags, is_add=1) + sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1 + ) self.vapi.nat44_ei_interface_add_del_feature( - sw_if_index=self.pg1.sw_if_index, - is_add=1) + sw_if_index=self.pg1.sw_if_index, is_add=1 + ) # add static mapping for servers self.nat44_add_static_mapping(server1.ip4, server1_nat_ip) @@ -4109,17 +4402,23 @@ class TestNAT44EIMW(MethodHolder): # host to server1 pkts = [] - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=host.ip4, dst=server1_nat_ip) / - TCP(sport=self.tcp_port_in, dport=server_tcp_port)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=host.ip4, dst=server1_nat_ip) + / TCP(sport=self.tcp_port_in, dport=server_tcp_port) + ) pkts.append(p) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=host.ip4, dst=server1_nat_ip) / - UDP(sport=self.udp_port_in, dport=server_udp_port)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=host.ip4, dst=server1_nat_ip) + / UDP(sport=self.udp_port_in, dport=server_udp_port) + ) pkts.append(p) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=host.ip4, dst=server1_nat_ip) / - ICMP(id=self.icmp_id_in, type='echo-request')) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=host.ip4, dst=server1_nat_ip) + / ICMP(id=self.icmp_id_in, type="echo-request") + ) pkts.append(p) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) @@ -4147,17 +4446,23 @@ class TestNAT44EIMW(MethodHolder): # server1 to host pkts = [] - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=server1.ip4, dst=self.nat_addr) / - TCP(sport=server_tcp_port, dport=self.tcp_port_out)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=server1.ip4, dst=self.nat_addr) + / TCP(sport=server_tcp_port, dport=self.tcp_port_out) + ) pkts.append(p) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=server1.ip4, dst=self.nat_addr) / - UDP(sport=server_udp_port, dport=self.udp_port_out)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=server1.ip4, dst=self.nat_addr) + / UDP(sport=server_udp_port, dport=self.udp_port_out) + ) pkts.append(p) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=server1.ip4, dst=self.nat_addr) / - ICMP(id=self.icmp_id_out, type='echo-reply')) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=server1.ip4, dst=self.nat_addr) + / ICMP(id=self.icmp_id_out, type="echo-reply") + ) pkts.append(p) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) @@ -4182,17 +4487,23 @@ class TestNAT44EIMW(MethodHolder): # server2 to server1 pkts = [] - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=server2.ip4, dst=server1_nat_ip) / - TCP(sport=self.tcp_port_in, dport=server_tcp_port)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=server2.ip4, dst=server1_nat_ip) + / TCP(sport=self.tcp_port_in, dport=server_tcp_port) + ) pkts.append(p) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=server2.ip4, dst=server1_nat_ip) / - UDP(sport=self.udp_port_in, dport=server_udp_port)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=server2.ip4, dst=server1_nat_ip) + / UDP(sport=self.udp_port_in, dport=server_udp_port) + ) pkts.append(p) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=server2.ip4, dst=server1_nat_ip) / - ICMP(id=self.icmp_id_in, type='echo-request')) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=server2.ip4, dst=server1_nat_ip) + / ICMP(id=self.icmp_id_in, type="echo-request") + ) pkts.append(p) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) @@ -4220,17 +4531,23 @@ class TestNAT44EIMW(MethodHolder): # server1 to server2 pkts = [] - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=server1.ip4, dst=server2_nat_ip) / - TCP(sport=server_tcp_port, dport=self.tcp_port_out)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=server1.ip4, dst=server2_nat_ip) + / TCP(sport=server_tcp_port, dport=self.tcp_port_out) + ) pkts.append(p) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=server1.ip4, dst=server2_nat_ip) / - UDP(sport=server_udp_port, dport=self.udp_port_out)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=server1.ip4, dst=server2_nat_ip) + / UDP(sport=server_udp_port, dport=self.udp_port_out) + ) pkts.append(p) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=server1.ip4, dst=server2_nat_ip) / - ICMP(id=self.icmp_id_out, type='echo-reply')) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=server1.ip4, dst=server2_nat_ip) + / ICMP(id=self.icmp_id_out, type="echo-reply") + ) pkts.append(p) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) @@ -4254,5 +4571,5 @@ class TestNAT44EIMW(MethodHolder): raise -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_nat64.py b/test/test_nat64.py index c51adac09de..214072addc9 100644 --- a/test/test_nat64.py +++ b/test/test_nat64.py @@ -16,8 +16,15 @@ from scapy.data import IP_PROTOS from scapy.layers.inet import IP, TCP, UDP, ICMP from scapy.layers.inet import IPerror, TCPerror, UDPerror, ICMPerror from scapy.layers.inet6 import ICMPv6DestUnreach, IPerror6, IPv6ExtHdrFragment -from scapy.layers.inet6 import IPv6, ICMPv6EchoRequest, ICMPv6EchoReply, \ - ICMPv6ND_NS, ICMPv6ND_NA, ICMPv6NDOptDstLLAddr, fragment6 +from scapy.layers.inet6 import ( + IPv6, + ICMPv6EchoRequest, + ICMPv6EchoReply, + ICMPv6ND_NS, + ICMPv6ND_NA, + ICMPv6NDOptDstLLAddr, + fragment6, +) from scapy.layers.l2 import Ether, GRE from scapy.packet import Raw from syslog_rfc5424_parser import SyslogMessage, ParseError @@ -28,7 +35,7 @@ from vpp_papi import VppEnum @tag_fixme_vpp_workers class TestNAT64(VppTestCase): - """ NAT64 Test Cases """ + """NAT64 Test Cases""" @property def SYSLOG_SEVERITY(self): @@ -49,10 +56,10 @@ class TestNAT64(VppTestCase): cls.icmp_id_in = 6305 cls.icmp_id_out = 6305 cls.tcp_external_port = 80 - cls.nat_addr = '10.0.0.3' + cls.nat_addr = "10.0.0.3" cls.nat_addr_n = socket.inet_pton(socket.AF_INET, cls.nat_addr) cls.vrf1_id = 10 - cls.vrf1_nat_addr = '10.0.10.3' + cls.vrf1_nat_addr = "10.0.10.3" cls.ipfix_src_port = 4739 cls.ipfix_domain_id = 1 @@ -61,9 +68,9 @@ class TestNAT64(VppTestCase): cls.ip6_interfaces.append(cls.pg_interfaces[2]) cls.ip4_interfaces = list(cls.pg_interfaces[1:2]) - cls.vapi.ip_table_add_del(is_add=1, - table={'table_id': cls.vrf1_id, - 'is_ip6': 1}) + cls.vapi.ip_table_add_del( + is_add=1, table={"table_id": cls.vrf1_id, "is_ip6": 1} + ) cls.pg_interfaces[2].set_table_ip6(cls.vrf1_id) @@ -94,8 +101,7 @@ class TestNAT64(VppTestCase): def setUp(self): super(TestNAT64, self).setUp() - self.vapi.nat64_plugin_enable_disable(enable=1, - bib_buckets=128, st_buckets=256) + self.vapi.nat64_plugin_enable_disable(enable=1, bib_buckets=128, st_buckets=256) def tearDown(self): super(TestNAT64, self).tearDown() @@ -121,32 +127,37 @@ class TestNAT64(VppTestCase): """ pkts = [] if pref is None: - dst = ''.join(['64:ff9b::', out_if.remote_ip4]) + dst = "".join(["64:ff9b::", out_if.remote_ip4]) else: dst = self.compose_ip6(out_if.remote_ip4, pref, plen) # TCP - p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) / - IPv6(src=in_if.remote_ip6, dst=dst, hlim=hlim) / - TCP(sport=self.tcp_port_in, dport=20)) + p = ( + Ether(dst=in_if.local_mac, src=in_if.remote_mac) + / IPv6(src=in_if.remote_ip6, dst=dst, hlim=hlim) + / TCP(sport=self.tcp_port_in, dport=20) + ) pkts.append(p) # UDP - p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) / - IPv6(src=in_if.remote_ip6, dst=dst, hlim=hlim) / - UDP(sport=self.udp_port_in, dport=20)) + p = ( + Ether(dst=in_if.local_mac, src=in_if.remote_mac) + / IPv6(src=in_if.remote_ip6, dst=dst, hlim=hlim) + / UDP(sport=self.udp_port_in, dport=20) + ) pkts.append(p) # ICMP - p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) / - IPv6(src=in_if.remote_ip6, dst=dst, hlim=hlim) / - ICMPv6EchoRequest(id=self.icmp_id_in)) + p = ( + Ether(dst=in_if.local_mac, src=in_if.remote_mac) + / IPv6(src=in_if.remote_ip6, dst=dst, hlim=hlim) + / ICMPv6EchoRequest(id=self.icmp_id_in) + ) pkts.append(p) return pkts - def create_stream_out(self, out_if, dst_ip=None, ttl=64, - use_inside_ports=False): + def create_stream_out(self, out_if, dst_ip=None, ttl=64, use_inside_ports=False): """ Create packet stream for outside network @@ -168,27 +179,40 @@ class TestNAT64(VppTestCase): icmp_id = self.icmp_id_in pkts = [] # TCP - p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) / - IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) / - TCP(dport=tcp_port, sport=20)) + p = ( + Ether(dst=out_if.local_mac, src=out_if.remote_mac) + / IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) + / TCP(dport=tcp_port, sport=20) + ) pkts.extend([p, p]) # UDP - p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) / - IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) / - UDP(dport=udp_port, sport=20)) + p = ( + Ether(dst=out_if.local_mac, src=out_if.remote_mac) + / IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) + / UDP(dport=udp_port, sport=20) + ) pkts.append(p) # ICMP - p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) / - IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) / - ICMP(id=icmp_id, type='echo-reply')) + p = ( + Ether(dst=out_if.local_mac, src=out_if.remote_mac) + / IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) + / ICMP(id=icmp_id, type="echo-reply") + ) pkts.append(p) return pkts - def verify_capture_out(self, capture, nat_ip=None, same_port=False, - dst_ip=None, is_ip6=False, ignore_port=False): + def verify_capture_out( + self, + capture, + nat_ip=None, + same_port=False, + dst_ip=None, + is_ip6=False, + ignore_port=False, + ): """ Verify captured packets on outside network @@ -216,35 +240,30 @@ class TestNAT64(VppTestCase): if packet.haslayer(TCP): if not ignore_port: if same_port: - self.assertEqual( - packet[TCP].sport, self.tcp_port_in) + self.assertEqual(packet[TCP].sport, self.tcp_port_in) else: - self.assertNotEqual( - packet[TCP].sport, self.tcp_port_in) + self.assertNotEqual(packet[TCP].sport, self.tcp_port_in) self.tcp_port_out = packet[TCP].sport self.assert_packet_checksums_valid(packet) elif packet.haslayer(UDP): if not ignore_port: if same_port: - self.assertEqual( - packet[UDP].sport, self.udp_port_in) + self.assertEqual(packet[UDP].sport, self.udp_port_in) else: - self.assertNotEqual( - packet[UDP].sport, self.udp_port_in) + self.assertNotEqual(packet[UDP].sport, self.udp_port_in) self.udp_port_out = packet[UDP].sport else: if not ignore_port: if same_port: - self.assertEqual( - packet[ICMP46].id, self.icmp_id_in) + self.assertEqual(packet[ICMP46].id, self.icmp_id_in) else: - self.assertNotEqual( - packet[ICMP46].id, self.icmp_id_in) + self.assertNotEqual(packet[ICMP46].id, self.icmp_id_in) self.icmp_id_out = packet[ICMP46].id self.assert_packet_checksums_valid(packet) except: - self.logger.error(ppp("Unexpected or invalid packet " - "(outside network):", packet)) + self.logger.error( + ppp("Unexpected or invalid packet (outside network):", packet) + ) raise def verify_capture_in_ip6(self, capture, src_ip, dst_ip): @@ -265,15 +284,16 @@ class TestNAT64(VppTestCase): elif packet.haslayer(UDP): self.assertEqual(packet[UDP].dport, self.udp_port_in) else: - self.assertEqual(packet[ICMPv6EchoReply].id, - self.icmp_id_in) + self.assertEqual(packet[ICMPv6EchoReply].id, self.icmp_id_in) except: - self.logger.error(ppp("Unexpected or invalid packet " - "(inside network):", packet)) + self.logger.error( + ppp("Unexpected or invalid packet (inside network):", packet) + ) raise - def create_stream_frag(self, src_if, dst, sport, dport, data, - proto=IP_PROTOS.tcp, echo_reply=False): + def create_stream_frag( + self, src_if, dst, sport, dport, data, proto=IP_PROTOS.tcp, echo_reply=False + ): """ Create fragmented packet stream @@ -287,9 +307,11 @@ class TestNAT64(VppTestCase): :returns: Fragments """ if proto == IP_PROTOS.tcp: - p = (IP(src=src_if.remote_ip4, dst=dst) / - TCP(sport=sport, dport=dport) / - Raw(data)) + p = ( + IP(src=src_if.remote_ip4, dst=dst) + / TCP(sport=sport, dport=dport) + / Raw(data) + ) p = p.__class__(scapy.compat.raw(p)) chksum = p[TCP].chksum proto_header = TCP(sport=sport, dport=dport, chksum=chksum) @@ -297,9 +319,9 @@ class TestNAT64(VppTestCase): proto_header = UDP(sport=sport, dport=dport) elif proto == IP_PROTOS.icmp: if not echo_reply: - proto_header = ICMP(id=sport, type='echo-request') + proto_header = ICMP(id=sport, type="echo-request") else: - proto_header = ICMP(id=sport, type='echo-reply') + proto_header = ICMP(id=sport, type="echo-reply") else: raise Exception("Unsupported protocol") id = random.randint(0, 65535) @@ -308,33 +330,38 @@ class TestNAT64(VppTestCase): raw = Raw(data[0:4]) else: raw = Raw(data[0:16]) - p = (Ether(src=src_if.remote_mac, dst=src_if.local_mac) / - IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=0, id=id) / - proto_header / - raw) + p = ( + Ether(src=src_if.remote_mac, dst=src_if.local_mac) + / IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=0, id=id) + / proto_header + / raw + ) pkts.append(p) if proto == IP_PROTOS.tcp: raw = Raw(data[4:20]) else: raw = Raw(data[16:32]) - p = (Ether(src=src_if.remote_mac, dst=src_if.local_mac) / - IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=3, id=id, - proto=proto) / - raw) + p = ( + Ether(src=src_if.remote_mac, dst=src_if.local_mac) + / IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=3, id=id, proto=proto) + / raw + ) pkts.append(p) if proto == IP_PROTOS.tcp: raw = Raw(data[20:]) else: raw = Raw(data[32:]) - p = (Ether(src=src_if.remote_mac, dst=src_if.local_mac) / - IP(src=src_if.remote_ip4, dst=dst, frag=5, proto=proto, - id=id) / - raw) + p = ( + Ether(src=src_if.remote_mac, dst=src_if.local_mac) + / IP(src=src_if.remote_ip4, dst=dst, frag=5, proto=proto, id=id) + / raw + ) pkts.append(p) return pkts - def create_stream_frag_ip6(self, src_if, dst, sport, dport, data, - pref=None, plen=0, frag_size=128): + def create_stream_frag_ip6( + self, src_if, dst, sport, dport, data, pref=None, plen=0, frag_size=128 + ): """ Create fragmented packet stream @@ -349,15 +376,17 @@ class TestNAT64(VppTestCase): :returns: Fragments """ if pref is None: - dst_ip6 = ''.join(['64:ff9b::', dst]) + dst_ip6 = "".join(["64:ff9b::", dst]) else: dst_ip6 = self.compose_ip6(dst, pref, plen) - p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - IPv6(src=src_if.remote_ip6, dst=dst_ip6) / - IPv6ExtHdrFragment(id=random.randint(0, 65535)) / - TCP(sport=sport, dport=dport) / - Raw(data)) + p = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / IPv6(src=src_if.remote_ip6, dst=dst_ip6) + / IPv6ExtHdrFragment(id=random.randint(0, 65535)) + / TCP(sport=sport, dport=dport) + / Raw(data) + ) return fragment6(p, frag_size) @@ -378,17 +407,15 @@ class TestNAT64(VppTestCase): self.assert_ip_checksum_valid(p) buffer.seek(p[IP].frag * 8) buffer.write(bytes(p[IP].payload)) - ip = IP(src=frags[0][IP].src, dst=frags[0][IP].dst, - proto=frags[0][IP].proto) + ip = IP(src=frags[0][IP].src, dst=frags[0][IP].dst, proto=frags[0][IP].proto) if ip.proto == IP_PROTOS.tcp: - p = (ip / TCP(buffer.getvalue())) + p = ip / TCP(buffer.getvalue()) self.logger.debug(ppp("Reassembled:", p)) self.assert_tcp_checksum_valid(p) elif ip.proto == IP_PROTOS.udp: - p = (ip / UDP(buffer.getvalue()[:8]) / - Raw(buffer.getvalue()[8:])) + p = ip / UDP(buffer.getvalue()[:8]) / Raw(buffer.getvalue()[8:]) elif ip.proto == IP_PROTOS.icmp: - p = (ip / ICMP(buffer.getvalue())) + p = ip / ICMP(buffer.getvalue()) return p def reass_frags_and_verify_ip6(self, frags, src, dst): @@ -407,12 +434,15 @@ class TestNAT64(VppTestCase): self.assertEqual(p[IPv6].dst, dst) buffer.seek(p[IPv6ExtHdrFragment].offset * 8) buffer.write(bytes(p[IPv6ExtHdrFragment].payload)) - ip = IPv6(src=frags[0][IPv6].src, dst=frags[0][IPv6].dst, - nh=frags[0][IPv6ExtHdrFragment].nh) + ip = IPv6( + src=frags[0][IPv6].src, + dst=frags[0][IPv6].dst, + nh=frags[0][IPv6ExtHdrFragment].nh, + ) if ip.nh == IP_PROTOS.tcp: - p = (ip / TCP(buffer.getvalue())) + p = ip / TCP(buffer.getvalue()) elif ip.nh == IP_PROTOS.udp: - p = (ip / UDP(buffer.getvalue())) + p = ip / UDP(buffer.getvalue()) self.logger.debug(ppp("Reassembled:", p)) self.assert_packet_checksums_valid(p) return p @@ -461,8 +491,7 @@ class TestNAT64(VppTestCase): # postNAPTSourceTransportPort self.assertEqual(struct.pack("!H", self.tcp_port_out), record[227]) - def verify_ipfix_nat64_ses(self, data, is_create, src_addr, dst_addr, - dst_port): + def verify_ipfix_nat64_ses(self, data, is_create, src_addr, dst_addr, dst_port): """ Verify IPFIX NAT64 session create and delete events @@ -482,16 +511,16 @@ class TestNAT64(VppTestCase): # sourceIPv6Address self.assertEqual(src_addr, str(ipaddress.IPv6Address(record[27]))) # destinationIPv6Address - self.assertEqual(socket.inet_pton(socket.AF_INET6, - self.compose_ip6(dst_addr, - '64:ff9b::', - 96)), - record[28]) + self.assertEqual( + socket.inet_pton( + socket.AF_INET6, self.compose_ip6(dst_addr, "64:ff9b::", 96) + ), + record[28], + ) # postNATSourceIPv4Address self.assertEqual(self.nat_addr_n, record[225]) # postNATDestinationIPv4Address - self.assertEqual(socket.inet_pton(socket.AF_INET, dst_addr), - record[226]) + self.assertEqual(socket.inet_pton(socket.AF_INET, dst_addr), record[226]) # protocolIdentifier self.assertEqual(IP_PROTOS.tcp, scapy.compat.orb(record[4])) # ingressVRFID @@ -506,7 +535,7 @@ class TestNAT64(VppTestCase): self.assertEqual(struct.pack("!H", dst_port), record[228]) def verify_syslog_sess(self, data, is_add=True, is_ip6=False): - message = data.decode('utf-8') + message = data.decode("utf-8") try: message = SyslogMessage.parse(message) except ParseError as e: @@ -514,26 +543,25 @@ class TestNAT64(VppTestCase): raise else: self.assertEqual(message.severity, SyslogSeverity.info) - self.assertEqual(message.appname, 'NAT') - self.assertEqual(message.msgid, 'SADD' if is_add else 'SDEL') - sd_params = message.sd.get('nsess') + self.assertEqual(message.appname, "NAT") + self.assertEqual(message.msgid, "SADD" if is_add else "SDEL") + sd_params = message.sd.get("nsess") self.assertTrue(sd_params is not None) if is_ip6: - self.assertEqual(sd_params.get('IATYP'), 'IPv6') - self.assertEqual(sd_params.get('ISADDR'), self.pg0.remote_ip6) + self.assertEqual(sd_params.get("IATYP"), "IPv6") + self.assertEqual(sd_params.get("ISADDR"), self.pg0.remote_ip6) else: - self.assertEqual(sd_params.get('IATYP'), 'IPv4') - self.assertEqual(sd_params.get('ISADDR'), self.pg0.remote_ip4) - self.assertTrue(sd_params.get('SSUBIX') is not None) - self.assertEqual(sd_params.get('ISPORT'), "%d" % self.tcp_port_in) - self.assertEqual(sd_params.get('XATYP'), 'IPv4') - self.assertEqual(sd_params.get('XSADDR'), self.nat_addr) - self.assertEqual(sd_params.get('XSPORT'), "%d" % self.tcp_port_out) - self.assertEqual(sd_params.get('PROTO'), "%d" % IP_PROTOS.tcp) - self.assertEqual(sd_params.get('SVLAN'), '0') - self.assertEqual(sd_params.get('XDADDR'), self.pg1.remote_ip4) - self.assertEqual(sd_params.get('XDPORT'), - "%d" % self.tcp_external_port) + self.assertEqual(sd_params.get("IATYP"), "IPv4") + self.assertEqual(sd_params.get("ISADDR"), self.pg0.remote_ip4) + self.assertTrue(sd_params.get("SSUBIX") is not None) + self.assertEqual(sd_params.get("ISPORT"), "%d" % self.tcp_port_in) + self.assertEqual(sd_params.get("XATYP"), "IPv4") + self.assertEqual(sd_params.get("XSADDR"), self.nat_addr) + self.assertEqual(sd_params.get("XSPORT"), "%d" % self.tcp_port_out) + self.assertEqual(sd_params.get("PROTO"), "%d" % IP_PROTOS.tcp) + self.assertEqual(sd_params.get("SVLAN"), "0") + self.assertEqual(sd_params.get("XDADDR"), self.pg1.remote_ip4) + self.assertEqual(sd_params.get("XDPORT"), "%d" % self.tcp_external_port) def compose_ip6(self, ip4, pref, plen): """ @@ -576,7 +604,7 @@ class TestNAT64(VppTestCase): pref_n[13] = ip4_n[1] pref_n[14] = ip4_n[2] pref_n[15] = ip4_n[3] - packed_pref_n = b''.join([scapy.compat.chb(x) for x in pref_n]) + packed_pref_n = b"".join([scapy.compat.chb(x) for x in pref_n]) return socket.inet_ntop(socket.AF_INET6, packed_pref_n) def verify_ipfix_max_sessions(self, data, limit): @@ -596,16 +624,19 @@ class TestNAT64(VppTestCase): self.assertEqual(struct.pack("I", limit), record[471]) def test_nat64_inside_interface_handles_neighbor_advertisement(self): - """ NAT64 inside interface handles Neighbor Advertisement """ + """NAT64 inside interface handles Neighbor Advertisement""" flags = self.config_flags.NAT_IS_INSIDE - self.vapi.nat64_add_del_interface(is_add=1, flags=flags, - sw_if_index=self.pg5.sw_if_index) + self.vapi.nat64_add_del_interface( + is_add=1, flags=flags, sw_if_index=self.pg5.sw_if_index + ) # Try to send ping - ping = (Ether(dst=self.pg5.local_mac, src=self.pg5.remote_mac) / - IPv6(src=self.pg5.remote_ip6, dst=self.pg5.local_ip6) / - ICMPv6EchoRequest()) + ping = ( + Ether(dst=self.pg5.local_mac, src=self.pg5.remote_mac) + / IPv6(src=self.pg5.remote_ip6, dst=self.pg5.local_ip6) + / ICMPv6EchoRequest() + ) pkts = [ping] self.pg5.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) @@ -623,10 +654,12 @@ class TestNAT64(VppTestCase): raise # Send Neighbor Advertisement - p = (Ether(dst=self.pg5.local_mac, src=self.pg5.remote_mac) / - IPv6(src=self.pg5.remote_ip6, dst=self.pg5.local_ip6) / - ICMPv6ND_NA(tgt=tgt) / - ICMPv6NDOptDstLLAddr(lladdr=self.pg5.remote_mac)) + p = ( + Ether(dst=self.pg5.local_mac, src=self.pg5.remote_mac) + / IPv6(src=self.pg5.remote_ip6, dst=self.pg5.local_ip6) + / ICMPv6ND_NA(tgt=tgt) + / ICMPv6NDOptDstLLAddr(lladdr=self.pg5.remote_mac) + ) pkts = [p] self.pg5.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) @@ -650,31 +683,33 @@ class TestNAT64(VppTestCase): raise def test_pool(self): - """ Add/delete address to NAT64 pool """ - nat_addr = '1.2.3.4' + """Add/delete address to NAT64 pool""" + nat_addr = "1.2.3.4" - self.vapi.nat64_add_del_pool_addr_range(start_addr=nat_addr, - end_addr=nat_addr, - vrf_id=0xFFFFFFFF, is_add=1) + self.vapi.nat64_add_del_pool_addr_range( + start_addr=nat_addr, end_addr=nat_addr, vrf_id=0xFFFFFFFF, is_add=1 + ) addresses = self.vapi.nat64_pool_addr_dump() self.assertEqual(len(addresses), 1) self.assertEqual(str(addresses[0].address), nat_addr) - self.vapi.nat64_add_del_pool_addr_range(start_addr=nat_addr, - end_addr=nat_addr, - vrf_id=0xFFFFFFFF, is_add=0) + self.vapi.nat64_add_del_pool_addr_range( + start_addr=nat_addr, end_addr=nat_addr, vrf_id=0xFFFFFFFF, is_add=0 + ) addresses = self.vapi.nat64_pool_addr_dump() self.assertEqual(len(addresses), 0) def test_interface(self): - """ Enable/disable NAT64 feature on the interface """ + """Enable/disable NAT64 feature on the interface""" flags = self.config_flags.NAT_IS_INSIDE - self.vapi.nat64_add_del_interface(is_add=1, flags=flags, - sw_if_index=self.pg0.sw_if_index) - self.vapi.nat64_add_del_interface(is_add=1, flags=0, - sw_if_index=self.pg1.sw_if_index) + self.vapi.nat64_add_del_interface( + is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index + ) + self.vapi.nat64_add_del_interface( + is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index + ) interfaces = self.vapi.nat64_interface_dump() self.assertEqual(len(interfaces), 2) @@ -691,29 +726,37 @@ class TestNAT64(VppTestCase): self.assertTrue(pg1_found) features = self.vapi.cli("show interface features pg0") - self.assertIn('nat64-in2out', features) + self.assertIn("nat64-in2out", features) features = self.vapi.cli("show interface features pg1") - self.assertIn('nat64-out2in', features) + self.assertIn("nat64-out2in", features) - self.vapi.nat64_add_del_interface(is_add=0, flags=flags, - sw_if_index=self.pg0.sw_if_index) - self.vapi.nat64_add_del_interface(is_add=0, flags=flags, - sw_if_index=self.pg1.sw_if_index) + self.vapi.nat64_add_del_interface( + is_add=0, flags=flags, sw_if_index=self.pg0.sw_if_index + ) + self.vapi.nat64_add_del_interface( + is_add=0, flags=flags, sw_if_index=self.pg1.sw_if_index + ) interfaces = self.vapi.nat64_interface_dump() self.assertEqual(len(interfaces), 0) def test_static_bib(self): - """ Add/delete static BIB entry """ - in_addr = '2001:db8:85a3::8a2e:370:7334' - out_addr = '10.1.1.3' + """Add/delete static BIB entry""" + in_addr = "2001:db8:85a3::8a2e:370:7334" + out_addr = "10.1.1.3" in_port = 1234 out_port = 5678 proto = IP_PROTOS.tcp - self.vapi.nat64_add_del_static_bib(i_addr=in_addr, o_addr=out_addr, - i_port=in_port, o_port=out_port, - proto=proto, vrf_id=0, is_add=1) + self.vapi.nat64_add_del_static_bib( + i_addr=in_addr, + o_addr=out_addr, + i_port=in_port, + o_port=out_port, + proto=proto, + vrf_id=0, + is_add=1, + ) bib = self.vapi.nat64_bib_dump(proto=IP_PROTOS.tcp) static_bib_num = 0 for bibe in bib: @@ -724,23 +767,29 @@ class TestNAT64(VppTestCase): self.assertEqual(bibe.i_port, in_port) self.assertEqual(bibe.o_port, out_port) self.assertEqual(static_bib_num, 1) - bibs = self.statistics.get_counter('/nat64/total-bibs') + bibs = self.statistics.get_counter("/nat64/total-bibs") self.assertEqual(bibs[0][0], 1) - self.vapi.nat64_add_del_static_bib(i_addr=in_addr, o_addr=out_addr, - i_port=in_port, o_port=out_port, - proto=proto, vrf_id=0, is_add=0) + self.vapi.nat64_add_del_static_bib( + i_addr=in_addr, + o_addr=out_addr, + i_port=in_port, + o_port=out_port, + proto=proto, + vrf_id=0, + is_add=0, + ) bib = self.vapi.nat64_bib_dump(proto=IP_PROTOS.tcp) static_bib_num = 0 for bibe in bib: if bibe.flags & self.config_flags.NAT_IS_STATIC: static_bib_num += 1 self.assertEqual(static_bib_num, 0) - bibs = self.statistics.get_counter('/nat64/total-bibs') + bibs = self.statistics.get_counter("/nat64/total-bibs") self.assertEqual(bibs[0][0], 0) def test_set_timeouts(self): - """ Set NAT64 timeouts """ + """Set NAT64 timeouts""" # verify default values timeouts = self.vapi.nat64_get_timeouts() self.assertEqual(timeouts.udp, 300) @@ -749,8 +798,9 @@ class TestNAT64(VppTestCase): self.assertEqual(timeouts.tcp_established, 7440) # set and verify custom values - self.vapi.nat64_set_timeouts(udp=200, tcp_established=7450, - tcp_transitory=250, icmp=30) + self.vapi.nat64_set_timeouts( + udp=200, tcp_established=7450, tcp_transitory=250, icmp=30 + ) timeouts = self.vapi.nat64_get_timeouts() self.assertEqual(timeouts.udp, 200) self.assertEqual(timeouts.icmp, 30) @@ -758,74 +808,79 @@ class TestNAT64(VppTestCase): self.assertEqual(timeouts.tcp_established, 7450) def test_dynamic(self): - """ NAT64 dynamic translation test """ + """NAT64 dynamic translation test""" self.tcp_port_in = 6303 self.udp_port_in = 6304 self.icmp_id_in = 6305 ses_num_start = self.nat64_get_ses_num() - self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr, - end_addr=self.nat_addr, - vrf_id=0xFFFFFFFF, - is_add=1) + self.vapi.nat64_add_del_pool_addr_range( + start_addr=self.nat_addr, + end_addr=self.nat_addr, + vrf_id=0xFFFFFFFF, + is_add=1, + ) flags = self.config_flags.NAT_IS_INSIDE - self.vapi.nat64_add_del_interface(is_add=1, flags=flags, - sw_if_index=self.pg0.sw_if_index) - self.vapi.nat64_add_del_interface(is_add=1, flags=0, - sw_if_index=self.pg1.sw_if_index) + self.vapi.nat64_add_del_interface( + is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index + ) + self.vapi.nat64_add_del_interface( + is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index + ) # in2out - tcpn = self.statistics.get_counter('/nat64/in2out/tcp')[0] - udpn = self.statistics.get_counter('/nat64/in2out/udp')[0] - icmpn = self.statistics.get_counter('/nat64/in2out/icmp')[0] - drops = self.statistics.get_counter('/nat64/in2out/drops')[0] + tcpn = self.statistics.get_counter("/nat64/in2out/tcp")[0] + udpn = self.statistics.get_counter("/nat64/in2out/udp")[0] + icmpn = self.statistics.get_counter("/nat64/in2out/icmp")[0] + drops = self.statistics.get_counter("/nat64/in2out/drops")[0] pkts = self.create_stream_in_ip6(self.pg0, self.pg1) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() capture = self.pg1.get_capture(len(pkts)) - self.verify_capture_out(capture, nat_ip=self.nat_addr, - dst_ip=self.pg1.remote_ip4) + self.verify_capture_out( + capture, nat_ip=self.nat_addr, dst_ip=self.pg1.remote_ip4 + ) if_idx = self.pg0.sw_if_index - cnt = self.statistics.get_counter('/nat64/in2out/tcp')[0] + cnt = self.statistics.get_counter("/nat64/in2out/tcp")[0] self.assertEqual(cnt[if_idx] - tcpn[if_idx], 1) - cnt = self.statistics.get_counter('/nat64/in2out/udp')[0] + cnt = self.statistics.get_counter("/nat64/in2out/udp")[0] self.assertEqual(cnt[if_idx] - udpn[if_idx], 1) - cnt = self.statistics.get_counter('/nat64/in2out/icmp')[0] + cnt = self.statistics.get_counter("/nat64/in2out/icmp")[0] self.assertEqual(cnt[if_idx] - icmpn[if_idx], 1) - cnt = self.statistics.get_counter('/nat64/in2out/drops')[0] + cnt = self.statistics.get_counter("/nat64/in2out/drops")[0] self.assertEqual(cnt[if_idx] - drops[if_idx], 0) # out2in - tcpn = self.statistics.get_counter('/nat64/out2in/tcp')[0] - udpn = self.statistics.get_counter('/nat64/out2in/udp')[0] - icmpn = self.statistics.get_counter('/nat64/out2in/icmp')[0] - drops = self.statistics.get_counter('/nat64/out2in/drops')[0] + tcpn = self.statistics.get_counter("/nat64/out2in/tcp")[0] + udpn = self.statistics.get_counter("/nat64/out2in/udp")[0] + icmpn = self.statistics.get_counter("/nat64/out2in/icmp")[0] + drops = self.statistics.get_counter("/nat64/out2in/drops")[0] pkts = self.create_stream_out(self.pg1, dst_ip=self.nat_addr) self.pg1.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() capture = self.pg0.get_capture(len(pkts)) - ip = IPv6(src=''.join(['64:ff9b::', self.pg1.remote_ip4])) + ip = IPv6(src="".join(["64:ff9b::", self.pg1.remote_ip4])) self.verify_capture_in_ip6(capture, ip[IPv6].src, self.pg0.remote_ip6) if_idx = self.pg1.sw_if_index - cnt = self.statistics.get_counter('/nat64/out2in/tcp')[0] + cnt = self.statistics.get_counter("/nat64/out2in/tcp")[0] self.assertEqual(cnt[if_idx] - tcpn[if_idx], 2) - cnt = self.statistics.get_counter('/nat64/out2in/udp')[0] + cnt = self.statistics.get_counter("/nat64/out2in/udp")[0] self.assertEqual(cnt[if_idx] - udpn[if_idx], 1) - cnt = self.statistics.get_counter('/nat64/out2in/icmp')[0] + cnt = self.statistics.get_counter("/nat64/out2in/icmp")[0] self.assertEqual(cnt[if_idx] - icmpn[if_idx], 1) - cnt = self.statistics.get_counter('/nat64/out2in/drops')[0] + cnt = self.statistics.get_counter("/nat64/out2in/drops")[0] self.assertEqual(cnt[if_idx] - drops[if_idx], 0) - bibs = self.statistics.get_counter('/nat64/total-bibs') + bibs = self.statistics.get_counter("/nat64/total-bibs") self.assertEqual(bibs[0][0], 3) - sessions = self.statistics.get_counter('/nat64/total-sessions') + sessions = self.statistics.get_counter("/nat64/total-sessions") self.assertEqual(sessions[0][0], 3) # in2out @@ -834,8 +889,9 @@ class TestNAT64(VppTestCase): self.pg_enable_capture(self.pg_interfaces) self.pg_start() capture = self.pg1.get_capture(len(pkts)) - self.verify_capture_out(capture, nat_ip=self.nat_addr, - dst_ip=self.pg1.remote_ip4) + self.verify_capture_out( + capture, nat_ip=self.nat_addr, dst_ip=self.pg1.remote_ip4 + ) # out2in pkts = self.create_stream_out(self.pg1, dst_ip=self.nat_addr) @@ -850,20 +906,25 @@ class TestNAT64(VppTestCase): self.assertEqual(ses_num_end - ses_num_start, 3) # tenant with specific VRF - self.vapi.nat64_add_del_pool_addr_range(start_addr=self.vrf1_nat_addr, - end_addr=self.vrf1_nat_addr, - vrf_id=self.vrf1_id, is_add=1) + self.vapi.nat64_add_del_pool_addr_range( + start_addr=self.vrf1_nat_addr, + end_addr=self.vrf1_nat_addr, + vrf_id=self.vrf1_id, + is_add=1, + ) flags = self.config_flags.NAT_IS_INSIDE - self.vapi.nat64_add_del_interface(is_add=1, flags=flags, - sw_if_index=self.pg2.sw_if_index) + self.vapi.nat64_add_del_interface( + is_add=1, flags=flags, sw_if_index=self.pg2.sw_if_index + ) pkts = self.create_stream_in_ip6(self.pg2, self.pg1) self.pg2.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() capture = self.pg1.get_capture(len(pkts)) - self.verify_capture_out(capture, nat_ip=self.vrf1_nat_addr, - dst_ip=self.pg1.remote_ip4) + self.verify_capture_out( + capture, nat_ip=self.vrf1_nat_addr, dst_ip=self.pg1.remote_ip4 + ) pkts = self.create_stream_out(self.pg1, dst_ip=self.vrf1_nat_addr) self.pg1.add_stream(pkts) @@ -873,7 +934,7 @@ class TestNAT64(VppTestCase): self.verify_capture_in_ip6(capture, ip[IPv6].src, self.pg2.remote_ip6) def test_static(self): - """ NAT64 static translation test """ + """NAT64 static translation test""" self.tcp_port_in = 60303 self.udp_port_in = 60304 self.icmp_id_in = 60305 @@ -883,34 +944,47 @@ class TestNAT64(VppTestCase): ses_num_start = self.nat64_get_ses_num() - self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr, - end_addr=self.nat_addr, - vrf_id=0xFFFFFFFF, - is_add=1) + self.vapi.nat64_add_del_pool_addr_range( + start_addr=self.nat_addr, + end_addr=self.nat_addr, + vrf_id=0xFFFFFFFF, + is_add=1, + ) flags = self.config_flags.NAT_IS_INSIDE - self.vapi.nat64_add_del_interface(is_add=1, flags=flags, - sw_if_index=self.pg0.sw_if_index) - self.vapi.nat64_add_del_interface(is_add=1, flags=0, - sw_if_index=self.pg1.sw_if_index) - - self.vapi.nat64_add_del_static_bib(i_addr=self.pg0.remote_ip6, - o_addr=self.nat_addr, - i_port=self.tcp_port_in, - o_port=self.tcp_port_out, - proto=IP_PROTOS.tcp, vrf_id=0, - is_add=1) - self.vapi.nat64_add_del_static_bib(i_addr=self.pg0.remote_ip6, - o_addr=self.nat_addr, - i_port=self.udp_port_in, - o_port=self.udp_port_out, - proto=IP_PROTOS.udp, vrf_id=0, - is_add=1) - self.vapi.nat64_add_del_static_bib(i_addr=self.pg0.remote_ip6, - o_addr=self.nat_addr, - i_port=self.icmp_id_in, - o_port=self.icmp_id_out, - proto=IP_PROTOS.icmp, vrf_id=0, - is_add=1) + self.vapi.nat64_add_del_interface( + is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index + ) + self.vapi.nat64_add_del_interface( + is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index + ) + + self.vapi.nat64_add_del_static_bib( + i_addr=self.pg0.remote_ip6, + o_addr=self.nat_addr, + i_port=self.tcp_port_in, + o_port=self.tcp_port_out, + proto=IP_PROTOS.tcp, + vrf_id=0, + is_add=1, + ) + self.vapi.nat64_add_del_static_bib( + i_addr=self.pg0.remote_ip6, + o_addr=self.nat_addr, + i_port=self.udp_port_in, + o_port=self.udp_port_out, + proto=IP_PROTOS.udp, + vrf_id=0, + is_add=1, + ) + self.vapi.nat64_add_del_static_bib( + i_addr=self.pg0.remote_ip6, + o_addr=self.nat_addr, + i_port=self.icmp_id_in, + o_port=self.icmp_id_out, + proto=IP_PROTOS.icmp, + vrf_id=0, + is_add=1, + ) # in2out pkts = self.create_stream_in_ip6(self.pg0, self.pg1) @@ -918,8 +992,9 @@ class TestNAT64(VppTestCase): self.pg_enable_capture(self.pg_interfaces) self.pg_start() capture = self.pg1.get_capture(len(pkts)) - self.verify_capture_out(capture, nat_ip=self.nat_addr, - dst_ip=self.pg1.remote_ip4, same_port=True) + self.verify_capture_out( + capture, nat_ip=self.nat_addr, dst_ip=self.pg1.remote_ip4, same_port=True + ) # out2in pkts = self.create_stream_out(self.pg1, dst_ip=self.nat_addr) @@ -927,7 +1002,7 @@ class TestNAT64(VppTestCase): self.pg_enable_capture(self.pg_interfaces) self.pg_start() capture = self.pg0.get_capture(len(pkts)) - ip = IPv6(src=''.join(['64:ff9b::', self.pg1.remote_ip4])) + ip = IPv6(src="".join(["64:ff9b::", self.pg1.remote_ip4])) self.verify_capture_in_ip6(capture, ip[IPv6].src, self.pg0.remote_ip6) ses_num_end = self.nat64_get_ses_num() @@ -935,20 +1010,24 @@ class TestNAT64(VppTestCase): self.assertEqual(ses_num_end - ses_num_start, 3) def test_session_timeout(self): - """ NAT64 session timeout """ + """NAT64 session timeout""" self.icmp_id_in = 1234 - self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr, - end_addr=self.nat_addr, - vrf_id=0xFFFFFFFF, - is_add=1) + self.vapi.nat64_add_del_pool_addr_range( + start_addr=self.nat_addr, + end_addr=self.nat_addr, + vrf_id=0xFFFFFFFF, + is_add=1, + ) flags = self.config_flags.NAT_IS_INSIDE - self.vapi.nat64_add_del_interface(is_add=1, flags=flags, - sw_if_index=self.pg0.sw_if_index) - self.vapi.nat64_add_del_interface(is_add=1, flags=0, - sw_if_index=self.pg1.sw_if_index) - self.vapi.nat64_set_timeouts(udp=300, tcp_established=5, - tcp_transitory=5, - icmp=5) + self.vapi.nat64_add_del_interface( + is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index + ) + self.vapi.nat64_add_del_interface( + is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index + ) + self.vapi.nat64_set_timeouts( + udp=300, tcp_established=5, tcp_transitory=5, icmp=5 + ) pkts = self.create_stream_in_ip6(self.pg0, self.pg1) self.pg0.add_stream(pkts) @@ -965,20 +1044,24 @@ class TestNAT64(VppTestCase): self.assertEqual(ses_num_before_timeout - ses_num_after_timeout, 2) def test_icmp_error(self): - """ NAT64 ICMP Error message translation """ + """NAT64 ICMP Error message translation""" self.tcp_port_in = 6303 self.udp_port_in = 6304 self.icmp_id_in = 6305 - self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr, - end_addr=self.nat_addr, - vrf_id=0xFFFFFFFF, - is_add=1) + self.vapi.nat64_add_del_pool_addr_range( + start_addr=self.nat_addr, + end_addr=self.nat_addr, + vrf_id=0xFFFFFFFF, + is_add=1, + ) flags = self.config_flags.NAT_IS_INSIDE - self.vapi.nat64_add_del_interface(is_add=1, flags=flags, - sw_if_index=self.pg0.sw_if_index) - self.vapi.nat64_add_del_interface(is_add=1, flags=0, - sw_if_index=self.pg1.sw_if_index) + self.vapi.nat64_add_del_interface( + is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index + ) + self.vapi.nat64_add_del_interface( + is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index + ) # send some packets to create sessions pkts = self.create_stream_in_ip6(self.pg0, self.pg1) @@ -986,24 +1069,26 @@ class TestNAT64(VppTestCase): self.pg_enable_capture(self.pg_interfaces) self.pg_start() capture_ip4 = self.pg1.get_capture(len(pkts)) - self.verify_capture_out(capture_ip4, - nat_ip=self.nat_addr, - dst_ip=self.pg1.remote_ip4) + self.verify_capture_out( + capture_ip4, nat_ip=self.nat_addr, dst_ip=self.pg1.remote_ip4 + ) pkts = self.create_stream_out(self.pg1, dst_ip=self.nat_addr) self.pg1.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() capture_ip6 = self.pg0.get_capture(len(pkts)) - ip = IPv6(src=''.join(['64:ff9b::', self.pg1.remote_ip4])) - self.verify_capture_in_ip6(capture_ip6, ip[IPv6].src, - self.pg0.remote_ip6) + ip = IPv6(src="".join(["64:ff9b::", self.pg1.remote_ip4])) + self.verify_capture_in_ip6(capture_ip6, ip[IPv6].src, self.pg0.remote_ip6) # in2out - pkts = [Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst=ip[IPv6].src) / - ICMPv6DestUnreach(code=1) / - packet[IPv6] for packet in capture_ip6] + pkts = [ + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=ip[IPv6].src) + / ICMPv6DestUnreach(code=1) + / packet[IPv6] + for packet in capture_ip6 + ] self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1029,10 +1114,13 @@ class TestNAT64(VppTestCase): raise # out2in - pkts = [Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - ICMP(type=3, code=13) / - packet[IP] for packet in capture_ip4] + pkts = [ + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / ICMP(type=3, code=13) + / packet[IP] + for packet in capture_ip4 + ] self.pg1.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1052,14 +1140,13 @@ class TestNAT64(VppTestCase): elif inner.haslayer(UDPerror): self.assertEqual(inner[UDPerror].sport, self.udp_port_in) else: - self.assertEqual(inner[ICMPv6EchoRequest].id, - self.icmp_id_in) + self.assertEqual(inner[ICMPv6EchoRequest].id, self.icmp_id_in) except: self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise def test_hairpinning(self): - """ NAT64 hairpinning """ + """NAT64 hairpinning""" client = self.pg0.remote_hosts[0] server = self.pg0.remote_hosts[1] @@ -1071,41 +1158,55 @@ class TestNAT64(VppTestCase): client_udp_in_port = 1235 client_tcp_out_port = 0 client_udp_out_port = 0 - ip = IPv6(src=''.join(['64:ff9b::', self.nat_addr])) + ip = IPv6(src="".join(["64:ff9b::", self.nat_addr])) nat_addr_ip6 = ip.src - self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr, - end_addr=self.nat_addr, - vrf_id=0xFFFFFFFF, - is_add=1) + self.vapi.nat64_add_del_pool_addr_range( + start_addr=self.nat_addr, + end_addr=self.nat_addr, + vrf_id=0xFFFFFFFF, + is_add=1, + ) flags = self.config_flags.NAT_IS_INSIDE - self.vapi.nat64_add_del_interface(is_add=1, flags=flags, - sw_if_index=self.pg0.sw_if_index) - self.vapi.nat64_add_del_interface(is_add=1, flags=0, - sw_if_index=self.pg1.sw_if_index) - - self.vapi.nat64_add_del_static_bib(i_addr=server.ip6n, - o_addr=self.nat_addr, - i_port=server_tcp_in_port, - o_port=server_tcp_out_port, - proto=IP_PROTOS.tcp, vrf_id=0, - is_add=1) - self.vapi.nat64_add_del_static_bib(i_addr=server.ip6n, - o_addr=self.nat_addr, - i_port=server_udp_in_port, - o_port=server_udp_out_port, - proto=IP_PROTOS.udp, vrf_id=0, - is_add=1) + self.vapi.nat64_add_del_interface( + is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index + ) + self.vapi.nat64_add_del_interface( + is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index + ) + + self.vapi.nat64_add_del_static_bib( + i_addr=server.ip6n, + o_addr=self.nat_addr, + i_port=server_tcp_in_port, + o_port=server_tcp_out_port, + proto=IP_PROTOS.tcp, + vrf_id=0, + is_add=1, + ) + self.vapi.nat64_add_del_static_bib( + i_addr=server.ip6n, + o_addr=self.nat_addr, + i_port=server_udp_in_port, + o_port=server_udp_out_port, + proto=IP_PROTOS.udp, + vrf_id=0, + is_add=1, + ) # client to server pkts = [] - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src=client.ip6, dst=nat_addr_ip6) / - TCP(sport=client_tcp_in_port, dport=server_tcp_out_port)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=client.ip6, dst=nat_addr_ip6) + / TCP(sport=client_tcp_in_port, dport=server_tcp_out_port) + ) pkts.append(p) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src=client.ip6, dst=nat_addr_ip6) / - UDP(sport=client_udp_in_port, dport=server_udp_out_port)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=client.ip6, dst=nat_addr_ip6) + / UDP(sport=client_udp_in_port, dport=server_udp_out_port) + ) pkts.append(p) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) @@ -1130,13 +1231,17 @@ class TestNAT64(VppTestCase): # server to client pkts = [] - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src=server.ip6, dst=nat_addr_ip6) / - TCP(sport=server_tcp_in_port, dport=client_tcp_out_port)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=server.ip6, dst=nat_addr_ip6) + / TCP(sport=server_tcp_in_port, dport=client_tcp_out_port) + ) pkts.append(p) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src=server.ip6, dst=nat_addr_ip6) / - UDP(sport=server_udp_in_port, dport=client_udp_out_port)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=server.ip6, dst=nat_addr_ip6) + / UDP(sport=server_udp_in_port, dport=client_udp_out_port) + ) pkts.append(p) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) @@ -1159,10 +1264,13 @@ class TestNAT64(VppTestCase): # ICMP error pkts = [] - pkts = [Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src=client.ip6, dst=nat_addr_ip6) / - ICMPv6DestUnreach(code=1) / - packet[IPv6] for packet in capture] + pkts = [ + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=client.ip6, dst=nat_addr_ip6) + / ICMPv6DestUnreach(code=1) + / packet[IPv6] + for packet in capture + ] self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1179,40 +1287,45 @@ class TestNAT64(VppTestCase): self.assert_packet_checksums_valid(packet) if inner.haslayer(TCPerror): self.assertEqual(inner[TCPerror].sport, server_tcp_in_port) - self.assertEqual(inner[TCPerror].dport, - client_tcp_out_port) + self.assertEqual(inner[TCPerror].dport, client_tcp_out_port) else: self.assertEqual(inner[UDPerror].sport, server_udp_in_port) - self.assertEqual(inner[UDPerror].dport, - client_udp_out_port) + self.assertEqual(inner[UDPerror].dport, client_udp_out_port) except: self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise def test_prefix(self): - """ NAT64 Network-Specific Prefix """ + """NAT64 Network-Specific Prefix""" - self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr, - end_addr=self.nat_addr, - vrf_id=0xFFFFFFFF, - is_add=1) + self.vapi.nat64_add_del_pool_addr_range( + start_addr=self.nat_addr, + end_addr=self.nat_addr, + vrf_id=0xFFFFFFFF, + is_add=1, + ) flags = self.config_flags.NAT_IS_INSIDE - self.vapi.nat64_add_del_interface(is_add=1, flags=flags, - sw_if_index=self.pg0.sw_if_index) - self.vapi.nat64_add_del_interface(is_add=1, flags=0, - sw_if_index=self.pg1.sw_if_index) - self.vapi.nat64_add_del_pool_addr_range(start_addr=self.vrf1_nat_addr, - end_addr=self.vrf1_nat_addr, - vrf_id=self.vrf1_id, is_add=1) - self.vapi.nat64_add_del_interface(is_add=1, flags=flags, - sw_if_index=self.pg2.sw_if_index) + self.vapi.nat64_add_del_interface( + is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index + ) + self.vapi.nat64_add_del_interface( + is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index + ) + self.vapi.nat64_add_del_pool_addr_range( + start_addr=self.vrf1_nat_addr, + end_addr=self.vrf1_nat_addr, + vrf_id=self.vrf1_id, + is_add=1, + ) + self.vapi.nat64_add_del_interface( + is_add=1, flags=flags, sw_if_index=self.pg2.sw_if_index + ) # Add global prefix global_pref64 = "2001:db8::" global_pref64_len = 32 global_pref64_str = "{}/{}".format(global_pref64, global_pref64_len) - self.vapi.nat64_add_del_prefix(prefix=global_pref64_str, vrf_id=0, - is_add=1) + self.vapi.nat64_add_del_prefix(prefix=global_pref64_str, vrf_id=0, is_add=1) prefix = self.vapi.nat64_prefix_dump() self.assertEqual(len(prefix), 1) @@ -1223,84 +1336,89 @@ class TestNAT64(VppTestCase): vrf1_pref64 = "2001:db8:122:300::" vrf1_pref64_len = 56 vrf1_pref64_str = "{}/{}".format(vrf1_pref64, vrf1_pref64_len) - self.vapi.nat64_add_del_prefix(prefix=vrf1_pref64_str, - vrf_id=self.vrf1_id, is_add=1) + self.vapi.nat64_add_del_prefix( + prefix=vrf1_pref64_str, vrf_id=self.vrf1_id, is_add=1 + ) prefix = self.vapi.nat64_prefix_dump() self.assertEqual(len(prefix), 2) # Global prefix - pkts = self.create_stream_in_ip6(self.pg0, - self.pg1, - pref=global_pref64, - plen=global_pref64_len) + pkts = self.create_stream_in_ip6( + self.pg0, self.pg1, pref=global_pref64, plen=global_pref64_len + ) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() capture = self.pg1.get_capture(len(pkts)) - self.verify_capture_out(capture, nat_ip=self.nat_addr, - dst_ip=self.pg1.remote_ip4) + self.verify_capture_out( + capture, nat_ip=self.nat_addr, dst_ip=self.pg1.remote_ip4 + ) pkts = self.create_stream_out(self.pg1, dst_ip=self.nat_addr) self.pg1.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() capture = self.pg0.get_capture(len(pkts)) - dst_ip = self.compose_ip6(self.pg1.remote_ip4, - global_pref64, - global_pref64_len) + dst_ip = self.compose_ip6(self.pg1.remote_ip4, global_pref64, global_pref64_len) self.verify_capture_in_ip6(capture, dst_ip, self.pg0.remote_ip6) # Tenant specific prefix - pkts = self.create_stream_in_ip6(self.pg2, - self.pg1, - pref=vrf1_pref64, - plen=vrf1_pref64_len) + pkts = self.create_stream_in_ip6( + self.pg2, self.pg1, pref=vrf1_pref64, plen=vrf1_pref64_len + ) self.pg2.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() capture = self.pg1.get_capture(len(pkts)) - self.verify_capture_out(capture, nat_ip=self.vrf1_nat_addr, - dst_ip=self.pg1.remote_ip4) + self.verify_capture_out( + capture, nat_ip=self.vrf1_nat_addr, dst_ip=self.pg1.remote_ip4 + ) pkts = self.create_stream_out(self.pg1, dst_ip=self.vrf1_nat_addr) self.pg1.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() capture = self.pg2.get_capture(len(pkts)) - dst_ip = self.compose_ip6(self.pg1.remote_ip4, - vrf1_pref64, - vrf1_pref64_len) + dst_ip = self.compose_ip6(self.pg1.remote_ip4, vrf1_pref64, vrf1_pref64_len) self.verify_capture_in_ip6(capture, dst_ip, self.pg2.remote_ip6) def test_unknown_proto(self): - """ NAT64 translate packet with unknown protocol """ + """NAT64 translate packet with unknown protocol""" - self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr, - end_addr=self.nat_addr, - vrf_id=0xFFFFFFFF, - is_add=1) + self.vapi.nat64_add_del_pool_addr_range( + start_addr=self.nat_addr, + end_addr=self.nat_addr, + vrf_id=0xFFFFFFFF, + is_add=1, + ) flags = self.config_flags.NAT_IS_INSIDE - self.vapi.nat64_add_del_interface(is_add=1, flags=flags, - sw_if_index=self.pg0.sw_if_index) - self.vapi.nat64_add_del_interface(is_add=1, flags=0, - sw_if_index=self.pg1.sw_if_index) - remote_ip6 = self.compose_ip6(self.pg1.remote_ip4, '64:ff9b::', 96) + self.vapi.nat64_add_del_interface( + is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index + ) + self.vapi.nat64_add_del_interface( + is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index + ) + remote_ip6 = self.compose_ip6(self.pg1.remote_ip4, "64:ff9b::", 96) # in2out - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst=remote_ip6) / - TCP(sport=self.tcp_port_in, dport=20)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=remote_ip6) + / TCP(sport=self.tcp_port_in, dport=20) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() p = self.pg1.get_capture(1) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst=remote_ip6, nh=47) / - GRE() / - IP(src=self.pg2.local_ip4, dst=self.pg2.remote_ip4) / - TCP(sport=1234, dport=1234)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=remote_ip6, nh=47) + / GRE() + / IP(src=self.pg2.local_ip4, dst=self.pg2.remote_ip4) + / TCP(sport=1234, dport=1234) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1316,11 +1434,13 @@ class TestNAT64(VppTestCase): raise # out2in - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IP(src=self.pg1.remote_ip4, dst=self.nat_addr) / - GRE() / - IP(src=self.pg2.remote_ip4, dst=self.pg2.local_ip4) / - TCP(sport=1234, dport=1234)) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src=self.pg1.remote_ip4, dst=self.nat_addr) + / GRE() + / IP(src=self.pg2.remote_ip4, dst=self.pg2.local_ip4) + / TCP(sport=1234, dport=1234) + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1335,7 +1455,7 @@ class TestNAT64(VppTestCase): raise def test_hairpinning_unknown_proto(self): - """ NAT64 translate packet with unknown protocol - hairpinning """ + """NAT64 translate packet with unknown protocol - hairpinning""" client = self.pg0.remote_hosts[0] server = self.pg0.remote_hosts[1] @@ -1345,53 +1465,71 @@ class TestNAT64(VppTestCase): client_tcp_out_port = 1235 server_nat_ip = "10.0.0.100" client_nat_ip = "10.0.0.110" - server_nat_ip6 = self.compose_ip6(server_nat_ip, '64:ff9b::', 96) - client_nat_ip6 = self.compose_ip6(client_nat_ip, '64:ff9b::', 96) + server_nat_ip6 = self.compose_ip6(server_nat_ip, "64:ff9b::", 96) + client_nat_ip6 = self.compose_ip6(client_nat_ip, "64:ff9b::", 96) - self.vapi.nat64_add_del_pool_addr_range(start_addr=server_nat_ip, - end_addr=client_nat_ip, - vrf_id=0xFFFFFFFF, - is_add=1) + self.vapi.nat64_add_del_pool_addr_range( + start_addr=server_nat_ip, + end_addr=client_nat_ip, + vrf_id=0xFFFFFFFF, + is_add=1, + ) flags = self.config_flags.NAT_IS_INSIDE - self.vapi.nat64_add_del_interface(is_add=1, flags=flags, - sw_if_index=self.pg0.sw_if_index) - self.vapi.nat64_add_del_interface(is_add=1, flags=0, - sw_if_index=self.pg1.sw_if_index) - - self.vapi.nat64_add_del_static_bib(i_addr=server.ip6n, - o_addr=server_nat_ip, - i_port=server_tcp_in_port, - o_port=server_tcp_out_port, - proto=IP_PROTOS.tcp, vrf_id=0, - is_add=1) - - self.vapi.nat64_add_del_static_bib(i_addr=server.ip6n, - o_addr=server_nat_ip, i_port=0, - o_port=0, - proto=IP_PROTOS.gre, vrf_id=0, - is_add=1) - - self.vapi.nat64_add_del_static_bib(i_addr=client.ip6n, - o_addr=client_nat_ip, - i_port=client_tcp_in_port, - o_port=client_tcp_out_port, - proto=IP_PROTOS.tcp, vrf_id=0, - is_add=1) + self.vapi.nat64_add_del_interface( + is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index + ) + self.vapi.nat64_add_del_interface( + is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index + ) + + self.vapi.nat64_add_del_static_bib( + i_addr=server.ip6n, + o_addr=server_nat_ip, + i_port=server_tcp_in_port, + o_port=server_tcp_out_port, + proto=IP_PROTOS.tcp, + vrf_id=0, + is_add=1, + ) + + self.vapi.nat64_add_del_static_bib( + i_addr=server.ip6n, + o_addr=server_nat_ip, + i_port=0, + o_port=0, + proto=IP_PROTOS.gre, + vrf_id=0, + is_add=1, + ) + + self.vapi.nat64_add_del_static_bib( + i_addr=client.ip6n, + o_addr=client_nat_ip, + i_port=client_tcp_in_port, + o_port=client_tcp_out_port, + proto=IP_PROTOS.tcp, + vrf_id=0, + is_add=1, + ) # client to server - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src=client.ip6, dst=server_nat_ip6) / - TCP(sport=client_tcp_in_port, dport=server_tcp_out_port)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=client.ip6, dst=server_nat_ip6) + / TCP(sport=client_tcp_in_port, dport=server_tcp_out_port) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() p = self.pg0.get_capture(1) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src=client.ip6, dst=server_nat_ip6, nh=IP_PROTOS.gre) / - GRE() / - IP(src=self.pg2.local_ip4, dst=self.pg2.remote_ip4) / - TCP(sport=1234, dport=1234)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=client.ip6, dst=server_nat_ip6, nh=IP_PROTOS.gre) + / GRE() + / IP(src=self.pg2.local_ip4, dst=self.pg2.remote_ip4) + / TCP(sport=1234, dport=1234) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1406,11 +1544,13 @@ class TestNAT64(VppTestCase): raise # server to client - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src=server.ip6, dst=client_nat_ip6, nh=IP_PROTOS.gre) / - GRE() / - IP(src=self.pg2.remote_ip4, dst=self.pg2.local_ip4) / - TCP(sport=1234, dport=1234)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=server.ip6, dst=client_nat_ip6, nh=IP_PROTOS.gre) + / GRE() + / IP(src=self.pg2.remote_ip4, dst=self.pg2.local_ip4) + / TCP(sport=1234, dport=1234) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1425,26 +1565,30 @@ class TestNAT64(VppTestCase): raise def test_one_armed_nat64(self): - """ One armed NAT64 """ + """One armed NAT64""" external_port = 0 - remote_host_ip6 = self.compose_ip6(self.pg3.remote_ip4, - '64:ff9b::', - 96) - - self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr, - end_addr=self.nat_addr, - vrf_id=0xFFFFFFFF, - is_add=1) + remote_host_ip6 = self.compose_ip6(self.pg3.remote_ip4, "64:ff9b::", 96) + + self.vapi.nat64_add_del_pool_addr_range( + start_addr=self.nat_addr, + end_addr=self.nat_addr, + vrf_id=0xFFFFFFFF, + is_add=1, + ) flags = self.config_flags.NAT_IS_INSIDE - self.vapi.nat64_add_del_interface(is_add=1, flags=flags, - sw_if_index=self.pg3.sw_if_index) - self.vapi.nat64_add_del_interface(is_add=1, flags=0, - sw_if_index=self.pg3.sw_if_index) + self.vapi.nat64_add_del_interface( + is_add=1, flags=flags, sw_if_index=self.pg3.sw_if_index + ) + self.vapi.nat64_add_del_interface( + is_add=1, flags=0, sw_if_index=self.pg3.sw_if_index + ) # in2out - p = (Ether(src=self.pg3.remote_mac, dst=self.pg3.local_mac) / - IPv6(src=self.pg3.remote_ip6, dst=remote_host_ip6) / - TCP(sport=12345, dport=80)) + p = ( + Ether(src=self.pg3.remote_mac, dst=self.pg3.local_mac) + / IPv6(src=self.pg3.remote_ip6, dst=remote_host_ip6) + / TCP(sport=12345, dport=80) + ) self.pg3.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1464,9 +1608,11 @@ class TestNAT64(VppTestCase): raise # out2in - p = (Ether(src=self.pg3.remote_mac, dst=self.pg3.local_mac) / - IP(src=self.pg3.remote_ip4, dst=self.nat_addr) / - TCP(sport=80, dport=external_port)) + p = ( + Ether(src=self.pg3.remote_mac, dst=self.pg3.local_mac) + / IP(src=self.pg3.remote_ip4, dst=self.nat_addr) + / TCP(sport=80, dport=external_port) + ) self.pg3.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1485,30 +1631,33 @@ class TestNAT64(VppTestCase): raise def test_frag_in_order(self): - """ NAT64 translate fragments arriving in order """ + """NAT64 translate fragments arriving in order""" self.tcp_port_in = random.randint(1025, 65535) - self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr, - end_addr=self.nat_addr, - vrf_id=0xFFFFFFFF, - is_add=1) + self.vapi.nat64_add_del_pool_addr_range( + start_addr=self.nat_addr, + end_addr=self.nat_addr, + vrf_id=0xFFFFFFFF, + is_add=1, + ) flags = self.config_flags.NAT_IS_INSIDE - self.vapi.nat64_add_del_interface(is_add=1, flags=flags, - sw_if_index=self.pg0.sw_if_index) - self.vapi.nat64_add_del_interface(is_add=1, flags=0, - sw_if_index=self.pg1.sw_if_index) + self.vapi.nat64_add_del_interface( + is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index + ) + self.vapi.nat64_add_del_interface( + is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index + ) # in2out - data = b'a' * 200 - pkts = self.create_stream_frag_ip6(self.pg0, self.pg1.remote_ip4, - self.tcp_port_in, 20, data) + data = b"a" * 200 + pkts = self.create_stream_frag_ip6( + self.pg0, self.pg1.remote_ip4, self.tcp_port_in, 20, data + ) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() frags = self.pg1.get_capture(len(pkts)) - p = self.reass_frags_and_verify(frags, - self.nat_addr, - self.pg1.remote_ip4) + p = self.reass_frags_and_verify(frags, self.nat_addr, self.pg1.remote_ip4) self.assertEqual(p[TCP].dport, 20) self.assertNotEqual(p[TCP].sport, self.tcp_port_in) self.tcp_port_out = p[TCP].sport @@ -1516,56 +1665,59 @@ class TestNAT64(VppTestCase): # out2in data = b"A" * 4 + b"b" * 16 + b"C" * 3 - pkts = self.create_stream_frag(self.pg1, - self.nat_addr, - 20, - self.tcp_port_out, - data) + pkts = self.create_stream_frag( + self.pg1, self.nat_addr, 20, self.tcp_port_out, data + ) self.pg1.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() frags = self.pg0.get_capture(len(pkts)) self.logger.debug(ppc("Captured:", frags)) - src = self.compose_ip6(self.pg1.remote_ip4, '64:ff9b::', 96) + src = self.compose_ip6(self.pg1.remote_ip4, "64:ff9b::", 96) p = self.reass_frags_and_verify_ip6(frags, src, self.pg0.remote_ip6) self.assertEqual(p[TCP].sport, 20) self.assertEqual(p[TCP].dport, self.tcp_port_in) self.assertEqual(data, p[Raw].load) def test_reass_hairpinning(self): - """ NAT64 fragments hairpinning """ - data = b'a' * 200 + """NAT64 fragments hairpinning""" + data = b"a" * 200 server = self.pg0.remote_hosts[1] server_in_port = random.randint(1025, 65535) server_out_port = random.randint(1025, 65535) client_in_port = random.randint(1025, 65535) - ip = IPv6(src=''.join(['64:ff9b::', self.nat_addr])) + ip = IPv6(src="".join(["64:ff9b::", self.nat_addr])) nat_addr_ip6 = ip.src - self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr, - end_addr=self.nat_addr, - vrf_id=0xFFFFFFFF, - is_add=1) + self.vapi.nat64_add_del_pool_addr_range( + start_addr=self.nat_addr, + end_addr=self.nat_addr, + vrf_id=0xFFFFFFFF, + is_add=1, + ) flags = self.config_flags.NAT_IS_INSIDE - self.vapi.nat64_add_del_interface(is_add=1, flags=flags, - sw_if_index=self.pg0.sw_if_index) - self.vapi.nat64_add_del_interface(is_add=1, flags=0, - sw_if_index=self.pg1.sw_if_index) + self.vapi.nat64_add_del_interface( + is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index + ) + self.vapi.nat64_add_del_interface( + is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index + ) # add static BIB entry for server - self.vapi.nat64_add_del_static_bib(i_addr=server.ip6n, - o_addr=self.nat_addr, - i_port=server_in_port, - o_port=server_out_port, - proto=IP_PROTOS.tcp, vrf_id=0, - is_add=1) + self.vapi.nat64_add_del_static_bib( + i_addr=server.ip6n, + o_addr=self.nat_addr, + i_port=server_in_port, + o_port=server_out_port, + proto=IP_PROTOS.tcp, + vrf_id=0, + is_add=1, + ) # send packet from host to server - pkts = self.create_stream_frag_ip6(self.pg0, - self.nat_addr, - client_in_port, - server_out_port, - data) + pkts = self.create_stream_frag_ip6( + self.pg0, self.nat_addr, client_in_port, server_out_port, data + ) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1577,31 +1729,34 @@ class TestNAT64(VppTestCase): self.assertEqual(data, p[Raw].load) def test_frag_out_of_order(self): - """ NAT64 translate fragments arriving out of order """ + """NAT64 translate fragments arriving out of order""" self.tcp_port_in = random.randint(1025, 65535) - self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr, - end_addr=self.nat_addr, - vrf_id=0xFFFFFFFF, - is_add=1) + self.vapi.nat64_add_del_pool_addr_range( + start_addr=self.nat_addr, + end_addr=self.nat_addr, + vrf_id=0xFFFFFFFF, + is_add=1, + ) flags = self.config_flags.NAT_IS_INSIDE - self.vapi.nat64_add_del_interface(is_add=1, flags=flags, - sw_if_index=self.pg0.sw_if_index) - self.vapi.nat64_add_del_interface(is_add=1, flags=0, - sw_if_index=self.pg1.sw_if_index) + self.vapi.nat64_add_del_interface( + is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index + ) + self.vapi.nat64_add_del_interface( + is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index + ) # in2out - data = b'a' * 200 - pkts = self.create_stream_frag_ip6(self.pg0, self.pg1.remote_ip4, - self.tcp_port_in, 20, data) + data = b"a" * 200 + pkts = self.create_stream_frag_ip6( + self.pg0, self.pg1.remote_ip4, self.tcp_port_in, 20, data + ) pkts.reverse() self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() frags = self.pg1.get_capture(len(pkts)) - p = self.reass_frags_and_verify(frags, - self.nat_addr, - self.pg1.remote_ip4) + p = self.reass_frags_and_verify(frags, self.nat_addr, self.pg1.remote_ip4) self.assertEqual(p[TCP].dport, 20) self.assertNotEqual(p[TCP].sport, self.tcp_port_in) self.tcp_port_out = p[TCP].sport @@ -1609,27 +1764,25 @@ class TestNAT64(VppTestCase): # out2in data = b"A" * 4 + b"B" * 16 + b"C" * 3 - pkts = self.create_stream_frag(self.pg1, - self.nat_addr, - 20, - self.tcp_port_out, - data) + pkts = self.create_stream_frag( + self.pg1, self.nat_addr, 20, self.tcp_port_out, data + ) pkts.reverse() self.pg1.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() frags = self.pg0.get_capture(len(pkts)) - src = self.compose_ip6(self.pg1.remote_ip4, '64:ff9b::', 96) + src = self.compose_ip6(self.pg1.remote_ip4, "64:ff9b::", 96) p = self.reass_frags_and_verify_ip6(frags, src, self.pg0.remote_ip6) self.assertEqual(p[TCP].sport, 20) self.assertEqual(p[TCP].dport, self.tcp_port_in) self.assertEqual(data, p[Raw].load) def test_interface_addr(self): - """ Acquire NAT64 pool addresses from interface """ + """Acquire NAT64 pool addresses from interface""" self.vapi.nat64_add_del_interface_addr( - is_add=1, - sw_if_index=self.pg4.sw_if_index) + is_add=1, sw_if_index=self.pg4.sw_if_index + ) # no address in NAT64 pool addresses = self.vapi.nat44_address_dump() @@ -1640,8 +1793,7 @@ class TestNAT64(VppTestCase): addresses = self.vapi.nat64_pool_addr_dump() self.assertEqual(len(addresses), 1) - self.assertEqual(str(addresses[0].address), - self.pg4.local_ip4) + self.assertEqual(str(addresses[0].address), self.pg4.local_ip4) # remove interface address and check NAT64 address pool self.pg4.unconfig_ip4() @@ -1650,51 +1802,61 @@ class TestNAT64(VppTestCase): @unittest.skipUnless(config.extended, "part of extended tests") def test_ipfix_max_bibs_sessions(self): - """ IPFIX logging maximum session and BIB entries exceeded """ + """IPFIX logging maximum session and BIB entries exceeded""" max_bibs = 1280 max_sessions = 2560 - remote_host_ip6 = self.compose_ip6(self.pg1.remote_ip4, - '64:ff9b::', - 96) - - self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr, - end_addr=self.nat_addr, - vrf_id=0xFFFFFFFF, - is_add=1) + remote_host_ip6 = self.compose_ip6(self.pg1.remote_ip4, "64:ff9b::", 96) + + self.vapi.nat64_add_del_pool_addr_range( + start_addr=self.nat_addr, + end_addr=self.nat_addr, + vrf_id=0xFFFFFFFF, + is_add=1, + ) flags = self.config_flags.NAT_IS_INSIDE - self.vapi.nat64_add_del_interface(is_add=1, flags=flags, - sw_if_index=self.pg0.sw_if_index) - self.vapi.nat64_add_del_interface(is_add=1, flags=0, - sw_if_index=self.pg1.sw_if_index) + self.vapi.nat64_add_del_interface( + is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index + ) + self.vapi.nat64_add_del_interface( + is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index + ) pkts = [] src = "" for i in range(0, max_bibs): src = "fd01:aa::%x" % (i) - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IPv6(src=src, dst=remote_host_ip6) / - TCP(sport=12345, dport=80)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=src, dst=remote_host_ip6) + / TCP(sport=12345, dport=80) + ) pkts.append(p) - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IPv6(src=src, dst=remote_host_ip6) / - TCP(sport=12345, dport=22)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=src, dst=remote_host_ip6) + / TCP(sport=12345, dport=22) + ) pkts.append(p) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) self.pg_start() self.pg1.get_capture(max_sessions) - self.vapi.set_ipfix_exporter(collector_address=self.pg3.remote_ip4, - src_address=self.pg3.local_ip4, - path_mtu=512, - template_interval=10) - self.vapi.nat_ipfix_enable_disable(domain_id=self.ipfix_domain_id, - src_port=self.ipfix_src_port, - enable=1) - - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IPv6(src=src, dst=remote_host_ip6) / - TCP(sport=12345, dport=25)) + self.vapi.set_ipfix_exporter( + collector_address=self.pg3.remote_ip4, + src_address=self.pg3.local_ip4, + path_mtu=512, + template_interval=10, + ) + self.vapi.nat_ipfix_enable_disable( + domain_id=self.ipfix_domain_id, src_port=self.ipfix_src_port, enable=1 + ) + + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=src, dst=remote_host_ip6) + / TCP(sport=12345, dport=25) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1709,8 +1871,7 @@ class TestNAT64(VppTestCase): self.assertEqual(p[IP].dst, self.pg3.remote_ip4) self.assertEqual(p[UDP].sport, self.ipfix_src_port) self.assertEqual(p[UDP].dport, 4739) - self.assertEqual(p[IPFIX].observationDomainID, - self.ipfix_domain_id) + self.assertEqual(p[IPFIX].observationDomainID, self.ipfix_domain_id) if p.haslayer(Template): ipfix.add_template(p.getlayer(Template)) # verify events in data set @@ -1719,9 +1880,11 @@ class TestNAT64(VppTestCase): data = ipfix.decode_data_set(p.getlayer(Set)) self.verify_ipfix_max_sessions(data, max_sessions) - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IPv6(src=self.pg0.remote_ip6, dst=remote_host_ip6) / - TCP(sport=12345, dport=80)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=self.pg0.remote_ip6, dst=remote_host_ip6) + / TCP(sport=12345, dport=80) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1735,40 +1898,45 @@ class TestNAT64(VppTestCase): self.assertEqual(p[IP].dst, self.pg3.remote_ip4) self.assertEqual(p[UDP].sport, self.ipfix_src_port) self.assertEqual(p[UDP].dport, 4739) - self.assertEqual(p[IPFIX].observationDomainID, - self.ipfix_domain_id) + self.assertEqual(p[IPFIX].observationDomainID, self.ipfix_domain_id) if p.haslayer(Data): data = ipfix.decode_data_set(p.getlayer(Set)) self.verify_ipfix_max_bibs(data, max_bibs) def test_ipfix_bib_ses(self): - """ IPFIX logging NAT64 BIB/session create and delete events """ + """IPFIX logging NAT64 BIB/session create and delete events""" self.tcp_port_in = random.randint(1025, 65535) - remote_host_ip6 = self.compose_ip6(self.pg1.remote_ip4, - '64:ff9b::', - 96) - - self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr, - end_addr=self.nat_addr, - vrf_id=0xFFFFFFFF, - is_add=1) + remote_host_ip6 = self.compose_ip6(self.pg1.remote_ip4, "64:ff9b::", 96) + + self.vapi.nat64_add_del_pool_addr_range( + start_addr=self.nat_addr, + end_addr=self.nat_addr, + vrf_id=0xFFFFFFFF, + is_add=1, + ) flags = self.config_flags.NAT_IS_INSIDE - self.vapi.nat64_add_del_interface(is_add=1, flags=flags, - sw_if_index=self.pg0.sw_if_index) - self.vapi.nat64_add_del_interface(is_add=1, flags=0, - sw_if_index=self.pg1.sw_if_index) - self.vapi.set_ipfix_exporter(collector_address=self.pg3.remote_ip4, - src_address=self.pg3.local_ip4, - path_mtu=512, - template_interval=10) - self.vapi.nat_ipfix_enable_disable(domain_id=self.ipfix_domain_id, - src_port=self.ipfix_src_port, - enable=1) + self.vapi.nat64_add_del_interface( + is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index + ) + self.vapi.nat64_add_del_interface( + is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index + ) + self.vapi.set_ipfix_exporter( + collector_address=self.pg3.remote_ip4, + src_address=self.pg3.local_ip4, + path_mtu=512, + template_interval=10, + ) + self.vapi.nat_ipfix_enable_disable( + domain_id=self.ipfix_domain_id, src_port=self.ipfix_src_port, enable=1 + ) # Create - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IPv6(src=self.pg0.remote_ip6, dst=remote_host_ip6) / - TCP(sport=self.tcp_port_in, dport=25)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=self.pg0.remote_ip6, dst=remote_host_ip6) + / TCP(sport=self.tcp_port_in, dport=25) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1784,8 +1952,7 @@ class TestNAT64(VppTestCase): self.assertEqual(p[IP].dst, self.pg3.remote_ip4) self.assertEqual(p[UDP].sport, self.ipfix_src_port) self.assertEqual(p[UDP].dport, 4739) - self.assertEqual(p[IPFIX].observationDomainID, - self.ipfix_domain_id) + self.assertEqual(p[IPFIX].observationDomainID, self.ipfix_domain_id) if p.haslayer(Template): ipfix.add_template(p.getlayer(Template)) # verify events in data set @@ -1795,20 +1962,20 @@ class TestNAT64(VppTestCase): if scapy.compat.orb(data[0][230]) == 10: self.verify_ipfix_bib(data, 1, self.pg0.remote_ip6) elif scapy.compat.orb(data[0][230]) == 6: - self.verify_ipfix_nat64_ses(data, - 1, - self.pg0.remote_ip6, - self.pg1.remote_ip4, - 25) + self.verify_ipfix_nat64_ses( + data, 1, self.pg0.remote_ip6, self.pg1.remote_ip4, 25 + ) else: self.logger.error(ppp("Unexpected or invalid packet: ", p)) # Delete self.pg_enable_capture(self.pg_interfaces) - self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr, - end_addr=self.nat_addr, - vrf_id=0xFFFFFFFF, - is_add=0) + self.vapi.nat64_add_del_pool_addr_range( + start_addr=self.nat_addr, + end_addr=self.nat_addr, + vrf_id=0xFFFFFFFF, + is_add=0, + ) self.vapi.ipfix_flush() capture = self.pg3.get_capture(2) # verify events in data set @@ -1818,44 +1985,44 @@ class TestNAT64(VppTestCase): self.assertEqual(p[IP].dst, self.pg3.remote_ip4) self.assertEqual(p[UDP].sport, self.ipfix_src_port) self.assertEqual(p[UDP].dport, 4739) - self.assertEqual(p[IPFIX].observationDomainID, - self.ipfix_domain_id) + self.assertEqual(p[IPFIX].observationDomainID, self.ipfix_domain_id) if p.haslayer(Data): data = ipfix.decode_data_set(p.getlayer(Set)) if scapy.compat.orb(data[0][230]) == 11: self.verify_ipfix_bib(data, 0, self.pg0.remote_ip6) elif scapy.compat.orb(data[0][230]) == 7: - self.verify_ipfix_nat64_ses(data, - 0, - self.pg0.remote_ip6, - self.pg1.remote_ip4, - 25) + self.verify_ipfix_nat64_ses( + data, 0, self.pg0.remote_ip6, self.pg1.remote_ip4, 25 + ) else: self.logger.error(ppp("Unexpected or invalid packet: ", p)) def test_syslog_sess(self): - """ Test syslog session creation and deletion """ + """Test syslog session creation and deletion""" self.tcp_port_in = random.randint(1025, 65535) - remote_host_ip6 = self.compose_ip6(self.pg1.remote_ip4, - '64:ff9b::', - 96) - - self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr, - end_addr=self.nat_addr, - vrf_id=0xFFFFFFFF, - is_add=1) + remote_host_ip6 = self.compose_ip6(self.pg1.remote_ip4, "64:ff9b::", 96) + + self.vapi.nat64_add_del_pool_addr_range( + start_addr=self.nat_addr, + end_addr=self.nat_addr, + vrf_id=0xFFFFFFFF, + is_add=1, + ) flags = self.config_flags.NAT_IS_INSIDE - self.vapi.nat64_add_del_interface(is_add=1, flags=flags, - sw_if_index=self.pg0.sw_if_index) - self.vapi.nat64_add_del_interface(is_add=1, flags=0, - sw_if_index=self.pg1.sw_if_index) - self.vapi.syslog_set_filter( - self.SYSLOG_SEVERITY.SYSLOG_API_SEVERITY_INFO) + self.vapi.nat64_add_del_interface( + is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index + ) + self.vapi.nat64_add_del_interface( + is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index + ) + self.vapi.syslog_set_filter(self.SYSLOG_SEVERITY.SYSLOG_API_SEVERITY_INFO) self.vapi.syslog_set_sender(self.pg3.local_ip4, self.pg3.remote_ip4) - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IPv6(src=self.pg0.remote_ip6, dst=remote_host_ip6) / - TCP(sport=self.tcp_port_in, dport=self.tcp_external_port)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=self.pg0.remote_ip6, dst=remote_host_ip6) + / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1866,10 +2033,12 @@ class TestNAT64(VppTestCase): self.pg_enable_capture(self.pg_interfaces) self.pg_start() - self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr, - end_addr=self.nat_addr, - vrf_id=0xFFFFFFFF, - is_add=0) + self.vapi.nat64_add_del_pool_addr_range( + start_addr=self.nat_addr, + end_addr=self.nat_addr, + vrf_id=0xFFFFFFFF, + is_add=0, + ) capture = self.pg3.get_capture(1) self.verify_syslog_sess(capture[0][Raw].load, False, True) @@ -1884,51 +2053,57 @@ class TestNAT64(VppTestCase): """ Clear NAT64 configuration. """ - self.vapi.nat_ipfix_enable_disable(domain_id=self.ipfix_domain_id, - src_port=self.ipfix_src_port, - enable=0) + self.vapi.nat_ipfix_enable_disable( + domain_id=self.ipfix_domain_id, src_port=self.ipfix_src_port, enable=0 + ) self.ipfix_src_port = 4739 self.ipfix_domain_id = 1 - self.vapi.syslog_set_filter( - self.SYSLOG_SEVERITY.SYSLOG_API_SEVERITY_EMERG) + self.vapi.syslog_set_filter(self.SYSLOG_SEVERITY.SYSLOG_API_SEVERITY_EMERG) - self.vapi.nat64_set_timeouts(udp=300, tcp_established=7440, - tcp_transitory=240, icmp=60) + self.vapi.nat64_set_timeouts( + udp=300, tcp_established=7440, tcp_transitory=240, icmp=60 + ) interfaces = self.vapi.nat64_interface_dump() for intf in interfaces: - self.vapi.nat64_add_del_interface(is_add=0, flags=intf.flags, - sw_if_index=intf.sw_if_index) + self.vapi.nat64_add_del_interface( + is_add=0, flags=intf.flags, sw_if_index=intf.sw_if_index + ) bib = self.vapi.nat64_bib_dump(proto=255) for bibe in bib: if bibe.flags & self.config_flags.NAT_IS_STATIC: - self.vapi.nat64_add_del_static_bib(i_addr=bibe.i_addr, - o_addr=bibe.o_addr, - i_port=bibe.i_port, - o_port=bibe.o_port, - proto=bibe.proto, - vrf_id=bibe.vrf_id, - is_add=0) + self.vapi.nat64_add_del_static_bib( + i_addr=bibe.i_addr, + o_addr=bibe.o_addr, + i_port=bibe.i_port, + o_port=bibe.o_port, + proto=bibe.proto, + vrf_id=bibe.vrf_id, + is_add=0, + ) adresses = self.vapi.nat64_pool_addr_dump() for addr in adresses: - self.vapi.nat64_add_del_pool_addr_range(start_addr=addr.address, - end_addr=addr.address, - vrf_id=addr.vrf_id, - is_add=0) + self.vapi.nat64_add_del_pool_addr_range( + start_addr=addr.address, + end_addr=addr.address, + vrf_id=addr.vrf_id, + is_add=0, + ) prefixes = self.vapi.nat64_prefix_dump() for prefix in prefixes: - self.vapi.nat64_add_del_prefix(prefix=str(prefix.prefix), - vrf_id=prefix.vrf_id, is_add=0) + self.vapi.nat64_add_del_prefix( + prefix=str(prefix.prefix), vrf_id=prefix.vrf_id, is_add=0 + ) - bibs = self.statistics.get_counter('/nat64/total-bibs') + bibs = self.statistics.get_counter("/nat64/total-bibs") self.assertEqual(bibs[0][0], 0) - sessions = self.statistics.get_counter('/nat64/total-sessions') + sessions = self.statistics.get_counter("/nat64/total-sessions") self.assertEqual(sessions[0][0], 0) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_nat66.py b/test/test_nat66.py index 02b2882a28b..f3bec78ec5a 100644 --- a/test/test_nat66.py +++ b/test/test_nat66.py @@ -10,15 +10,32 @@ from io import BytesIO import scapy.compat from framework import VppTestCase, VppTestRunner from ipfix import IPFIX, Set, Template, Data, IPFIXDecoder -from scapy.all import bind_layers, Packet, ByteEnumField, ShortField, \ - IPField, IntField, LongField, XByteField, FlagsField, FieldLenField, \ - PacketListField +from scapy.all import ( + bind_layers, + Packet, + ByteEnumField, + ShortField, + IPField, + IntField, + LongField, + XByteField, + FlagsField, + FieldLenField, + PacketListField, +) from scapy.data import IP_PROTOS from scapy.layers.inet import IP, TCP, UDP, ICMP from scapy.layers.inet import IPerror, TCPerror, UDPerror, ICMPerror from scapy.layers.inet6 import ICMPv6DestUnreach, IPerror6, IPv6ExtHdrFragment -from scapy.layers.inet6 import IPv6, ICMPv6EchoRequest, ICMPv6EchoReply, \ - ICMPv6ND_NS, ICMPv6ND_NA, ICMPv6NDOptDstLLAddr, fragment6 +from scapy.layers.inet6 import ( + IPv6, + ICMPv6EchoRequest, + ICMPv6EchoReply, + ICMPv6ND_NS, + ICMPv6ND_NA, + ICMPv6NDOptDstLLAddr, + fragment6, +) from scapy.layers.l2 import Ether, ARP, GRE from scapy.packet import Raw from syslog_rfc5424_parser import SyslogMessage, ParseError @@ -32,13 +49,13 @@ from vpp_papi import VppEnum class TestNAT66(VppTestCase): - """ NAT66 Test Cases """ + """NAT66 Test Cases""" @classmethod def setUpClass(cls): super(TestNAT66, cls).setUpClass() - cls.nat_addr = 'fd01:ff::2' + cls.nat_addr = "fd01:ff::2" cls.create_pg_interfaces(range(2)) cls.interfaces = list(cls.pg_interfaces) @@ -67,34 +84,45 @@ class TestNAT66(VppTestCase): self.plugin_disable() def test_static(self): - """ 1:1 NAT66 test """ + """1:1 NAT66 test""" flags = self.config_flags.NAT_IS_INSIDE - self.vapi.nat66_add_del_interface(is_add=1, flags=flags, - sw_if_index=self.pg0.sw_if_index) - self.vapi.nat66_add_del_interface(is_add=1, - sw_if_index=self.pg1.sw_if_index) + self.vapi.nat66_add_del_interface( + is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index + ) + self.vapi.nat66_add_del_interface(is_add=1, sw_if_index=self.pg1.sw_if_index) self.vapi.nat66_add_del_static_mapping( local_ip_address=self.pg0.remote_ip6, external_ip_address=self.nat_addr, - is_add=1) + is_add=1, + ) # in2out pkts = [] - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6) / - TCP()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6) + / TCP() + ) pkts.append(p) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6) / - UDP()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6) + / UDP() + ) pkts.append(p) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6) / - ICMPv6EchoRequest()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6) + / ICMPv6EchoRequest() + ) pkts.append(p) - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6) / - GRE() / IP() / TCP()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6) + / GRE() + / IP() + / TCP() + ) pkts.append(p) self.pg0.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) @@ -112,21 +140,31 @@ class TestNAT66(VppTestCase): # out2in pkts = [] - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IPv6(src=self.pg1.remote_ip6, dst=self.nat_addr) / - TCP()) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(src=self.pg1.remote_ip6, dst=self.nat_addr) + / TCP() + ) pkts.append(p) - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IPv6(src=self.pg1.remote_ip6, dst=self.nat_addr) / - UDP()) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(src=self.pg1.remote_ip6, dst=self.nat_addr) + / UDP() + ) pkts.append(p) - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IPv6(src=self.pg1.remote_ip6, dst=self.nat_addr) / - ICMPv6EchoReply()) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(src=self.pg1.remote_ip6, dst=self.nat_addr) + / ICMPv6EchoReply() + ) pkts.append(p) - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IPv6(src=self.pg1.remote_ip6, dst=self.nat_addr) / - GRE() / IP() / TCP()) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(src=self.pg1.remote_ip6, dst=self.nat_addr) + / GRE() + / IP() + / TCP() + ) pkts.append(p) self.pg1.add_stream(pkts) self.pg_enable_capture(self.pg_interfaces) @@ -146,21 +184,26 @@ class TestNAT66(VppTestCase): self.assertEqual(sm[0].total_pkts, 8) def test_check_no_translate(self): - """ NAT66 translate only when egress interface is outside interface """ + """NAT66 translate only when egress interface is outside interface""" flags = self.config_flags.NAT_IS_INSIDE - self.vapi.nat66_add_del_interface(is_add=1, flags=flags, - sw_if_index=self.pg0.sw_if_index) - self.vapi.nat66_add_del_interface(is_add=1, flags=flags, - sw_if_index=self.pg1.sw_if_index) + self.vapi.nat66_add_del_interface( + is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index + ) + self.vapi.nat66_add_del_interface( + is_add=1, flags=flags, sw_if_index=self.pg1.sw_if_index + ) self.vapi.nat66_add_del_static_mapping( local_ip_address=self.pg0.remote_ip6, external_ip_address=self.nat_addr, - is_add=1) + is_add=1, + ) # in2out - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6) / - UDP()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6) + / UDP() + ) self.pg0.add_stream([p]) self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -174,5 +217,5 @@ class TestNAT66(VppTestCase): raise -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_neighbor.py b/test/test_neighbor.py index 0cbaf062f12..e1b37a0a124 100644 --- a/test/test_neighbor.py +++ b/test/test_neighbor.py @@ -7,8 +7,15 @@ from socket import AF_INET, AF_INET6, inet_pton from framework import tag_fixme_vpp_workers from framework import VppTestCase, VppTestRunner from vpp_neighbor import VppNeighbor, find_nbr -from vpp_ip_route import VppIpRoute, VppRoutePath, find_route, \ - VppIpTable, DpoProto, FibPathType, VppIpInterfaceAddress +from vpp_ip_route import ( + VppIpRoute, + VppRoutePath, + find_route, + VppIpTable, + DpoProto, + FibPathType, + VppIpInterfaceAddress, +) from vpp_papi import VppEnum from vpp_ip import VppIpPuntRedirect @@ -28,7 +35,7 @@ arp_opts = {"who-has": 1, "is-at": 2} class ARPTestCase(VppTestCase): - """ ARP Test Case """ + """ARP Test Case""" @classmethod def setUpClass(cls): @@ -125,8 +132,7 @@ class ARPTestCase(VppTestCase): self.assertEqual(arp.plen, 4) self.assertEqual(arp.op, arp_opts["is-at"]) self.assertNotEqual(arp.hwsrc, smac) - self.assertTrue("00:00:5e:00:01" in arp.hwsrc or - "00:00:5E:00:01" in arp.hwsrc) + self.assertTrue("00:00:5e:00:01" in arp.hwsrc or "00:00:5E:00:01" in arp.hwsrc) self.assertEqual(arp.hwdst, dmac) self.assertEqual(arp.psrc, sip) self.assertEqual(arp.pdst, dip) @@ -155,7 +161,7 @@ class ARPTestCase(VppTestCase): self.assertEqual(ip.dst, dip) def test_arp(self): - """ ARP """ + """ARP""" # # Generate some hosts on the LAN @@ -168,15 +174,16 @@ class ARPTestCase(VppTestCase): # - all neighbor events on pg1 # - neighbor events for host[1] on pg1 # - self.vapi.want_ip_neighbor_events(enable=1, - pid=os.getpid()) - self.vapi.want_ip_neighbor_events(enable=1, - pid=os.getpid(), - sw_if_index=self.pg1.sw_if_index) - self.vapi.want_ip_neighbor_events(enable=1, - pid=os.getpid(), - sw_if_index=self.pg1.sw_if_index, - ip=self.pg1.remote_hosts[1].ip4) + self.vapi.want_ip_neighbor_events(enable=1, pid=os.getpid()) + self.vapi.want_ip_neighbor_events( + enable=1, pid=os.getpid(), sw_if_index=self.pg1.sw_if_index + ) + self.vapi.want_ip_neighbor_events( + enable=1, + pid=os.getpid(), + sw_if_index=self.pg1.sw_if_index, + ip=self.pg1.remote_hosts[1].ip4, + ) self.logger.info(self.vapi.cli("sh ip neighbor-watcher")) @@ -184,10 +191,12 @@ class ARPTestCase(VppTestCase): # Send IP traffic to one of these unresolved hosts. # expect the generation of an ARP request # - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1._remote_hosts[1].ip4) / - UDP(sport=1234, dport=1234) / - Raw()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1._remote_hosts[1].ip4) + / UDP(sport=1234, dport=1234) + / Raw() + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) @@ -195,38 +204,38 @@ class ARPTestCase(VppTestCase): rx = self.pg1.get_capture(1) - self.verify_arp_req(rx[0], - self.pg1.local_mac, - self.pg1.local_ip4, - self.pg1._remote_hosts[1].ip4) + self.verify_arp_req( + rx[0], self.pg1.local_mac, self.pg1.local_ip4, self.pg1._remote_hosts[1].ip4 + ) # # And a dynamic ARP entry for host 1 # - dyn_arp = VppNeighbor(self, - self.pg1.sw_if_index, - self.pg1.remote_hosts[1].mac, - self.pg1.remote_hosts[1].ip4) + dyn_arp = VppNeighbor( + self, + self.pg1.sw_if_index, + self.pg1.remote_hosts[1].mac, + self.pg1.remote_hosts[1].ip4, + ) dyn_arp.add_vpp_config() self.assertTrue(dyn_arp.query_vpp_config()) self.logger.info(self.vapi.cli("show ip neighbor-watcher")) # this matches all of the listnerers - es = [self.vapi.wait_for_event(1, "ip_neighbor_event") - for i in range(3)] + es = [self.vapi.wait_for_event(1, "ip_neighbor_event") for i in range(3)] for e in es: - self.assertEqual(str(e.neighbor.ip_address), - self.pg1.remote_hosts[1].ip4) + self.assertEqual(str(e.neighbor.ip_address), self.pg1.remote_hosts[1].ip4) # # now we expect IP traffic forwarded # - dyn_p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, - dst=self.pg1._remote_hosts[1].ip4) / - UDP(sport=1234, dport=1234) / - Raw()) + dyn_p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1._remote_hosts[1].ip4) + / UDP(sport=1234, dport=1234) + / Raw() + ) self.pg0.add_stream(dyn_p) self.pg_enable_capture(self.pg_interfaces) @@ -234,32 +243,35 @@ class ARPTestCase(VppTestCase): rx = self.pg1.get_capture(1) - self.verify_ip(rx[0], - self.pg1.local_mac, - self.pg1.remote_hosts[1].mac, - self.pg0.remote_ip4, - self.pg1._remote_hosts[1].ip4) + self.verify_ip( + rx[0], + self.pg1.local_mac, + self.pg1.remote_hosts[1].mac, + self.pg0.remote_ip4, + self.pg1._remote_hosts[1].ip4, + ) # # And a Static ARP entry for host 2 # - static_arp = VppNeighbor(self, - self.pg1.sw_if_index, - self.pg1.remote_hosts[2].mac, - self.pg1.remote_hosts[2].ip4, - is_static=1) + static_arp = VppNeighbor( + self, + self.pg1.sw_if_index, + self.pg1.remote_hosts[2].mac, + self.pg1.remote_hosts[2].ip4, + is_static=1, + ) static_arp.add_vpp_config() - es = [self.vapi.wait_for_event(1, "ip_neighbor_event") - for i in range(2)] + es = [self.vapi.wait_for_event(1, "ip_neighbor_event") for i in range(2)] for e in es: - self.assertEqual(str(e.neighbor.ip_address), - self.pg1.remote_hosts[2].ip4) + self.assertEqual(str(e.neighbor.ip_address), self.pg1.remote_hosts[2].ip4) - static_p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, - dst=self.pg1._remote_hosts[2].ip4) / - UDP(sport=1234, dport=1234) / - Raw()) + static_p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1._remote_hosts[2].ip4) + / UDP(sport=1234, dport=1234) + / Raw() + ) self.pg0.add_stream(static_p) self.pg_enable_capture(self.pg_interfaces) @@ -267,24 +279,27 @@ class ARPTestCase(VppTestCase): rx = self.pg1.get_capture(1) - self.verify_ip(rx[0], - self.pg1.local_mac, - self.pg1.remote_hosts[2].mac, - self.pg0.remote_ip4, - self.pg1._remote_hosts[2].ip4) + self.verify_ip( + rx[0], + self.pg1.local_mac, + self.pg1.remote_hosts[2].mac, + self.pg0.remote_ip4, + self.pg1._remote_hosts[2].ip4, + ) # # remove all the listeners # - self.vapi.want_ip_neighbor_events(enable=0, - pid=os.getpid()) - self.vapi.want_ip_neighbor_events(enable=0, - pid=os.getpid(), - sw_if_index=self.pg1.sw_if_index) - self.vapi.want_ip_neighbor_events(enable=0, - pid=os.getpid(), - sw_if_index=self.pg1.sw_if_index, - ip=self.pg1.remote_hosts[1].ip4) + self.vapi.want_ip_neighbor_events(enable=0, pid=os.getpid()) + self.vapi.want_ip_neighbor_events( + enable=0, pid=os.getpid(), sw_if_index=self.pg1.sw_if_index + ) + self.vapi.want_ip_neighbor_events( + enable=0, + pid=os.getpid(), + sw_if_index=self.pg1.sw_if_index, + ip=self.pg1.remote_hosts[1].ip4, + ) # # flap the link. dynamic ARPs get flush, statics don't @@ -297,69 +312,76 @@ class ARPTestCase(VppTestCase): self.pg_start() rx = self.pg1.get_capture(1) - self.verify_ip(rx[0], - self.pg1.local_mac, - self.pg1.remote_hosts[2].mac, - self.pg0.remote_ip4, - self.pg1._remote_hosts[2].ip4) + self.verify_ip( + rx[0], + self.pg1.local_mac, + self.pg1.remote_hosts[2].mac, + self.pg0.remote_ip4, + self.pg1._remote_hosts[2].ip4, + ) self.pg0.add_stream(dyn_p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() rx = self.pg1.get_capture(1) - self.verify_arp_req(rx[0], - self.pg1.local_mac, - self.pg1.local_ip4, - self.pg1._remote_hosts[1].ip4) + self.verify_arp_req( + rx[0], self.pg1.local_mac, self.pg1.local_ip4, self.pg1._remote_hosts[1].ip4 + ) self.assertFalse(dyn_arp.query_vpp_config()) self.assertTrue(static_arp.query_vpp_config()) # # Send an ARP request from one of the so-far unlearned remote hosts # - p = (Ether(dst="ff:ff:ff:ff:ff:ff", - src=self.pg1._remote_hosts[3].mac) / - ARP(op="who-has", - hwsrc=self.pg1._remote_hosts[3].mac, - pdst=self.pg1.local_ip4, - psrc=self.pg1._remote_hosts[3].ip4)) + p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg1._remote_hosts[3].mac) / ARP( + op="who-has", + hwsrc=self.pg1._remote_hosts[3].mac, + pdst=self.pg1.local_ip4, + psrc=self.pg1._remote_hosts[3].ip4, + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() rx = self.pg1.get_capture(1) - self.verify_arp_resp(rx[0], - self.pg1.local_mac, - self.pg1._remote_hosts[3].mac, - self.pg1.local_ip4, - self.pg1._remote_hosts[3].ip4) + self.verify_arp_resp( + rx[0], + self.pg1.local_mac, + self.pg1._remote_hosts[3].mac, + self.pg1.local_ip4, + self.pg1._remote_hosts[3].ip4, + ) # # VPP should have learned the mapping for the remote host # - self.assertTrue(find_nbr(self, - self.pg1.sw_if_index, - self.pg1._remote_hosts[3].ip4)) + self.assertTrue( + find_nbr(self, self.pg1.sw_if_index, self.pg1._remote_hosts[3].ip4) + ) # # Fire in an ARP request before the interface becomes IP enabled # self.pg2.generate_remote_hosts(4) - p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) / - ARP(op="who-has", - hwsrc=self.pg2.remote_mac, - pdst=self.pg1.local_ip4, - psrc=self.pg2.remote_hosts[3].ip4)) - pt = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) / - Dot1Q(vlan=0) / - ARP(op="who-has", - hwsrc=self.pg2.remote_mac, - pdst=self.pg1.local_ip4, - psrc=self.pg2.remote_hosts[3].ip4)) - self.send_and_assert_no_replies(self.pg2, p, - "interface not IP enabled") + p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) / ARP( + op="who-has", + hwsrc=self.pg2.remote_mac, + pdst=self.pg1.local_ip4, + psrc=self.pg2.remote_hosts[3].ip4, + ) + pt = ( + Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) + / Dot1Q(vlan=0) + / ARP( + op="who-has", + hwsrc=self.pg2.remote_mac, + pdst=self.pg1.local_ip4, + psrc=self.pg2.remote_hosts[3].ip4, + ) + ) + self.send_and_assert_no_replies(self.pg2, p, "interface not IP enabled") # # Make pg2 un-numbered to pg1 @@ -384,12 +406,15 @@ class ARPTestCase(VppTestCase): # once an attached route to the source is known # self.send_and_assert_no_replies( - self.pg2, p, - "ARP req for unnumbered address - no source") - - attached_host = VppIpRoute(self, self.pg2.remote_hosts[3].ip4, 32, - [VppRoutePath("0.0.0.0", - self.pg2.sw_if_index)]) + self.pg2, p, "ARP req for unnumbered address - no source" + ) + + attached_host = VppIpRoute( + self, + self.pg2.remote_hosts[3].ip4, + 32, + [VppRoutePath("0.0.0.0", self.pg2.sw_if_index)], + ) attached_host.add_vpp_config() self.pg2.add_stream(p) @@ -397,57 +422,64 @@ class ARPTestCase(VppTestCase): self.pg_start() rx = self.pg2.get_capture(1) - self.verify_arp_resp(rx[0], - self.pg2.local_mac, - self.pg2.remote_mac, - self.pg1.local_ip4, - self.pg2.remote_hosts[3].ip4) + self.verify_arp_resp( + rx[0], + self.pg2.local_mac, + self.pg2.remote_mac, + self.pg1.local_ip4, + self.pg2.remote_hosts[3].ip4, + ) self.pg2.add_stream(pt) self.pg_enable_capture(self.pg_interfaces) self.pg_start() rx = self.pg2.get_capture(1) - self.verify_arp_resp(rx[0], - self.pg2.local_mac, - self.pg2.remote_mac, - self.pg1.local_ip4, - self.pg2.remote_hosts[3].ip4) + self.verify_arp_resp( + rx[0], + self.pg2.local_mac, + self.pg2.remote_mac, + self.pg1.local_ip4, + self.pg2.remote_hosts[3].ip4, + ) # # A neighbor entry that has no associated FIB-entry # - arp_no_fib = VppNeighbor(self, - self.pg1.sw_if_index, - self.pg1.remote_hosts[4].mac, - self.pg1.remote_hosts[4].ip4, - is_no_fib_entry=1) + arp_no_fib = VppNeighbor( + self, + self.pg1.sw_if_index, + self.pg1.remote_hosts[4].mac, + self.pg1.remote_hosts[4].ip4, + is_no_fib_entry=1, + ) arp_no_fib.add_vpp_config() # # check we have the neighbor, but no route # - self.assertTrue(find_nbr(self, - self.pg1.sw_if_index, - self.pg1._remote_hosts[4].ip4)) - self.assertFalse(find_route(self, - self.pg1._remote_hosts[4].ip4, - 32)) + self.assertTrue( + find_nbr(self, self.pg1.sw_if_index, self.pg1._remote_hosts[4].ip4) + ) + self.assertFalse(find_route(self, self.pg1._remote_hosts[4].ip4, 32)) # # pg2 is unnumbered to pg1, so we can form adjacencies out of pg2 # from within pg1's subnet # - arp_unnum = VppNeighbor(self, - self.pg2.sw_if_index, - self.pg1.remote_hosts[5].mac, - self.pg1.remote_hosts[5].ip4) + arp_unnum = VppNeighbor( + self, + self.pg2.sw_if_index, + self.pg1.remote_hosts[5].mac, + self.pg1.remote_hosts[5].ip4, + ) arp_unnum.add_vpp_config() - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, - dst=self.pg1._remote_hosts[5].ip4) / - UDP(sport=1234, dport=1234) / - Raw()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1._remote_hosts[5].ip4) + / UDP(sport=1234, dport=1234) + / Raw() + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) @@ -455,47 +487,56 @@ class ARPTestCase(VppTestCase): rx = self.pg2.get_capture(1) - self.verify_ip(rx[0], - self.pg2.local_mac, - self.pg1.remote_hosts[5].mac, - self.pg0.remote_ip4, - self.pg1._remote_hosts[5].ip4) + self.verify_ip( + rx[0], + self.pg2.local_mac, + self.pg1.remote_hosts[5].mac, + self.pg0.remote_ip4, + self.pg1._remote_hosts[5].ip4, + ) # # ARP requests from hosts in pg1's subnet sent on pg2 are replied to # with the unnumbered interface's address as the source # - p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) / - ARP(op="who-has", - hwsrc=self.pg2.remote_mac, - pdst=self.pg1.local_ip4, - psrc=self.pg1.remote_hosts[6].ip4)) + p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) / ARP( + op="who-has", + hwsrc=self.pg2.remote_mac, + pdst=self.pg1.local_ip4, + psrc=self.pg1.remote_hosts[6].ip4, + ) self.pg2.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() rx = self.pg2.get_capture(1) - self.verify_arp_resp(rx[0], - self.pg2.local_mac, - self.pg2.remote_mac, - self.pg1.local_ip4, - self.pg1.remote_hosts[6].ip4) + self.verify_arp_resp( + rx[0], + self.pg2.local_mac, + self.pg2.remote_mac, + self.pg1.local_ip4, + self.pg1.remote_hosts[6].ip4, + ) # # An attached host route out of pg2 for an undiscovered hosts generates # an ARP request with the unnumbered address as the source # - att_unnum = VppIpRoute(self, self.pg1.remote_hosts[7].ip4, 32, - [VppRoutePath("0.0.0.0", - self.pg2.sw_if_index)]) + att_unnum = VppIpRoute( + self, + self.pg1.remote_hosts[7].ip4, + 32, + [VppRoutePath("0.0.0.0", self.pg2.sw_if_index)], + ) att_unnum.add_vpp_config() - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, - dst=self.pg1._remote_hosts[7].ip4) / - UDP(sport=1234, dport=1234) / - Raw()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1._remote_hosts[7].ip4) + / UDP(sport=1234, dport=1234) + / Raw() + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) @@ -503,135 +544,158 @@ class ARPTestCase(VppTestCase): rx = self.pg2.get_capture(1) - self.verify_arp_req(rx[0], - self.pg2.local_mac, - self.pg1.local_ip4, - self.pg1._remote_hosts[7].ip4) + self.verify_arp_req( + rx[0], self.pg2.local_mac, self.pg1.local_ip4, self.pg1._remote_hosts[7].ip4 + ) - p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) / - ARP(op="who-has", - hwsrc=self.pg2.remote_mac, - pdst=self.pg1.local_ip4, - psrc=self.pg1.remote_hosts[7].ip4)) + p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) / ARP( + op="who-has", + hwsrc=self.pg2.remote_mac, + pdst=self.pg1.local_ip4, + psrc=self.pg1.remote_hosts[7].ip4, + ) self.pg2.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() rx = self.pg2.get_capture(1) - self.verify_arp_resp(rx[0], - self.pg2.local_mac, - self.pg2.remote_mac, - self.pg1.local_ip4, - self.pg1.remote_hosts[7].ip4) + self.verify_arp_resp( + rx[0], + self.pg2.local_mac, + self.pg2.remote_mac, + self.pg1.local_ip4, + self.pg1.remote_hosts[7].ip4, + ) # # An attached host route as yet unresolved out of pg2 for an # undiscovered host, an ARP requests begets a response. # - att_unnum1 = VppIpRoute(self, self.pg1.remote_hosts[8].ip4, 32, - [VppRoutePath("0.0.0.0", - self.pg2.sw_if_index)]) + att_unnum1 = VppIpRoute( + self, + self.pg1.remote_hosts[8].ip4, + 32, + [VppRoutePath("0.0.0.0", self.pg2.sw_if_index)], + ) att_unnum1.add_vpp_config() - p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) / - ARP(op="who-has", - hwsrc=self.pg2.remote_mac, - pdst=self.pg1.local_ip4, - psrc=self.pg1.remote_hosts[8].ip4)) + p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) / ARP( + op="who-has", + hwsrc=self.pg2.remote_mac, + pdst=self.pg1.local_ip4, + psrc=self.pg1.remote_hosts[8].ip4, + ) self.pg2.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() rx = self.pg2.get_capture(1) - self.verify_arp_resp(rx[0], - self.pg2.local_mac, - self.pg2.remote_mac, - self.pg1.local_ip4, - self.pg1.remote_hosts[8].ip4) + self.verify_arp_resp( + rx[0], + self.pg2.local_mac, + self.pg2.remote_mac, + self.pg1.local_ip4, + self.pg1.remote_hosts[8].ip4, + ) # # Send an ARP request from one of the so-far unlearned remote hosts # with a VLAN0 tag # - p = (Ether(dst="ff:ff:ff:ff:ff:ff", - src=self.pg1._remote_hosts[9].mac) / - Dot1Q(vlan=0) / - ARP(op="who-has", - hwsrc=self.pg1._remote_hosts[9].mac, - pdst=self.pg1.local_ip4, - psrc=self.pg1._remote_hosts[9].ip4)) + p = ( + Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg1._remote_hosts[9].mac) + / Dot1Q(vlan=0) + / ARP( + op="who-has", + hwsrc=self.pg1._remote_hosts[9].mac, + pdst=self.pg1.local_ip4, + psrc=self.pg1._remote_hosts[9].ip4, + ) + ) self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() rx = self.pg1.get_capture(1) - self.verify_arp_resp(rx[0], - self.pg1.local_mac, - self.pg1._remote_hosts[9].mac, - self.pg1.local_ip4, - self.pg1._remote_hosts[9].ip4) + self.verify_arp_resp( + rx[0], + self.pg1.local_mac, + self.pg1._remote_hosts[9].mac, + self.pg1.local_ip4, + self.pg1._remote_hosts[9].ip4, + ) # # Add a hierarchy of routes for a host in the sub-net. # Should still get an ARP resp since the cover is attached # - p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg1.remote_mac) / - ARP(op="who-has", - hwsrc=self.pg1.remote_mac, - pdst=self.pg1.local_ip4, - psrc=self.pg1.remote_hosts[10].ip4)) - - r1 = VppIpRoute(self, self.pg1.remote_hosts[10].ip4, 30, - [VppRoutePath(self.pg1.remote_hosts[10].ip4, - self.pg1.sw_if_index)]) + p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg1.remote_mac) / ARP( + op="who-has", + hwsrc=self.pg1.remote_mac, + pdst=self.pg1.local_ip4, + psrc=self.pg1.remote_hosts[10].ip4, + ) + + r1 = VppIpRoute( + self, + self.pg1.remote_hosts[10].ip4, + 30, + [VppRoutePath(self.pg1.remote_hosts[10].ip4, self.pg1.sw_if_index)], + ) r1.add_vpp_config() self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() rx = self.pg1.get_capture(1) - self.verify_arp_resp(rx[0], - self.pg1.local_mac, - self.pg1.remote_mac, - self.pg1.local_ip4, - self.pg1.remote_hosts[10].ip4) - - r2 = VppIpRoute(self, self.pg1.remote_hosts[10].ip4, 32, - [VppRoutePath(self.pg1.remote_hosts[10].ip4, - self.pg1.sw_if_index)]) + self.verify_arp_resp( + rx[0], + self.pg1.local_mac, + self.pg1.remote_mac, + self.pg1.local_ip4, + self.pg1.remote_hosts[10].ip4, + ) + + r2 = VppIpRoute( + self, + self.pg1.remote_hosts[10].ip4, + 32, + [VppRoutePath(self.pg1.remote_hosts[10].ip4, self.pg1.sw_if_index)], + ) r2.add_vpp_config() self.pg1.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() rx = self.pg1.get_capture(1) - self.verify_arp_resp(rx[0], - self.pg1.local_mac, - self.pg1.remote_mac, - self.pg1.local_ip4, - self.pg1.remote_hosts[10].ip4) + self.verify_arp_resp( + rx[0], + self.pg1.local_mac, + self.pg1.remote_mac, + self.pg1.local_ip4, + self.pg1.remote_hosts[10].ip4, + ) # # add an ARP entry that's not on the sub-net and so whose # adj-fib fails the refinement check. then send an ARP request # from that source # - a1 = VppNeighbor(self, - self.pg0.sw_if_index, - self.pg0.remote_mac, - "100.100.100.50") + a1 = VppNeighbor( + self, self.pg0.sw_if_index, self.pg0.remote_mac, "100.100.100.50" + ) a1.add_vpp_config() - p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / - ARP(op="who-has", - hwsrc=self.pg0.remote_mac, - psrc="100.100.100.50", - pdst=self.pg0.remote_ip4)) - self.send_and_assert_no_replies(self.pg0, p, - "ARP req for from failed adj-fib") + p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / ARP( + op="who-has", + hwsrc=self.pg0.remote_mac, + psrc="100.100.100.50", + pdst=self.pg0.remote_ip4, + ) + self.send_and_assert_no_replies(self.pg0, p, "ARP req for from failed adj-fib") # # ERROR Cases @@ -640,101 +704,103 @@ class ARPTestCase(VppTestCase): # 1b - nor within the unnumbered subnet # 1c - nor within the subnet of a different interface # - p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / - ARP(op="who-has", - hwsrc=self.pg0.remote_mac, - pdst="10.10.10.3", - psrc=self.pg0.remote_ip4)) - self.send_and_assert_no_replies(self.pg0, p, - "ARP req for non-local destination") - self.assertFalse(find_nbr(self, - self.pg0.sw_if_index, - "10.10.10.3")) - - p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) / - ARP(op="who-has", - hwsrc=self.pg2.remote_mac, - pdst="10.10.10.3", - psrc=self.pg1.remote_hosts[7].ip4)) + p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / ARP( + op="who-has", + hwsrc=self.pg0.remote_mac, + pdst="10.10.10.3", + psrc=self.pg0.remote_ip4, + ) + self.send_and_assert_no_replies( + self.pg0, p, "ARP req for non-local destination" + ) + self.assertFalse(find_nbr(self, self.pg0.sw_if_index, "10.10.10.3")) + + p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) / ARP( + op="who-has", + hwsrc=self.pg2.remote_mac, + pdst="10.10.10.3", + psrc=self.pg1.remote_hosts[7].ip4, + ) self.send_and_assert_no_replies( - self.pg0, p, - "ARP req for non-local destination - unnum") + self.pg0, p, "ARP req for non-local destination - unnum" + ) - p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / - ARP(op="who-has", - hwsrc=self.pg0.remote_mac, - pdst=self.pg1.local_ip4, - psrc=self.pg1.remote_ip4)) - self.send_and_assert_no_replies(self.pg0, p, - "ARP req diff sub-net") - self.assertFalse(find_nbr(self, - self.pg0.sw_if_index, - self.pg1.remote_ip4)) + p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / ARP( + op="who-has", + hwsrc=self.pg0.remote_mac, + pdst=self.pg1.local_ip4, + psrc=self.pg1.remote_ip4, + ) + self.send_and_assert_no_replies(self.pg0, p, "ARP req diff sub-net") + self.assertFalse(find_nbr(self, self.pg0.sw_if_index, self.pg1.remote_ip4)) # # 2 - don't respond to ARP request from an address not within the # interface's sub-net # 2b - to a proxied address # 2c - not within a different interface's sub-net - p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / - ARP(op="who-has", - hwsrc=self.pg0.remote_mac, - psrc="10.10.10.3", - pdst=self.pg0.local_ip4)) - self.send_and_assert_no_replies(self.pg0, p, - "ARP req for non-local source") - p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) / - ARP(op="who-has", - hwsrc=self.pg2.remote_mac, - psrc="10.10.10.3", - pdst=self.pg0.local_ip4)) + p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / ARP( + op="who-has", + hwsrc=self.pg0.remote_mac, + psrc="10.10.10.3", + pdst=self.pg0.local_ip4, + ) + self.send_and_assert_no_replies(self.pg0, p, "ARP req for non-local source") + p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) / ARP( + op="who-has", + hwsrc=self.pg2.remote_mac, + psrc="10.10.10.3", + pdst=self.pg0.local_ip4, + ) self.send_and_assert_no_replies( - self.pg0, p, - "ARP req for non-local source - unnum") - p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / - ARP(op="who-has", - hwsrc=self.pg0.remote_mac, - psrc=self.pg1.remote_ip4, - pdst=self.pg0.local_ip4)) - self.send_and_assert_no_replies(self.pg0, p, - "ARP req for non-local source 2c") + self.pg0, p, "ARP req for non-local source - unnum" + ) + p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / ARP( + op="who-has", + hwsrc=self.pg0.remote_mac, + psrc=self.pg1.remote_ip4, + pdst=self.pg0.local_ip4, + ) + self.send_and_assert_no_replies(self.pg0, p, "ARP req for non-local source 2c") # # 3 - don't respond to ARP request from an address that belongs to # the router # - p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / - ARP(op="who-has", - hwsrc=self.pg0.remote_mac, - psrc=self.pg0.local_ip4, - pdst=self.pg0.local_ip4)) - self.send_and_assert_no_replies(self.pg0, p, - "ARP req for non-local source") + p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / ARP( + op="who-has", + hwsrc=self.pg0.remote_mac, + psrc=self.pg0.local_ip4, + pdst=self.pg0.local_ip4, + ) + self.send_and_assert_no_replies(self.pg0, p, "ARP req for non-local source") # # 4 - don't respond to ARP requests that has mac source different # from ARP request HW source # - p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / - ARP(op="who-has", - hwsrc="00:00:00:DE:AD:BE", - psrc=self.pg0.remote_ip4, - pdst=self.pg0.local_ip4)) - self.send_and_assert_no_replies(self.pg0, p, - "ARP req for non-local source") + p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / ARP( + op="who-has", + hwsrc="00:00:00:DE:AD:BE", + psrc=self.pg0.remote_ip4, + pdst=self.pg0.local_ip4, + ) + self.send_and_assert_no_replies(self.pg0, p, "ARP req for non-local source") # # 5 - don't respond to ARP requests for address within the # interface's sub-net but not the interface's address # self.pg0.generate_remote_hosts(2) - p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / - ARP(op="who-has", - hwsrc=self.pg0.remote_mac, - psrc=self.pg0.remote_hosts[0].ip4, - pdst=self.pg0.remote_hosts[1].ip4)) - self.send_and_assert_no_replies(self.pg0, p, - "ARP req for non-local destination") + p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / ARP( + op="who-has", + hwsrc=self.pg0.remote_mac, + psrc=self.pg0.remote_hosts[0].ip4, + pdst=self.pg0.remote_hosts[1].ip4, + ) + self.send_and_assert_no_replies( + self.pg0, p, "ARP req for non-local destination" + ) # # cleanup @@ -748,7 +814,7 @@ class ARPTestCase(VppTestCase): self.pg1.admin_down() def test_proxy_mirror_arp(self): - """ Interface Mirror Proxy ARP """ + """Interface Mirror Proxy ARP""" # # When VPP has an interface whose address is also applied to a TAP @@ -759,20 +825,24 @@ class ARPTestCase(VppTestCase): # self.pg0.generate_remote_hosts(2) - arp_req_from_me = (Ether(src=self.pg2.remote_mac, - dst="ff:ff:ff:ff:ff:ff") / - ARP(op="who-has", - hwsrc=self.pg2.remote_mac, - pdst=self.pg0.remote_hosts[1].ip4, - psrc=self.pg0.local_ip4)) + arp_req_from_me = Ether(src=self.pg2.remote_mac, dst="ff:ff:ff:ff:ff:ff") / ARP( + op="who-has", + hwsrc=self.pg2.remote_mac, + pdst=self.pg0.remote_hosts[1].ip4, + psrc=self.pg0.local_ip4, + ) # # Configure Proxy ARP for the subnet on PG0addresses on pg0 # - self.vapi.proxy_arp_add_del(proxy={'table_id': 0, - 'low': self.pg0._local_ip4_subnet, - 'hi': self.pg0._local_ip4_bcast}, - is_add=1) + self.vapi.proxy_arp_add_del( + proxy={ + "table_id": 0, + "low": self.pg0._local_ip4_subnet, + "hi": self.pg0._local_ip4_bcast, + }, + is_add=1, + ) # Make pg2 un-numbered to pg0 # @@ -788,43 +858,49 @@ class ARPTestCase(VppTestCase): # is VPP's own address # rx = self.send_and_expect(self.pg2, [arp_req_from_me], self.pg2) - self.verify_arp_resp(rx[0], - self.pg2.local_mac, - self.pg2.remote_mac, - self.pg0.remote_hosts[1].ip4, - self.pg0.local_ip4) + self.verify_arp_resp( + rx[0], + self.pg2.local_mac, + self.pg2.remote_mac, + self.pg0.remote_hosts[1].ip4, + self.pg0.local_ip4, + ) # # validate we have not learned an ARP entry as a result of this # - self.assertFalse(find_nbr(self, - self.pg2.sw_if_index, - self.pg0.local_ip4)) + self.assertFalse(find_nbr(self, self.pg2.sw_if_index, self.pg0.local_ip4)) # # setup a punt redirect so packets from the uplink go to the tap # - redirect = VppIpPuntRedirect(self, self.pg0.sw_if_index, - self.pg2.sw_if_index, self.pg0.local_ip4) + redirect = VppIpPuntRedirect( + self, self.pg0.sw_if_index, self.pg2.sw_if_index, self.pg0.local_ip4 + ) redirect.add_vpp_config() - p_tcp = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac,) / - IP(src=self.pg0.remote_ip4, - dst=self.pg0.local_ip4) / - TCP(sport=80, dport=80) / - Raw()) + p_tcp = ( + Ether( + src=self.pg0.remote_mac, + dst=self.pg0.local_mac, + ) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / TCP(sport=80, dport=80) + / Raw() + ) rx = self.send_and_expect(self.pg0, [p_tcp], self.pg2) # there's no ARP entry so this is an ARP req self.assertTrue(rx[0].haslayer(ARP)) # and ARP entry for VPP's pg0 address on the host interface - n1 = VppNeighbor(self, - self.pg2.sw_if_index, - self.pg2.remote_mac, - self.pg0.local_ip4, - is_no_fib_entry=True).add_vpp_config() + n1 = VppNeighbor( + self, + self.pg2.sw_if_index, + self.pg2.remote_mac, + self.pg0.local_ip4, + is_no_fib_entry=True, + ).add_vpp_config() # now the packets shold forward rx = self.send_and_expect(self.pg0, [p_tcp], self.pg2) self.assertFalse(rx[0].haslayer(ARP)) @@ -839,75 +915,81 @@ class ARPTestCase(VppTestCase): # ensure we can still resolve the ARPs on the uplink self.pg0.resolve_arp() - self.assertTrue(find_nbr(self, - self.pg0.sw_if_index, - self.pg0.remote_ip4)) + self.assertTrue(find_nbr(self, self.pg0.sw_if_index, self.pg0.remote_ip4)) # # cleanup # - self.vapi.proxy_arp_add_del(proxy={'table_id': 0, - 'low': self.pg0._local_ip4_subnet, - 'hi': self.pg0._local_ip4_bcast}, - is_add=0) + self.vapi.proxy_arp_add_del( + proxy={ + "table_id": 0, + "low": self.pg0._local_ip4_subnet, + "hi": self.pg0._local_ip4_bcast, + }, + is_add=0, + ) redirect.remove_vpp_config() def test_proxy_arp(self): - """ Proxy ARP """ + """Proxy ARP""" self.pg1.generate_remote_hosts(2) # # Proxy ARP request packets for each interface # - arp_req_pg0 = (Ether(src=self.pg0.remote_mac, - dst="ff:ff:ff:ff:ff:ff") / - ARP(op="who-has", - hwsrc=self.pg0.remote_mac, - pdst="10.10.10.3", - psrc=self.pg0.remote_ip4)) - arp_req_pg0_tagged = (Ether(src=self.pg0.remote_mac, - dst="ff:ff:ff:ff:ff:ff") / - Dot1Q(vlan=0) / - ARP(op="who-has", - hwsrc=self.pg0.remote_mac, - pdst="10.10.10.3", - psrc=self.pg0.remote_ip4)) - arp_req_pg1 = (Ether(src=self.pg1.remote_mac, - dst="ff:ff:ff:ff:ff:ff") / - ARP(op="who-has", - hwsrc=self.pg1.remote_mac, - pdst="10.10.10.3", - psrc=self.pg1.remote_ip4)) - arp_req_pg2 = (Ether(src=self.pg2.remote_mac, - dst="ff:ff:ff:ff:ff:ff") / - ARP(op="who-has", - hwsrc=self.pg2.remote_mac, - pdst="10.10.10.3", - psrc=self.pg1.remote_hosts[1].ip4)) - arp_req_pg3 = (Ether(src=self.pg3.remote_mac, - dst="ff:ff:ff:ff:ff:ff") / - ARP(op="who-has", - hwsrc=self.pg3.remote_mac, - pdst="10.10.10.3", - psrc=self.pg3.remote_ip4)) + arp_req_pg0 = Ether(src=self.pg0.remote_mac, dst="ff:ff:ff:ff:ff:ff") / ARP( + op="who-has", + hwsrc=self.pg0.remote_mac, + pdst="10.10.10.3", + psrc=self.pg0.remote_ip4, + ) + arp_req_pg0_tagged = ( + Ether(src=self.pg0.remote_mac, dst="ff:ff:ff:ff:ff:ff") + / Dot1Q(vlan=0) + / ARP( + op="who-has", + hwsrc=self.pg0.remote_mac, + pdst="10.10.10.3", + psrc=self.pg0.remote_ip4, + ) + ) + arp_req_pg1 = Ether(src=self.pg1.remote_mac, dst="ff:ff:ff:ff:ff:ff") / ARP( + op="who-has", + hwsrc=self.pg1.remote_mac, + pdst="10.10.10.3", + psrc=self.pg1.remote_ip4, + ) + arp_req_pg2 = Ether(src=self.pg2.remote_mac, dst="ff:ff:ff:ff:ff:ff") / ARP( + op="who-has", + hwsrc=self.pg2.remote_mac, + pdst="10.10.10.3", + psrc=self.pg1.remote_hosts[1].ip4, + ) + arp_req_pg3 = Ether(src=self.pg3.remote_mac, dst="ff:ff:ff:ff:ff:ff") / ARP( + op="who-has", + hwsrc=self.pg3.remote_mac, + pdst="10.10.10.3", + psrc=self.pg3.remote_ip4, + ) # # Configure Proxy ARP for 10.10.10.0 -> 10.10.10.124 # - self.vapi.proxy_arp_add_del(proxy={'table_id': 0, - 'low': "10.10.10.2", - 'hi': "10.10.10.124"}, - is_add=1) + self.vapi.proxy_arp_add_del( + proxy={"table_id": 0, "low": "10.10.10.2", "hi": "10.10.10.124"}, is_add=1 + ) # # No responses are sent when the interfaces are not enabled for proxy # ARP # - self.send_and_assert_no_replies(self.pg0, arp_req_pg0, - "ARP req from unconfigured interface") - self.send_and_assert_no_replies(self.pg2, arp_req_pg2, - "ARP req from unconfigured interface") + self.send_and_assert_no_replies( + self.pg0, arp_req_pg0, "ARP req from unconfigured interface" + ) + self.send_and_assert_no_replies( + self.pg2, arp_req_pg2, "ARP req from unconfigured interface" + ) # # Make pg2 un-numbered to pg1 @@ -915,8 +997,9 @@ class ARPTestCase(VppTestCase): # self.pg2.set_unnumbered(self.pg1.sw_if_index) - self.send_and_assert_no_replies(self.pg2, arp_req_pg2, - "ARP req from unnumbered interface") + self.send_and_assert_no_replies( + self.pg2, arp_req_pg2, "ARP req from unnumbered interface" + ) # # Enable each interface to reply to proxy ARPs @@ -933,71 +1016,82 @@ class ARPTestCase(VppTestCase): self.pg_start() rx = self.pg0.get_capture(1) - self.verify_arp_resp(rx[0], - self.pg0.local_mac, - self.pg0.remote_mac, - "10.10.10.3", - self.pg0.remote_ip4) + self.verify_arp_resp( + rx[0], + self.pg0.local_mac, + self.pg0.remote_mac, + "10.10.10.3", + self.pg0.remote_ip4, + ) self.pg0.add_stream(arp_req_pg0_tagged) self.pg_enable_capture(self.pg_interfaces) self.pg_start() rx = self.pg0.get_capture(1) - self.verify_arp_resp(rx[0], - self.pg0.local_mac, - self.pg0.remote_mac, - "10.10.10.3", - self.pg0.remote_ip4) + self.verify_arp_resp( + rx[0], + self.pg0.local_mac, + self.pg0.remote_mac, + "10.10.10.3", + self.pg0.remote_ip4, + ) self.pg1.add_stream(arp_req_pg1) self.pg_enable_capture(self.pg_interfaces) self.pg_start() rx = self.pg1.get_capture(1) - self.verify_arp_resp(rx[0], - self.pg1.local_mac, - self.pg1.remote_mac, - "10.10.10.3", - self.pg1.remote_ip4) + self.verify_arp_resp( + rx[0], + self.pg1.local_mac, + self.pg1.remote_mac, + "10.10.10.3", + self.pg1.remote_ip4, + ) self.pg2.add_stream(arp_req_pg2) self.pg_enable_capture(self.pg_interfaces) self.pg_start() rx = self.pg2.get_capture(1) - self.verify_arp_resp(rx[0], - self.pg2.local_mac, - self.pg2.remote_mac, - "10.10.10.3", - self.pg1.remote_hosts[1].ip4) + self.verify_arp_resp( + rx[0], + self.pg2.local_mac, + self.pg2.remote_mac, + "10.10.10.3", + self.pg1.remote_hosts[1].ip4, + ) # # A request for an address out of the configured range # - arp_req_pg1_hi = (Ether(src=self.pg1.remote_mac, - dst="ff:ff:ff:ff:ff:ff") / - ARP(op="who-has", - hwsrc=self.pg1.remote_mac, - pdst="10.10.10.125", - psrc=self.pg1.remote_ip4)) - self.send_and_assert_no_replies(self.pg1, arp_req_pg1_hi, - "ARP req out of range HI") - arp_req_pg1_low = (Ether(src=self.pg1.remote_mac, - dst="ff:ff:ff:ff:ff:ff") / - ARP(op="who-has", - hwsrc=self.pg1.remote_mac, - pdst="10.10.10.1", - psrc=self.pg1.remote_ip4)) - self.send_and_assert_no_replies(self.pg1, arp_req_pg1_low, - "ARP req out of range Low") + arp_req_pg1_hi = Ether(src=self.pg1.remote_mac, dst="ff:ff:ff:ff:ff:ff") / ARP( + op="who-has", + hwsrc=self.pg1.remote_mac, + pdst="10.10.10.125", + psrc=self.pg1.remote_ip4, + ) + self.send_and_assert_no_replies( + self.pg1, arp_req_pg1_hi, "ARP req out of range HI" + ) + arp_req_pg1_low = Ether(src=self.pg1.remote_mac, dst="ff:ff:ff:ff:ff:ff") / ARP( + op="who-has", + hwsrc=self.pg1.remote_mac, + pdst="10.10.10.1", + psrc=self.pg1.remote_ip4, + ) + self.send_and_assert_no_replies( + self.pg1, arp_req_pg1_low, "ARP req out of range Low" + ) # # Request for an address in the proxy range but from an interface # in a different VRF # - self.send_and_assert_no_replies(self.pg3, arp_req_pg3, - "ARP req from different VRF") + self.send_and_assert_no_replies( + self.pg3, arp_req_pg3, "ARP req from different VRF" + ) # # Disable Each interface for proxy ARP @@ -1006,12 +1100,9 @@ class ARPTestCase(VppTestCase): for i in self.pg_interfaces: i.set_proxy_arp(0) - self.send_and_assert_no_replies(self.pg0, arp_req_pg0, - "ARP req from disable") - self.send_and_assert_no_replies(self.pg1, arp_req_pg1, - "ARP req from disable") - self.send_and_assert_no_replies(self.pg2, arp_req_pg2, - "ARP req from disable") + self.send_and_assert_no_replies(self.pg0, arp_req_pg0, "ARP req from disable") + self.send_and_assert_no_replies(self.pg1, arp_req_pg1, "ARP req from disable") + self.send_and_assert_no_replies(self.pg2, arp_req_pg2, "ARP req from disable") # # clean up on interface 2 @@ -1019,7 +1110,7 @@ class ARPTestCase(VppTestCase): self.pg2.unset_unnumbered(self.pg1.sw_if_index) def test_mpls(self): - """ MPLS """ + """MPLS""" # # Interface 2 does not yet have ip4 config @@ -1030,30 +1121,36 @@ class ARPTestCase(VppTestCase): # # Add a route with out going label via an ARP unresolved next-hop # - ip_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32, - [VppRoutePath(self.pg2.remote_hosts[1].ip4, - self.pg2.sw_if_index, - labels=[55])]) + ip_10_0_0_1 = VppIpRoute( + self, + "10.0.0.1", + 32, + [ + VppRoutePath( + self.pg2.remote_hosts[1].ip4, self.pg2.sw_if_index, labels=[55] + ) + ], + ) ip_10_0_0_1.add_vpp_config() # # packets should generate an ARP request # - p = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst="10.0.0.1") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst="10.0.0.1") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) self.pg_start() rx = self.pg2.get_capture(1) - self.verify_arp_req(rx[0], - self.pg2.local_mac, - self.pg2.local_ip4, - self.pg2._remote_hosts[1].ip4) + self.verify_arp_req( + rx[0], self.pg2.local_mac, self.pg2.local_ip4, self.pg2._remote_hosts[1].ip4 + ) # # now resolve the neighbours @@ -1070,42 +1167,48 @@ class ARPTestCase(VppTestCase): self.pg_start() rx = self.pg2.get_capture(1) - self.verify_ip_o_mpls(rx[0], - self.pg2.local_mac, - self.pg2.remote_hosts[1].mac, - 55, - self.pg0.remote_ip4, - "10.0.0.1") + self.verify_ip_o_mpls( + rx[0], + self.pg2.local_mac, + self.pg2.remote_hosts[1].mac, + 55, + self.pg0.remote_ip4, + "10.0.0.1", + ) self.pg2.unconfig_ip4() def test_arp_vrrp(self): - """ ARP reply with VRRP virtual src hw addr """ + """ARP reply with VRRP virtual src hw addr""" # # IP packet destined for pg1 remote host arrives on pg0 resulting # in an ARP request for the address of the remote host on pg1 # - p0 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - UDP(sport=1234, dport=1234) / - Raw()) + p0 = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / UDP(sport=1234, dport=1234) + / Raw() + ) rx1 = self.send_and_expect(self.pg0, [p0], self.pg1) - self.verify_arp_req(rx1[0], - self.pg1.local_mac, - self.pg1.local_ip4, - self.pg1.remote_ip4) + self.verify_arp_req( + rx1[0], self.pg1.local_mac, self.pg1.local_ip4, self.pg1.remote_ip4 + ) # # ARP reply for address of pg1 remote host arrives on pg1 with # the hw src addr set to a value in the VRRP IPv4 range of # MAC addresses # - p1 = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - ARP(op="is-at", hwdst=self.pg1.local_mac, - hwsrc="00:00:5e:00:01:09", pdst=self.pg1.local_ip4, - psrc=self.pg1.remote_ip4)) + p1 = Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / ARP( + op="is-at", + hwdst=self.pg1.local_mac, + hwsrc="00:00:5e:00:01:09", + pdst=self.pg1.local_ip4, + psrc=self.pg1.remote_ip4, + ) self.send_and_assert_no_replies(self.pg1, p1, "ARP reply") @@ -1116,17 +1219,19 @@ class ARPTestCase(VppTestCase): # rx1 = self.send_and_expect(self.pg0, [p0], self.pg1) - self.verify_ip(rx1[0], - self.pg1.local_mac, - "00:00:5e:00:01:09", - self.pg0.remote_ip4, - self.pg1.remote_ip4) + self.verify_ip( + rx1[0], + self.pg1.local_mac, + "00:00:5e:00:01:09", + self.pg0.remote_ip4, + self.pg1.remote_ip4, + ) self.pg1.admin_down() self.pg1.admin_up() def test_arp_duplicates(self): - """ ARP Duplicates""" + """ARP Duplicates""" # # Generate some hosts on the LAN @@ -1136,26 +1241,30 @@ class ARPTestCase(VppTestCase): # # Add host 1 on pg1 and pg2 # - arp_pg1 = VppNeighbor(self, - self.pg1.sw_if_index, - self.pg1.remote_hosts[1].mac, - self.pg1.remote_hosts[1].ip4) + arp_pg1 = VppNeighbor( + self, + self.pg1.sw_if_index, + self.pg1.remote_hosts[1].mac, + self.pg1.remote_hosts[1].ip4, + ) arp_pg1.add_vpp_config() - arp_pg2 = VppNeighbor(self, - self.pg2.sw_if_index, - self.pg2.remote_mac, - self.pg1.remote_hosts[1].ip4) + arp_pg2 = VppNeighbor( + self, + self.pg2.sw_if_index, + self.pg2.remote_mac, + self.pg1.remote_hosts[1].ip4, + ) arp_pg2.add_vpp_config() # # IP packet destined for pg1 remote host arrives on pg1 again. # - p = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, - dst=self.pg1.remote_hosts[1].ip4) / - UDP(sport=1234, dport=1234) / - Raw()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_hosts[1].ip4) + / UDP(sport=1234, dport=1234) + / Raw() + ) self.pg0.add_stream(p) self.pg_enable_capture(self.pg_interfaces) @@ -1163,11 +1272,13 @@ class ARPTestCase(VppTestCase): rx1 = self.pg1.get_capture(1) - self.verify_ip(rx1[0], - self.pg1.local_mac, - self.pg1.remote_hosts[1].mac, - self.pg0.remote_ip4, - self.pg1.remote_hosts[1].ip4) + self.verify_ip( + rx1[0], + self.pg1.local_mac, + self.pg1.remote_hosts[1].mac, + self.pg0.remote_ip4, + self.pg1.remote_hosts[1].ip4, + ) # # remove the duplicate on pg1 @@ -1181,10 +1292,9 @@ class ARPTestCase(VppTestCase): rx1 = self.pg1.get_capture(1) - self.verify_arp_req(rx1[0], - self.pg1.local_mac, - self.pg1.local_ip4, - self.pg1.remote_hosts[1].ip4) + self.verify_arp_req( + rx1[0], self.pg1.local_mac, self.pg1.local_ip4, self.pg1.remote_hosts[1].ip4 + ) # # Add it back @@ -1197,24 +1307,28 @@ class ARPTestCase(VppTestCase): rx1 = self.pg1.get_capture(1) - self.verify_ip(rx1[0], - self.pg1.local_mac, - self.pg1.remote_hosts[1].mac, - self.pg0.remote_ip4, - self.pg1.remote_hosts[1].ip4) + self.verify_ip( + rx1[0], + self.pg1.local_mac, + self.pg1.remote_hosts[1].mac, + self.pg0.remote_ip4, + self.pg1.remote_hosts[1].ip4, + ) def test_arp_static(self): - """ ARP Static""" + """ARP Static""" self.pg2.generate_remote_hosts(3) # # Add a static ARP entry # - static_arp = VppNeighbor(self, - self.pg2.sw_if_index, - self.pg2.remote_hosts[1].mac, - self.pg2.remote_hosts[1].ip4, - is_static=1) + static_arp = VppNeighbor( + self, + self.pg2.sw_if_index, + self.pg2.remote_hosts[1].mac, + self.pg2.remote_hosts[1].ip4, + is_static=1, + ) static_arp.add_vpp_config() # @@ -1225,13 +1339,12 @@ class ARPTestCase(VppTestCase): # # We should now find the adj-fib # - self.assertTrue(find_nbr(self, - self.pg2.sw_if_index, - self.pg2.remote_hosts[1].ip4, - is_static=1)) - self.assertTrue(find_route(self, - self.pg2.remote_hosts[1].ip4, - 32)) + self.assertTrue( + find_nbr( + self, self.pg2.sw_if_index, self.pg2.remote_hosts[1].ip4, is_static=1 + ) + ) + self.assertTrue(find_route(self, self.pg2.remote_hosts[1].ip4, 32)) # # remove the connected @@ -1248,10 +1361,7 @@ class ARPTestCase(VppTestCase): # adj fib in the new table # self.pg2.config_ip4() - self.assertTrue(find_route(self, - self.pg2.remote_hosts[1].ip4, - 32, - table_id=1)) + self.assertTrue(find_route(self, self.pg2.remote_hosts[1].ip4, 32, table_id=1)) # # clean-up @@ -1261,18 +1371,22 @@ class ARPTestCase(VppTestCase): self.pg2.set_table_ip4(0) def test_arp_static_replace_dynamic_same_mac(self): - """ ARP Static can replace Dynamic (same mac) """ + """ARP Static can replace Dynamic (same mac)""" self.pg2.generate_remote_hosts(1) - dyn_arp = VppNeighbor(self, - self.pg2.sw_if_index, - self.pg2.remote_hosts[0].mac, - self.pg2.remote_hosts[0].ip4) - static_arp = VppNeighbor(self, - self.pg2.sw_if_index, - self.pg2.remote_hosts[0].mac, - self.pg2.remote_hosts[0].ip4, - is_static=1) + dyn_arp = VppNeighbor( + self, + self.pg2.sw_if_index, + self.pg2.remote_hosts[0].mac, + self.pg2.remote_hosts[0].ip4, + ) + static_arp = VppNeighbor( + self, + self.pg2.sw_if_index, + self.pg2.remote_hosts[0].mac, + self.pg2.remote_hosts[0].ip4, + is_static=1, + ) # # Add a dynamic ARP entry @@ -1282,15 +1396,20 @@ class ARPTestCase(VppTestCase): # # We should find the dynamic nbr # - self.assertFalse(find_nbr(self, - self.pg2.sw_if_index, - self.pg2.remote_hosts[0].ip4, - is_static=1)) - self.assertTrue(find_nbr(self, - self.pg2.sw_if_index, - self.pg2.remote_hosts[0].ip4, - is_static=0, - mac=self.pg2.remote_hosts[0].mac)) + self.assertFalse( + find_nbr( + self, self.pg2.sw_if_index, self.pg2.remote_hosts[0].ip4, is_static=1 + ) + ) + self.assertTrue( + find_nbr( + self, + self.pg2.sw_if_index, + self.pg2.remote_hosts[0].ip4, + is_static=0, + mac=self.pg2.remote_hosts[0].mac, + ) + ) # # Add a static ARP entry with the same mac @@ -1300,15 +1419,20 @@ class ARPTestCase(VppTestCase): # # We should now find the static nbr with the same mac # - self.assertFalse(find_nbr(self, - self.pg2.sw_if_index, - self.pg2.remote_hosts[0].ip4, - is_static=0)) - self.assertTrue(find_nbr(self, - self.pg2.sw_if_index, - self.pg2.remote_hosts[0].ip4, - is_static=1, - mac=self.pg2.remote_hosts[0].mac)) + self.assertFalse( + find_nbr( + self, self.pg2.sw_if_index, self.pg2.remote_hosts[0].ip4, is_static=0 + ) + ) + self.assertTrue( + find_nbr( + self, + self.pg2.sw_if_index, + self.pg2.remote_hosts[0].ip4, + is_static=1, + mac=self.pg2.remote_hosts[0].mac, + ) + ) # # clean-up @@ -1316,18 +1440,22 @@ class ARPTestCase(VppTestCase): static_arp.remove_vpp_config() def test_arp_static_replace_dynamic_diff_mac(self): - """ ARP Static can replace Dynamic (diff mac) """ + """ARP Static can replace Dynamic (diff mac)""" self.pg2.generate_remote_hosts(2) - dyn_arp = VppNeighbor(self, - self.pg2.sw_if_index, - self.pg2.remote_hosts[0].mac, - self.pg2.remote_hosts[0].ip4) - static_arp = VppNeighbor(self, - self.pg2.sw_if_index, - self.pg2.remote_hosts[1].mac, - self.pg2.remote_hosts[0].ip4, - is_static=1) + dyn_arp = VppNeighbor( + self, + self.pg2.sw_if_index, + self.pg2.remote_hosts[0].mac, + self.pg2.remote_hosts[0].ip4, + ) + static_arp = VppNeighbor( + self, + self.pg2.sw_if_index, + self.pg2.remote_hosts[1].mac, + self.pg2.remote_hosts[0].ip4, + is_static=1, + ) # # Add a dynamic ARP entry @@ -1337,15 +1465,20 @@ class ARPTestCase(VppTestCase): # # We should find the dynamic nbr # - self.assertFalse(find_nbr(self, - self.pg2.sw_if_index, - self.pg2.remote_hosts[0].ip4, - is_static=1)) - self.assertTrue(find_nbr(self, - self.pg2.sw_if_index, - self.pg2.remote_hosts[0].ip4, - is_static=0, - mac=self.pg2.remote_hosts[0].mac)) + self.assertFalse( + find_nbr( + self, self.pg2.sw_if_index, self.pg2.remote_hosts[0].ip4, is_static=1 + ) + ) + self.assertTrue( + find_nbr( + self, + self.pg2.sw_if_index, + self.pg2.remote_hosts[0].ip4, + is_static=0, + mac=self.pg2.remote_hosts[0].mac, + ) + ) # # Add a static ARP entry with a changed mac @@ -1355,15 +1488,20 @@ class ARPTestCase(VppTestCase): # # We should now find the static nbr with a changed mac # - self.assertFalse(find_nbr(self, - self.pg2.sw_if_index, - self.pg2.remote_hosts[0].ip4, - is_static=0)) - self.assertTrue(find_nbr(self, - self.pg2.sw_if_index, - self.pg2.remote_hosts[0].ip4, - is_static=1, - mac=self.pg2.remote_hosts[1].mac)) + self.assertFalse( + find_nbr( + self, self.pg2.sw_if_index, self.pg2.remote_hosts[0].ip4, is_static=0 + ) + ) + self.assertTrue( + find_nbr( + self, + self.pg2.sw_if_index, + self.pg2.remote_hosts[0].ip4, + is_static=1, + mac=self.pg2.remote_hosts[1].mac, + ) + ) # # clean-up @@ -1371,95 +1509,109 @@ class ARPTestCase(VppTestCase): static_arp.remove_vpp_config() def test_arp_incomplete(self): - """ ARP Incomplete""" + """ARP Incomplete""" self.pg1.generate_remote_hosts(4) - p0 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, - dst=self.pg1.remote_hosts[1].ip4) / - UDP(sport=1234, dport=1234) / - Raw()) - p1 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, - dst=self.pg1.remote_hosts[2].ip4) / - UDP(sport=1234, dport=1234) / - Raw()) - p2 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, - dst="1.1.1.1") / - UDP(sport=1234, dport=1234) / - Raw()) + p0 = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_hosts[1].ip4) + / UDP(sport=1234, dport=1234) + / Raw() + ) + p1 = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_hosts[2].ip4) + / UDP(sport=1234, dport=1234) + / Raw() + ) + p2 = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst="1.1.1.1") + / UDP(sport=1234, dport=1234) + / Raw() + ) # # a packet to an unresolved destination generates an ARP request # rx = self.send_and_expect(self.pg0, [p0], self.pg1) - self.verify_arp_req(rx[0], - self.pg1.local_mac, - self.pg1.local_ip4, - self.pg1._remote_hosts[1].ip4) + self.verify_arp_req( + rx[0], self.pg1.local_mac, self.pg1.local_ip4, self.pg1._remote_hosts[1].ip4 + ) # # add a neighbour for remote host 1 # - static_arp = VppNeighbor(self, - self.pg1.sw_if_index, - self.pg1.remote_hosts[1].mac, - self.pg1.remote_hosts[1].ip4, - is_static=1) + static_arp = VppNeighbor( + self, + self.pg1.sw_if_index, + self.pg1.remote_hosts[1].mac, + self.pg1.remote_hosts[1].ip4, + is_static=1, + ) static_arp.add_vpp_config() # # add a route through remote host 3 hence we get an incomplete # - VppIpRoute(self, "1.1.1.1", 32, - [VppRoutePath(self.pg1.remote_hosts[3].ip4, - self.pg1.sw_if_index)]).add_vpp_config() + VppIpRoute( + self, + "1.1.1.1", + 32, + [VppRoutePath(self.pg1.remote_hosts[3].ip4, self.pg1.sw_if_index)], + ).add_vpp_config() rx = self.send_and_expect(self.pg0, [p2], self.pg1) - self.verify_arp_req(rx[0], - self.pg1.local_mac, - self.pg1.local_ip4, - self.pg1._remote_hosts[3].ip4) + self.verify_arp_req( + rx[0], self.pg1.local_mac, self.pg1.local_ip4, self.pg1._remote_hosts[3].ip4 + ) # # change the interface's MAC # - self.vapi.sw_interface_set_mac_address(self.pg1.sw_if_index, - "00:00:00:33:33:33") + self.vapi.sw_interface_set_mac_address( + self.pg1.sw_if_index, "00:00:00:33:33:33" + ) # # now ARP requests come from the new source mac # rx = self.send_and_expect(self.pg0, [p1], self.pg1) - self.verify_arp_req(rx[0], - "00:00:00:33:33:33", - self.pg1.local_ip4, - self.pg1._remote_hosts[2].ip4) + self.verify_arp_req( + rx[0], + "00:00:00:33:33:33", + self.pg1.local_ip4, + self.pg1._remote_hosts[2].ip4, + ) rx = self.send_and_expect(self.pg0, [p2], self.pg1) - self.verify_arp_req(rx[0], - "00:00:00:33:33:33", - self.pg1.local_ip4, - self.pg1._remote_hosts[3].ip4) + self.verify_arp_req( + rx[0], + "00:00:00:33:33:33", + self.pg1.local_ip4, + self.pg1._remote_hosts[3].ip4, + ) # # packets to the resolved host also have the new source mac # rx = self.send_and_expect(self.pg0, [p0], self.pg1) - self.verify_ip(rx[0], - "00:00:00:33:33:33", - self.pg1.remote_hosts[1].mac, - self.pg0.remote_ip4, - self.pg1.remote_hosts[1].ip4) + self.verify_ip( + rx[0], + "00:00:00:33:33:33", + self.pg1.remote_hosts[1].mac, + self.pg0.remote_ip4, + self.pg1.remote_hosts[1].ip4, + ) # # set the mac address on the interface that does not have a # configured subnet and thus no glean # - self.vapi.sw_interface_set_mac_address(self.pg2.sw_if_index, - "00:00:00:33:33:33") + self.vapi.sw_interface_set_mac_address( + self.pg2.sw_if_index, "00:00:00:33:33:33" + ) def test_garp(self): - """ GARP """ + """GARP""" # # Generate some hosts on the LAN @@ -1470,92 +1622,106 @@ class ARPTestCase(VppTestCase): # # And an ARP entry # - arp = VppNeighbor(self, - self.pg1.sw_if_index, - self.pg1.remote_hosts[1].mac, - self.pg1.remote_hosts[1].ip4) + arp = VppNeighbor( + self, + self.pg1.sw_if_index, + self.pg1.remote_hosts[1].mac, + self.pg1.remote_hosts[1].ip4, + ) arp.add_vpp_config() - self.assertTrue(find_nbr(self, - self.pg1.sw_if_index, - self.pg1.remote_hosts[1].ip4, - mac=self.pg1.remote_hosts[1].mac)) + self.assertTrue( + find_nbr( + self, + self.pg1.sw_if_index, + self.pg1.remote_hosts[1].ip4, + mac=self.pg1.remote_hosts[1].mac, + ) + ) # # Send a GARP (request) to swap the host 1's address to that of host 2 # - p1 = (Ether(dst="ff:ff:ff:ff:ff:ff", - src=self.pg1.remote_hosts[2].mac) / - ARP(op="who-has", - hwdst=self.pg1.local_mac, - hwsrc=self.pg1.remote_hosts[2].mac, - pdst=self.pg1.remote_hosts[1].ip4, - psrc=self.pg1.remote_hosts[1].ip4)) + p1 = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg1.remote_hosts[2].mac) / ARP( + op="who-has", + hwdst=self.pg1.local_mac, + hwsrc=self.pg1.remote_hosts[2].mac, + pdst=self.pg1.remote_hosts[1].ip4, + psrc=self.pg1.remote_hosts[1].ip4, + ) self.pg1.add_stream(p1) self.pg_enable_capture(self.pg_interfaces) self.pg_start() - self.assertTrue(find_nbr(self, - self.pg1.sw_if_index, - self.pg1.remote_hosts[1].ip4, - mac=self.pg1.remote_hosts[2].mac)) + self.assertTrue( + find_nbr( + self, + self.pg1.sw_if_index, + self.pg1.remote_hosts[1].ip4, + mac=self.pg1.remote_hosts[2].mac, + ) + ) # # Send a GARP (reply) to swap the host 1's address to that of host 3 # - p1 = (Ether(dst="ff:ff:ff:ff:ff:ff", - src=self.pg1.remote_hosts[3].mac) / - ARP(op="is-at", - hwdst=self.pg1.local_mac, - hwsrc=self.pg1.remote_hosts[3].mac, - pdst=self.pg1.remote_hosts[1].ip4, - psrc=self.pg1.remote_hosts[1].ip4)) + p1 = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg1.remote_hosts[3].mac) / ARP( + op="is-at", + hwdst=self.pg1.local_mac, + hwsrc=self.pg1.remote_hosts[3].mac, + pdst=self.pg1.remote_hosts[1].ip4, + psrc=self.pg1.remote_hosts[1].ip4, + ) self.pg1.add_stream(p1) self.pg_enable_capture(self.pg_interfaces) self.pg_start() - self.assertTrue(find_nbr(self, - self.pg1.sw_if_index, - self.pg1.remote_hosts[1].ip4, - mac=self.pg1.remote_hosts[3].mac)) + self.assertTrue( + find_nbr( + self, + self.pg1.sw_if_index, + self.pg1.remote_hosts[1].ip4, + mac=self.pg1.remote_hosts[3].mac, + ) + ) # # GARPs (request nor replies) for host we don't know yet # don't result in new neighbour entries # - p1 = (Ether(dst="ff:ff:ff:ff:ff:ff", - src=self.pg1.remote_hosts[3].mac) / - ARP(op="who-has", - hwdst=self.pg1.local_mac, - hwsrc=self.pg1.remote_hosts[3].mac, - pdst=self.pg1.remote_hosts[2].ip4, - psrc=self.pg1.remote_hosts[2].ip4)) + p1 = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg1.remote_hosts[3].mac) / ARP( + op="who-has", + hwdst=self.pg1.local_mac, + hwsrc=self.pg1.remote_hosts[3].mac, + pdst=self.pg1.remote_hosts[2].ip4, + psrc=self.pg1.remote_hosts[2].ip4, + ) self.pg1.add_stream(p1) self.pg_enable_capture(self.pg_interfaces) self.pg_start() - self.assertFalse(find_nbr(self, - self.pg1.sw_if_index, - self.pg1.remote_hosts[2].ip4)) + self.assertFalse( + find_nbr(self, self.pg1.sw_if_index, self.pg1.remote_hosts[2].ip4) + ) - p1 = (Ether(dst="ff:ff:ff:ff:ff:ff", - src=self.pg1.remote_hosts[3].mac) / - ARP(op="is-at", - hwdst=self.pg1.local_mac, - hwsrc=self.pg1.remote_hosts[3].mac, - pdst=self.pg1.remote_hosts[2].ip4, - psrc=self.pg1.remote_hosts[2].ip4)) + p1 = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg1.remote_hosts[3].mac) / ARP( + op="is-at", + hwdst=self.pg1.local_mac, + hwsrc=self.pg1.remote_hosts[3].mac, + pdst=self.pg1.remote_hosts[2].ip4, + psrc=self.pg1.remote_hosts[2].ip4, + ) self.pg1.add_stream(p1) self.pg_enable_capture(self.pg_interfaces) self.pg_start() - self.assertFalse(find_nbr(self, - self.pg1.sw_if_index, - self.pg1.remote_hosts[2].ip4)) + self.assertFalse( + find_nbr(self, self.pg1.sw_if_index, self.pg1.remote_hosts[2].ip4) + ) # # IP address in different subnets are not learnt @@ -1563,32 +1729,44 @@ class ARPTestCase(VppTestCase): self.pg2.configure_ipv4_neighbors() for op in ["is-at", "who-has"]: - p1 = [(Ether(dst="ff:ff:ff:ff:ff:ff", - src=self.pg2.remote_hosts[1].mac) / - ARP(op=op, - hwdst=self.pg2.local_mac, - hwsrc=self.pg2.remote_hosts[1].mac, - pdst=self.pg2.remote_hosts[1].ip4, - psrc=self.pg2.remote_hosts[1].ip4)), - (Ether(dst="ff:ff:ff:ff:ff:ff", - src=self.pg2.remote_hosts[1].mac) / - ARP(op=op, - hwdst="ff:ff:ff:ff:ff:ff", - hwsrc=self.pg2.remote_hosts[1].mac, - pdst=self.pg2.remote_hosts[1].ip4, - psrc=self.pg2.remote_hosts[1].ip4))] + p1 = [ + ( + Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_hosts[1].mac) + / ARP( + op=op, + hwdst=self.pg2.local_mac, + hwsrc=self.pg2.remote_hosts[1].mac, + pdst=self.pg2.remote_hosts[1].ip4, + psrc=self.pg2.remote_hosts[1].ip4, + ) + ), + ( + Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_hosts[1].mac) + / ARP( + op=op, + hwdst="ff:ff:ff:ff:ff:ff", + hwsrc=self.pg2.remote_hosts[1].mac, + pdst=self.pg2.remote_hosts[1].ip4, + psrc=self.pg2.remote_hosts[1].ip4, + ) + ), + ] self.send_and_assert_no_replies(self.pg1, p1) - self.assertFalse(find_nbr(self, - self.pg1.sw_if_index, - self.pg2.remote_hosts[1].ip4)) + self.assertFalse( + find_nbr(self, self.pg1.sw_if_index, self.pg2.remote_hosts[1].ip4) + ) # they are all dropped because the subnet's don't match - self.assertEqual(4, self.statistics.get_err_counter( - "/err/arp-reply/IP4 destination address not local to subnet")) + self.assertEqual( + 4, + self.statistics.get_err_counter( + "/err/arp-reply/IP4 destination address not local to subnet" + ), + ) def test_arp_incomplete2(self): - """ Incomplete Entries """ + """Incomplete Entries""" # # ensure that we throttle the ARP and ND requests @@ -1598,17 +1776,20 @@ class ARPTestCase(VppTestCase): # # IPv4/ARP # - ip_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32, - [VppRoutePath(self.pg0.remote_hosts[1].ip4, - self.pg0.sw_if_index)]) + ip_10_0_0_1 = VppIpRoute( + self, + "10.0.0.1", + 32, + [VppRoutePath(self.pg0.remote_hosts[1].ip4, self.pg0.sw_if_index)], + ) ip_10_0_0_1.add_vpp_config() - p1 = (Ether(dst=self.pg1.local_mac, - src=self.pg1.remote_mac) / - IP(src=self.pg1.remote_ip4, - dst="10.0.0.1") / - UDP(sport=1234, dport=1234) / - Raw()) + p1 = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src=self.pg1.remote_ip4, dst="10.0.0.1") + / UDP(sport=1234, dport=1234) + / Raw() + ) self.pg1.add_stream(p1 * 257) self.pg_enable_capture(self.pg_interfaces) @@ -1624,18 +1805,26 @@ class ARPTestCase(VppTestCase): # # IPv6/ND # - ip_10_1 = VppIpRoute(self, "10::1", 128, - [VppRoutePath(self.pg0.remote_hosts[1].ip6, - self.pg0.sw_if_index, - proto=DpoProto.DPO_PROTO_IP6)]) + ip_10_1 = VppIpRoute( + self, + "10::1", + 128, + [ + VppRoutePath( + self.pg0.remote_hosts[1].ip6, + self.pg0.sw_if_index, + proto=DpoProto.DPO_PROTO_IP6, + ) + ], + ) ip_10_1.add_vpp_config() - p1 = (Ether(dst=self.pg1.local_mac, - src=self.pg1.remote_mac) / - IPv6(src=self.pg1.remote_ip6, - dst="10::1") / - UDP(sport=1234, dport=1234) / - Raw()) + p1 = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(src=self.pg1.remote_ip6, dst="10::1") + / UDP(sport=1234, dport=1234) + / Raw() + ) self.pg1.add_stream(p1 * 257) self.pg_enable_capture(self.pg_interfaces) @@ -1649,7 +1838,7 @@ class ARPTestCase(VppTestCase): self.assertLess(len(rx), 64) def test_arp_forus(self): - """ ARP for for-us """ + """ARP for for-us""" # # Test that VPP responds with ARP requests to addresses that @@ -1661,27 +1850,36 @@ class ARPTestCase(VppTestCase): self.pg0.generate_remote_hosts(2) forus = VppIpRoute( - self, self.pg0.remote_hosts[1].ip4, 32, - [VppRoutePath("0.0.0.0", - self.pg0.sw_if_index, - type=FibPathType.FIB_PATH_TYPE_LOCAL)]) + self, + self.pg0.remote_hosts[1].ip4, + 32, + [ + VppRoutePath( + "0.0.0.0", + self.pg0.sw_if_index, + type=FibPathType.FIB_PATH_TYPE_LOCAL, + ) + ], + ) forus.add_vpp_config() - p = (Ether(dst="ff:ff:ff:ff:ff:ff", - src=self.pg0.remote_mac) / - ARP(op="who-has", - hwdst=self.pg0.local_mac, - hwsrc=self.pg0.remote_mac, - pdst=self.pg0.remote_hosts[1].ip4, - psrc=self.pg0.remote_ip4)) + p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / ARP( + op="who-has", + hwdst=self.pg0.local_mac, + hwsrc=self.pg0.remote_mac, + pdst=self.pg0.remote_hosts[1].ip4, + psrc=self.pg0.remote_ip4, + ) rx = self.send_and_expect(self.pg0, [p], self.pg0) - self.verify_arp_resp(rx[0], - self.pg0.local_mac, - self.pg0.remote_mac, - self.pg0.remote_hosts[1].ip4, - self.pg0.remote_ip4) + self.verify_arp_resp( + rx[0], + self.pg0.local_mac, + self.pg0.remote_mac, + self.pg0.remote_hosts[1].ip4, + self.pg0.remote_ip4, + ) def test_arp_table_swap(self): # @@ -1692,15 +1890,21 @@ class ARPTestCase(VppTestCase): for n in range(N_NBRS): # a route thru each neighbour - VppIpRoute(self, "10.0.0.%d" % n, 32, - [VppRoutePath(self.pg1.remote_hosts[n].ip4, - self.pg1.sw_if_index)]).add_vpp_config() + VppIpRoute( + self, + "10.0.0.%d" % n, + 32, + [VppRoutePath(self.pg1.remote_hosts[n].ip4, self.pg1.sw_if_index)], + ).add_vpp_config() # resolve each neighbour - p1 = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - ARP(op="is-at", hwdst=self.pg1.local_mac, - hwsrc="00:00:5e:00:01:09", pdst=self.pg1.local_ip4, - psrc=self.pg1.remote_hosts[n].ip4)) + p1 = Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / ARP( + op="is-at", + hwdst=self.pg1.local_mac, + hwsrc="00:00:5e:00:01:09", + pdst=self.pg1.local_ip4, + psrc=self.pg1.remote_hosts[n].ip4, + ) self.send_and_assert_no_replies(self.pg1, p1, "ARP reply") @@ -1719,87 +1923,80 @@ class ARPTestCase(VppTestCase): # all neighbours are cleared # for n in range(N_NBRS): - self.assertFalse(find_nbr(self, - self.pg1.sw_if_index, - self.pg1.remote_hosts[n].ip4)) + self.assertFalse( + find_nbr(self, self.pg1.sw_if_index, self.pg1.remote_hosts[n].ip4) + ) # # packets to all neighbours generate ARP requests # for n in range(N_NBRS): # a route thru each neighbour - VppIpRoute(self, "10.0.0.%d" % n, 32, - [VppRoutePath(self.pg1.remote_hosts[n].ip4, - self.pg1.sw_if_index)], - table_id=100).add_vpp_config() - - p = (Ether(src=self.pg1.remote_hosts[n].mac, - dst=self.pg1.local_mac) / - IP(src=self.pg1.remote_hosts[n].ip4, - dst="10.0.0.%d" % n) / - Raw(b'0x5' * 100)) + VppIpRoute( + self, + "10.0.0.%d" % n, + 32, + [VppRoutePath(self.pg1.remote_hosts[n].ip4, self.pg1.sw_if_index)], + table_id=100, + ).add_vpp_config() + + p = ( + Ether(src=self.pg1.remote_hosts[n].mac, dst=self.pg1.local_mac) + / IP(src=self.pg1.remote_hosts[n].ip4, dst="10.0.0.%d" % n) + / Raw(b"0x5" * 100) + ) rxs = self.send_and_expect(self.pg1, [p], self.pg1) for rx in rxs: - self.verify_arp_req(rx, - self.pg1.local_mac, - self.pg1.local_ip4, - self.pg1.remote_hosts[n].ip4) + self.verify_arp_req( + rx, + self.pg1.local_mac, + self.pg1.local_ip4, + self.pg1.remote_hosts[n].ip4, + ) self.pg1.unconfig_ip4() self.pg1.set_table_ip4(0) def test_glean_src_select(self): - """ Multi Connecteds """ + """Multi Connecteds""" # # configure multiple connected subnets on an interface # and ensure that ARP requests for hosts on those subnets # pick up the correct source address # - conn1 = VppIpInterfaceAddress(self, self.pg1, - "10.0.0.1", 24).add_vpp_config() - conn2 = VppIpInterfaceAddress(self, self.pg1, - "10.0.1.1", 24).add_vpp_config() + conn1 = VppIpInterfaceAddress(self, self.pg1, "10.0.0.1", 24).add_vpp_config() + conn2 = VppIpInterfaceAddress(self, self.pg1, "10.0.1.1", 24).add_vpp_config() - p1 = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg1.remote_ip4, - dst="10.0.0.128") / - Raw(b'0x5' * 100)) + p1 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg1.remote_ip4, dst="10.0.0.128") + / Raw(b"0x5" * 100) + ) rxs = self.send_and_expect(self.pg0, [p1], self.pg1) for rx in rxs: - self.verify_arp_req(rx, - self.pg1.local_mac, - "10.0.0.1", - "10.0.0.128") + self.verify_arp_req(rx, self.pg1.local_mac, "10.0.0.1", "10.0.0.128") - p2 = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg1.remote_ip4, - dst="10.0.1.128") / - Raw(b'0x5' * 100)) + p2 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg1.remote_ip4, dst="10.0.1.128") + / Raw(b"0x5" * 100) + ) rxs = self.send_and_expect(self.pg0, [p2], self.pg1) for rx in rxs: - self.verify_arp_req(rx, - self.pg1.local_mac, - "10.0.1.1", - "10.0.1.128") + self.verify_arp_req(rx, self.pg1.local_mac, "10.0.1.1", "10.0.1.128") # # add a local address in the same subnet # the source addresses are equivalent. VPP happens to # choose the last one that was added - conn3 = VppIpInterfaceAddress(self, self.pg1, - "10.0.1.2", 24).add_vpp_config() + conn3 = VppIpInterfaceAddress(self, self.pg1, "10.0.1.2", 24).add_vpp_config() rxs = self.send_and_expect(self.pg0, [p2], self.pg1) for rx in rxs: - self.verify_arp_req(rx, - self.pg1.local_mac, - "10.0.1.2", - "10.0.1.128") + self.verify_arp_req(rx, self.pg1.local_mac, "10.0.1.2", "10.0.1.128") # # remove @@ -1807,44 +2004,34 @@ class ARPTestCase(VppTestCase): conn3.remove_vpp_config() rxs = self.send_and_expect(self.pg0, [p2], self.pg1) for rx in rxs: - self.verify_arp_req(rx, - self.pg1.local_mac, - "10.0.1.1", - "10.0.1.128") + self.verify_arp_req(rx, self.pg1.local_mac, "10.0.1.1", "10.0.1.128") # # add back, this time remove the first one # - conn3 = VppIpInterfaceAddress(self, self.pg1, - "10.0.1.2", 24).add_vpp_config() + conn3 = VppIpInterfaceAddress(self, self.pg1, "10.0.1.2", 24).add_vpp_config() rxs = self.send_and_expect(self.pg0, [p2], self.pg1) for rx in rxs: - self.verify_arp_req(rx, - self.pg1.local_mac, - "10.0.1.2", - "10.0.1.128") + self.verify_arp_req(rx, self.pg1.local_mac, "10.0.1.2", "10.0.1.128") conn1.remove_vpp_config() rxs = self.send_and_expect(self.pg0, [p2], self.pg1) for rx in rxs: - self.verify_arp_req(rx, - self.pg1.local_mac, - "10.0.1.2", - "10.0.1.128") + self.verify_arp_req(rx, self.pg1.local_mac, "10.0.1.2", "10.0.1.128") # apply a connected prefix to an interface in a different table - VppIpRoute(self, "10.0.1.0", 24, - [VppRoutePath("0.0.0.0", - self.pg1.sw_if_index)], - table_id=1).add_vpp_config() + VppIpRoute( + self, + "10.0.1.0", + 24, + [VppRoutePath("0.0.0.0", self.pg1.sw_if_index)], + table_id=1, + ).add_vpp_config() rxs = self.send_and_expect(self.pg3, [p2], self.pg1) for rx in rxs: - self.verify_arp_req(rx, - self.pg1.local_mac, - "10.0.1.2", - "10.0.1.128") + self.verify_arp_req(rx, self.pg1.local_mac, "10.0.1.2", "10.0.1.128") # cleanup conn3.remove_vpp_config() @@ -1853,7 +2040,7 @@ class ARPTestCase(VppTestCase): @tag_fixme_vpp_workers class NeighborStatsTestCase(VppTestCase): - """ ARP/ND Counters """ + """ARP/ND Counters""" @classmethod def setUpClass(cls): @@ -1887,86 +2074,94 @@ class NeighborStatsTestCase(VppTestCase): i.admin_down() def test_arp_stats(self): - """ ARP Counters """ + """ARP Counters""" self.vapi.cli("adj counters enable") self.pg1.generate_remote_hosts(2) - arp1 = VppNeighbor(self, - self.pg1.sw_if_index, - self.pg1.remote_hosts[0].mac, - self.pg1.remote_hosts[0].ip4) + arp1 = VppNeighbor( + self, + self.pg1.sw_if_index, + self.pg1.remote_hosts[0].mac, + self.pg1.remote_hosts[0].ip4, + ) arp1.add_vpp_config() - arp2 = VppNeighbor(self, - self.pg1.sw_if_index, - self.pg1.remote_hosts[1].mac, - self.pg1.remote_hosts[1].ip4) + arp2 = VppNeighbor( + self, + self.pg1.sw_if_index, + self.pg1.remote_hosts[1].mac, + self.pg1.remote_hosts[1].ip4, + ) arp2.add_vpp_config() - p1 = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, - dst=self.pg1.remote_hosts[0].ip4) / - UDP(sport=1234, dport=1234) / - Raw()) - p2 = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, - dst=self.pg1.remote_hosts[1].ip4) / - UDP(sport=1234, dport=1234) / - Raw()) + p1 = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_hosts[0].ip4) + / UDP(sport=1234, dport=1234) + / Raw() + ) + p2 = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_hosts[1].ip4) + / UDP(sport=1234, dport=1234) + / Raw() + ) rx = self.send_and_expect(self.pg0, p1 * NUM_PKTS, self.pg1) rx = self.send_and_expect(self.pg0, p2 * NUM_PKTS, self.pg1) - self.assertEqual(NUM_PKTS, arp1.get_stats()['packets']) - self.assertEqual(NUM_PKTS, arp2.get_stats()['packets']) + self.assertEqual(NUM_PKTS, arp1.get_stats()["packets"]) + self.assertEqual(NUM_PKTS, arp2.get_stats()["packets"]) rx = self.send_and_expect(self.pg0, p1 * NUM_PKTS, self.pg1) - self.assertEqual(NUM_PKTS*2, arp1.get_stats()['packets']) + self.assertEqual(NUM_PKTS * 2, arp1.get_stats()["packets"]) def test_nd_stats(self): - """ ND Counters """ + """ND Counters""" self.vapi.cli("adj counters enable") self.pg0.generate_remote_hosts(3) - nd1 = VppNeighbor(self, - self.pg0.sw_if_index, - self.pg0.remote_hosts[1].mac, - self.pg0.remote_hosts[1].ip6) + nd1 = VppNeighbor( + self, + self.pg0.sw_if_index, + self.pg0.remote_hosts[1].mac, + self.pg0.remote_hosts[1].ip6, + ) nd1.add_vpp_config() - nd2 = VppNeighbor(self, - self.pg0.sw_if_index, - self.pg0.remote_hosts[2].mac, - self.pg0.remote_hosts[2].ip6) + nd2 = VppNeighbor( + self, + self.pg0.sw_if_index, + self.pg0.remote_hosts[2].mac, + self.pg0.remote_hosts[2].ip6, + ) nd2.add_vpp_config() - p1 = (Ether(dst=self.pg1.local_mac, - src=self.pg1.remote_mac) / - IPv6(src=self.pg1.remote_ip6, - dst=self.pg0.remote_hosts[1].ip6) / - UDP(sport=1234, dport=1234) / - Raw()) - p2 = (Ether(dst=self.pg1.local_mac, - src=self.pg1.remote_mac) / - IPv6(src=self.pg1.remote_ip6, - dst=self.pg0.remote_hosts[2].ip6) / - UDP(sport=1234, dport=1234) / - Raw()) + p1 = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(src=self.pg1.remote_ip6, dst=self.pg0.remote_hosts[1].ip6) + / UDP(sport=1234, dport=1234) + / Raw() + ) + p2 = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(src=self.pg1.remote_ip6, dst=self.pg0.remote_hosts[2].ip6) + / UDP(sport=1234, dport=1234) + / Raw() + ) rx = self.send_and_expect(self.pg1, p1 * 16, self.pg0) rx = self.send_and_expect(self.pg1, p2 * 16, self.pg0) - self.assertEqual(16, nd1.get_stats()['packets']) - self.assertEqual(16, nd2.get_stats()['packets']) + self.assertEqual(16, nd1.get_stats()["packets"]) + self.assertEqual(16, nd2.get_stats()["packets"]) rx = self.send_and_expect(self.pg1, p1 * NUM_PKTS, self.pg0) - self.assertEqual(NUM_PKTS+16, nd1.get_stats()['packets']) + self.assertEqual(NUM_PKTS + 16, nd1.get_stats()["packets"]) class NeighborAgeTestCase(VppTestCase): - """ ARP/ND Aging """ + """ARP/ND Aging""" @classmethod def setUpClass(cls): @@ -2016,10 +2211,10 @@ class NeighborAgeTestCase(VppTestCase): self.assertEqual(arp.pdst, dip) def test_age(self): - """ Aging/Recycle """ + """Aging/Recycle""" self.vapi.cli("set logging unthrottle 0") - self.vapi.cli("set logging size %d" % 0xffff) + self.vapi.cli("set logging size %d" % 0xFFFF) self.pg0.generate_remote_hosts(201) @@ -2036,56 +2231,59 @@ class NeighborAgeTestCase(VppTestCase): # age = 0 seconds # recycle = false # - self.vapi.ip_neighbor_config(af=vaf.ADDRESS_IP4, - max_number=200, - max_age=0, - recycle=False) + self.vapi.ip_neighbor_config( + af=vaf.ADDRESS_IP4, max_number=200, max_age=0, recycle=False + ) self.vapi.cli("sh ip neighbor-config") # add the 198 neighbours that should pass (-1 for one created in setup) for ii in range(200): - VppNeighbor(self, - self.pg0.sw_if_index, - self.pg0.remote_hosts[ii].mac, - self.pg0.remote_hosts[ii].ip4).add_vpp_config() + VppNeighbor( + self, + self.pg0.sw_if_index, + self.pg0.remote_hosts[ii].mac, + self.pg0.remote_hosts[ii].ip4, + ).add_vpp_config() # one more neighbor over the limit should fail with self.vapi.assert_negative_api_retval(): - VppNeighbor(self, - self.pg0.sw_if_index, - self.pg0.remote_hosts[200].mac, - self.pg0.remote_hosts[200].ip4).add_vpp_config() + VppNeighbor( + self, + self.pg0.sw_if_index, + self.pg0.remote_hosts[200].mac, + self.pg0.remote_hosts[200].ip4, + ).add_vpp_config() # # change the config to allow recycling the old neighbors # - self.vapi.ip_neighbor_config(af=vaf.ADDRESS_IP4, - max_number=200, - max_age=0, - recycle=True) + self.vapi.ip_neighbor_config( + af=vaf.ADDRESS_IP4, max_number=200, max_age=0, recycle=True + ) # now new additions are allowed - VppNeighbor(self, - self.pg0.sw_if_index, - self.pg0.remote_hosts[200].mac, - self.pg0.remote_hosts[200].ip4).add_vpp_config() + VppNeighbor( + self, + self.pg0.sw_if_index, + self.pg0.remote_hosts[200].mac, + self.pg0.remote_hosts[200].ip4, + ).add_vpp_config() # add the first neighbor we configured has been re-used - self.assertFalse(find_nbr(self, - self.pg0.sw_if_index, - self.pg0.remote_hosts[0].ip4)) - self.assertTrue(find_nbr(self, - self.pg0.sw_if_index, - self.pg0.remote_hosts[200].ip4)) + self.assertFalse( + find_nbr(self, self.pg0.sw_if_index, self.pg0.remote_hosts[0].ip4) + ) + self.assertTrue( + find_nbr(self, self.pg0.sw_if_index, self.pg0.remote_hosts[200].ip4) + ) # # change the config to age old neighbors # - self.vapi.ip_neighbor_config(af=vaf.ADDRESS_IP4, - max_number=200, - max_age=2, - recycle=True) + self.vapi.ip_neighbor_config( + af=vaf.ADDRESS_IP4, max_number=200, max_age=2, recycle=True + ) self.vapi.cli("sh ip4 neighbor-sorted") @@ -2099,7 +2297,7 @@ class NeighborAgeTestCase(VppTestCase): for ii in range(3): for jj in range(200): - rx = rxs[ii*200 + jj] + rx = rxs[ii * 200 + jj] # rx.show() # @@ -2108,8 +2306,9 @@ class NeighborAgeTestCase(VppTestCase): # self.virtual_sleep(1) - self.assertFalse(self.vapi.ip_neighbor_dump(sw_if_index=0xffffffff, - af=vaf.ADDRESS_IP4)) + self.assertFalse( + self.vapi.ip_neighbor_dump(sw_if_index=0xFFFFFFFF, af=vaf.ADDRESS_IP4) + ) # # load up some neighbours again with 2s aging enabled @@ -2120,28 +2319,27 @@ class NeighborAgeTestCase(VppTestCase): self.vapi.want_ip_neighbor_events_v2(enable=1) for ii in range(10): - VppNeighbor(self, - self.pg0.sw_if_index, - self.pg0.remote_hosts[ii].mac, - self.pg0.remote_hosts[ii].ip4).add_vpp_config() + VppNeighbor( + self, + self.pg0.sw_if_index, + self.pg0.remote_hosts[ii].mac, + self.pg0.remote_hosts[ii].ip4, + ).add_vpp_config() e = self.vapi.wait_for_event(1, "ip_neighbor_event_v2") - self.assertEqual(e.flags, - enum.IP_NEIGHBOR_API_EVENT_FLAG_ADDED) - self.assertEqual(str(e.neighbor.ip_address), - self.pg0.remote_hosts[ii].ip4) - self.assertEqual(e.neighbor.mac_address, - self.pg0.remote_hosts[ii].mac) + self.assertEqual(e.flags, enum.IP_NEIGHBOR_API_EVENT_FLAG_ADDED) + self.assertEqual(str(e.neighbor.ip_address), self.pg0.remote_hosts[ii].ip4) + self.assertEqual(e.neighbor.mac_address, self.pg0.remote_hosts[ii].mac) self.virtual_sleep(10) - self.assertFalse(self.vapi.ip_neighbor_dump(sw_if_index=0xffffffff, - af=vaf.ADDRESS_IP4)) + self.assertFalse( + self.vapi.ip_neighbor_dump(sw_if_index=0xFFFFFFFF, af=vaf.ADDRESS_IP4) + ) evs = [] for ii in range(10): e = self.vapi.wait_for_event(1, "ip_neighbor_event_v2") - self.assertEqual(e.flags, - enum.IP_NEIGHBOR_API_EVENT_FLAG_REMOVED) + self.assertEqual(e.flags, enum.IP_NEIGHBOR_API_EVENT_FLAG_REMOVED) evs.append(e) # check we got the correct mac/ip pairs - done separately @@ -2153,8 +2351,7 @@ class NeighborAgeTestCase(VppTestCase): ip = self.pg0.remote_hosts[ii].ip4 for e in evs: - if (e.neighbor.mac_address == mac and - str(e.neighbor.ip_address) == ip): + if e.neighbor.mac_address == mac and str(e.neighbor.ip_address) == ip: found = True break self.assertTrue(found) @@ -2162,33 +2359,33 @@ class NeighborAgeTestCase(VppTestCase): # # check if we can set age and recycle with empty neighbor list # - self.vapi.ip_neighbor_config(af=vaf.ADDRESS_IP4, - max_number=200, - max_age=1000, - recycle=True) + self.vapi.ip_neighbor_config( + af=vaf.ADDRESS_IP4, max_number=200, max_age=1000, recycle=True + ) # # load up some neighbours again, then disable the aging # they should still be there in 10 seconds time # for ii in range(10): - VppNeighbor(self, - self.pg0.sw_if_index, - self.pg0.remote_hosts[ii].mac, - self.pg0.remote_hosts[ii].ip4).add_vpp_config() - self.vapi.ip_neighbor_config(af=vaf.ADDRESS_IP4, - max_number=200, - max_age=0, - recycle=False) + VppNeighbor( + self, + self.pg0.sw_if_index, + self.pg0.remote_hosts[ii].mac, + self.pg0.remote_hosts[ii].ip4, + ).add_vpp_config() + self.vapi.ip_neighbor_config( + af=vaf.ADDRESS_IP4, max_number=200, max_age=0, recycle=False + ) self.virtual_sleep(10) - self.assertTrue(find_nbr(self, - self.pg0.sw_if_index, - self.pg0.remote_hosts[0].ip4)) + self.assertTrue( + find_nbr(self, self.pg0.sw_if_index, self.pg0.remote_hosts[0].ip4) + ) class NeighborReplaceTestCase(VppTestCase): - """ ARP/ND Replacement """ + """ARP/ND Replacement""" @classmethod def setUpClass(cls): @@ -2222,7 +2419,7 @@ class NeighborReplaceTestCase(VppTestCase): i.admin_down() def test_replace(self): - """ replace """ + """replace""" N_HOSTS = 16 @@ -2237,26 +2434,24 @@ class NeighborReplaceTestCase(VppTestCase): for i in self.pg_interfaces: for h in range(N_HOSTS): - self.assertFalse(find_nbr(self, - self.pg0.sw_if_index, - self.pg0.remote_hosts[h].ip4)) - self.assertFalse(find_nbr(self, - self.pg0.sw_if_index, - self.pg0.remote_hosts[h].ip6)) + self.assertFalse( + find_nbr(self, self.pg0.sw_if_index, self.pg0.remote_hosts[h].ip4) + ) + self.assertFalse( + find_nbr(self, self.pg0.sw_if_index, self.pg0.remote_hosts[h].ip6) + ) # # and them all back via the API # for i in self.pg_interfaces: for h in range(N_HOSTS): - VppNeighbor(self, - i.sw_if_index, - i.remote_hosts[h].mac, - i.remote_hosts[h].ip4).add_vpp_config() - VppNeighbor(self, - i.sw_if_index, - i.remote_hosts[h].mac, - i.remote_hosts[h].ip6).add_vpp_config() + VppNeighbor( + self, i.sw_if_index, i.remote_hosts[h].mac, i.remote_hosts[h].ip4 + ).add_vpp_config() + VppNeighbor( + self, i.sw_if_index, i.remote_hosts[h].mac, i.remote_hosts[h].ip6 + ).add_vpp_config() # # begin the replacement again, this time touch some @@ -2266,14 +2461,18 @@ class NeighborReplaceTestCase(VppTestCase): # update from the API all neighbours on pg1 for h in range(N_HOSTS): - VppNeighbor(self, - self.pg1.sw_if_index, - self.pg1.remote_hosts[h].mac, - self.pg1.remote_hosts[h].ip4).add_vpp_config() - VppNeighbor(self, - self.pg1.sw_if_index, - self.pg1.remote_hosts[h].mac, - self.pg1.remote_hosts[h].ip6).add_vpp_config() + VppNeighbor( + self, + self.pg1.sw_if_index, + self.pg1.remote_hosts[h].mac, + self.pg1.remote_hosts[h].ip4, + ).add_vpp_config() + VppNeighbor( + self, + self.pg1.sw_if_index, + self.pg1.remote_hosts[h].mac, + self.pg1.remote_hosts[h].ip6, + ).add_vpp_config() # update from the data-plane all neighbours on pg3 self.pg3.configure_ipv4_neighbors() @@ -2287,25 +2486,25 @@ class NeighborReplaceTestCase(VppTestCase): if i == self.pg1 or i == self.pg3: # neighbours on pg1 and pg3 are still present for h in range(N_HOSTS): - self.assertTrue(find_nbr(self, - i.sw_if_index, - i.remote_hosts[h].ip4)) - self.assertTrue(find_nbr(self, - i.sw_if_index, - i.remote_hosts[h].ip6)) + self.assertTrue( + find_nbr(self, i.sw_if_index, i.remote_hosts[h].ip4) + ) + self.assertTrue( + find_nbr(self, i.sw_if_index, i.remote_hosts[h].ip6) + ) else: # all other neighbours are toast for h in range(N_HOSTS): - self.assertFalse(find_nbr(self, - i.sw_if_index, - i.remote_hosts[h].ip4)) - self.assertFalse(find_nbr(self, - i.sw_if_index, - i.remote_hosts[h].ip6)) + self.assertFalse( + find_nbr(self, i.sw_if_index, i.remote_hosts[h].ip4) + ) + self.assertFalse( + find_nbr(self, i.sw_if_index, i.remote_hosts[h].ip6) + ) class NeighborFlush(VppTestCase): - """ Neighbor Flush """ + """Neighbor Flush""" @classmethod def setUpClass(cls): @@ -2336,7 +2535,7 @@ class NeighborFlush(VppTestCase): i.admin_down() def test_flush(self): - """ Neighbour Flush """ + """Neighbour Flush""" e = VppEnum nf = e.vl_api_ip_neighbor_flags_t @@ -2349,72 +2548,88 @@ class NeighborFlush(VppTestCase): for s in static: # a few v4 and v6 dynamic neoghbors for n in range(N_HOSTS): - VppNeighbor(self, - self.pg0.sw_if_index, - self.pg0.remote_hosts[n].mac, - self.pg0.remote_hosts[n].ip4, - is_static=s).add_vpp_config() - VppNeighbor(self, - self.pg1.sw_if_index, - self.pg1.remote_hosts[n].mac, - self.pg1.remote_hosts[n].ip6, - is_static=s).add_vpp_config() + VppNeighbor( + self, + self.pg0.sw_if_index, + self.pg0.remote_hosts[n].mac, + self.pg0.remote_hosts[n].ip4, + is_static=s, + ).add_vpp_config() + VppNeighbor( + self, + self.pg1.sw_if_index, + self.pg1.remote_hosts[n].mac, + self.pg1.remote_hosts[n].ip6, + is_static=s, + ).add_vpp_config() # flush the interfaces individually self.vapi.ip_neighbor_flush(af.ADDRESS_IP4, self.pg0.sw_if_index) # check we haven't flushed that which we shouldn't for n in range(N_HOSTS): - self.assertTrue(find_nbr(self, - self.pg1.sw_if_index, - self.pg1.remote_hosts[n].ip6, - is_static=s)) + self.assertTrue( + find_nbr( + self, + self.pg1.sw_if_index, + self.pg1.remote_hosts[n].ip6, + is_static=s, + ) + ) self.vapi.ip_neighbor_flush(af.ADDRESS_IP6, self.pg1.sw_if_index) for n in range(N_HOSTS): - self.assertFalse(find_nbr(self, - self.pg0.sw_if_index, - self.pg0.remote_hosts[n].ip4)) - self.assertFalse(find_nbr(self, - self.pg1.sw_if_index, - self.pg1.remote_hosts[n].ip6)) + self.assertFalse( + find_nbr(self, self.pg0.sw_if_index, self.pg0.remote_hosts[n].ip4) + ) + self.assertFalse( + find_nbr(self, self.pg1.sw_if_index, self.pg1.remote_hosts[n].ip6) + ) # add the nieghbours back for n in range(N_HOSTS): - VppNeighbor(self, - self.pg0.sw_if_index, - self.pg0.remote_hosts[n].mac, - self.pg0.remote_hosts[n].ip4, - is_static=s).add_vpp_config() - VppNeighbor(self, - self.pg1.sw_if_index, - self.pg1.remote_hosts[n].mac, - self.pg1.remote_hosts[n].ip6, - is_static=s).add_vpp_config() + VppNeighbor( + self, + self.pg0.sw_if_index, + self.pg0.remote_hosts[n].mac, + self.pg0.remote_hosts[n].ip4, + is_static=s, + ).add_vpp_config() + VppNeighbor( + self, + self.pg1.sw_if_index, + self.pg1.remote_hosts[n].mac, + self.pg1.remote_hosts[n].ip6, + is_static=s, + ).add_vpp_config() self.logger.info(self.vapi.cli("sh ip neighbor")) # flush both interfaces at the same time - self.vapi.ip_neighbor_flush(af.ADDRESS_IP6, 0xffffffff) + self.vapi.ip_neighbor_flush(af.ADDRESS_IP6, 0xFFFFFFFF) # check we haven't flushed that which we shouldn't for n in range(N_HOSTS): - self.assertTrue(find_nbr(self, - self.pg0.sw_if_index, - self.pg0.remote_hosts[n].ip4, - is_static=s)) + self.assertTrue( + find_nbr( + self, + self.pg0.sw_if_index, + self.pg0.remote_hosts[n].ip4, + is_static=s, + ) + ) - self.vapi.ip_neighbor_flush(af.ADDRESS_IP4, 0xffffffff) + self.vapi.ip_neighbor_flush(af.ADDRESS_IP4, 0xFFFFFFFF) for n in range(N_HOSTS): - self.assertFalse(find_nbr(self, - self.pg0.sw_if_index, - self.pg0.remote_hosts[n].ip4)) - self.assertFalse(find_nbr(self, - self.pg1.sw_if_index, - self.pg1.remote_hosts[n].ip6)) + self.assertFalse( + find_nbr(self, self.pg0.sw_if_index, self.pg0.remote_hosts[n].ip4) + ) + self.assertFalse( + find_nbr(self, self.pg1.sw_if_index, self.pg1.remote_hosts[n].ip6) + ) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_node_variants.py b/test/test_node_variants.py index 3632910e3cb..a5c9137f9ba 100644 --- a/test/test_node_variants.py +++ b/test/test_node_variants.py @@ -13,15 +13,14 @@ def skipVariant(variant): with open("/proc/cpuinfo") as f: cpuinfo = f.read() - exp = re.compile( - r'(?:flags\s+:)(?:\s\w+)+(?:\s(' + variant + r'))(?:\s\w+)+') + exp = re.compile(r"(?:flags\s+:)(?:\s\w+)+(?:\s(" + variant + r"))(?:\s\w+)+") match = exp.search(cpuinfo, re.DOTALL | re.MULTILINE) return checkX86() and match is not None class TestNodeVariant(VppTestCase): - """ Test Node Variants """ + """Test Node Variants""" @classmethod def setUpConstants(cls, variant): @@ -30,9 +29,10 @@ class TestNodeVariant(VppTestCase): if checkX86(): node_variants = cls.vpp_cmdline.index("node { ") + 1 - cls.vpp_cmdline[node_variants] = ("default { variant default } " - "ip4-rewrite { variant " + - variant + " } ") + cls.vpp_cmdline[node_variants] = ( + "default { variant default } " + "ip4-rewrite { variant " + variant + " } " + ) @classmethod def setUpClass(cls): @@ -52,13 +52,14 @@ class TestNodeVariant(VppTestCase): node_desc = self.vapi.cli("show node " + node) self.logger.info(node_desc) - match = re.search(r'\s+(\S+)\s+(\d+)\s+(:?yes)', - node_desc, re.DOTALL | re.MULTILINE) + match = re.search( + r"\s+(\S+)\s+(\d+)\s+(:?yes)", node_desc, re.DOTALL | re.MULTILINE + ) return match.groups(0) def checkVariant(self, variant): - """ Test node variants defaults """ + """Test node variants defaults""" variant_info = self.getActiveVariant("ip4-lookup") self.assertEqual(variant_info[0], "default") @@ -68,7 +69,7 @@ class TestNodeVariant(VppTestCase): class TestICLVariant(TestNodeVariant): - """ Test icl Node Variants """ + """Test icl Node Variants""" VARIANT = "icl" LINUX_VARIANT = "avx512_bitalg" @@ -85,14 +86,15 @@ class TestICLVariant(TestNodeVariant): def tearDownClass(cls): super(TestICLVariant, cls).tearDownClass() - @unittest.skipUnless(skipVariant(LINUX_VARIANT), - VARIANT + " not a supported variant, skip.") + @unittest.skipUnless( + skipVariant(LINUX_VARIANT), VARIANT + " not a supported variant, skip." + ) def test_icl(self): self.checkVariant(self.VARIANT) class TestSKXVariant(TestNodeVariant): - """ Test skx Node Variants """ + """Test skx Node Variants""" VARIANT = "skx" LINUX_VARIANT = "avx512f" @@ -109,14 +111,15 @@ class TestSKXVariant(TestNodeVariant): def tearDownClass(cls): super(TestSKXVariant, cls).tearDownClass() - @unittest.skipUnless(skipVariant(LINUX_VARIANT), - VARIANT + " not a supported variant, skip.") + @unittest.skipUnless( + skipVariant(LINUX_VARIANT), VARIANT + " not a supported variant, skip." + ) def test_skx(self): self.checkVariant(self.VARIANT) class TestHSWVariant(TestNodeVariant): - """ Test avx2 Node Variants """ + """Test avx2 Node Variants""" VARIANT = "hsw" LINUX_VARIANT = "avx2" @@ -133,7 +136,8 @@ class TestHSWVariant(TestNodeVariant): def tearDownClass(cls): super(TestHSWVariant, cls).tearDownClass() - @unittest.skipUnless(skipVariant(LINUX_VARIANT), - VARIANT + " not a supported variant, skip.") + @unittest.skipUnless( + skipVariant(LINUX_VARIANT), VARIANT + " not a supported variant, skip." + ) def test_hsw(self): self.checkVariant(self.VARIANT) diff --git a/test/test_offload.py b/test/test_offload.py index ae5a5b3c6dc..d84f8ba63c0 100644 --- a/test/test_offload.py +++ b/test/test_offload.py @@ -7,7 +7,7 @@ from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath class TestOffload(VppTestCase): - """ Offload Unit Test Cases """ + """Offload Unit Test Cases""" @classmethod def setUpClass(cls): @@ -24,52 +24,55 @@ class TestOffload(VppTestCase): super(TestOffload, self).tearDown() def test_offload_unittest(self): - """ Checksum Offload Test """ - cmds = ["loop create", - "set int ip address loop0 11.22.33.1/24", - "set int state loop0 up", - "loop create", - "set int ip address loop1 11.22.34.1/24", - "set int state loop1 up", - "set ip neighbor loop1 11.22.34.44 03:00:11:22:34:44", - "packet-generator new {\n" - " name s0\n" - " limit 100\n" - " size 128-128\n" - " interface loop0\n" - " tx-interface loop1\n" - " node loop1-output\n" - " buffer-flags ip4 offload\n" - " buffer-offload-flags offload-ip-cksum offload-udp-cksum\n" - " data {\n" - " IP4: 1.2.3 -> dead.0000.0001\n" - " UDP: 11.22.33.44 -> 11.22.34.44\n" - " ttl 2 checksum 13\n" - " UDP: 1234 -> 2345\n" - " checksum 11\n" - " incrementing 114\n" - " }\n" - "}", - "trace add pg-input 1", - "pa en", - "show error"] + """Checksum Offload Test""" + cmds = [ + "loop create", + "set int ip address loop0 11.22.33.1/24", + "set int state loop0 up", + "loop create", + "set int ip address loop1 11.22.34.1/24", + "set int state loop1 up", + "set ip neighbor loop1 11.22.34.44 03:00:11:22:34:44", + "packet-generator new {\n" + " name s0\n" + " limit 100\n" + " size 128-128\n" + " interface loop0\n" + " tx-interface loop1\n" + " node loop1-output\n" + " buffer-flags ip4 offload\n" + " buffer-offload-flags offload-ip-cksum offload-udp-cksum\n" + " data {\n" + " IP4: 1.2.3 -> dead.0000.0001\n" + " UDP: 11.22.33.44 -> 11.22.34.44\n" + " ttl 2 checksum 13\n" + " UDP: 1234 -> 2345\n" + " checksum 11\n" + " incrementing 114\n" + " }\n" + "}", + "trace add pg-input 1", + "pa en", + "show error", + ] for cmd in cmds: r = self.vapi.cli_return_response(cmd) if r.retval != 0: - if hasattr(r, 'reply'): + if hasattr(r, "reply"): self.logger.info(cmd + " FAIL reply " + r.reply) else: self.logger.info(cmd + " FAIL retval " + str(r.retval)) r = self.vapi.cli_return_response("show trace") self.assertTrue(r.retval == 0) - self.assertTrue(hasattr(r, 'reply')) + self.assertTrue(hasattr(r, "reply")) rv = r.reply - look_here = rv.find('ethernet-input') + look_here = rv.find("ethernet-input") self.assertFalse(look_here == -1) - bad_checksum_index = rv[look_here:].find('should be') + bad_checksum_index = rv[look_here:].find("should be") self.assertTrue(bad_checksum_index == -1) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_p2p_ethernet.py b/test/test_p2p_ethernet.py index fb55a365bee..97cd7b4f0bd 100644 --- a/test/test_p2p_ethernet.py +++ b/test/test_p2p_ethernet.py @@ -41,8 +41,7 @@ class P2PEthernetAPI(VppTestCase): self.p2p_sub_ifs.append(p2p) def delete_p2p_ethernet(self, parent_if, remote_mac): - self.vapi.p2p_ethernet_del(parent_if.sw_if_index, - mac_pton(remote_mac)) + self.vapi.p2p_ethernet_del(parent_if.sw_if_index, mac_pton(remote_mac)) def test_api(self): """delete/create p2p subif""" @@ -52,22 +51,22 @@ class P2PEthernetAPI(VppTestCase): self.create_p2p_ethernet(self.pg0, 2, "de:ad:00:00:00:02") intfs = self.vapi.cli("show interface") - self.assertIn('pg0.1', intfs) - self.assertIn('pg0.2', intfs) - self.assertNotIn('pg0.5', intfs) + self.assertIn("pg0.1", intfs) + self.assertIn("pg0.2", intfs) + self.assertNotIn("pg0.5", intfs) # create pg2.5 subif self.create_p2p_ethernet(self.pg0, 5, "de:ad:00:00:00:ff") intfs = self.vapi.cli("show interface") - self.assertIn('pg0.5', intfs) + self.assertIn("pg0.5", intfs) # delete pg2.5 subif self.delete_p2p_ethernet(self.pg0, "de:ad:00:00:00:ff") intfs = self.vapi.cli("show interface") - self.assertIn('pg0.1', intfs) - self.assertIn('pg0.2', intfs) - self.assertNotIn('pg0.5', intfs) + self.assertIn("pg0.1", intfs) + self.assertIn("pg0.2", intfs) + self.assertNotIn("pg0.5", intfs) self.logger.info("FFP_TEST_FINISH_0000") @@ -79,22 +78,20 @@ class P2PEthernetAPI(VppTestCase): clients = 1000 mac = int("dead00000000", 16) - for i in range(1, clients+1): + for i in range(1, clients + 1): try: - macs.append(':'.join(re.findall('..', '{:02x}'.format( - mac+i)))) - self.vapi.p2p_ethernet_add(self.pg2.sw_if_index, - mac_pton(macs[i-1]), - i) + macs.append(":".join(re.findall("..", "{:02x}".format(mac + i)))) + self.vapi.p2p_ethernet_add( + self.pg2.sw_if_index, mac_pton(macs[i - 1]), i + ) except Exception: - self.logger.info("Failed to create subif %d %s" % ( - i, macs[i-1])) + self.logger.info("Failed to create subif %d %s" % (i, macs[i - 1])) raise intfs = self.vapi.cli("show interface").split("\n") count = 0 for intf in intfs: - if intf.startswith('pg2.'): + if intf.startswith("pg2."): count += 1 self.assertEqual(count, clients) @@ -138,11 +135,11 @@ class P2PEthernetIPV6(VppTestCase): for p in self.packets: self.packets.remove(p) self.p2p_sub_ifs.append( - self.create_p2p_ethernet(self.pg0, 1, - self.pg0._remote_hosts[0].mac)) + self.create_p2p_ethernet(self.pg0, 1, self.pg0._remote_hosts[0].mac) + ) self.p2p_sub_ifs.append( - self.create_p2p_ethernet(self.pg0, 2, - self.pg0._remote_hosts[1].mac)) + self.create_p2p_ethernet(self.pg0, 2, self.pg0._remote_hosts[1].mac) + ) self.vapi.cli("trace add p2p-ethernet-input 50") def tearDown(self): @@ -162,17 +159,17 @@ class P2PEthernetIPV6(VppTestCase): def delete_p2p_ethernet(self, p2p): p2p.unconfig_ip6() p2p.admin_down() - self.vapi.p2p_ethernet_del(p2p.parent.sw_if_index, - p2p.p2p_remote_mac) + self.vapi.p2p_ethernet_del(p2p.parent.sw_if_index, p2p.p2p_remote_mac) - def create_stream(self, src_mac=None, dst_mac=None, - src_ip=None, dst_ip=None, size=None): + def create_stream( + self, src_mac=None, dst_mac=None, src_ip=None, dst_ip=None, size=None + ): pkt_size = size if size is None: pkt_size = random.choice(self.pg_if_packet_sizes) p = Ether(src=src_mac, dst=dst_mac) p /= IPv6(src=src_ip, dst=dst_ip) - p /= (UDP(sport=1234, dport=4321) / Raw(b'\xa5' * 20)) + p /= UDP(sport=1234, dport=4321) / Raw(b"\xa5" * 20) self.extend_packet(p, pkt_size) return p @@ -191,16 +188,22 @@ class P2PEthernetIPV6(VppTestCase): self.logger.info("FFP_TEST_START_0001") self.pg0.config_ip6() - route_8000 = VppIpRoute(self, "8000::", 64, - [VppRoutePath(self.pg0.remote_ip6, - self.pg0.sw_if_index)]) + route_8000 = VppIpRoute( + self, + "8000::", + 64, + [VppRoutePath(self.pg0.remote_ip6, self.pg0.sw_if_index)], + ) route_8000.add_vpp_config() - self.packets = [(Ether(dst=self.pg1.local_mac, - src=self.pg1.remote_mac) / - IPv6(src="3001::1", dst="8000::100") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100))] + self.packets = [ + ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(src="3001::1", dst="8000::100") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + ] self.send_packets(self.pg1, self.pg0) self.pg0.unconfig_ip6() @@ -210,19 +213,25 @@ class P2PEthernetIPV6(VppTestCase): """receive ipv6 packet via p2p subinterface""" self.logger.info("FFP_TEST_START_0002") - route_9001 = VppIpRoute(self, "9001::", 64, - [VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index)]) + route_9001 = VppIpRoute( + self, + "9001::", + 64, + [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)], + ) route_9001.add_vpp_config() self.packets.append( - self.create_stream(src_mac=self.pg0._remote_hosts[0].mac, - dst_mac=self.pg0.local_mac, - src_ip=self.p2p_sub_ifs[0].remote_ip6, - dst_ip="9001::100")) + self.create_stream( + src_mac=self.pg0._remote_hosts[0].mac, + dst_mac=self.pg0.local_mac, + src_ip=self.p2p_sub_ifs[0].remote_ip6, + dst_ip="9001::100", + ) + ) self.send_packets(self.pg0, self.pg1, self.packets) - self.assert_packet_counter_equal('p2p-ethernet-input', 1) + self.assert_packet_counter_equal("p2p-ethernet-input", 1) route_9001.remove_vpp_config() self.logger.info("FFP_TEST_FINISH_0002") @@ -233,16 +242,22 @@ class P2PEthernetIPV6(VppTestCase): self.pg0.config_ip6() - route_3 = VppIpRoute(self, "9000::", 64, - [VppRoutePath(self.pg1._remote_hosts[0].ip6, - self.pg1.sw_if_index)]) + route_3 = VppIpRoute( + self, + "9000::", + 64, + [VppRoutePath(self.pg1._remote_hosts[0].ip6, self.pg1.sw_if_index)], + ) route_3.add_vpp_config() self.packets.append( - self.create_stream(src_mac="02:03:00:00:ff:ff", - dst_mac=self.pg0.local_mac, - src_ip="a000::100", - dst_ip="9000::100")) + self.create_stream( + src_mac="02:03:00:00:ff:ff", + dst_mac=self.pg0.local_mac, + src_ip="a000::100", + dst_ip="9000::100", + ) + ) self.send_packets(self.pg0, self.pg1) @@ -256,16 +271,22 @@ class P2PEthernetIPV6(VppTestCase): """drop rx packet not matching p2p subinterface""" self.logger.info("FFP_TEST_START_0004") - route_9001 = VppIpRoute(self, "9000::", 64, - [VppRoutePath(self.pg1._remote_hosts[0].ip6, - self.pg1.sw_if_index)]) + route_9001 = VppIpRoute( + self, + "9000::", + 64, + [VppRoutePath(self.pg1._remote_hosts[0].ip6, self.pg1.sw_if_index)], + ) route_9001.add_vpp_config() self.packets.append( - self.create_stream(src_mac="02:03:00:00:ff:ff", - dst_mac=self.pg0.local_mac, - src_ip="a000::100", - dst_ip="9000::100")) + self.create_stream( + src_mac="02:03:00:00:ff:ff", + dst_mac=self.pg0.local_mac, + src_ip="a000::100", + dst_ip="9000::100", + ) + ) # no packet received self.send_packets(self.pg0, self.pg1, count=0) @@ -277,27 +298,45 @@ class P2PEthernetIPV6(VppTestCase): self.pg0.config_ip6() - route_8000 = VppIpRoute(self, "8000::", 64, - [VppRoutePath(self.pg0.remote_hosts[0].ip6, - self.pg0.sw_if_index)]) + route_8000 = VppIpRoute( + self, + "8000::", + 64, + [VppRoutePath(self.pg0.remote_hosts[0].ip6, self.pg0.sw_if_index)], + ) route_8000.add_vpp_config() - route_8001 = VppIpRoute(self, "8001::", 64, - [VppRoutePath( - self.p2p_sub_ifs[0].remote_ip6, - self.p2p_sub_ifs[0].sw_if_index)]) + route_8001 = VppIpRoute( + self, + "8001::", + 64, + [ + VppRoutePath( + self.p2p_sub_ifs[0].remote_ip6, self.p2p_sub_ifs[0].sw_if_index + ) + ], + ) route_8001.add_vpp_config() - route_8002 = VppIpRoute(self, "8002::", 64, - [VppRoutePath( - self.p2p_sub_ifs[1].remote_ip6, - self.p2p_sub_ifs[1].sw_if_index)]) + route_8002 = VppIpRoute( + self, + "8002::", + 64, + [ + VppRoutePath( + self.p2p_sub_ifs[1].remote_ip6, self.p2p_sub_ifs[1].sw_if_index + ) + ], + ) route_8002.add_vpp_config() for i in range(0, 3): self.packets.append( - self.create_stream(src_mac=self.pg1.remote_mac, - dst_mac=self.pg1.local_mac, - src_ip=self.pg1.remote_ip6, - dst_ip="800%d::100" % i)) + self.create_stream( + src_mac=self.pg1.remote_mac, + dst_mac=self.pg1.local_mac, + src_ip=self.pg1.remote_ip6, + dst_ip="800%d::100" % i, + ) + ) self.send_packets(self.pg1, self.pg0, count=3) @@ -313,10 +352,13 @@ class P2PEthernetIPV6(VppTestCase): self.logger.info("FFP_TEST_START_0006") self.packets.append( - self.create_stream(src_mac="02:03:00:00:ff:ff", - dst_mac=self.pg0.local_mac, - src_ip="a000::100", - dst_ip="9000::100")) + self.create_stream( + src_mac="02:03:00:00:ff:ff", + dst_mac=self.pg0.local_mac, + src_ip="a000::100", + dst_ip="9000::100", + ) + ) # no packet received self.send_packets(self.pg0, self.pg1, count=0) @@ -360,11 +402,11 @@ class P2PEthernetIPV4(VppTestCase): for p in self.packets: self.packets.remove(p) self.p2p_sub_ifs.append( - self.create_p2p_ethernet(self.pg0, 1, - self.pg0._remote_hosts[0].mac)) + self.create_p2p_ethernet(self.pg0, 1, self.pg0._remote_hosts[0].mac) + ) self.p2p_sub_ifs.append( - self.create_p2p_ethernet(self.pg0, 2, - self.pg0._remote_hosts[1].mac)) + self.create_p2p_ethernet(self.pg0, 2, self.pg0._remote_hosts[1].mac) + ) self.vapi.cli("trace add p2p-ethernet-input 50") def tearDown(self): @@ -373,14 +415,15 @@ class P2PEthernetIPV4(VppTestCase): self.delete_p2p_ethernet(p2p) super(P2PEthernetIPV4, self).tearDown() - def create_stream(self, src_mac=None, dst_mac=None, - src_ip=None, dst_ip=None, size=None): + def create_stream( + self, src_mac=None, dst_mac=None, src_ip=None, dst_ip=None, size=None + ): pkt_size = size if size is None: pkt_size = random.choice(self.pg_if_packet_sizes) p = Ether(src=src_mac, dst=dst_mac) p /= IP(src=src_ip, dst=dst_ip) - p /= (UDP(sport=1234, dport=4321) / Raw(b'\xa5' * 20)) + p /= UDP(sport=1234, dport=4321) / Raw(b"\xa5" * 20) self.extend_packet(p, pkt_size) return p @@ -403,27 +446,32 @@ class P2PEthernetIPV4(VppTestCase): def delete_p2p_ethernet(self, p2p): p2p.unconfig_ip4() p2p.admin_down() - self.vapi.p2p_ethernet_del(p2p.parent.sw_if_index, - p2p.p2p_remote_mac) + self.vapi.p2p_ethernet_del(p2p.parent.sw_if_index, p2p.p2p_remote_mac) def test_ip4_rx_p2p_subif(self): """receive ipv4 packet via p2p subinterface""" self.logger.info("FFP_TEST_START_0002") - route_9000 = VppIpRoute(self, "9.0.0.0", 16, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index)]) + route_9000 = VppIpRoute( + self, + "9.0.0.0", + 16, + [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)], + ) route_9000.add_vpp_config() self.packets.append( - self.create_stream(src_mac=self.pg0._remote_hosts[0].mac, - dst_mac=self.pg0.local_mac, - src_ip=self.p2p_sub_ifs[0].remote_ip4, - dst_ip="9.0.0.100")) + self.create_stream( + src_mac=self.pg0._remote_hosts[0].mac, + dst_mac=self.pg0.local_mac, + src_ip=self.p2p_sub_ifs[0].remote_ip4, + dst_ip="9.0.0.100", + ) + ) self.send_packets(self.pg0, self.pg1, self.packets) - self.assert_packet_counter_equal('p2p-ethernet-input', 1) + self.assert_packet_counter_equal("p2p-ethernet-input", 1) route_9000.remove_vpp_config() self.logger.info("FFP_TEST_FINISH_0002") @@ -432,16 +480,22 @@ class P2PEthernetIPV4(VppTestCase): """route rx packet not matching p2p subinterface""" self.logger.info("FFP_TEST_START_0003") - route_9001 = VppIpRoute(self, "9.0.0.0", 24, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index)]) + route_9001 = VppIpRoute( + self, + "9.0.0.0", + 24, + [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)], + ) route_9001.add_vpp_config() self.packets.append( - self.create_stream(src_mac="02:01:00:00:ff:ff", - dst_mac=self.pg0.local_mac, - src_ip="8.0.0.100", - dst_ip="9.0.0.100")) + self.create_stream( + src_mac="02:01:00:00:ff:ff", + dst_mac=self.pg0.local_mac, + src_ip="8.0.0.100", + dst_ip="9.0.0.100", + ) + ) self.send_packets(self.pg0, self.pg1) @@ -453,28 +507,51 @@ class P2PEthernetIPV4(VppTestCase): """send ip4 packet via p2p subinterface""" self.logger.info("FFP_TEST_START_0005") - route_9100 = VppIpRoute(self, "9.1.0.100", 24, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index, - )]) + route_9100 = VppIpRoute( + self, + "9.1.0.100", + 24, + [ + VppRoutePath( + self.pg0.remote_ip4, + self.pg0.sw_if_index, + ) + ], + ) route_9100.add_vpp_config() - route_9200 = VppIpRoute(self, "9.2.0.100", 24, - [VppRoutePath(self.p2p_sub_ifs[0].remote_ip4, - self.p2p_sub_ifs[0].sw_if_index, - )]) + route_9200 = VppIpRoute( + self, + "9.2.0.100", + 24, + [ + VppRoutePath( + self.p2p_sub_ifs[0].remote_ip4, + self.p2p_sub_ifs[0].sw_if_index, + ) + ], + ) route_9200.add_vpp_config() - route_9300 = VppIpRoute(self, "9.3.0.100", 24, - [VppRoutePath(self.p2p_sub_ifs[1].remote_ip4, - self.p2p_sub_ifs[1].sw_if_index - )]) + route_9300 = VppIpRoute( + self, + "9.3.0.100", + 24, + [ + VppRoutePath( + self.p2p_sub_ifs[1].remote_ip4, self.p2p_sub_ifs[1].sw_if_index + ) + ], + ) route_9300.add_vpp_config() for i in range(0, 3): self.packets.append( - self.create_stream(src_mac=self.pg1.remote_mac, - dst_mac=self.pg1.local_mac, - src_ip=self.pg1.remote_ip4, - dst_ip="9.%d.0.100" % (i+1))) + self.create_stream( + src_mac=self.pg1.remote_mac, + dst_mac=self.pg1.local_mac, + src_ip=self.pg1.remote_ip4, + dst_ip="9.%d.0.100" % (i + 1), + ) + ) self.send_packets(self.pg1, self.pg0) @@ -490,15 +567,18 @@ class P2PEthernetIPV4(VppTestCase): self.logger.info("FFP_TEST_START_0006") self.packets.append( - self.create_stream(src_mac="02:01:00:00:ff:ff", - dst_mac=self.pg0.local_mac, - src_ip="8.0.0.100", - dst_ip="9.0.0.100")) + self.create_stream( + src_mac="02:01:00:00:ff:ff", + dst_mac=self.pg0.local_mac, + src_ip="8.0.0.100", + dst_ip="9.0.0.100", + ) + ) # no packet received self.send_packets(self.pg0, self.pg1, count=0) self.logger.info("FFP_TEST_FINISH_0006") -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_pcap.py b/test/test_pcap.py index 5bfac523e43..7405d2e5153 100644 --- a/test/test_pcap.py +++ b/test/test_pcap.py @@ -8,7 +8,7 @@ from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath class TestPcap(VppTestCase): - """ Pcap Unit Test Cases """ + """Pcap Unit Test Cases""" @classmethod def setUpClass(cls): @@ -24,67 +24,68 @@ class TestPcap(VppTestCase): def tearDown(self): super(TestPcap, self).tearDown() -# This is a code coverage test, but it only runs for 0.3 seconds -# might as well just run it... + # This is a code coverage test, but it only runs for 0.3 seconds + # might as well just run it... def test_pcap_unittest(self): - """ PCAP Capture Tests """ - cmds = ["loop create", - "set int ip address loop0 11.22.33.1/24", - "set int state loop0 up", - "loop create", - "set int ip address loop1 11.22.34.1/24", - "set int state loop1 up", - "set ip neighbor loop1 11.22.34.44 03:00:11:22:34:44", - "packet-generator new {\n" - " name s0\n" - " limit 10\n" - " size 128-128\n" - " interface loop0\n" - " tx-interface loop1\n" - " node loop1-output\n" - " buffer-flags ip4 offload\n" - " buffer-offload-flags offload-ip-cksum offload-udp-cksum\n" - " data {\n" - " IP4: 1.2.3 -> dead.0000.0001\n" - " UDP: 11.22.33.44 -> 11.22.34.44\n" - " ttl 2 checksum 13\n" - " UDP: 1234 -> 2345\n" - " checksum 11\n" - " incrementing 114\n" - " }\n" - "}", - "pcap dispatch trace on max 100 buffer-trace pg-input 10", - "pa en", - "pcap dispatch trace off", - "pcap trace rx tx max 1000 intfc any", - "pa en", - "pcap trace status", - "pcap trace rx tx off", - "classify filter pcap mask l3 ip4 src " - "match l3 ip4 src 11.22.33.44", - "pcap trace rx tx max 1000 intfc any file filt.pcap filter", - "show cla t verbose 2", - "show cla t verbose", - "show cla t", - "pa en", - "pcap trace rx tx off", - "classify filter pcap del mask l3 ip4 src"] + """PCAP Capture Tests""" + cmds = [ + "loop create", + "set int ip address loop0 11.22.33.1/24", + "set int state loop0 up", + "loop create", + "set int ip address loop1 11.22.34.1/24", + "set int state loop1 up", + "set ip neighbor loop1 11.22.34.44 03:00:11:22:34:44", + "packet-generator new {\n" + " name s0\n" + " limit 10\n" + " size 128-128\n" + " interface loop0\n" + " tx-interface loop1\n" + " node loop1-output\n" + " buffer-flags ip4 offload\n" + " buffer-offload-flags offload-ip-cksum offload-udp-cksum\n" + " data {\n" + " IP4: 1.2.3 -> dead.0000.0001\n" + " UDP: 11.22.33.44 -> 11.22.34.44\n" + " ttl 2 checksum 13\n" + " UDP: 1234 -> 2345\n" + " checksum 11\n" + " incrementing 114\n" + " }\n" + "}", + "pcap dispatch trace on max 100 buffer-trace pg-input 10", + "pa en", + "pcap dispatch trace off", + "pcap trace rx tx max 1000 intfc any", + "pa en", + "pcap trace status", + "pcap trace rx tx off", + "classify filter pcap mask l3 ip4 src match l3 ip4 src 11.22.33.44", + "pcap trace rx tx max 1000 intfc any file filt.pcap filter", + "show cla t verbose 2", + "show cla t verbose", + "show cla t", + "pa en", + "pcap trace rx tx off", + "classify filter pcap del mask l3 ip4 src", + ] for cmd in cmds: r = self.vapi.cli_return_response(cmd) if r.retval != 0: - if hasattr(r, 'reply'): + if hasattr(r, "reply"): self.logger.info(cmd + " FAIL reply " + r.reply) else: self.logger.info(cmd + " FAIL retval " + str(r.retval)) - self.assertTrue(os.path.exists('/tmp/dispatch.pcap')) - self.assertTrue(os.path.exists('/tmp/rxtx.pcap')) - self.assertTrue(os.path.exists('/tmp/filt.pcap')) - os.remove('/tmp/dispatch.pcap') - os.remove('/tmp/rxtx.pcap') - os.remove('/tmp/filt.pcap') + self.assertTrue(os.path.exists("/tmp/dispatch.pcap")) + self.assertTrue(os.path.exists("/tmp/rxtx.pcap")) + self.assertTrue(os.path.exists("/tmp/filt.pcap")) + os.remove("/tmp/dispatch.pcap") + os.remove("/tmp/rxtx.pcap") + os.remove("/tmp/filt.pcap") -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_pg.py b/test/test_pg.py index 76b7fd7f1d9..f2a23e55f23 100644 --- a/test/test_pg.py +++ b/test/test_pg.py @@ -12,7 +12,7 @@ from framework import VppTestCase, VppTestRunner class TestPgTun(VppTestCase): - """ PG Test Case """ + """PG Test Case""" def setUp(self): super(TestPgTun, self).setUp() @@ -41,7 +41,7 @@ class TestPgTun(VppTestCase): super(TestPgTun, self).tearDown() def test_pg_tun(self): - """ IP[46] Tunnel Mode PG """ + """IP[46] Tunnel Mode PG""" # # test that we can send and receive IP encap'd packets on the @@ -50,9 +50,11 @@ class TestPgTun(VppTestCase): N_PKTS = 31 # v4 tun to ethernet - p = (IP(src=self.pg1.remote_ip4, dst=self.pg0.remote_ip4) / - UDP(sport=1234, dport=1234) / - Raw('0' * 48)) + p = ( + IP(src=self.pg1.remote_ip4, dst=self.pg0.remote_ip4) + / UDP(sport=1234, dport=1234) + / Raw("0" * 48) + ) rxs = self.send_and_expect(self.pg1, p * N_PKTS, self.pg0) for rx in rxs: @@ -60,9 +62,11 @@ class TestPgTun(VppTestCase): self.assertEqual(rx[IP].dst, self.pg0.remote_ip4) # v6 tun to ethernet - p = (IPv6(src=self.pg2.remote_ip6, dst=self.pg0.remote_ip6) / - UDP(sport=1234, dport=1234) / - Raw('0' * 48)) + p = ( + IPv6(src=self.pg2.remote_ip6, dst=self.pg0.remote_ip6) + / UDP(sport=1234, dport=1234) + / Raw("0" * 48) + ) rxs = self.send_and_expect(self.pg2, p * N_PKTS, self.pg0) for rx in rxs: @@ -70,10 +74,12 @@ class TestPgTun(VppTestCase): self.assertEqual(rx[IPv6].dst, self.pg0.remote_ip6) # eth to v4 tun - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - UDP(sport=1234, dport=1234) / - Raw('0' * 48)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / UDP(sport=1234, dport=1234) + / Raw("0" * 48) + ) rxs = self.send_and_expect(self.pg0, p * N_PKTS, self.pg1) for rx in rxs: @@ -82,10 +88,12 @@ class TestPgTun(VppTestCase): self.assertEqual(rx[IP].dst, self.pg1.remote_ip4) # eth to v6 tun - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg2.remote_ip6) / - UDP(sport=1234, dport=1234) / - Raw('0' * 48)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg2.remote_ip6) + / UDP(sport=1234, dport=1234) + / Raw("0" * 48) + ) rxs = self.send_and_expect(self.pg0, p * N_PKTS, self.pg2) for rx in rxs: @@ -94,5 +102,5 @@ class TestPgTun(VppTestCase): self.assertEqual(rx[IPv6].dst, self.pg2.remote_ip6) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_ping.py b/test/test_ping.py index 8c5c087b0c5..c2eb8b75299 100644 --- a/test/test_ping.py +++ b/test/test_ping.py @@ -18,7 +18,7 @@ Basic test for sanity check of the ping. class TestPing(VppTestCase): - """ Ping Test Case """ + """Ping Test Case""" @classmethod def setUpClass(cls): @@ -64,7 +64,7 @@ class TestPing(VppTestCase): return icmp def test_ping_basic(self): - """ basic ping test """ + """basic ping test""" try: self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -79,8 +79,9 @@ class TestPing(VppTestCase): icmp_id = None icmp_seq = 1 for p in out: - icmp = self.verify_ping_request(p, self.pg1.local_ip4, - self.pg1.remote_ip4, icmp_seq) + icmp = self.verify_ping_request( + p, self.pg1.local_ip4, self.pg1.remote_ip4, icmp_seq + ) icmp_seq = icmp_seq + 1 if icmp_id is None: icmp_id = icmp.id @@ -90,7 +91,7 @@ class TestPing(VppTestCase): self.vapi.cli("show error") def test_ping_burst(self): - """ burst ping test """ + """burst ping test""" try: self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -100,13 +101,14 @@ class TestPing(VppTestCase): ping_cmd = "ping " + remote_ip4 + " interval 0.01 burst 3" ret = self.vapi.cli(ping_cmd) self.logger.info(ret) - out = self.pg1.get_capture(3*5) + out = self.pg1.get_capture(3 * 5) icmp_id = None icmp_seq = 1 count = 0 for p in out: - icmp = self.verify_ping_request(p, self.pg1.local_ip4, - self.pg1.remote_ip4, icmp_seq) + icmp = self.verify_ping_request( + p, self.pg1.local_ip4, self.pg1.remote_ip4, icmp_seq + ) count = count + 1 if count >= 3: icmp_seq = icmp_seq + 1 @@ -119,7 +121,7 @@ class TestPing(VppTestCase): self.vapi.cli("show error") def test_ping_src(self): - """ ping with source address set """ + """ping with source address set""" self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -128,17 +130,18 @@ class TestPing(VppTestCase): nbr_addr = "10.0.0.2" VppIpInterfaceAddress(self, self.pg1, "10.0.0.1", 24).add_vpp_config() - VppNeighbor(self, self.pg1.sw_if_index, - "00:11:22:33:44:55", - nbr_addr).add_vpp_config() + VppNeighbor( + self, self.pg1.sw_if_index, "00:11:22:33:44:55", nbr_addr + ).add_vpp_config() ping_cmd = "ping %s interval 0.01 repeat 3" % self.pg1.remote_ip4 ret = self.vapi.cli(ping_cmd) out = self.pg1.get_capture(3) icmp_seq = 1 for p in out: - icmp = self.verify_ping_request(p, self.pg1.local_ip4, - self.pg1.remote_ip4, icmp_seq) + icmp = self.verify_ping_request( + p, self.pg1.local_ip4, self.pg1.remote_ip4, icmp_seq + ) icmp_seq = icmp_seq + 1 self.pg_enable_capture(self.pg_interfaces) @@ -152,7 +155,7 @@ class TestPing(VppTestCase): icmp_seq = icmp_seq + 1 def test_ping_fib_routed_dst(self): - """ ping destination routed according to FIB table """ + """ping destination routed according to FIB table""" try: self.pg1.generate_remote_hosts(1) @@ -160,17 +163,19 @@ class TestPing(VppTestCase): self.pg_start() routed_dst = "10.0.2.0" self.logger.info(self.vapi.cli("show ip4 neighbors")) - VppIpRoute(self, routed_dst, 24, - [VppRoutePath(self.pg1.remote_hosts[0].ip4, - self.pg1.sw_if_index)]).add_vpp_config() + VppIpRoute( + self, + routed_dst, + 24, + [VppRoutePath(self.pg1.remote_hosts[0].ip4, self.pg1.sw_if_index)], + ).add_vpp_config() ping_cmd = "ping %s interval 0.01 repeat 3" % routed_dst ret = self.vapi.cli(ping_cmd) self.logger.info(ret) out = self.pg1.get_capture(3) icmp_seq = 1 for p in out: - self.verify_ping_request(p, self.pg1.local_ip4, routed_dst, - icmp_seq) + self.verify_ping_request(p, self.pg1.local_ip4, routed_dst, icmp_seq) icmp_seq = icmp_seq + 1 finally: self.vapi.cli("show error") diff --git a/test/test_pipe.py b/test/test_pipe.py index 937a28ef826..30540997ff6 100644 --- a/test/test_pipe.py +++ b/test/test_pipe.py @@ -28,20 +28,19 @@ class VppPipe(VppInterface): def west(self): return self.result.pipe_sw_if_index[0] - def __init__(self, test, instance=0xffffffff): + def __init__(self, test, instance=0xFFFFFFFF): super(VppPipe, self).__init__(test) self._test = test self.instance = instance def add_vpp_config(self): self.result = self._test.vapi.pipe_create( - 0 if self.instance == 0xffffffff else 1, - self.instance) + 0 if self.instance == 0xFFFFFFFF else 1, self.instance + ) self.set_sw_if_index(self.result.sw_if_index) def remove_vpp_config(self): - self._test.vapi.pipe_delete( - self.result.sw_if_index) + self._test.vapi.pipe_delete(self.result.sw_if_index) def object_id(self): return "pipe-%d" % (self._sw_if_index) @@ -56,14 +55,16 @@ class VppPipe(VppInterface): def set_unnumbered(self, ip_sw_if_index, is_east, is_add=True): if is_east: res = self._test.vapi.sw_interface_set_unnumbered( - ip_sw_if_index, self.east, is_add) + ip_sw_if_index, self.east, is_add + ) else: res = self._test.vapi.sw_interface_set_unnumbered( - ip_sw_if_index, self.west, is_add) + ip_sw_if_index, self.west, is_add + ) class TestPipe(VppTestCase): - """ Pipes """ + """Pipes""" @classmethod def setUpClass(cls): @@ -88,7 +89,7 @@ class TestPipe(VppTestCase): super(TestPipe, self).tearDown() def test_pipe(self): - """ Pipes """ + """Pipes""" pipes = [VppPipe(self), VppPipe(self, 10)] @@ -99,26 +100,26 @@ class TestPipe(VppTestCase): # # L2 cross-connect pipe0 east with pg0 and west with pg1 # - self.vapi.sw_interface_set_l2_xconnect(self.pg0.sw_if_index, - pipes[0].east, - enable=1) - self.vapi.sw_interface_set_l2_xconnect(pipes[0].east, - self.pg0.sw_if_index, - enable=1) - self.vapi.sw_interface_set_l2_xconnect(self.pg1.sw_if_index, - pipes[0].west, - enable=1) - self.vapi.sw_interface_set_l2_xconnect(pipes[0].west, - self.pg1.sw_if_index, - enable=1) + self.vapi.sw_interface_set_l2_xconnect( + self.pg0.sw_if_index, pipes[0].east, enable=1 + ) + self.vapi.sw_interface_set_l2_xconnect( + pipes[0].east, self.pg0.sw_if_index, enable=1 + ) + self.vapi.sw_interface_set_l2_xconnect( + self.pg1.sw_if_index, pipes[0].west, enable=1 + ) + self.vapi.sw_interface_set_l2_xconnect( + pipes[0].west, self.pg1.sw_if_index, enable=1 + ) # test bi-directional L2 flow pg0<->pg1 - p = (Ether(src=self.pg0.remote_mac, - dst=self.pg1.remote_mac) / - IP(src="1.1.1.1", - dst="1.1.1.2") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg1.remote_mac) + / IP(src="1.1.1.1", dst="1.1.1.2") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) self.send_and_expect(self.pg0, p * NUM_PKTS, self.pg1) self.send_and_expect(self.pg1, p * NUM_PKTS, self.pg0) @@ -126,15 +127,20 @@ class TestPipe(VppTestCase): # # Attach ACL to ensure features are run on the pipe # - rule_1 = AclRule(is_permit=0, proto=17, - src_prefix=IPv4Network("1.1.1.1/32"), - dst_prefix=IPv4Network("1.1.1.2/32"), ports=1234) + rule_1 = AclRule( + is_permit=0, + proto=17, + src_prefix=IPv4Network("1.1.1.1/32"), + dst_prefix=IPv4Network("1.1.1.2/32"), + ports=1234, + ) acl = VppAcl(self, rules=[rule_1]) acl.add_vpp_config() # Apply the ACL on the pipe on output - acl_if_e = VppAclInterface(self, sw_if_index=pipes[0].east, n_input=0, - acls=[acl]) + acl_if_e = VppAclInterface( + self, sw_if_index=pipes[0].east, n_input=0, acls=[acl] + ) acl_if_e.add_vpp_config() self.send_and_assert_no_replies(self.pg0, p * NUM_PKTS) @@ -142,8 +148,9 @@ class TestPipe(VppTestCase): # remove from output and apply on input acl_if_e.remove_vpp_config() - acl_if_w = VppAclInterface(self, sw_if_index=pipes[0].west, n_input=1, - acls=[acl]) + acl_if_w = VppAclInterface( + self, sw_if_index=pipes[0].west, n_input=1, acls=[acl] + ) acl_if_w.add_vpp_config() self.send_and_assert_no_replies(self.pg0, p * NUM_PKTS) @@ -172,30 +179,52 @@ class TestPipe(VppTestCase): self.pg3.resolve_arp() routes = [] - routes.append(VppIpRoute(self, "1.1.1.1", 32, - [VppRoutePath(self.pg3.remote_ip4, - self.pg3.sw_if_index)], - table_id=2)) - routes.append(VppIpRoute(self, "1.1.1.1", 32, - [VppRoutePath("0.0.0.0", pipes[1].east)], - table_id=1)) - routes.append(VppIpRoute(self, "1.1.1.2", 32, - [VppRoutePath("0.0.0.0", pipes[1].west)], - table_id=2)) - routes.append(VppIpRoute(self, "1.1.1.2", 32, - [VppRoutePath(self.pg2.remote_ip4, - self.pg2.sw_if_index)], - table_id=1)) + routes.append( + VppIpRoute( + self, + "1.1.1.1", + 32, + [VppRoutePath(self.pg3.remote_ip4, self.pg3.sw_if_index)], + table_id=2, + ) + ) + routes.append( + VppIpRoute( + self, + "1.1.1.1", + 32, + [VppRoutePath("0.0.0.0", pipes[1].east)], + table_id=1, + ) + ) + routes.append( + VppIpRoute( + self, + "1.1.1.2", + 32, + [VppRoutePath("0.0.0.0", pipes[1].west)], + table_id=2, + ) + ) + routes.append( + VppIpRoute( + self, + "1.1.1.2", + 32, + [VppRoutePath(self.pg2.remote_ip4, self.pg2.sw_if_index)], + table_id=1, + ) + ) for r in routes: r.add_vpp_config() - p_east = (Ether(src=self.pg2.remote_mac, - dst=self.pg2.local_mac) / - IP(src="1.1.1.2", - dst="1.1.1.1") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p_east = ( + Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) + / IP(src="1.1.1.2", dst="1.1.1.1") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) # bind the pipe ends to the correct tables self.vapi.sw_interface_set_table(pipes[1].west, 0, 2) @@ -211,27 +240,29 @@ class TestPipe(VppTestCase): self.send_and_expect(self.pg2, p_east * NUM_PKTS, self.pg3) # and the return path - p_west = (Ether(src=self.pg3.remote_mac, - dst=self.pg3.local_mac) / - IP(src="1.1.1.1", - dst="1.1.1.2") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p_west = ( + Ether(src=self.pg3.remote_mac, dst=self.pg3.local_mac) + / IP(src="1.1.1.1", dst="1.1.1.2") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) self.send_and_expect(self.pg3, p_west * NUM_PKTS, self.pg2) # # Use ACLs to test features run on the Pipes # - acl_if_e1 = VppAclInterface(self, sw_if_index=pipes[1].east, n_input=0, - acls=[acl]) + acl_if_e1 = VppAclInterface( + self, sw_if_index=pipes[1].east, n_input=0, acls=[acl] + ) acl_if_e1.add_vpp_config() self.send_and_assert_no_replies(self.pg2, p_east * NUM_PKTS) self.send_and_expect(self.pg3, p_west * NUM_PKTS, self.pg2) # remove from output and apply on input acl_if_e1.remove_vpp_config() - acl_if_w1 = VppAclInterface(self, sw_if_index=pipes[1].west, n_input=1, - acls=[acl]) + acl_if_w1 = VppAclInterface( + self, sw_if_index=pipes[1].west, n_input=1, acls=[acl] + ) acl_if_w1.add_vpp_config() self.send_and_assert_no_replies(self.pg2, p_east * NUM_PKTS) self.send_and_expect(self.pg3, p_west * NUM_PKTS, self.pg2) @@ -249,5 +280,5 @@ class TestPipe(VppTestCase): self.vapi.sw_interface_set_table(pipes[1].east, 0, 0) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_pnat.py b/test/test_pnat.py index d5b60050691..faf66e6ed53 100644 --- a/test/test_pnat.py +++ b/test/test_pnat.py @@ -8,7 +8,8 @@ from vpp_papi import VppEnum class TestPNAT(VppTestCase): - """ PNAT Test Case """ + """PNAT Test Case""" + maxDiff = None @classmethod @@ -42,147 +43,187 @@ class TestPNAT(VppTestCase): self.assertEqual(rx, expected) def ping_check(self): - """ Verify non matching traffic works. """ + """Verify non matching traffic works.""" p_ether = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) - icmpecho = (IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / - ICMP()) - reply = (IP(src=self.pg0.local_ip4, dst=self.pg0.remote_ip4) / - ICMP(type='echo-reply')) - rx = self.send_and_expect(self.pg0, p_ether/icmpecho * 1, self.pg0) + icmpecho = IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / ICMP() + reply = IP(src=self.pg0.local_ip4, dst=self.pg0.remote_ip4) / ICMP( + type="echo-reply" + ) + rx = self.send_and_expect(self.pg0, p_ether / icmpecho * 1, self.pg0) for p in rx: reply[IP].id = p[IP].id self.validate(p[1], reply) def test_pnat(self): - """ PNAT test """ + """PNAT test""" PNAT_IP4_INPUT = VppEnum.vl_api_pnat_attachment_point_t.PNAT_IP4_INPUT - PNAT_IP4_OUTPUT = \ - VppEnum.vl_api_pnat_attachment_point_t.PNAT_IP4_OUTPUT + PNAT_IP4_OUTPUT = VppEnum.vl_api_pnat_attachment_point_t.PNAT_IP4_OUTPUT tests = [ { - 'input': PNAT_IP4_INPUT, - 'sw_if_index': self.pg0.sw_if_index, - 'match': {'mask': 0xa, 'dst': '10.10.10.10', 'proto': 17, - 'dport': 6871}, - 'rewrite': {'mask': 0x2, 'dst': self.pg1.remote_ip4}, - 'send': (IP(src=self.pg0.remote_ip4, dst='10.10.10.10') / - UDP(dport=6871)), - 'reply': (IP(src=self.pg0.remote_ip4, - dst=self.pg1.remote_ip4) / - UDP(dport=6871)) + "input": PNAT_IP4_INPUT, + "sw_if_index": self.pg0.sw_if_index, + "match": { + "mask": 0xA, + "dst": "10.10.10.10", + "proto": 17, + "dport": 6871, + }, + "rewrite": {"mask": 0x2, "dst": self.pg1.remote_ip4}, + "send": ( + IP(src=self.pg0.remote_ip4, dst="10.10.10.10") / UDP(dport=6871) + ), + "reply": ( + IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / UDP(dport=6871) + ), }, { - 'input': PNAT_IP4_OUTPUT, - 'sw_if_index': self.pg1.sw_if_index, - 'match': {'mask': 0x9, 'src': self.pg0.remote_ip4, 'proto': 17, - 'dport': 6871}, - 'rewrite': {'mask': 0x1, 'src': '11.11.11.11'}, - 'send': (IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - UDP(dport=6871)), - 'reply': (IP(src='11.11.11.11', dst=self.pg1.remote_ip4) / - UDP(dport=6871)) + "input": PNAT_IP4_OUTPUT, + "sw_if_index": self.pg1.sw_if_index, + "match": { + "mask": 0x9, + "src": self.pg0.remote_ip4, + "proto": 17, + "dport": 6871, + }, + "rewrite": {"mask": 0x1, "src": "11.11.11.11"}, + "send": ( + IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / UDP(dport=6871) + ), + "reply": ( + IP(src="11.11.11.11", dst=self.pg1.remote_ip4) / UDP(dport=6871) + ), }, { - 'input': PNAT_IP4_INPUT, - 'sw_if_index': self.pg0.sw_if_index, - 'match': {'mask': 0xa, 'dst': '10.10.10.10', 'proto': 17, - 'dport': 6871}, - 'rewrite': {'mask': 0xa, 'dst': self.pg1.remote_ip4, - 'dport': 5555}, - 'send': (IP(src=self.pg0.remote_ip4, dst='10.10.10.10') / - UDP(sport=65530, dport=6871)), - 'reply': (IP(src=self.pg0.remote_ip4, - dst=self.pg1.remote_ip4) / - UDP(sport=65530, dport=5555)) + "input": PNAT_IP4_INPUT, + "sw_if_index": self.pg0.sw_if_index, + "match": { + "mask": 0xA, + "dst": "10.10.10.10", + "proto": 17, + "dport": 6871, + }, + "rewrite": {"mask": 0xA, "dst": self.pg1.remote_ip4, "dport": 5555}, + "send": ( + IP(src=self.pg0.remote_ip4, dst="10.10.10.10") + / UDP(sport=65530, dport=6871) + ), + "reply": ( + IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / UDP(sport=65530, dport=5555) + ), }, { - 'input': PNAT_IP4_INPUT, - 'sw_if_index': self.pg0.sw_if_index, - 'match': {'mask': 0xa, 'dst': self.pg1.remote_ip4, 'proto': 17, - 'dport': 6871}, - 'rewrite': {'mask': 0x8, 'dport': 5555}, - 'send': (IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - UDP(dport=6871, chksum=0)), - 'reply': (IP(src=self.pg0.remote_ip4, - dst=self.pg1.remote_ip4) / - UDP(dport=5555, chksum=0)) + "input": PNAT_IP4_INPUT, + "sw_if_index": self.pg0.sw_if_index, + "match": { + "mask": 0xA, + "dst": self.pg1.remote_ip4, + "proto": 17, + "dport": 6871, + }, + "rewrite": {"mask": 0x8, "dport": 5555}, + "send": ( + IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / UDP(dport=6871, chksum=0) + ), + "reply": ( + IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / UDP(dport=5555, chksum=0) + ), }, { - 'input': PNAT_IP4_INPUT, - 'sw_if_index': self.pg0.sw_if_index, - 'match': {'mask': 0x2, 'dst': self.pg1.remote_ip4, 'proto': 1}, - 'rewrite': {'mask': 0x1, 'src': '8.8.8.8'}, - 'send': (IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - ICMP()), - 'reply': IP(src='8.8.8.8', dst=self.pg1.remote_ip4)/ICMP(), + "input": PNAT_IP4_INPUT, + "sw_if_index": self.pg0.sw_if_index, + "match": {"mask": 0x2, "dst": self.pg1.remote_ip4, "proto": 1}, + "rewrite": {"mask": 0x1, "src": "8.8.8.8"}, + "send": (IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / ICMP()), + "reply": IP(src="8.8.8.8", dst=self.pg1.remote_ip4) / ICMP(), }, ] p_ether = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) for t in tests: - rv = self.vapi.pnat_binding_add(match=t['match'], - rewrite=t['rewrite']) - self.vapi.pnat_binding_attach(sw_if_index=t['sw_if_index'], - attachment=t['input'], - binding_index=rv.binding_index) - - reply = t['reply'] + rv = self.vapi.pnat_binding_add(match=t["match"], rewrite=t["rewrite"]) + self.vapi.pnat_binding_attach( + sw_if_index=t["sw_if_index"], + attachment=t["input"], + binding_index=rv.binding_index, + ) + + reply = t["reply"] reply[IP].ttl -= 1 - rx = self.send_and_expect(self.pg0, p_ether/t['send']*1, self.pg1) + rx = self.send_and_expect(self.pg0, p_ether / t["send"] * 1, self.pg1) for p in rx: # p.show2() self.validate(p[1], reply) self.ping_check() - self.vapi.pnat_binding_detach(sw_if_index=t['sw_if_index'], - attachment=t['input'], - binding_index=rv.binding_index) + self.vapi.pnat_binding_detach( + sw_if_index=t["sw_if_index"], + attachment=t["input"], + binding_index=rv.binding_index, + ) self.vapi.pnat_binding_del(binding_index=rv.binding_index) def test_pnat_show(self): - """ PNAT show tests """ + """PNAT show tests""" PNAT_IP4_INPUT = VppEnum.vl_api_pnat_attachment_point_t.PNAT_IP4_INPUT - PNAT_IP4_OUTPUT = \ - VppEnum.vl_api_pnat_attachment_point_t.PNAT_IP4_OUTPUT + PNAT_IP4_OUTPUT = VppEnum.vl_api_pnat_attachment_point_t.PNAT_IP4_OUTPUT tests = [ { - 'input': PNAT_IP4_INPUT, - 'sw_if_index': self.pg0.sw_if_index, - 'match': {'mask': 0xa, 'dst': '10.10.10.10', 'proto': 17, - 'dport': 6871}, - 'rewrite': {'mask': 0x2, 'dst': self.pg1.remote_ip4}, - 'send': (IP(src=self.pg0.remote_ip4, dst='10.10.10.10') / - UDP(dport=6871)), - 'reply': (IP(src=self.pg0.remote_ip4, - dst=self.pg1.remote_ip4) / - UDP(dport=6871)) + "input": PNAT_IP4_INPUT, + "sw_if_index": self.pg0.sw_if_index, + "match": { + "mask": 0xA, + "dst": "10.10.10.10", + "proto": 17, + "dport": 6871, + }, + "rewrite": {"mask": 0x2, "dst": self.pg1.remote_ip4}, + "send": ( + IP(src=self.pg0.remote_ip4, dst="10.10.10.10") / UDP(dport=6871) + ), + "reply": ( + IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / UDP(dport=6871) + ), }, { - 'input': PNAT_IP4_OUTPUT, - 'sw_if_index': self.pg1.sw_if_index, - 'match': {'mask': 0x9, 'src': self.pg0.remote_ip4, 'proto': 17, - 'dport': 6871}, - 'rewrite': {'mask': 0x1, 'src': '11.11.11.11'}, - 'send': (IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - UDP(dport=6871)), - 'reply': (IP(src='11.11.11.11', dst=self.pg1.remote_ip4) / - UDP(dport=6871)) + "input": PNAT_IP4_OUTPUT, + "sw_if_index": self.pg1.sw_if_index, + "match": { + "mask": 0x9, + "src": self.pg0.remote_ip4, + "proto": 17, + "dport": 6871, + }, + "rewrite": {"mask": 0x1, "src": "11.11.11.11"}, + "send": ( + IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / UDP(dport=6871) + ), + "reply": ( + IP(src="11.11.11.11", dst=self.pg1.remote_ip4) / UDP(dport=6871) + ), }, ] binding_index = [] for t in tests: - rv = self.vapi.pnat_binding_add(match=t['match'], - rewrite=t['rewrite']) + rv = self.vapi.pnat_binding_add(match=t["match"], rewrite=t["rewrite"]) binding_index.append(rv.binding_index) - self.vapi.pnat_binding_attach(sw_if_index=t['sw_if_index'], - attachment=t['input'], - binding_index=rv.binding_index) + self.vapi.pnat_binding_attach( + sw_if_index=t["sw_if_index"], + attachment=t["input"], + binding_index=rv.binding_index, + ) rv, l = self.vapi.pnat_bindings_get() self.assertEqual(len(l), len(tests)) @@ -194,10 +235,13 @@ class TestPNAT(VppTestCase): self.logger.info(self.vapi.cli("show pnat interfaces")) for i, t in enumerate(tests): - self.vapi.pnat_binding_detach(sw_if_index=t['sw_if_index'], - attachment=t['input'], - binding_index=binding_index[i]) + self.vapi.pnat_binding_detach( + sw_if_index=t["sw_if_index"], + attachment=t["input"], + binding_index=binding_index[i], + ) self.vapi.pnat_binding_del(binding_index=binding_index[i]) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_policer.py b/test/test_policer.py index 6b15a0234a3..01ee2b750bc 100644 --- a/test/test_policer.py +++ b/test/test_policer.py @@ -9,42 +9,53 @@ from vpp_policer import VppPolicer, PolicerAction # Default for the tests is 10s of "Green" packets at 8Mbps, ie. 10M bytes. # The policer helper CLI "sends" 500 byte packets, so default is 20000. -TEST_RATE = 8000 # kbps +TEST_RATE = 8000 # kbps TEST_BURST = 10000 # ms -CIR_OK = 8500 # CIR in kbps, above test rate -CIR_LOW = 7000 # CIR in kbps, below test rate -EIR_OK = 9000 # EIR in kbps, above test rate -EIR_LOW = 7500 # EIR in kbps, below test rate +CIR_OK = 8500 # CIR in kbps, above test rate +CIR_LOW = 7000 # CIR in kbps, below test rate +EIR_OK = 9000 # EIR in kbps, above test rate +EIR_LOW = 7500 # EIR in kbps, below test rate NUM_PKTS = 20000 -CBURST = 100000 # Committed burst in bytes -EBURST = 200000 # Excess burst in bytes +CBURST = 100000 # Committed burst in bytes +EBURST = 200000 # Excess burst in bytes class TestPolicer(VppTestCase): - """ Policer Test Case """ + """Policer Test Case""" - def run_policer_test(self, type, cir, cb, eir, eb, rate=8000, burst=10000, - colour=0): + def run_policer_test( + self, type, cir, cb, eir, eb, rate=8000, burst=10000, colour=0 + ): """ Configure a Policer and push traffic through it. """ types = { - '1R2C': 0, - '1R3C': 1, - '2R3C': 3, + "1R2C": 0, + "1R3C": 1, + "2R3C": 3, } pol_type = types.get(type) - policer = VppPolicer(self, "pol1", cir, eir, cb, eb, rate_type=0, - type=pol_type, color_aware=colour) + policer = VppPolicer( + self, + "pol1", + cir, + eir, + cb, + eb, + rate_type=0, + type=pol_type, + color_aware=colour, + ) policer.add_vpp_config() error = self.vapi.cli( f"test policing index {policer.policer_index} rate {rate} " - f"burst {burst} colour {colour}") + f"burst {burst} colour {colour}" + ) stats = policer.get_stats() policer.remove_vpp_config() @@ -52,66 +63,64 @@ class TestPolicer(VppTestCase): return stats def test_policer_1r2c(self): - """ Single rate, 2 colour policer """ + """Single rate, 2 colour policer""" stats = self.run_policer_test("1R2C", CIR_OK, CBURST, 0, 0) - self.assertEqual(stats['conform_packets'], NUM_PKTS) + self.assertEqual(stats["conform_packets"], NUM_PKTS) stats = self.run_policer_test("1R2C", CIR_LOW, CBURST, 0, 0) - self.assertLess(stats['conform_packets'], NUM_PKTS) - self.assertEqual(stats['exceed_packets'], 0) - self.assertGreater(stats['violate_packets'], 0) + self.assertLess(stats["conform_packets"], NUM_PKTS) + self.assertEqual(stats["exceed_packets"], 0) + self.assertGreater(stats["violate_packets"], 0) stats = self.run_policer_test("1R2C", CIR_LOW, CBURST, 0, 0, colour=2) - self.assertEqual(stats['violate_packets'], NUM_PKTS) + self.assertEqual(stats["violate_packets"], NUM_PKTS) def test_policer_1r3c(self): - """ Single rate, 3 colour policer """ + """Single rate, 3 colour policer""" stats = self.run_policer_test("1R3C", CIR_OK, CBURST, 0, 0) - self.assertEqual(stats['conform_packets'], NUM_PKTS) + self.assertEqual(stats["conform_packets"], NUM_PKTS) stats = self.run_policer_test("1R3C", CIR_LOW, CBURST, 0, EBURST) - self.assertLess(stats['conform_packets'], NUM_PKTS) - self.assertGreater(stats['exceed_packets'], 0) - self.assertGreater(stats['violate_packets'], 0) + self.assertLess(stats["conform_packets"], NUM_PKTS) + self.assertGreater(stats["exceed_packets"], 0) + self.assertGreater(stats["violate_packets"], 0) - stats = self.run_policer_test("1R3C", CIR_LOW, CBURST, 0, EBURST, - colour=1) - self.assertEqual(stats['conform_packets'], 0) - self.assertGreater(stats['exceed_packets'], 0) - self.assertGreater(stats['violate_packets'], 0) + stats = self.run_policer_test("1R3C", CIR_LOW, CBURST, 0, EBURST, colour=1) + self.assertEqual(stats["conform_packets"], 0) + self.assertGreater(stats["exceed_packets"], 0) + self.assertGreater(stats["violate_packets"], 0) - stats = self.run_policer_test("1R3C", CIR_LOW, CBURST, 0, EBURST, - colour=2) - self.assertEqual(stats['violate_packets'], NUM_PKTS) + stats = self.run_policer_test("1R3C", CIR_LOW, CBURST, 0, EBURST, colour=2) + self.assertEqual(stats["violate_packets"], NUM_PKTS) def test_policer_2r3c(self): - """ Dual rate, 3 colour policer """ + """Dual rate, 3 colour policer""" stats = self.run_policer_test("2R3C", CIR_OK, CBURST, EIR_OK, EBURST) - self.assertEqual(stats['conform_packets'], NUM_PKTS) + self.assertEqual(stats["conform_packets"], NUM_PKTS) stats = self.run_policer_test("2R3C", CIR_LOW, CBURST, EIR_OK, EBURST) - self.assertLess(stats['conform_packets'], NUM_PKTS) - self.assertGreater(stats['exceed_packets'], 0) - self.assertEqual(stats['violate_packets'], 0) + self.assertLess(stats["conform_packets"], NUM_PKTS) + self.assertGreater(stats["exceed_packets"], 0) + self.assertEqual(stats["violate_packets"], 0) stats = self.run_policer_test("2R3C", CIR_LOW, CBURST, EIR_LOW, EBURST) - self.assertLess(stats['conform_packets'], NUM_PKTS) - self.assertGreater(stats['exceed_packets'], 0) - self.assertGreater(stats['violate_packets'], 0) + self.assertLess(stats["conform_packets"], NUM_PKTS) + self.assertGreater(stats["exceed_packets"], 0) + self.assertGreater(stats["violate_packets"], 0) - stats = self.run_policer_test("2R3C", CIR_LOW, CBURST, EIR_OK, EBURST, - colour=1) - self.assertEqual(stats['exceed_packets'], NUM_PKTS) + stats = self.run_policer_test("2R3C", CIR_LOW, CBURST, EIR_OK, EBURST, colour=1) + self.assertEqual(stats["exceed_packets"], NUM_PKTS) - stats = self.run_policer_test("2R3C", CIR_LOW, CBURST, EIR_LOW, EBURST, - colour=1) - self.assertEqual(stats['conform_packets'], 0) - self.assertGreater(stats['exceed_packets'], 0) - self.assertGreater(stats['violate_packets'], 0) + stats = self.run_policer_test( + "2R3C", CIR_LOW, CBURST, EIR_LOW, EBURST, colour=1 + ) + self.assertEqual(stats["conform_packets"], 0) + self.assertGreater(stats["exceed_packets"], 0) + self.assertGreater(stats["violate_packets"], 0) - stats = self.run_policer_test("2R3C", CIR_LOW, CBURST, EIR_OK, EBURST, - colour=2) - self.assertEqual(stats['violate_packets'], NUM_PKTS) + stats = self.run_policer_test("2R3C", CIR_LOW, CBURST, EIR_OK, EBURST, colour=2) + self.assertEqual(stats["violate_packets"], NUM_PKTS) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_policer_input.py b/test/test_policer_input.py index 9a4266ceb12..9d44fc1a21c 100644 --- a/test/test_policer_input.py +++ b/test/test_policer_input.py @@ -14,7 +14,8 @@ NUM_PKTS = 67 class TestPolicerInput(VppTestCase): - """ Policer on an interface """ + """Policer on an interface""" + vpp_worker_count = 2 def setUp(self): @@ -26,11 +27,12 @@ class TestPolicerInput(VppTestCase): i.config_ip4() i.resolve_arp() - self.pkt = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + self.pkt = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) def tearDown(self): for i in self.pg_interfaces: @@ -42,17 +44,22 @@ class TestPolicerInput(VppTestCase): pkts = self.pkt * NUM_PKTS action_tx = PolicerAction( - VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT, - 0) - policer = VppPolicer(self, "pol1", 80, 0, 1000, 0, - conform_action=action_tx, - exceed_action=action_tx, - violate_action=action_tx) + VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT, 0 + ) + policer = VppPolicer( + self, + "pol1", + 80, + 0, + 1000, + 0, + conform_action=action_tx, + exceed_action=action_tx, + violate_action=action_tx, + ) policer.add_vpp_config() - sw_if_index = (self.pg0.sw_if_index - if dir == Dir.RX - else self.pg1.sw_if_index) + sw_if_index = self.pg0.sw_if_index if dir == Dir.RX else self.pg1.sw_if_index # Start policing on pg0 policer.apply_vpp_config(sw_if_index, dir, True) @@ -61,9 +68,9 @@ class TestPolicerInput(VppTestCase): stats = policer.get_stats() # Single rate, 2 colour policer - expect conform, violate but no exceed - self.assertGreater(stats['conform_packets'], 0) - self.assertEqual(stats['exceed_packets'], 0) - self.assertGreater(stats['violate_packets'], 0) + self.assertGreater(stats["conform_packets"], 0) + self.assertEqual(stats["exceed_packets"], 0) + self.assertGreater(stats["violate_packets"], 0) # Stop policing on pg0 policer.apply_vpp_config(sw_if_index, dir, False) @@ -78,28 +85,33 @@ class TestPolicerInput(VppTestCase): policer.remove_vpp_config() def test_policer_input(self): - """ Input Policing """ + """Input Policing""" self.policer_interface_test(Dir.RX) def test_policer_output(self): - """ Output Policing """ + """Output Policing""" self.policer_interface_test(Dir.TX) def policer_handoff_test(self, dir: Dir): pkts = self.pkt * NUM_PKTS action_tx = PolicerAction( - VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT, - 0) - policer = VppPolicer(self, "pol2", 80, 0, 1000, 0, - conform_action=action_tx, - exceed_action=action_tx, - violate_action=action_tx) + VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT, 0 + ) + policer = VppPolicer( + self, + "pol2", + 80, + 0, + 1000, + 0, + conform_action=action_tx, + exceed_action=action_tx, + violate_action=action_tx, + ) policer.add_vpp_config() - sw_if_index = (self.pg0.sw_if_index - if dir == Dir.RX - else self.pg1.sw_if_index) + sw_if_index = self.pg0.sw_if_index if dir == Dir.RX else self.pg1.sw_if_index # Bind the policer to worker 1 policer.bind_vpp_config(1, True) @@ -119,9 +131,9 @@ class TestPolicerInput(VppTestCase): self.assertEqual(stats, stats1) # Worker 0, should have handed everything off - self.assertEqual(stats0['conform_packets'], 0) - self.assertEqual(stats0['exceed_packets'], 0) - self.assertEqual(stats0['violate_packets'], 0) + self.assertEqual(stats0["conform_packets"], 0) + self.assertEqual(stats0["exceed_packets"], 0) + self.assertEqual(stats0["violate_packets"], 0) # Unbind the policer from worker 1 and repeat policer.bind_vpp_config(1, False) @@ -137,19 +149,23 @@ class TestPolicerInput(VppTestCase): stats0 = policer.get_stats(worker=0) stats1 = policer.get_stats(worker=1) - self.assertGreater(stats0['conform_packets'], 0) - self.assertEqual(stats0['exceed_packets'], 0) - self.assertGreater(stats0['violate_packets'], 0) + self.assertGreater(stats0["conform_packets"], 0) + self.assertEqual(stats0["exceed_packets"], 0) + self.assertGreater(stats0["violate_packets"], 0) - self.assertGreater(stats1['conform_packets'], 0) - self.assertEqual(stats1['exceed_packets'], 0) - self.assertGreater(stats1['violate_packets'], 0) + self.assertGreater(stats1["conform_packets"], 0) + self.assertEqual(stats1["exceed_packets"], 0) + self.assertGreater(stats1["violate_packets"], 0) - self.assertEqual(stats0['conform_packets'] + stats1['conform_packets'], - stats['conform_packets']) + self.assertEqual( + stats0["conform_packets"] + stats1["conform_packets"], + stats["conform_packets"], + ) - self.assertEqual(stats0['violate_packets'] + stats1['violate_packets'], - stats['violate_packets']) + self.assertEqual( + stats0["violate_packets"] + stats1["violate_packets"], + stats["violate_packets"], + ) # Stop policing on pg0 policer.apply_vpp_config(sw_if_index, dir, False) @@ -157,13 +173,13 @@ class TestPolicerInput(VppTestCase): policer.remove_vpp_config() def test_policer_handoff_input(self): - """ Worker thread handoff policer input""" + """Worker thread handoff policer input""" self.policer_handoff_test(Dir.RX) def test_policer_handoff_output(self): - """ Worker thread handoff policer output""" + """Worker thread handoff policer output""" self.policer_handoff_test(Dir.TX) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_pppoe.py b/test/test_pppoe.py index 99dba01cdc9..c83d7d5f874 100644 --- a/test/test_pppoe.py +++ b/test/test_pppoe.py @@ -15,7 +15,7 @@ from util import ppp, ppc class TestPPPoE(VppTestCase): - """ PPPoE Test Case """ + """PPPoE Test Case""" @classmethod def setUpClass(cls): @@ -54,8 +54,7 @@ class TestPPPoE(VppTestCase): self.logger.info(self.vapi.cli("show ip fib")) self.logger.info(self.vapi.cli("show trace")) - def create_stream_pppoe_discovery(self, src_if, dst_if, - client_mac, count=1): + def create_stream_pppoe_discovery(self, src_if, dst_if, client_mac, count=1): packets = [] for i in range(count): # create packet info stored in the test case instance @@ -63,9 +62,11 @@ class TestPPPoE(VppTestCase): # convert the info into packet payload payload = self.info_to_payload(info) # create the packet itself - p = (Ether(dst=src_if.local_mac, src=client_mac) / - PPPoED(sessionid=0) / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=client_mac) + / PPPoED(sessionid=0) + / Raw(payload) + ) # store a copy of the packet in the packet info info.data = p.copy() # append the packet to the list @@ -74,8 +75,7 @@ class TestPPPoE(VppTestCase): # return the created packet list return packets - def create_stream_pppoe_lcp(self, src_if, dst_if, - client_mac, session_id, count=1): + def create_stream_pppoe_lcp(self, src_if, dst_if, client_mac, session_id, count=1): packets = [] for i in range(count): # create packet info stored in the test case instance @@ -83,10 +83,12 @@ class TestPPPoE(VppTestCase): # convert the info into packet payload payload = self.info_to_payload(info) # create the packet itself - p = (Ether(dst=src_if.local_mac, src=client_mac) / - PPPoE(sessionid=session_id) / - PPP(proto=0xc021) / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=client_mac) + / PPPoE(sessionid=session_id) + / PPP(proto=0xC021) + / Raw(payload) + ) # store a copy of the packet in the packet info info.data = p.copy() # append the packet to the list @@ -95,8 +97,9 @@ class TestPPPoE(VppTestCase): # return the created packet list return packets - def create_stream_pppoe_ip4(self, src_if, dst_if, - client_mac, session_id, client_ip, count=1): + def create_stream_pppoe_ip4( + self, src_if, dst_if, client_mac, session_id, client_ip, count=1 + ): packets = [] for i in range(count): # create packet info stored in the test case instance @@ -104,11 +107,13 @@ class TestPPPoE(VppTestCase): # convert the info into packet payload payload = self.info_to_payload(info) # create the packet itself - p = (Ether(dst=src_if.local_mac, src=client_mac) / - PPPoE(sessionid=session_id) / - PPP(proto=0x0021) / - IP(src=client_ip, dst=self.dst_ip) / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=client_mac) + / PPPoE(sessionid=session_id) + / PPP(proto=0x0021) + / IP(src=client_ip, dst=self.dst_ip) + / Raw(payload) + ) # store a copy of the packet in the packet info info.data = p.copy() # append the packet to the list @@ -125,9 +130,11 @@ class TestPPPoE(VppTestCase): # convert the info into packet payload payload = self.info_to_payload(info) # create the packet itself - p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - IP(src=dst_ip, dst=client_ip) / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / IP(src=dst_ip, dst=client_ip) + / Raw(payload) + ) # store a copy of the packet in the packet info info.data = p.copy() # append the packet to the list @@ -180,36 +187,39 @@ class TestPPPoE(VppTestCase): raise def test_PPPoE_Decap(self): - """ PPPoE Decap Test """ + """PPPoE Decap Test""" self.vapi.cli("clear trace") # # Add a route that resolves the server's destination # - route_sever_dst = VppIpRoute(self, "100.1.1.100", 32, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index)]) + route_sever_dst = VppIpRoute( + self, + "100.1.1.100", + 32, + [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)], + ) route_sever_dst.add_vpp_config() # Send PPPoE Discovery - tx0 = self.create_stream_pppoe_discovery(self.pg0, self.pg1, - self.pg0.remote_mac) + tx0 = self.create_stream_pppoe_discovery( + self.pg0, self.pg1, self.pg0.remote_mac + ) self.pg0.add_stream(tx0) self.pg_start() # Send PPPoE PPP LCP - tx1 = self.create_stream_pppoe_lcp(self.pg0, self.pg1, - self.pg0.remote_mac, - self.session_id) + tx1 = self.create_stream_pppoe_lcp( + self.pg0, self.pg1, self.pg0.remote_mac, self.session_id + ) self.pg0.add_stream(tx1) self.pg_start() # Create PPPoE session - pppoe_if = VppPppoeInterface(self, - self.pg0.remote_ip4, - self.pg0.remote_mac, - self.session_id) + pppoe_if = VppPppoeInterface( + self, self.pg0.remote_ip4, self.pg0.remote_mac, self.session_id + ) pppoe_if.add_vpp_config() pppoe_if.set_unnumbered(self.pg0.sw_if_index) @@ -217,10 +227,13 @@ class TestPPPoE(VppTestCase): # Send tunneled packets that match the created tunnel and # are decapped and forwarded # - tx2 = self.create_stream_pppoe_ip4(self.pg0, self.pg1, - self.pg0.remote_mac, - self.session_id, - self.pg0.remote_ip4) + tx2 = self.create_stream_pppoe_ip4( + self.pg0, + self.pg1, + self.pg0.remote_mac, + self.session_id, + self.pg0.remote_ip4, + ) self.pg0.add_stream(tx2) self.pg_enable_capture(self.pg_interfaces) @@ -244,36 +257,39 @@ class TestPPPoE(VppTestCase): route_sever_dst.remove_vpp_config() def test_PPPoE_Encap(self): - """ PPPoE Encap Test """ + """PPPoE Encap Test""" self.vapi.cli("clear trace") # # Add a route that resolves the server's destination # - route_sever_dst = VppIpRoute(self, "100.1.1.100", 32, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index)]) + route_sever_dst = VppIpRoute( + self, + "100.1.1.100", + 32, + [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)], + ) route_sever_dst.add_vpp_config() # Send PPPoE Discovery - tx0 = self.create_stream_pppoe_discovery(self.pg0, self.pg1, - self.pg0.remote_mac) + tx0 = self.create_stream_pppoe_discovery( + self.pg0, self.pg1, self.pg0.remote_mac + ) self.pg0.add_stream(tx0) self.pg_start() # Send PPPoE PPP LCP - tx1 = self.create_stream_pppoe_lcp(self.pg0, self.pg1, - self.pg0.remote_mac, - self.session_id) + tx1 = self.create_stream_pppoe_lcp( + self.pg0, self.pg1, self.pg0.remote_mac, self.session_id + ) self.pg0.add_stream(tx1) self.pg_start() # Create PPPoE session - pppoe_if = VppPppoeInterface(self, - self.pg0.remote_ip4, - self.pg0.remote_mac, - self.session_id) + pppoe_if = VppPppoeInterface( + self, self.pg0.remote_ip4, self.pg0.remote_mac, self.session_id + ) pppoe_if.add_vpp_config() pppoe_if.set_unnumbered(self.pg0.sw_if_index) @@ -282,8 +298,9 @@ class TestPPPoE(VppTestCase): # - packets are PPPoE encapped # self.vapi.cli("clear trace") - tx2 = self.create_stream_ip4(self.pg1, self.pg0, - self.pg0.remote_ip4, self.dst_ip, 65) + tx2 = self.create_stream_ip4( + self.pg1, self.pg0, self.pg0.remote_ip4, self.dst_ip, 65 + ) self.pg1.add_stream(tx2) self.pg_enable_capture(self.pg_interfaces) @@ -308,36 +325,39 @@ class TestPPPoE(VppTestCase): route_sever_dst.remove_vpp_config() def test_PPPoE_Add_Twice(self): - """ PPPoE Add Same Session Twice Test """ + """PPPoE Add Same Session Twice Test""" self.vapi.cli("clear trace") # # Add a route that resolves the server's destination # - route_sever_dst = VppIpRoute(self, "100.1.1.100", 32, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index)]) + route_sever_dst = VppIpRoute( + self, + "100.1.1.100", + 32, + [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)], + ) route_sever_dst.add_vpp_config() # Send PPPoE Discovery - tx0 = self.create_stream_pppoe_discovery(self.pg0, self.pg1, - self.pg0.remote_mac) + tx0 = self.create_stream_pppoe_discovery( + self.pg0, self.pg1, self.pg0.remote_mac + ) self.pg0.add_stream(tx0) self.pg_start() # Send PPPoE PPP LCP - tx1 = self.create_stream_pppoe_lcp(self.pg0, self.pg1, - self.pg0.remote_mac, - self.session_id) + tx1 = self.create_stream_pppoe_lcp( + self.pg0, self.pg1, self.pg0.remote_mac, self.session_id + ) self.pg0.add_stream(tx1) self.pg_start() # Create PPPoE session - pppoe_if = VppPppoeInterface(self, - self.pg0.remote_ip4, - self.pg0.remote_mac, - self.session_id) + pppoe_if = VppPppoeInterface( + self, self.pg0.remote_ip4, self.pg0.remote_mac, self.session_id + ) pppoe_if.add_vpp_config() pppoe_if.set_unnumbered(self.pg0.sw_if_index) @@ -363,36 +383,39 @@ class TestPPPoE(VppTestCase): route_sever_dst.remove_vpp_config() def test_PPPoE_Del_Twice(self): - """ PPPoE Delete Same Session Twice Test """ + """PPPoE Delete Same Session Twice Test""" self.vapi.cli("clear trace") # # Add a route that resolves the server's destination # - route_sever_dst = VppIpRoute(self, "100.1.1.100", 32, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index)]) + route_sever_dst = VppIpRoute( + self, + "100.1.1.100", + 32, + [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)], + ) route_sever_dst.add_vpp_config() # Send PPPoE Discovery - tx0 = self.create_stream_pppoe_discovery(self.pg0, self.pg1, - self.pg0.remote_mac) + tx0 = self.create_stream_pppoe_discovery( + self.pg0, self.pg1, self.pg0.remote_mac + ) self.pg0.add_stream(tx0) self.pg_start() # Send PPPoE PPP LCP - tx1 = self.create_stream_pppoe_lcp(self.pg0, self.pg1, - self.pg0.remote_mac, - self.session_id) + tx1 = self.create_stream_pppoe_lcp( + self.pg0, self.pg1, self.pg0.remote_mac, self.session_id + ) self.pg0.add_stream(tx1) self.pg_start() # Create PPPoE session - pppoe_if = VppPppoeInterface(self, - self.pg0.remote_ip4, - self.pg0.remote_mac, - self.session_id) + pppoe_if = VppPppoeInterface( + self, self.pg0.remote_ip4, self.pg0.remote_mac, self.session_id + ) pppoe_if.add_vpp_config() # Delete PPPoE session @@ -417,57 +440,60 @@ class TestPPPoE(VppTestCase): route_sever_dst.remove_vpp_config() def test_PPPoE_Decap_Multiple(self): - """ PPPoE Decap Multiple Sessions Test """ + """PPPoE Decap Multiple Sessions Test""" self.vapi.cli("clear trace") # # Add a route that resolves the server's destination # - route_sever_dst = VppIpRoute(self, "100.1.1.100", 32, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index)]) + route_sever_dst = VppIpRoute( + self, + "100.1.1.100", + 32, + [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)], + ) route_sever_dst.add_vpp_config() # Send PPPoE Discovery 1 - tx0 = self.create_stream_pppoe_discovery(self.pg0, self.pg1, - self.pg0.remote_mac) + tx0 = self.create_stream_pppoe_discovery( + self.pg0, self.pg1, self.pg0.remote_mac + ) self.pg0.add_stream(tx0) self.pg_start() # Send PPPoE PPP LCP 1 - tx1 = self.create_stream_pppoe_lcp(self.pg0, self.pg1, - self.pg0.remote_mac, - self.session_id) + tx1 = self.create_stream_pppoe_lcp( + self.pg0, self.pg1, self.pg0.remote_mac, self.session_id + ) self.pg0.add_stream(tx1) self.pg_start() # Create PPPoE session 1 - pppoe_if1 = VppPppoeInterface(self, - self.pg0.remote_ip4, - self.pg0.remote_mac, - self.session_id) + pppoe_if1 = VppPppoeInterface( + self, self.pg0.remote_ip4, self.pg0.remote_mac, self.session_id + ) pppoe_if1.add_vpp_config() pppoe_if1.set_unnumbered(self.pg0.sw_if_index) # Send PPPoE Discovery 2 - tx3 = self.create_stream_pppoe_discovery(self.pg2, self.pg1, - self.pg2.remote_mac) + tx3 = self.create_stream_pppoe_discovery( + self.pg2, self.pg1, self.pg2.remote_mac + ) self.pg2.add_stream(tx3) self.pg_start() # Send PPPoE PPP LCP 2 - tx4 = self.create_stream_pppoe_lcp(self.pg2, self.pg1, - self.pg2.remote_mac, - self.session_id + 1) + tx4 = self.create_stream_pppoe_lcp( + self.pg2, self.pg1, self.pg2.remote_mac, self.session_id + 1 + ) self.pg2.add_stream(tx4) self.pg_start() # Create PPPoE session 2 - pppoe_if2 = VppPppoeInterface(self, - self.pg2.remote_ip4, - self.pg2.remote_mac, - self.session_id + 1) + pppoe_if2 = VppPppoeInterface( + self, self.pg2.remote_ip4, self.pg2.remote_mac, self.session_id + 1 + ) pppoe_if2.add_vpp_config() pppoe_if2.set_unnumbered(self.pg0.sw_if_index) @@ -475,10 +501,13 @@ class TestPPPoE(VppTestCase): # Send tunneled packets that match the created tunnel and # are decapped and forwarded # - tx2 = self.create_stream_pppoe_ip4(self.pg0, self.pg1, - self.pg0.remote_mac, - self.session_id, - self.pg0.remote_ip4) + tx2 = self.create_stream_pppoe_ip4( + self.pg0, + self.pg1, + self.pg0.remote_mac, + self.session_id, + self.pg0.remote_ip4, + ) self.pg0.add_stream(tx2) self.pg_enable_capture(self.pg_interfaces) @@ -487,10 +516,13 @@ class TestPPPoE(VppTestCase): rx2 = self.pg1.get_capture(len(tx2)) self.verify_decapped_pppoe(self.pg0, rx2, tx2) - tx5 = self.create_stream_pppoe_ip4(self.pg2, self.pg1, - self.pg2.remote_mac, - self.session_id + 1, - self.pg2.remote_ip4) + tx5 = self.create_stream_pppoe_ip4( + self.pg2, + self.pg1, + self.pg2.remote_mac, + self.session_id + 1, + self.pg2.remote_ip4, + ) self.pg2.add_stream(tx5) self.pg_enable_capture(self.pg_interfaces) @@ -515,56 +547,59 @@ class TestPPPoE(VppTestCase): route_sever_dst.remove_vpp_config() def test_PPPoE_Encap_Multiple(self): - """ PPPoE Encap Multiple Sessions Test """ + """PPPoE Encap Multiple Sessions Test""" self.vapi.cli("clear trace") # # Add a route that resolves the server's destination # - route_sever_dst = VppIpRoute(self, "100.1.1.100", 32, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index)]) + route_sever_dst = VppIpRoute( + self, + "100.1.1.100", + 32, + [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)], + ) route_sever_dst.add_vpp_config() # Send PPPoE Discovery 1 - tx0 = self.create_stream_pppoe_discovery(self.pg0, self.pg1, - self.pg0.remote_mac) + tx0 = self.create_stream_pppoe_discovery( + self.pg0, self.pg1, self.pg0.remote_mac + ) self.pg0.add_stream(tx0) self.pg_start() # Send PPPoE PPP LCP 1 - tx1 = self.create_stream_pppoe_lcp(self.pg0, self.pg1, - self.pg0.remote_mac, - self.session_id) + tx1 = self.create_stream_pppoe_lcp( + self.pg0, self.pg1, self.pg0.remote_mac, self.session_id + ) self.pg0.add_stream(tx1) self.pg_start() # Create PPPoE session 1 - pppoe_if1 = VppPppoeInterface(self, - self.pg0.remote_ip4, - self.pg0.remote_mac, - self.session_id) + pppoe_if1 = VppPppoeInterface( + self, self.pg0.remote_ip4, self.pg0.remote_mac, self.session_id + ) pppoe_if1.add_vpp_config() # Send PPPoE Discovery 2 - tx3 = self.create_stream_pppoe_discovery(self.pg2, self.pg1, - self.pg2.remote_mac) + tx3 = self.create_stream_pppoe_discovery( + self.pg2, self.pg1, self.pg2.remote_mac + ) self.pg2.add_stream(tx3) self.pg_start() # Send PPPoE PPP LCP 2 - tx4 = self.create_stream_pppoe_lcp(self.pg2, self.pg1, - self.pg2.remote_mac, - self.session_id + 1) + tx4 = self.create_stream_pppoe_lcp( + self.pg2, self.pg1, self.pg2.remote_mac, self.session_id + 1 + ) self.pg2.add_stream(tx4) self.pg_start() # Create PPPoE session 2 - pppoe_if2 = VppPppoeInterface(self, - self.pg2.remote_ip4, - self.pg2.remote_mac, - self.session_id + 1) + pppoe_if2 = VppPppoeInterface( + self, self.pg2.remote_ip4, self.pg2.remote_mac, self.session_id + 1 + ) pppoe_if2.add_vpp_config() # @@ -572,8 +607,9 @@ class TestPPPoE(VppTestCase): # - packets are PPPoE encapped # self.vapi.cli("clear trace") - tx2 = self.create_stream_ip4(self.pg1, self.pg0, - self.pg0.remote_ip4, self.dst_ip) + tx2 = self.create_stream_ip4( + self.pg1, self.pg0, self.pg0.remote_ip4, self.dst_ip + ) self.pg1.add_stream(tx2) self.pg_enable_capture(self.pg_interfaces) @@ -582,8 +618,9 @@ class TestPPPoE(VppTestCase): rx2 = self.pg0.get_capture(len(tx2)) self.verify_encaped_pppoe(self.pg1, rx2, tx2, self.session_id) - tx5 = self.create_stream_ip4(self.pg1, self.pg2, - self.pg2.remote_ip4, self.dst_ip) + tx5 = self.create_stream_ip4( + self.pg1, self.pg2, self.pg2.remote_ip4, self.dst_ip + ) self.pg1.add_stream(tx5) self.pg_enable_capture(self.pg_interfaces) @@ -607,5 +644,6 @@ class TestPPPoE(VppTestCase): # Delete a route that resolves the server's destination route_sever_dst.remove_vpp_config() -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_punt.py b/test/test_punt.py index ac059e904bd..f33ab4ce3d5 100644 --- a/test/test_punt.py +++ b/test/test_punt.py @@ -38,7 +38,7 @@ NUM_PKTS = 67 class serverSocketThread(threading.Thread): - """ Socket server thread""" + """Socket server thread""" def __init__(self, threadID, sockName): threading.Thread.__init__(self) @@ -90,7 +90,7 @@ class serverSocketThread(threading.Thread): class TestPuntSocket(VppTestCase): - """ Punt Socket """ + """Punt Socket""" ports = [1111, 2222, 3333, 4444] sock_servers = list() @@ -109,7 +109,12 @@ class TestPuntSocket(VppTestCase): @classmethod def setUpConstants(cls): cls.extra_vpp_punt_config = [ - "punt", "{", "socket", cls.tempdir+"/socket_punt", "}"] + "punt", + "{", + "socket", + cls.tempdir + "/socket_punt", + "}", + ] super(TestPuntSocket, cls).setUpConstants() def setUp(self): @@ -137,25 +142,21 @@ class TestPuntSocket(VppTestCase): return rx_pkts def verify_port(self, pr, vpr): - self.assertEqual(vpr.punt.type, pr['type']) - self.assertEqual(vpr.punt.punt.l4.port, - pr['punt']['l4']['port']) - self.assertEqual(vpr.punt.punt.l4.protocol, - pr['punt']['l4']['protocol']) - self.assertEqual(vpr.punt.punt.l4.af, - pr['punt']['l4']['af']) + self.assertEqual(vpr.punt.type, pr["type"]) + self.assertEqual(vpr.punt.punt.l4.port, pr["punt"]["l4"]["port"]) + self.assertEqual(vpr.punt.punt.l4.protocol, pr["punt"]["l4"]["protocol"]) + self.assertEqual(vpr.punt.punt.l4.af, pr["punt"]["l4"]["af"]) def verify_exception(self, pr, vpr): - self.assertEqual(vpr.punt.type, pr['type']) - self.assertEqual(vpr.punt.punt.exception.id, - pr['punt']['exception']['id']) + self.assertEqual(vpr.punt.type, pr["type"]) + self.assertEqual(vpr.punt.punt.exception.id, pr["punt"]["exception"]["id"]) def verify_ip_proto(self, pr, vpr): - self.assertEqual(vpr.punt.type, pr['type']) - self.assertEqual(vpr.punt.punt.ip_proto.af, - pr['punt']['ip_proto']['af']) - self.assertEqual(vpr.punt.punt.ip_proto.protocol, - pr['punt']['ip_proto']['protocol']) + self.assertEqual(vpr.punt.type, pr["type"]) + self.assertEqual(vpr.punt.punt.ip_proto.af, pr["punt"]["ip_proto"]["af"]) + self.assertEqual( + vpr.punt.punt.ip_proto.protocol, pr["punt"]["ip_proto"]["protocol"] + ) def verify_udp_pkts(self, rxs, n_rx, port): n_match = 0 @@ -167,12 +168,12 @@ class TestPuntSocket(VppTestCase): def set_port(pr, port): - pr['punt']['l4']['port'] = port + pr["punt"]["l4"]["port"] = port return pr def set_reason(pr, reason): - pr['punt']['exception']['id'] = reason + pr["punt"]["exception"]["id"] = reason return pr @@ -180,15 +181,7 @@ def mk_vpp_cfg4(): pt_l4 = VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_L4 af_ip4 = VppEnum.vl_api_address_family_t.ADDRESS_IP4 udp_proto = VppEnum.vl_api_ip_proto_t.IP_API_PROTO_UDP - punt_l4 = { - 'type': pt_l4, - 'punt': { - 'l4': { - 'af': af_ip4, - 'protocol': udp_proto - } - } - } + punt_l4 = {"type": pt_l4, "punt": {"l4": {"af": af_ip4, "protocol": udp_proto}}} return punt_l4 @@ -196,20 +189,12 @@ def mk_vpp_cfg6(): pt_l4 = VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_L4 af_ip6 = VppEnum.vl_api_address_family_t.ADDRESS_IP6 udp_proto = VppEnum.vl_api_ip_proto_t.IP_API_PROTO_UDP - punt_l4 = { - 'type': pt_l4, - 'punt': { - 'l4': { - 'af': af_ip6, - 'protocol': udp_proto - } - } - } + punt_l4 = {"type": pt_l4, "punt": {"l4": {"af": af_ip6, "protocol": udp_proto}}} return punt_l4 class TestIP4PuntSocket(TestPuntSocket): - """ Punt Socket for IPv4 UDP """ + """Punt Socket for IPv4 UDP""" @classmethod def setUpClass(cls): @@ -233,7 +218,7 @@ class TestIP4PuntSocket(TestPuntSocket): i.admin_down() def test_punt_socket_dump(self): - """ Punt socket registration/deregistration""" + """Punt socket registration/deregistration""" pt_l4 = VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_L4 af_ip4 = VppEnum.vl_api_address_family_t.ADDRESS_IP4 @@ -247,10 +232,12 @@ class TestIP4PuntSocket(TestPuntSocket): # punt_l4 = mk_vpp_cfg4() - self.vapi.punt_socket_register(set_port(punt_l4, 1111), - "%s/socket_punt_1111" % self.tempdir) - self.vapi.punt_socket_register(set_port(punt_l4, 2222), - "%s/socket_punt_2222" % self.tempdir) + self.vapi.punt_socket_register( + set_port(punt_l4, 1111), "%s/socket_punt_1111" % self.tempdir + ) + self.vapi.punt_socket_register( + set_port(punt_l4, 2222), "%s/socket_punt_2222" % self.tempdir + ) punts = self.vapi.punt_socket_dump(type=pt_l4) self.assertEqual(len(punts), 2) self.verify_port(set_port(punt_l4, 1111), punts[0]) @@ -266,10 +253,12 @@ class TestIP4PuntSocket(TestPuntSocket): # # configure a punt socket again # - self.vapi.punt_socket_register(set_port(punt_l4, 1111), - "%s/socket_punt_1111" % self.tempdir) - self.vapi.punt_socket_register(set_port(punt_l4, 3333), - "%s/socket_punt_3333" % self.tempdir) + self.vapi.punt_socket_register( + set_port(punt_l4, 1111), "%s/socket_punt_1111" % self.tempdir + ) + self.vapi.punt_socket_register( + set_port(punt_l4, 3333), "%s/socket_punt_3333" % self.tempdir + ) punts = self.vapi.punt_socket_dump(type=pt_l4) self.assertEqual(len(punts), 3) @@ -285,17 +274,18 @@ class TestIP4PuntSocket(TestPuntSocket): self.assertEqual(len(punts), 0) def test_punt_socket_traffic_single_port_single_socket(self): - """ Punt socket traffic single port single socket""" + """Punt socket traffic single port single socket""" port = self.ports[0] pt_l4 = VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_L4 punt_l4 = set_port(mk_vpp_cfg4(), port) - p = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / - UDP(sport=9876, dport=port) / - Raw(b'\xa5' * 100)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / UDP(sport=9876, dport=port) + / Raw(b"\xa5" * 100) + ) pkts = p * self.nr_packets @@ -308,15 +298,14 @@ class TestIP4PuntSocket(TestPuntSocket): rx = self.send_and_expect_some(self.pg0, pkts, self.pg0) for p in rx: - self.assertEqual(int(p[IP].proto), 1) # ICMP + self.assertEqual(int(p[IP].proto), 1) # ICMP self.assertEqual(int(p[ICMP].code), 3) # unreachable # # configure a punt socket # self.socket_client_create("%s/socket_%d" % (self.tempdir, port)) - self.vapi.punt_socket_register(punt_l4, "%s/socket_%d" % - (self.tempdir, port)) + self.vapi.punt_socket_register(punt_l4, "%s/socket_%d" % (self.tempdir, port)) punts = self.vapi.punt_socket_dump(type=pt_l4) self.assertEqual(len(punts), 1) @@ -336,11 +325,11 @@ class TestIP4PuntSocket(TestPuntSocket): rx = self.send_and_expect_some(self.pg0, pkts, self.pg0) for p in rx: - self.assertEqual(int(p[IP].proto), 1) # ICMP + self.assertEqual(int(p[IP].proto), 1) # ICMP self.assertEqual(int(p[ICMP].code), 3) # unreachable def test_punt_socket_traffic_multi_ports_multi_sockets(self): - """ Punt socket traffic multi ports and multi sockets""" + """Punt socket traffic multi ports and multi sockets""" punt_l4 = mk_vpp_cfg4() @@ -354,38 +343,40 @@ class TestIP4PuntSocket(TestPuntSocket): # choose port from port list cfgs[port] = {} - pkt = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / - UDP(sport=9876, dport=port) / - Raw(b'\xa5' * 100)) - cfgs[port]['pkts'] = pkt * self.nr_packets - cfgs[port]['port'] = port - cfgs[port]['vpp'] = copy.deepcopy(set_port(punt_l4, port)) + pkt = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / UDP(sport=9876, dport=port) + / Raw(b"\xa5" * 100) + ) + cfgs[port]["pkts"] = pkt * self.nr_packets + cfgs[port]["port"] = port + cfgs[port]["vpp"] = copy.deepcopy(set_port(punt_l4, port)) # configure punt sockets - cfgs[port]['sock'] = self.socket_client_create( - "%s/socket_%d" % (self.tempdir, port)) + cfgs[port]["sock"] = self.socket_client_create( + "%s/socket_%d" % (self.tempdir, port) + ) self.vapi.punt_socket_register( - cfgs[port]['vpp'], - "%s/socket_%d" % (self.tempdir, port)) + cfgs[port]["vpp"], "%s/socket_%d" % (self.tempdir, port) + ) # # send the packets that get punted # for cfg in cfgs.values(): - self.send_and_assert_no_replies(self.pg0, cfg['pkts']) + self.send_and_assert_no_replies(self.pg0, cfg["pkts"]) # # test that we got the excepted packets on the expected socket # for cfg in cfgs.values(): - rx = cfg['sock'].close() - self.verify_udp_pkts(rx, len(cfg['pkts']), cfg['port']) - self.vapi.punt_socket_deregister(cfg['vpp']) + rx = cfg["sock"].close() + self.verify_udp_pkts(rx, len(cfg["pkts"]), cfg["port"]) + self.vapi.punt_socket_deregister(cfg["vpp"]) def test_punt_socket_traffic_multi_ports_single_socket(self): - """ Punt socket traffic multi ports and single socket""" + """Punt socket traffic multi ports and single socket""" pt_l4 = VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_L4 punt_l4 = mk_vpp_cfg4() @@ -396,11 +387,12 @@ class TestIP4PuntSocket(TestPuntSocket): pkts = [] for port in self.ports: # choose port from port list - pkt = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / - UDP(sport=9876, dport=port) / - Raw(b'\xa5' * 100)) + pkt = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / UDP(sport=9876, dport=port) + / Raw(b"\xa5" * 100) + ) pkts += pkt * self.nr_packets # @@ -408,8 +400,9 @@ class TestIP4PuntSocket(TestPuntSocket): # self.socket_client_create("%s/socket_multi" % self.tempdir) for p in self.ports: - self.vapi.punt_socket_register(set_port(punt_l4, p), - "%s/socket_multi" % self.tempdir) + self.vapi.punt_socket_register( + set_port(punt_l4, p), "%s/socket_multi" % self.tempdir + ) punts = self.vapi.punt_socket_dump(type=pt_l4) self.assertEqual(len(punts), len(self.ports)) @@ -428,7 +421,7 @@ class TestIP4PuntSocket(TestPuntSocket): class TestIP6PuntSocket(TestPuntSocket): - """ Punt Socket for IPv6 UDP """ + """Punt Socket for IPv6 UDP""" @classmethod def setUpClass(cls): @@ -452,7 +445,7 @@ class TestIP6PuntSocket(TestPuntSocket): i.admin_down() def test_punt_socket_dump(self): - """ Punt socket registration """ + """Punt socket registration""" pt_l4 = VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_L4 af_ip6 = VppEnum.vl_api_address_family_t.ADDRESS_IP6 @@ -460,15 +453,7 @@ class TestIP6PuntSocket(TestPuntSocket): # # configure a punt socket # - punt_l4 = { - 'type': pt_l4, - 'punt': { - 'l4': { - 'af': af_ip6, - 'protocol': udp_proto - } - } - } + punt_l4 = {"type": pt_l4, "punt": {"l4": {"af": af_ip6, "protocol": udp_proto}}} punts = self.vapi.punt_socket_dump(type=pt_l4) self.assertEqual(len(punts), 0) @@ -476,10 +461,12 @@ class TestIP6PuntSocket(TestPuntSocket): # # configure a punt socket # - self.vapi.punt_socket_register(set_port(punt_l4, 1111), - "%s/socket_1111" % self.tempdir) - self.vapi.punt_socket_register(set_port(punt_l4, 2222), - "%s/socket_2222" % self.tempdir) + self.vapi.punt_socket_register( + set_port(punt_l4, 1111), "%s/socket_1111" % self.tempdir + ) + self.vapi.punt_socket_register( + set_port(punt_l4, 2222), "%s/socket_2222" % self.tempdir + ) punts = self.vapi.punt_socket_dump(type=pt_l4) self.assertEqual(len(punts), 2) self.verify_port(set_port(punt_l4, 1111), punts[0]) @@ -495,8 +482,9 @@ class TestIP6PuntSocket(TestPuntSocket): # # configure a punt socket again # - self.vapi.punt_socket_register(set_port(punt_l4, 1111), - "%s/socket_1111" % self.tempdir) + self.vapi.punt_socket_register( + set_port(punt_l4, 1111), "%s/socket_1111" % self.tempdir + ) punts = self.vapi.punt_socket_dump(type=pt_l4) self.assertEqual(len(punts), 2) @@ -510,28 +498,29 @@ class TestIP6PuntSocket(TestPuntSocket): self.assertEqual(len(punts), 0) def test_punt_socket_traffic_single_port_single_socket(self): - """ Punt socket traffic single port single socket""" + """Punt socket traffic single port single socket""" port = self.ports[0] pt_l4 = VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_L4 af_ip6 = VppEnum.vl_api_address_family_t.ADDRESS_IP6 udp_proto = VppEnum.vl_api_ip_proto_t.IP_API_PROTO_UDP punt_l4 = { - 'type': pt_l4, - 'punt': { - 'l4': { - 'af': af_ip6, - 'protocol': udp_proto, - 'port': port, + "type": pt_l4, + "punt": { + "l4": { + "af": af_ip6, + "protocol": udp_proto, + "port": port, } - } + }, } - p = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) / - inet6.UDP(sport=9876, dport=port) / - Raw(b'\xa5' * 100)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) + / inet6.UDP(sport=9876, dport=port) + / Raw(b"\xa5" * 100) + ) pkts = p * self.nr_packets @@ -555,8 +544,7 @@ class TestIP6PuntSocket(TestPuntSocket): # configure a punt socket # self.socket_client_create("%s/socket_%d" % (self.tempdir, port)) - self.vapi.punt_socket_register(punt_l4, "%s/socket_%d" % - (self.tempdir, port)) + self.vapi.punt_socket_register(punt_l4, "%s/socket_%d" % (self.tempdir, port)) punts = self.vapi.punt_socket_dump(type=pt_l4) self.assertEqual(len(punts), 1) @@ -586,7 +574,7 @@ class TestIP6PuntSocket(TestPuntSocket): # self.pg0.get_capture(nr_packets) def test_punt_socket_traffic_multi_ports_multi_sockets(self): - """ Punt socket traffic multi ports and multi sockets""" + """Punt socket traffic multi ports and multi sockets""" punt_l4 = mk_vpp_cfg6() @@ -600,50 +588,52 @@ class TestIP6PuntSocket(TestPuntSocket): # choose port from port list cfgs[port] = {} - pkt = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) / - UDP(sport=9876, dport=port) / - Raw(b'\xa5' * 100)) - cfgs[port]['pkts'] = pkt * self.nr_packets - cfgs[port]['port'] = port - cfgs[port]['vpp'] = copy.deepcopy(set_port(punt_l4, port)) + pkt = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) + / UDP(sport=9876, dport=port) + / Raw(b"\xa5" * 100) + ) + cfgs[port]["pkts"] = pkt * self.nr_packets + cfgs[port]["port"] = port + cfgs[port]["vpp"] = copy.deepcopy(set_port(punt_l4, port)) # configure punt sockets - cfgs[port]['sock'] = self.socket_client_create( - "%s/socket_%d" % (self.tempdir, port)) + cfgs[port]["sock"] = self.socket_client_create( + "%s/socket_%d" % (self.tempdir, port) + ) self.vapi.punt_socket_register( - cfgs[port]['vpp'], - "%s/socket_%d" % (self.tempdir, port)) + cfgs[port]["vpp"], "%s/socket_%d" % (self.tempdir, port) + ) # # send the packets that get punted # for cfg in cfgs.values(): - self.send_and_assert_no_replies(self.pg0, cfg['pkts']) + self.send_and_assert_no_replies(self.pg0, cfg["pkts"]) # # test that we got the excepted packets on the expected socket # for cfg in cfgs.values(): - rx = cfg['sock'].close() - self.verify_udp_pkts(rx, len(cfg['pkts']), cfg['port']) - self.vapi.punt_socket_deregister(cfg['vpp']) + rx = cfg["sock"].close() + self.verify_udp_pkts(rx, len(cfg["pkts"]), cfg["port"]) + self.vapi.punt_socket_deregister(cfg["vpp"]) def test_punt_socket_traffic_multi_ports_single_socket(self): - """ Punt socket traffic multi ports and single socket""" + """Punt socket traffic multi ports and single socket""" pt_l4 = VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_L4 af_ip6 = VppEnum.vl_api_address_family_t.ADDRESS_IP6 udp_proto = VppEnum.vl_api_ip_proto_t.IP_API_PROTO_UDP punt_l4 = { - 'type': pt_l4, - 'punt': { - 'l4': { - 'af': af_ip6, - 'protocol': udp_proto, + "type": pt_l4, + "punt": { + "l4": { + "af": af_ip6, + "protocol": udp_proto, } - } + }, } # @@ -652,11 +642,12 @@ class TestIP6PuntSocket(TestPuntSocket): pkts = [] for port in self.ports: # choose port from port list - pkt = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) / - UDP(sport=9876, dport=port) / - Raw(b'\xa5' * 100)) + pkt = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) + / UDP(sport=9876, dport=port) + / Raw(b"\xa5" * 100) + ) pkts += pkt * self.nr_packets # @@ -670,8 +661,9 @@ class TestIP6PuntSocket(TestPuntSocket): # self.socket_client_create("%s/socket_multi" % self.tempdir) for p in self.ports: - self.vapi.punt_socket_register(set_port(punt_l4, p), - "%s/socket_multi" % self.tempdir) + self.vapi.punt_socket_register( + set_port(punt_l4, p), "%s/socket_multi" % self.tempdir + ) punts = self.vapi.punt_socket_dump(type=pt_l4) self.assertEqual(len(punts), len(self.ports)) @@ -696,7 +688,7 @@ class TestIP6PuntSocket(TestPuntSocket): class TestExceptionPuntSocket(TestPuntSocket): - """ Punt Socket for Exceptions """ + """Punt Socket for Exceptions""" @classmethod def setUpClass(cls): @@ -721,7 +713,7 @@ class TestExceptionPuntSocket(TestPuntSocket): i.admin_down() def test_registration(self): - """ Punt socket registration/deregistration""" + """Punt socket registration/deregistration""" pt_ex = VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_EXCEPTION @@ -731,17 +723,14 @@ class TestExceptionPuntSocket(TestPuntSocket): # # configure a punt socket # - punt_ex = { - 'type': pt_ex, - 'punt': { - 'exception': {} - } - } + punt_ex = {"type": pt_ex, "punt": {"exception": {}}} - self.vapi.punt_socket_register(set_reason(punt_ex, 1), - "%s/socket_punt_1" % self.tempdir) - self.vapi.punt_socket_register(set_reason(punt_ex, 2), - "%s/socket_punt_2" % self.tempdir) + self.vapi.punt_socket_register( + set_reason(punt_ex, 1), "%s/socket_punt_1" % self.tempdir + ) + self.vapi.punt_socket_register( + set_reason(punt_ex, 2), "%s/socket_punt_2" % self.tempdir + ) punts = self.vapi.punt_socket_dump(type=pt_ex) self.assertEqual(len(punts), 2) self.verify_exception(set_reason(punt_ex, 1), punts[0]) @@ -757,10 +746,12 @@ class TestExceptionPuntSocket(TestPuntSocket): # # configure a punt socket again # - self.vapi.punt_socket_register(set_reason(punt_ex, 1), - "%s/socket_punt_1" % self.tempdir) - self.vapi.punt_socket_register(set_reason(punt_ex, 3), - "%s/socket_punt_3" % self.tempdir) + self.vapi.punt_socket_register( + set_reason(punt_ex, 1), "%s/socket_punt_1" % self.tempdir + ) + self.vapi.punt_socket_register( + set_reason(punt_ex, 3), "%s/socket_punt_3" % self.tempdir + ) punts = self.vapi.punt_socket_dump(type=pt_ex) self.assertEqual(len(punts), 3) @@ -785,25 +776,18 @@ class TestExceptionPuntSocket(TestPuntSocket): self.assertTrue(rx.haslayer(UDP)) def test_traffic(self): - """ Punt socket traffic """ + """Punt socket traffic""" port = self.ports[0] pt_ex = VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_EXCEPTION - punt_ex = { - 'type': pt_ex, - 'punt': { - 'exception': {} - } - } + punt_ex = {"type": pt_ex, "punt": {"exception": {}}} # # we're dealing with IPSec tunnels punting for no-such-tunnel # (SPI=0 goes to ikev2) # cfgs = dict() - cfgs['ipsec4-no-such-tunnel'] = {'spi': 99, - 'udp': False, - 'itf': self.pg0} + cfgs["ipsec4-no-such-tunnel"] = {"spi": 99, "udp": False, "itf": self.pg0} # # find the VPP ID for these punt exception reasin @@ -814,99 +798,99 @@ class TestExceptionPuntSocket(TestPuntSocket): print(r.reason.name) print(key) if r.reason.name == key: - cfgs[key]['id'] = r.reason.id - cfgs[key]['vpp'] = copy.deepcopy( - set_reason(punt_ex, - cfgs[key]['id'])) + cfgs[key]["id"] = r.reason.id + cfgs[key]["vpp"] = copy.deepcopy( + set_reason(punt_ex, cfgs[key]["id"]) + ) break # # configure punt sockets # for cfg in cfgs.values(): - cfg['sock'] = self.socket_client_create("%s/socket_%d" % - (self.tempdir, cfg['id'])) + cfg["sock"] = self.socket_client_create( + "%s/socket_%d" % (self.tempdir, cfg["id"]) + ) self.vapi.punt_socket_register( - cfg['vpp'], "%s/socket_%d" % (self.tempdir, cfg['id'])) + cfg["vpp"], "%s/socket_%d" % (self.tempdir, cfg["id"]) + ) # # create packet streams for 'no-such-tunnel' exception # for cfg in cfgs.values(): - pkt = (Ether(src=cfg['itf'].remote_mac, - dst=cfg['itf'].local_mac) / - IP(src=cfg['itf'].remote_ip4, - dst=cfg['itf'].local_ip4)) - if (cfg['udp']): + pkt = Ether(src=cfg["itf"].remote_mac, dst=cfg["itf"].local_mac) / IP( + src=cfg["itf"].remote_ip4, dst=cfg["itf"].local_ip4 + ) + if cfg["udp"]: pkt = pkt / UDP(sport=666, dport=4500) - pkt = (pkt / ESP(spi=cfg['spi'], seq=3) / - Raw(b'\xa5' * 100)) - cfg['pkts'] = [pkt] + pkt = pkt / ESP(spi=cfg["spi"], seq=3) / Raw(b"\xa5" * 100) + cfg["pkts"] = [pkt] # # send packets for each SPI we expect to be punted # for cfg in cfgs.values(): - self.send_and_assert_no_replies(cfg['itf'], cfg['pkts']) + self.send_and_assert_no_replies(cfg["itf"], cfg["pkts"]) # # verify the punted packets arrived on the associated socket # for cfg in cfgs.values(): - rx = cfg['sock'].close() - self.verify_esp_pkts(rx, len(cfg['pkts']), - cfg['spi'], cfg['udp']) + rx = cfg["sock"].close() + self.verify_esp_pkts(rx, len(cfg["pkts"]), cfg["spi"], cfg["udp"]) # # add some tunnels, make sure it still punts # tun = VppIpsecInterface(self).add_vpp_config() - sa_in = VppIpsecSA(self, 11, 11, - (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_SHA1_96), - b"0123456701234567", - (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_AES_CBC_128), - b"0123456701234567", - 50, - self.pg0.local_ip4, - self.pg0.remote_ip4).add_vpp_config() - sa_out = VppIpsecSA(self, 22, 22, - (VppEnum.vl_api_ipsec_integ_alg_t. - IPSEC_API_INTEG_ALG_SHA1_96), - b"0123456701234567", - (VppEnum.vl_api_ipsec_crypto_alg_t. - IPSEC_API_CRYPTO_ALG_AES_CBC_128), - b"0123456701234567", - 50, - self.pg0.local_ip4, - self.pg0.remote_ip4).add_vpp_config() - protect = VppIpsecTunProtect(self, tun, - sa_out, - [sa_in]).add_vpp_config() + sa_in = VppIpsecSA( + self, + 11, + 11, + (VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96), + b"0123456701234567", + (VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CBC_128), + b"0123456701234567", + 50, + self.pg0.local_ip4, + self.pg0.remote_ip4, + ).add_vpp_config() + sa_out = VppIpsecSA( + self, + 22, + 22, + (VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96), + b"0123456701234567", + (VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CBC_128), + b"0123456701234567", + 50, + self.pg0.local_ip4, + self.pg0.remote_ip4, + ).add_vpp_config() + protect = VppIpsecTunProtect(self, tun, sa_out, [sa_in]).add_vpp_config() # # send packets for each SPI we expect to be punted # for cfg in cfgs.values(): - self.send_and_assert_no_replies(cfg['itf'], cfg['pkts']) + self.send_and_assert_no_replies(cfg["itf"], cfg["pkts"]) # # verify the punted packets arrived on the associated socket # for cfg in cfgs.values(): - rx = cfg['sock'].close() - self.verify_esp_pkts(rx, len(cfg['pkts']), - cfg['spi'], cfg['udp']) + rx = cfg["sock"].close() + self.verify_esp_pkts(rx, len(cfg["pkts"]), cfg["spi"], cfg["udp"]) # # socket deregister # for cfg in cfgs.values(): - self.vapi.punt_socket_deregister(cfg['vpp']) + self.vapi.punt_socket_deregister(cfg["vpp"]) class TestIpProtoPuntSocket(TestPuntSocket): - """ Punt Socket for IP packets """ + """Punt Socket for IP packets""" @classmethod def setUpClass(cls): @@ -930,7 +914,7 @@ class TestIpProtoPuntSocket(TestPuntSocket): i.admin_down() def test_registration(self): - """ Punt socket registration/deregistration""" + """Punt socket registration/deregistration""" af_ip4 = VppEnum.vl_api_address_family_t.ADDRESS_IP4 pt_ip = VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_IP_PROTO @@ -944,28 +928,16 @@ class TestIpProtoPuntSocket(TestPuntSocket): # configure a punt socket # punt_ospf = { - 'type': pt_ip, - 'punt': { - 'ip_proto': { - 'af': af_ip4, - 'protocol': proto_ospf - } - } + "type": pt_ip, + "punt": {"ip_proto": {"af": af_ip4, "protocol": proto_ospf}}, } punt_eigrp = { - 'type': pt_ip, - 'punt': { - 'ip_proto': { - 'af': af_ip4, - 'protocol': proto_eigrp - } - } + "type": pt_ip, + "punt": {"ip_proto": {"af": af_ip4, "protocol": proto_eigrp}}, } - self.vapi.punt_socket_register(punt_ospf, - "%s/socket_punt_1" % self.tempdir) - self.vapi.punt_socket_register(punt_eigrp, - "%s/socket_punt_2" % self.tempdir) + self.vapi.punt_socket_register(punt_ospf, "%s/socket_punt_1" % self.tempdir) + self.vapi.punt_socket_register(punt_eigrp, "%s/socket_punt_2" % self.tempdir) self.logger.info(self.vapi.cli("sh punt sock reg ip")) punts = self.vapi.punt_socket_dump(type=pt_ip) self.assertEqual(len(punts), 2) @@ -982,8 +954,7 @@ class TestIpProtoPuntSocket(TestPuntSocket): # # configure a punt socket again # - self.vapi.punt_socket_register(punt_ospf, - "%s/socket_punt_3" % self.tempdir) + self.vapi.punt_socket_register(punt_ospf, "%s/socket_punt_3" % self.tempdir) punts = self.vapi.punt_socket_dump(type=pt_ip) self.assertEqual(len(punts), 2) @@ -1003,7 +974,7 @@ class TestIpProtoPuntSocket(TestPuntSocket): self.assertTrue(rx.haslayer(OSPF_Hdr)) def test_traffic(self): - """ Punt socket traffic """ + """Punt socket traffic""" af_ip4 = VppEnum.vl_api_address_family_t.ADDRESS_IP4 pt_ip = VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_IP_PROTO @@ -1013,28 +984,23 @@ class TestIpProtoPuntSocket(TestPuntSocket): # configure a punt socket to capture OSPF packets # punt_ospf = { - 'type': pt_ip, - 'punt': { - 'ip_proto': { - 'af': af_ip4, - 'protocol': proto_ospf - } - } + "type": pt_ip, + "punt": {"ip_proto": {"af": af_ip4, "protocol": proto_ospf}}, } # # create packet streams and configure a punt sockets # - pkt = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / - OSPF_Hdr() / - OSPFv3_Hello()) + pkt = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / OSPF_Hdr() + / OSPFv3_Hello() + ) pkts = pkt * 7 sock = self.socket_client_create("%s/socket_1" % self.tempdir) - self.vapi.punt_socket_register( - punt_ospf, "%s/socket_1" % self.tempdir) + self.vapi.punt_socket_register(punt_ospf, "%s/socket_1" % self.tempdir) # # send packets for each SPI we expect to be punted @@ -1051,7 +1017,7 @@ class TestIpProtoPuntSocket(TestPuntSocket): @tag_fixme_vpp_workers class TestPunt(VppTestCase): - """ Exception Punt Test Case """ + """Exception Punt Test Case""" @classmethod def setUpClass(cls): @@ -1081,7 +1047,7 @@ class TestPunt(VppTestCase): super(TestPunt, self).tearDown() def test_punt(self): - """ Exception Path testing """ + """Exception Path testing""" # # dump the punt registered reasons @@ -1089,9 +1055,11 @@ class TestPunt(VppTestCase): # rs = self.vapi.punt_reason_dump() - reasons = ["ipsec6-no-such-tunnel", - "ipsec4-no-such-tunnel", - "ipsec4-spi-o-udp-0"] + reasons = [ + "ipsec6-no-such-tunnel", + "ipsec4-no-such-tunnel", + "ipsec4-spi-o-udp-0", + ] for reason in reasons: found = False @@ -1106,28 +1074,41 @@ class TestPunt(VppTestCase): # send ACL deny packets out of pg0 and pg1. # the ACL is src,dst = 1.1.1.1,1.1.1.2 # - ip_1_1_1_2 = VppIpRoute(self, "1.1.1.2", 32, - [VppRoutePath(self.pg3.remote_ip4, - self.pg3.sw_if_index)]) + ip_1_1_1_2 = VppIpRoute( + self, + "1.1.1.2", + 32, + [VppRoutePath(self.pg3.remote_ip4, self.pg3.sw_if_index)], + ) ip_1_1_1_2.add_vpp_config() - ip_1_2 = VppIpRoute(self, "1::2", 128, - [VppRoutePath(self.pg3.remote_ip6, - self.pg3.sw_if_index, - proto=DpoProto.DPO_PROTO_IP6)]) + ip_1_2 = VppIpRoute( + self, + "1::2", + 128, + [ + VppRoutePath( + self.pg3.remote_ip6, + self.pg3.sw_if_index, + proto=DpoProto.DPO_PROTO_IP6, + ) + ], + ) ip_1_2.add_vpp_config() - p4 = (Ether(src=self.pg2.remote_mac, - dst=self.pg2.local_mac) / - IP(src="1.1.1.1", dst="1.1.1.2") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - p6 = (Ether(src=self.pg2.remote_mac, - dst=self.pg2.local_mac) / - IPv6(src="1::1", dst="1::2") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - self.send_and_expect(self.pg2, p4*1, self.pg3) - self.send_and_expect(self.pg2, p6*1, self.pg3) + p4 = ( + Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) + / IP(src="1.1.1.1", dst="1.1.1.2") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + p6 = ( + Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) + / IPv6(src="1::1", dst="1::2") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + self.send_and_expect(self.pg2, p4 * 1, self.pg3) + self.send_and_expect(self.pg2, p6 * 1, self.pg3) # # apply the punting features @@ -1137,16 +1118,16 @@ class TestPunt(VppTestCase): # # dump the punt reasons to learn the IDs assigned # - rs = self.vapi.punt_reason_dump(reason={'name': "reason-v4"}) + rs = self.vapi.punt_reason_dump(reason={"name": "reason-v4"}) r4 = rs[0].reason.id - rs = self.vapi.punt_reason_dump(reason={'name': "reason-v6"}) + rs = self.vapi.punt_reason_dump(reason={"name": "reason-v6"}) r6 = rs[0].reason.id # # pkts now dropped # - self.send_and_assert_no_replies(self.pg2, p4*NUM_PKTS) - self.send_and_assert_no_replies(self.pg2, p6*NUM_PKTS) + self.send_and_assert_no_replies(self.pg2, p4 * NUM_PKTS) + self.send_and_assert_no_replies(self.pg2, p6 * NUM_PKTS) # # Check state: @@ -1154,13 +1135,12 @@ class TestPunt(VppTestCase): # 2 - per-reason counters # 2, 3 are the index of the assigned punt reason # - stats = self.statistics.get_err_counter( - "/err/punt-dispatch/No registrations") - self.assertEqual(stats, 2*NUM_PKTS) + stats = self.statistics.get_err_counter("/err/punt-dispatch/No registrations") + self.assertEqual(stats, 2 * NUM_PKTS) stats = self.statistics.get_counter("/net/punt") - self.assertEqual(stats[0][r4]['packets'], NUM_PKTS) - self.assertEqual(stats[0][r6]['packets'], NUM_PKTS) + self.assertEqual(stats[0][r4]["packets"], NUM_PKTS) + self.assertEqual(stats[0][r6]["packets"], NUM_PKTS) # # use the test CLI to test a client that punts exception @@ -1169,8 +1149,8 @@ class TestPunt(VppTestCase): self.vapi.cli("test punt pg0 %s" % self.pg0.remote_ip4) self.vapi.cli("test punt pg0 %s" % self.pg0.remote_ip6) - rx4s = self.send_and_expect(self.pg2, p4*NUM_PKTS, self.pg0) - rx6s = self.send_and_expect(self.pg2, p6*NUM_PKTS, self.pg0) + rx4s = self.send_and_expect(self.pg2, p4 * NUM_PKTS, self.pg0) + rx6s = self.send_and_expect(self.pg2, p6 * NUM_PKTS, self.pg0) # # check the packets come out IP unmodified but destined to pg0 host @@ -1187,8 +1167,8 @@ class TestPunt(VppTestCase): self.assertEqual(p6[IPv6].hlim, rx[IPv6].hlim) stats = self.statistics.get_counter("/net/punt") - self.assertEqual(stats[0][r4]['packets'], 2*NUM_PKTS) - self.assertEqual(stats[0][r6]['packets'], 2*NUM_PKTS) + self.assertEqual(stats[0][r4]["packets"], 2 * NUM_PKTS) + self.assertEqual(stats[0][r6]["packets"], 2 * NUM_PKTS) # # add another registration for the same reason to send packets @@ -1234,8 +1214,8 @@ class TestPunt(VppTestCase): self.assertEqual(p6[IPv6].hlim, rx[IPv6].hlim) stats = self.statistics.get_counter("/net/punt") - self.assertEqual(stats[0][r4]['packets'], 3*NUM_PKTS) - self.assertEqual(stats[0][r6]['packets'], 3*NUM_PKTS) + self.assertEqual(stats[0][r4]["packets"], 3 * NUM_PKTS) + self.assertEqual(stats[0][r6]["packets"], 3 * NUM_PKTS) self.logger.info(self.vapi.cli("show vlib graph punt-dispatch")) self.logger.info(self.vapi.cli("show punt client")) @@ -1244,5 +1224,5 @@ class TestPunt(VppTestCase): self.logger.info(self.vapi.cli("show punt db")) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_qos.py b/test/test_qos.py index 02941a163b4..40a3ddea4f5 100644 --- a/test/test_qos.py +++ b/test/test_qos.py @@ -5,8 +5,14 @@ import unittest from framework import VppTestCase, VppTestRunner from vpp_sub_interface import VppDot1QSubint from vpp_ip import DpoProto -from vpp_ip_route import VppIpRoute, VppRoutePath, VppMplsRoute, \ - VppMplsLabel, VppMplsTable, FibPathProto +from vpp_ip_route import ( + VppIpRoute, + VppRoutePath, + VppMplsRoute, + VppMplsLabel, + VppMplsTable, + FibPathProto, +) import scapy.compat from scapy.packet import Raw @@ -21,7 +27,7 @@ NUM_PKTS = 67 class TestQOS(VppTestCase): - """ QOS Test Case """ + """QOS Test Case""" # Note: Since the enums aren't created dynamically until after # the papi client attaches to VPP, we put it in a property to @@ -63,7 +69,7 @@ class TestQOS(VppTestCase): super(TestQOS, self).tearDown() def test_qos_ip(self): - """ QoS Mark/Record/Store IP """ + """QoS Mark/Record/Store IP""" # # for table 1 map the n=0xff possible values of input QoS mark, @@ -72,11 +78,8 @@ class TestQOS(VppTestCase): output = [scapy.compat.chb(0)] * 256 for i in range(0, 255): output[i] = scapy.compat.chb(255 - i) - os = b''.join(output) - rows = [{'outputs': os}, - {'outputs': os}, - {'outputs': os}, - {'outputs': os}] + os = b"".join(output) + rows = [{"outputs": os}, {"outputs": os}, {"outputs": os}, {"outputs": os}] qem1 = VppQosEgressMap(self, 1, rows).add_vpp_config() @@ -84,29 +87,20 @@ class TestQOS(VppTestCase): # For table 2 (and up) use the value n for everything # output = [scapy.compat.chb(2)] * 256 - os = b''.join(output) - rows = [{'outputs': os}, - {'outputs': os}, - {'outputs': os}, - {'outputs': os}] + os = b"".join(output) + rows = [{"outputs": os}, {"outputs": os}, {"outputs": os}, {"outputs": os}] qem2 = VppQosEgressMap(self, 2, rows).add_vpp_config() output = [scapy.compat.chb(3)] * 256 - os = b''.join(output) - rows = [{'outputs': os}, - {'outputs': os}, - {'outputs': os}, - {'outputs': os}] + os = b"".join(output) + rows = [{"outputs": os}, {"outputs": os}, {"outputs": os}, {"outputs": os}] qem3 = VppQosEgressMap(self, 3, rows).add_vpp_config() output = [scapy.compat.chb(4)] * 256 - os = b''.join(output) - rows = [{'outputs': os}, - {'outputs': os}, - {'outputs': os}, - {'outputs': os}] + os = b"".join(output) + rows = [{"outputs": os}, {"outputs": os}, {"outputs": os}, {"outputs": os}] qem4 = VppQosEgressMap(self, 4, rows).add_vpp_config() qem5 = VppQosEgressMap(self, 5, rows).add_vpp_config() @@ -119,14 +113,18 @@ class TestQOS(VppTestCase): # # Bind interface pgN to table n # - qm1 = VppQosMark(self, self.pg1, qem1, - self.QOS_SOURCE.QOS_API_SOURCE_IP).add_vpp_config() - qm2 = VppQosMark(self, self.pg2, qem2, - self.QOS_SOURCE.QOS_API_SOURCE_IP).add_vpp_config() - qm3 = VppQosMark(self, self.pg3, qem3, - self.QOS_SOURCE.QOS_API_SOURCE_IP).add_vpp_config() - qm4 = VppQosMark(self, self.pg4, qem4, - self.QOS_SOURCE.QOS_API_SOURCE_IP).add_vpp_config() + qm1 = VppQosMark( + self, self.pg1, qem1, self.QOS_SOURCE.QOS_API_SOURCE_IP + ).add_vpp_config() + qm2 = VppQosMark( + self, self.pg2, qem2, self.QOS_SOURCE.QOS_API_SOURCE_IP + ).add_vpp_config() + qm3 = VppQosMark( + self, self.pg3, qem3, self.QOS_SOURCE.QOS_API_SOURCE_IP + ).add_vpp_config() + qm4 = VppQosMark( + self, self.pg4, qem4, self.QOS_SOURCE.QOS_API_SOURCE_IP + ).add_vpp_config() self.assertTrue(qm3.query_vpp_config()) self.logger.info(self.vapi.cli("sh qos mark")) @@ -134,15 +132,18 @@ class TestQOS(VppTestCase): # # packets ingress on Pg0 # - p_v4 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, tos=1) / - UDP(sport=1234, dport=1234) / - Raw(scapy.compat.chb(100) * NUM_PKTS)) - p_v6 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6, - tc=1) / - UDP(sport=1234, dport=1234) / - Raw(scapy.compat.chb(100) * NUM_PKTS)) + p_v4 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, tos=1) + / UDP(sport=1234, dport=1234) + / Raw(scapy.compat.chb(100) * NUM_PKTS) + ) + p_v6 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6, tc=1) + / UDP(sport=1234, dport=1234) + / Raw(scapy.compat.chb(100) * NUM_PKTS) + ) # # Since we have not yet enabled the recording of the input QoS @@ -158,8 +159,7 @@ class TestQOS(VppTestCase): # # Enable QoS recording on IP input for pg0 # - qr1 = VppQosRecord(self, self.pg0, - self.QOS_SOURCE.QOS_API_SOURCE_IP) + qr1 = VppQosRecord(self, self.pg0, self.QOS_SOURCE.QOS_API_SOURCE_IP) qr1.add_vpp_config() self.logger.info(self.vapi.cli("sh qos record")) @@ -258,9 +258,9 @@ class TestQOS(VppTestCase): # # enable QoS stroe instead of record # - qst1 = VppQosStore(self, self.pg0, - self.QOS_SOURCE.QOS_API_SOURCE_IP, - 5).add_vpp_config() + qst1 = VppQosStore( + self, self.pg0, self.QOS_SOURCE.QOS_API_SOURCE_IP, 5 + ).add_vpp_config() self.logger.info(self.vapi.cli("sh qos store")) p_v4[IP].dst = self.pg1.remote_ip4 @@ -295,7 +295,7 @@ class TestQOS(VppTestCase): self.assertEqual(p[IP].tos, 254) def test_qos_mpls(self): - """ QoS Mark/Record MPLS """ + """QoS Mark/Record MPLS""" # # 255 QoS for all input values @@ -305,58 +305,69 @@ class TestQOS(VppTestCase): from_mpls = 5 from_vlan = 4 output = [scapy.compat.chb(from_ext)] * 256 - os1 = b''.join(output) + os1 = b"".join(output) output = [scapy.compat.chb(from_vlan)] * 256 - os2 = b''.join(output) + os2 = b"".join(output) output = [scapy.compat.chb(from_mpls)] * 256 - os3 = b''.join(output) + os3 = b"".join(output) output = [scapy.compat.chb(from_ip)] * 256 - os4 = b''.join(output) - rows = [{'outputs': os1}, - {'outputs': os2}, - {'outputs': os3}, - {'outputs': os4}] + os4 = b"".join(output) + rows = [{"outputs": os1}, {"outputs": os2}, {"outputs": os3}, {"outputs": os4}] qem1 = VppQosEgressMap(self, 1, rows).add_vpp_config() # # a route with 1 MPLS label # - route_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index, - labels=[32])]) + route_10_0_0_1 = VppIpRoute( + self, + "10.0.0.1", + 32, + [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index, labels=[32])], + ) route_10_0_0_1.add_vpp_config() # # a route with 3 MPLS labels # - route_10_0_0_3 = VppIpRoute(self, "10.0.0.3", 32, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index, - labels=[63, 33, 34])]) + route_10_0_0_3 = VppIpRoute( + self, + "10.0.0.3", + 32, + [ + VppRoutePath( + self.pg1.remote_ip4, self.pg1.sw_if_index, labels=[63, 33, 34] + ) + ], + ) route_10_0_0_3.add_vpp_config() # # enable IP QoS recording on the input Pg0 and MPLS egress marking # on Pg1 # - qr1 = VppQosRecord(self, self.pg0, - self.QOS_SOURCE.QOS_API_SOURCE_IP).add_vpp_config() - qm1 = VppQosMark(self, self.pg1, qem1, - self.QOS_SOURCE.QOS_API_SOURCE_MPLS).add_vpp_config() + qr1 = VppQosRecord( + self, self.pg0, self.QOS_SOURCE.QOS_API_SOURCE_IP + ).add_vpp_config() + qm1 = VppQosMark( + self, self.pg1, qem1, self.QOS_SOURCE.QOS_API_SOURCE_MPLS + ).add_vpp_config() # # packet that will get one label added and 3 labels added resp. # - p_1 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst="10.0.0.1", tos=1) / - UDP(sport=1234, dport=1234) / - Raw(scapy.compat.chb(100) * NUM_PKTS)) - p_3 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst="10.0.0.3", tos=1) / - UDP(sport=1234, dport=1234) / - Raw(scapy.compat.chb(100) * NUM_PKTS)) + p_1 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst="10.0.0.1", tos=1) + / UDP(sport=1234, dport=1234) + / Raw(scapy.compat.chb(100) * NUM_PKTS) + ) + p_3 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst="10.0.0.3", tos=1) + / UDP(sport=1234, dport=1234) + / Raw(scapy.compat.chb(100) * NUM_PKTS) + ) rx = self.send_and_expect(self.pg0, p_1 * NUM_PKTS, self.pg1) @@ -387,26 +398,34 @@ class TestQOS(VppTestCase): # on Pg1 # qr2 = VppQosRecord( - self, self.pg0, - self.QOS_SOURCE.QOS_API_SOURCE_MPLS).add_vpp_config() + self, self.pg0, self.QOS_SOURCE.QOS_API_SOURCE_MPLS + ).add_vpp_config() qm2 = VppQosMark( - self, self.pg1, qem1, - self.QOS_SOURCE.QOS_API_SOURCE_IP).add_vpp_config() + self, self.pg1, qem1, self.QOS_SOURCE.QOS_API_SOURCE_IP + ).add_vpp_config() # # MPLS x-connect - COS according to pg1 map # - route_32_eos = VppMplsRoute(self, 32, 1, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index, - labels=[VppMplsLabel(33)])]) + route_32_eos = VppMplsRoute( + self, + 32, + 1, + [ + VppRoutePath( + self.pg1.remote_ip4, self.pg1.sw_if_index, labels=[VppMplsLabel(33)] + ) + ], + ) route_32_eos.add_vpp_config() - p_m1 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - MPLS(label=32, cos=3, ttl=2) / - IP(src=self.pg0.remote_ip4, dst="10.0.0.1", tos=1) / - UDP(sport=1234, dport=1234) / - Raw(scapy.compat.chb(100) * NUM_PKTS)) + p_m1 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / MPLS(label=32, cos=3, ttl=2) + / IP(src=self.pg0.remote_ip4, dst="10.0.0.1", tos=1) + / UDP(sport=1234, dport=1234) + / Raw(scapy.compat.chb(100) * NUM_PKTS) + ) rx = self.send_and_expect(self.pg0, p_m1 * NUM_PKTS, self.pg1) for p in rx: @@ -417,22 +436,26 @@ class TestQOS(VppTestCase): # # MPLS deag - COS is copied from MPLS to IP # - route_33_eos = VppMplsRoute(self, 33, 1, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_table_id=0)]) + route_33_eos = VppMplsRoute( + self, 33, 1, [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=0)] + ) route_33_eos.add_vpp_config() - route_10_0_0_4 = VppIpRoute(self, "10.0.0.4", 32, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index)]) + route_10_0_0_4 = VppIpRoute( + self, + "10.0.0.4", + 32, + [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)], + ) route_10_0_0_4.add_vpp_config() - p_m2 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - MPLS(label=33, ttl=2, cos=3) / - IP(src=self.pg0.remote_ip4, dst="10.0.0.4", tos=1) / - UDP(sport=1234, dport=1234) / - Raw(scapy.compat.chb(100) * NUM_PKTS)) + p_m2 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / MPLS(label=33, ttl=2, cos=3) + / IP(src=self.pg0.remote_ip4, dst="10.0.0.4", tos=1) + / UDP(sport=1234, dport=1234) + / Raw(scapy.compat.chb(100) * NUM_PKTS) + ) rx = self.send_and_expect(self.pg0, p_m2 * NUM_PKTS, self.pg1) @@ -440,7 +463,7 @@ class TestQOS(VppTestCase): self.assertEqual(p[IP].tos, from_mpls) def test_qos_vlan(self): - """QoS mark/record VLAN """ + """QoS mark/record VLAN""" # # QoS for all input values @@ -448,11 +471,8 @@ class TestQOS(VppTestCase): output = [scapy.compat.chb(0)] * 256 for i in range(0, 255): output[i] = scapy.compat.chb(255 - i) - os = b''.join(output) - rows = [{'outputs': os}, - {'outputs': os}, - {'outputs': os}, - {'outputs': os}] + os = b"".join(output) + rows = [{"outputs": os}, {"outputs": os}, {"outputs": os}, {"outputs": os}] qem1 = VppQosEgressMap(self, 1, rows).add_vpp_config() @@ -468,58 +488,70 @@ class TestQOS(VppTestCase): # enable VLAN QoS recording/marking on the input Pg0 subinterface and # qr_v = VppQosRecord( - self, sub_if, - self.QOS_SOURCE.QOS_API_SOURCE_VLAN).add_vpp_config() + self, sub_if, self.QOS_SOURCE.QOS_API_SOURCE_VLAN + ).add_vpp_config() qm_v = VppQosMark( - self, sub_if, qem1, - self.QOS_SOURCE.QOS_API_SOURCE_VLAN).add_vpp_config() + self, sub_if, qem1, self.QOS_SOURCE.QOS_API_SOURCE_VLAN + ).add_vpp_config() # # IP marking/recording on pg1 # qr_ip = VppQosRecord( - self, self.pg1, - self.QOS_SOURCE.QOS_API_SOURCE_IP).add_vpp_config() + self, self.pg1, self.QOS_SOURCE.QOS_API_SOURCE_IP + ).add_vpp_config() qm_ip = VppQosMark( - self, self.pg1, qem1, - self.QOS_SOURCE.QOS_API_SOURCE_IP).add_vpp_config() + self, self.pg1, qem1, self.QOS_SOURCE.QOS_API_SOURCE_IP + ).add_vpp_config() # # a routes to/from sub-interface # - route_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32, - [VppRoutePath(sub_if.remote_ip4, - sub_if.sw_if_index)]) + route_10_0_0_1 = VppIpRoute( + self, "10.0.0.1", 32, [VppRoutePath(sub_if.remote_ip4, sub_if.sw_if_index)] + ) route_10_0_0_1.add_vpp_config() - route_10_0_0_2 = VppIpRoute(self, "10.0.0.2", 32, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index)]) + route_10_0_0_2 = VppIpRoute( + self, + "10.0.0.2", + 32, + [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)], + ) route_10_0_0_2.add_vpp_config() - route_2001_1 = VppIpRoute(self, "2001::1", 128, - [VppRoutePath(sub_if.remote_ip6, - sub_if.sw_if_index)]) + route_2001_1 = VppIpRoute( + self, "2001::1", 128, [VppRoutePath(sub_if.remote_ip6, sub_if.sw_if_index)] + ) route_2001_1.add_vpp_config() - route_2001_2 = VppIpRoute(self, "2001::2", 128, - [VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index)]) + route_2001_2 = VppIpRoute( + self, + "2001::2", + 128, + [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)], + ) route_2001_2.add_vpp_config() - p_v1 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - Dot1Q(vlan=11, prio=1) / - IP(src="1.1.1.1", dst="10.0.0.2", tos=1) / - UDP(sport=1234, dport=1234) / - Raw(scapy.compat.chb(100) * NUM_PKTS)) - - p_v2 = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IP(src="1.1.1.1", dst="10.0.0.1", tos=1) / - UDP(sport=1234, dport=1234) / - Raw(scapy.compat.chb(100) * NUM_PKTS)) - - p_v3 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - Dot1Q(vlan=11, prio=1, id=1) / - IP(src="1.1.1.1", dst="10.0.0.2", tos=2) / - UDP(sport=1234, dport=1234) / - Raw(scapy.compat.chb(100) * NUM_PKTS)) + p_v1 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / Dot1Q(vlan=11, prio=1) + / IP(src="1.1.1.1", dst="10.0.0.2", tos=1) + / UDP(sport=1234, dport=1234) + / Raw(scapy.compat.chb(100) * NUM_PKTS) + ) + + p_v2 = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src="1.1.1.1", dst="10.0.0.1", tos=1) + / UDP(sport=1234, dport=1234) + / Raw(scapy.compat.chb(100) * NUM_PKTS) + ) + + p_v3 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / Dot1Q(vlan=11, prio=1, id=1) + / IP(src="1.1.1.1", dst="10.0.0.2", tos=2) + / UDP(sport=1234, dport=1234) + / Raw(scapy.compat.chb(100) * NUM_PKTS) + ) rx = self.send_and_expect(self.pg1, p_v2 * NUM_PKTS, self.pg0) @@ -537,16 +569,20 @@ class TestQOS(VppTestCase): for p in rx: self.assertEqual(p[IP].tos, 253) - p_v1 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - Dot1Q(vlan=11, prio=2) / - IPv6(src="2001::1", dst="2001::2", tc=1) / - UDP(sport=1234, dport=1234) / - Raw(scapy.compat.chb(100) * NUM_PKTS)) - - p_v2 = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) / - IPv6(src="3001::1", dst="2001::1", tc=1) / - UDP(sport=1234, dport=1234) / - Raw(scapy.compat.chb(100) * NUM_PKTS)) + p_v1 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / Dot1Q(vlan=11, prio=2) + / IPv6(src="2001::1", dst="2001::2", tc=1) + / UDP(sport=1234, dport=1234) + / Raw(scapy.compat.chb(100) * NUM_PKTS) + ) + + p_v2 = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IPv6(src="3001::1", dst="2001::1", tc=1) + / UDP(sport=1234, dport=1234) + / Raw(scapy.compat.chb(100) * NUM_PKTS) + ) rx = self.send_and_expect(self.pg1, p_v2 * NUM_PKTS, self.pg0) @@ -566,5 +602,5 @@ class TestQOS(VppTestCase): sub_if.unconfig_ip6() -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_quic.py b/test/test_quic.py index 339557d4419..fde781c4f4a 100644 --- a/test/test_quic.py +++ b/test/test_quic.py @@ -12,20 +12,29 @@ from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath class QUICAppWorker(Worker): - """ QUIC Test Application Worker """ + """QUIC Test Application Worker""" + process = None - def __init__(self, appname, executable_args, logger, role, - testcase, env=None, *args, **kwargs): + def __init__( + self, + appname, + executable_args, + logger, + role, + testcase, + env=None, + *args, + **kwargs, + ): if env is None: env = {} app = f"{config.vpp_build_dir}/vpp/bin/{appname}" self.args = [app] + executable_args self.role = role - self.wait_for_gdb = 'wait-for-gdb' + self.wait_for_gdb = "wait-for-gdb" self.testcase = testcase - super(QUICAppWorker, self).__init__(self.args, logger, env, - *args, **kwargs) + super(QUICAppWorker, self).__init__(self.args, logger, env, *args, **kwargs) def run(self): super(QUICAppWorker, self).run() @@ -44,7 +53,7 @@ class QUICAppWorker(Worker): class QUICTestCase(VppTestCase): - """ QUIC Test Case """ + """QUIC Test Case""" timeout = 20 pre_test_sleep = 0.3 @@ -57,7 +66,7 @@ class QUICTestCase(VppTestCase): def setUp(self): super(QUICTestCase, self).setUp() - self.vppDebug = 'vpp_debug' in config.vpp_build_dir + self.vppDebug = "vpp_debug" in config.vpp_build_dir self.create_loopback_interfaces(2) self.uri = "quic://%s/1234" % self.loop0.local_ip4 @@ -74,20 +83,28 @@ class QUICTestCase(VppTestCase): table_id += 1 # Configure namespaces - self.vapi.app_namespace_add_del(namespace_id="server", - sw_if_index=self.loop0.sw_if_index) - self.vapi.app_namespace_add_del(namespace_id="client", - sw_if_index=self.loop1.sw_if_index) + self.vapi.app_namespace_add_del( + namespace_id="server", sw_if_index=self.loop0.sw_if_index + ) + self.vapi.app_namespace_add_del( + namespace_id="client", sw_if_index=self.loop1.sw_if_index + ) # Add inter-table routes - self.ip_t01 = VppIpRoute(self, self.loop1.local_ip4, 32, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_table_id=2)], table_id=1) - self.ip_t10 = VppIpRoute(self, self.loop0.local_ip4, 32, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_table_id=1)], table_id=2) + self.ip_t01 = VppIpRoute( + self, + self.loop1.local_ip4, + 32, + [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=2)], + table_id=1, + ) + self.ip_t10 = VppIpRoute( + self, + self.loop0.local_ip4, + 32, + [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=1)], + table_id=2, + ) self.ip_t01.add_vpp_config() self.ip_t10.add_vpp_config() self.logger.debug(self.vapi.cli("show ip fib")) @@ -106,13 +123,15 @@ class QUICTestCase(VppTestCase): class QUICEchoIntTestCase(QUICTestCase): """QUIC Echo Internal Test Case""" - test_bytes = ' test-bytes' + + test_bytes = " test-bytes" extra_vpp_punt_config = ["session", "{", "enable", "poll-main", "}"] def setUp(self): super(QUICEchoIntTestCase, self).setUp() - self.client_args = 'uri {uri} fifo-size 64{testbytes} appns client' \ - .format(uri=self.uri, testbytes=self.test_bytes) + self.client_args = "uri {uri} fifo-size 64{testbytes} appns client".format( + uri=self.uri, testbytes=self.test_bytes + ) self.server_args = "uri %s fifo-size 64 appns server" % self.uri def tearDown(self): @@ -120,16 +139,16 @@ class QUICEchoIntTestCase(QUICTestCase): def server(self, *args): error = self.vapi.cli( - "test echo server %s %s" % - (self.server_args, ' '.join(args))) + "test echo server %s %s" % (self.server_args, " ".join(args)) + ) if error: self.logger.critical(error) self.assertNotIn("failed", error) def client(self, *args): error = self.vapi.cli( - "test echo client %s %s" % - (self.client_args, ' '.join(args))) + "test echo client %s %s" % (self.client_args, " ".join(args)) + ) if error: self.logger.critical(error) self.assertNotIn("failed", error) @@ -138,6 +157,7 @@ class QUICEchoIntTestCase(QUICTestCase): @tag_fixme_vpp_workers class QUICEchoIntTransferTestCase(QUICEchoIntTestCase): """QUIC Echo Internal Transfer Test Case""" + def test_quic_int_transfer(self): """QUIC internal transfer""" self.server() @@ -147,6 +167,7 @@ class QUICEchoIntTransferTestCase(QUICEchoIntTestCase): @tag_fixme_vpp_workers class QUICEchoIntSerialTestCase(QUICEchoIntTestCase): """QUIC Echo Internal Serial Transfer Test Case""" + def test_quic_serial_int_transfer(self): """QUIC serial internal transfer""" self.server() @@ -160,6 +181,7 @@ class QUICEchoIntSerialTestCase(QUICEchoIntTestCase): @tag_fixme_vpp_workers class QUICEchoIntMStreamTestCase(QUICEchoIntTestCase): """QUIC Echo Internal MultiStream Test Case""" + def test_quic_int_multistream_transfer(self): """QUIC internal multi-stream transfer""" self.server() @@ -176,36 +198,63 @@ class QUICEchoExtTestCase(QUICTestCase): vpp_worker_count = 1 server_fifo_size = "1M" client_fifo_size = "4M" - extra_vpp_punt_config = ["session", "{", - "enable", "poll-main", "evt_qs_memfd_seg", - "evt_qs_seg_size", "64M", - "event-queue-length", f"{evt_q_len}", - "preallocated-sessions", "1024", - "v4-session-table-buckets", "20000", - "v4-session-table-memory", "64M", - "v4-halfopen-table-buckets", "20000", - "v4-halfopen-table-memory", "64M", - "local-endpoints-table-buckets", "250000", - "local-endpoints-table-memory", "512M", - "}"] + extra_vpp_punt_config = [ + "session", + "{", + "enable", + "poll-main", + "evt_qs_memfd_seg", + "evt_qs_seg_size", + "64M", + "event-queue-length", + f"{evt_q_len}", + "preallocated-sessions", + "1024", + "v4-session-table-buckets", + "20000", + "v4-session-table-memory", + "64M", + "v4-halfopen-table-buckets", + "20000", + "v4-halfopen-table-memory", + "64M", + "local-endpoints-table-buckets", + "250000", + "local-endpoints-table-memory", + "512M", + "}", + ] def setUp(self): super(QUICEchoExtTestCase, self).setUp() common_args = [ - "uri", self.uri, + "uri", + self.uri, "json", self.test_bytes, - "socket-name", self.get_api_sock_path(), - "quic-setup", self.quic_setup, - "nthreads", "1", - "mq-size", f"{self.evt_q_len}" + "socket-name", + self.get_api_sock_path(), + "quic-setup", + self.quic_setup, + "nthreads", + "1", + "mq-size", + f"{self.evt_q_len}", + ] + self.server_echo_test_args = common_args + [ + "server", + "appns", + "server", + "fifo-size", + f"{self.server_fifo_size}", + ] + self.client_echo_test_args = common_args + [ + "client", + "appns", + "client", + "fifo-size", + f"{self.client_fifo_size}", ] - self.server_echo_test_args = common_args + \ - ["server", "appns", "server", "fifo-size", - f"{self.server_fifo_size}"] - self.client_echo_test_args = common_args + \ - ["client", "appns", "client", "fifo-size", - f"{self.client_fifo_size}"] error = self.vapi.cli("quic set fifo-size 2M") if error: self.logger.critical(error) @@ -213,23 +262,13 @@ class QUICEchoExtTestCase(QUICTestCase): def server(self, *args): _args = self.server_echo_test_args + list(args) - self.worker_server = QUICAppWorker( - self.app, - _args, - self.logger, - 'server', - self) + self.worker_server = QUICAppWorker(self.app, _args, self.logger, "server", self) self.worker_server.start() self.sleep(self.pre_test_sleep) def client(self, *args): _args = self.client_echo_test_args + list(args) - self.worker_client = QUICAppWorker( - self.app, - _args, - self.logger, - 'client', - self) + self.worker_client = QUICAppWorker(self.app, _args, self.logger, "client", self) self.worker_client.start() timeout = None if self.debug_all else self.timeout self.worker_client.join(timeout) @@ -246,22 +285,18 @@ class QUICEchoExtTestCase(QUICTestCase): def validate_ext_test_results(self): server_result = self.worker_server.result client_result = self.worker_client.result - self.logger.info("Server worker result is `%s'" % - server_result) - self.logger.info("Client worker result is `%s'" % - client_result) + self.logger.info("Server worker result is `%s'" % server_result) + self.logger.info("Client worker result is `%s'" % client_result) server_kill_error = False if self.worker_server.result is None: - server_kill_error = self.worker_server.teardown( - self.logger, self.timeout) + server_kill_error = self.worker_server.teardown(self.logger, self.timeout) if self.worker_client.result is None: self.worker_client.teardown(self.logger, self.timeout) err_msg = "Wrong server worker return code (%s)" % server_result self.assertEqual(server_result, 0, err_msg) self.assertIsNotNone( - client_result, - "Timeout! Client worker did not finish in %ss" % - self.timeout) + client_result, "Timeout! Client worker did not finish in %ss" % self.timeout + ) err_msg = "Wrong client worker return code (%s)" % client_result self.assertEqual(client_result, 0, err_msg) self.assertFalse(server_kill_error, "Server kill errored") @@ -269,6 +304,7 @@ class QUICEchoExtTestCase(QUICTestCase): class QUICEchoExtTransferTestCase(QUICEchoExtTestCase): """QUIC Echo External Transfer Test Case""" + timeout = 60 def test_quic_ext_transfer(self): @@ -280,9 +316,10 @@ class QUICEchoExtTransferTestCase(QUICEchoExtTestCase): class QUICEchoExtTransferBigTestCase(QUICEchoExtTestCase): """QUIC Echo External Transfer Big Test Case""" - server_fifo_size = '4M' - client_fifo_size = '4M' - test_bytes = '' + + server_fifo_size = "4M" + client_fifo_size = "4M" + test_bytes = "" timeout = 60 @unittest.skipUnless(config.extended, "part of extended tests") @@ -312,8 +349,7 @@ class QUICEchoExtQcloseTxTestCase(QUICEchoExtTestCase): @unittest.skip("testcase under development") def test_quic_ext_qclose_tx(self): """QUIC external transfer, tx close""" - self.server("TX=0", "RX=10M", "qclose=W", "sclose=W", - "rx-results-diff") + self.server("TX=0", "RX=10M", "qclose=W", "sclose=W", "rx-results-diff") self.client("TX=10M", "RX=0", "qclose=Y", "sclose=N") self.validate_ext_test_results() @@ -326,8 +362,7 @@ class QUICEchoExtEarlyQcloseRxTestCase(QUICEchoExtTestCase): def test_quic_ext_early_qclose_rx(self): """QUIC external transfer, early rx close""" self.server("TX=0", "RX=10M", "qclose=Y", "sclose=N") - self.client("TX=20M", "RX=0", "qclose=W", "sclose=W", - "tx-results-diff") + self.client("TX=20M", "RX=0", "qclose=W", "sclose=W", "tx-results-diff") self.validate_ext_test_results() @@ -338,8 +373,7 @@ class QUICEchoExtEarlyQcloseTxTestCase(QUICEchoExtTestCase): @unittest.skip("testcase under development") def test_quic_ext_early_qclose_tx(self): """QUIC external transfer, early tx close""" - self.server("TX=0", "RX=20M", "qclose=W", "sclose=W", - "rx-results-diff") + self.server("TX=0", "RX=20M", "qclose=W", "sclose=W", "rx-results-diff") self.client("TX=10M", "RX=0", "qclose=Y", "sclose=N") self.validate_ext_test_results() @@ -376,8 +410,7 @@ class QUICEchoExtEarlyScloseRxTestCase(QUICEchoExtTestCase): def test_quic_ext_early_sclose_rx(self): """QUIC external transfer, early rx stream close""" self.server("TX=0", "RX=10M", "qclose=N", "sclose=Y") - self.client("TX=20M", "RX=0", "qclose=W", "sclose=W", - "tx-results-diff") + self.client("TX=20M", "RX=0", "qclose=W", "sclose=W", "tx-results-diff") self.validate_ext_test_results() @@ -388,14 +421,14 @@ class QUICEchoExtEarlyScloseTxTestCase(QUICEchoExtTestCase): @unittest.skip("testcase under development") def test_quic_ext_early_sclose_tx(self): """QUIC external transfer, early tx stream close""" - self.server("TX=0", "RX=20M", "qclose=W", "sclose=W", - "rx-results-diff") + self.server("TX=0", "RX=20M", "qclose=W", "sclose=W", "rx-results-diff") self.client("TX=10M", "RX=0", "qclose=Y", "sclose=Y") self.validate_ext_test_results() class QUICEchoExtServerStreamTestCase(QUICEchoExtTestCase): """QUIC Echo External Transfer Server Stream Test Case""" + quic_setup = "serverstream" timeout = 60 @@ -408,10 +441,11 @@ class QUICEchoExtServerStreamTestCase(QUICEchoExtTestCase): class QUICEchoExtServerStreamBigTestCase(QUICEchoExtTestCase): """QUIC Echo External Transfer Server Stream Big Test Case""" + quic_setup = "serverstream" - server_fifo_size = '4M' - client_fifo_size = '4M' - test_bytes = '' + server_fifo_size = "4M" + client_fifo_size = "4M" + test_bytes = "" timeout = 60 @unittest.skipUnless(config.extended, "part of extended tests") @@ -424,6 +458,7 @@ class QUICEchoExtServerStreamBigTestCase(QUICEchoExtTestCase): class QUICEchoExtServerStreamQcloseRxTestCase(QUICEchoExtTestCase): """QUIC Echo External Transfer Server Stream Qclose Rx Test Case""" + quic_setup = "serverstream" @unittest.skipUnless(config.extended, "part of extended tests") @@ -437,6 +472,7 @@ class QUICEchoExtServerStreamQcloseRxTestCase(QUICEchoExtTestCase): class QUICEchoExtServerStreamQcloseTxTestCase(QUICEchoExtTestCase): """QUIC Echo External Transfer Server Stream Qclose Tx Test Case""" + quic_setup = "serverstream" @unittest.skipUnless(config.extended, "part of extended tests") @@ -444,27 +480,27 @@ class QUICEchoExtServerStreamQcloseTxTestCase(QUICEchoExtTestCase): def test_quic_ext_server_stream_qclose_tx(self): """QUIC external server transfer, tx close""" self.server("TX=10M", "RX=0", "qclose=Y", "sclose=N") - self.client("TX=0", "RX=10M", "qclose=W", "sclose=W", - "rx-results-diff") + self.client("TX=0", "RX=10M", "qclose=W", "sclose=W", "rx-results-diff") self.validate_ext_test_results() class QUICEchoExtServerStreamEarlyQcloseRxTestCase(QUICEchoExtTestCase): """QUIC Echo External Transfer Server Stream Early Qclose Rx Test Case""" + quic_setup = "serverstream" @unittest.skipUnless(config.extended, "part of extended tests") @unittest.skip("testcase under development") def test_quic_ext_server_stream_early_qclose_rx(self): """QUIC external server transfer, early rx close""" - self.server("TX=20M", "RX=0", "qclose=W", "sclose=W", - "tx-results-diff") + self.server("TX=20M", "RX=0", "qclose=W", "sclose=W", "tx-results-diff") self.client("TX=0", "RX=10M", "qclose=Y", "sclose=N") self.validate_ext_test_results() class QUICEchoExtServerStreamEarlyQcloseTxTestCase(QUICEchoExtTestCase): """QUIC Echo External Transfer Server Stream Early Qclose Tx Test Case""" + quic_setup = "serverstream" @unittest.skipUnless(config.extended, "part of extended tests") @@ -472,13 +508,13 @@ class QUICEchoExtServerStreamEarlyQcloseTxTestCase(QUICEchoExtTestCase): def test_quic_ext_server_stream_early_qclose_tx(self): """QUIC external server transfer, early tx close""" self.server("TX=10M", "RX=0", "qclose=Y", "sclose=N") - self.client("TX=0", "RX=20M", "qclose=W", "sclose=W", - "rx-results-diff") + self.client("TX=0", "RX=20M", "qclose=W", "sclose=W", "rx-results-diff") self.validate_ext_test_results() class QUICEchoExtServerStreamScloseRxTestCase(QUICEchoExtTestCase): """QUIC Echo External Transfer Server Stream Sclose Rx Test Case""" + quic_setup = "serverstream" @unittest.skipUnless(config.extended, "part of extended tests") @@ -492,6 +528,7 @@ class QUICEchoExtServerStreamScloseRxTestCase(QUICEchoExtTestCase): class QUICEchoExtServerStreamScloseTxTestCase(QUICEchoExtTestCase): """QUIC Echo External Transfer Server Stream Sclose Tx Test Case""" + quic_setup = "serverstream" @unittest.skipUnless(config.extended, "part of extended tests") @@ -505,20 +542,21 @@ class QUICEchoExtServerStreamScloseTxTestCase(QUICEchoExtTestCase): class QUICEchoExtServerStreamEarlyScloseRxTestCase(QUICEchoExtTestCase): """QUIC Echo External Transfer Server Stream Early Sclose Rx Test Case""" + quic_setup = "serverstream" @unittest.skipUnless(config.extended, "part of extended tests") @unittest.skip("testcase under development") def test_quic_ext_server_stream_early_sclose_rx(self): """QUIC external server transfer, early rx stream close""" - self.server("TX=20M", "RX=0", "qclose=W", "sclose=W", - "tx-results-diff") + self.server("TX=20M", "RX=0", "qclose=W", "sclose=W", "tx-results-diff") self.client("TX=0", "RX=10M", "qclose=N", "sclose=Y") self.validate_ext_test_results() class QUICEchoExtServerStreamEarlyScloseTxTestCase(QUICEchoExtTestCase): """QUIC Echo Ext Transfer Server Stream Early Sclose Tx Test Case""" + quic_setup = "serverstream" @unittest.skipUnless(config.extended, "part of extended tests") @@ -526,13 +564,13 @@ class QUICEchoExtServerStreamEarlyScloseTxTestCase(QUICEchoExtTestCase): def test_quic_ext_server_stream_early_sclose_tx(self): """QUIC external server transfer, early tx stream close""" self.server("TX=10M", "RX=0", "qclose=Y", "sclose=Y") - self.client("TX=0", "RX=20M", "qclose=W", "sclose=W", - "rx-results-diff") + self.client("TX=0", "RX=20M", "qclose=W", "sclose=W", "rx-results-diff") self.validate_ext_test_results() class QUICEchoExtServerStreamWorkersTestCase(QUICEchoExtTestCase): """QUIC Echo External Transfer Server Stream MultiWorker Test Case""" + quic_setup = "serverstream" @unittest.skipUnless(config.extended, "part of extended tests") @@ -544,5 +582,5 @@ class QUICEchoExtServerStreamWorkersTestCase(QUICEchoExtTestCase): self.validate_ext_test_results() -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_reassembly.py b/test/test_reassembly.py index 4c7a7cd320b..cebe5837763 100644 --- a/test/test_reassembly.py +++ b/test/test_reassembly.py @@ -9,10 +9,18 @@ import scapy.compat from scapy.packet import Raw from scapy.layers.l2 import Ether, GRE from scapy.layers.inet import IP, UDP, ICMP, icmptypes -from scapy.layers.inet6 import HBHOptUnknown, ICMPv6ParamProblem,\ - ICMPv6TimeExceeded, IPv6, IPv6ExtHdrFragment,\ - IPv6ExtHdrHopByHop, IPv6ExtHdrDestOpt, PadN, ICMPv6EchoRequest,\ - ICMPv6EchoReply +from scapy.layers.inet6 import ( + HBHOptUnknown, + ICMPv6ParamProblem, + ICMPv6TimeExceeded, + IPv6, + IPv6ExtHdrFragment, + IPv6ExtHdrHopByHop, + IPv6ExtHdrDestOpt, + PadN, + ICMPv6EchoRequest, + ICMPv6EchoReply, +) from framework import VppTestCase, VppTestRunner from util import ppp, ppc, fragment_rfc791, fragment_rfc8200 from vpp_gre_interface import VppGreInterface @@ -25,7 +33,7 @@ test_packet_count = 35 class TestIPv4Reassembly(VppTestCase): - """ IPv4 Reassembly """ + """IPv4 Reassembly""" @classmethod def setUpClass(cls): @@ -52,21 +60,29 @@ class TestIPv4Reassembly(VppTestCase): super().tearDownClass() def setUp(self): - """ Test setup - force timeout on existing reassemblies """ + """Test setup - force timeout on existing reassemblies""" super().setUp() self.vapi.ip_reassembly_enable_disable( - sw_if_index=self.src_if.sw_if_index, enable_ip4=True) - self.vapi.ip_reassembly_set(timeout_ms=0, max_reassemblies=1000, - max_reassembly_length=1000, - expire_walk_interval_ms=10) - self.virtual_sleep(.25) - self.vapi.ip_reassembly_set(timeout_ms=1000000, max_reassemblies=1000, - max_reassembly_length=1000, - expire_walk_interval_ms=10000) + sw_if_index=self.src_if.sw_if_index, enable_ip4=True + ) + self.vapi.ip_reassembly_set( + timeout_ms=0, + max_reassemblies=1000, + max_reassembly_length=1000, + expire_walk_interval_ms=10, + ) + self.virtual_sleep(0.25) + self.vapi.ip_reassembly_set( + timeout_ms=1000000, + max_reassemblies=1000, + max_reassembly_length=1000, + expire_walk_interval_ms=10000, + ) def tearDown(self): self.vapi.ip_reassembly_enable_disable( - sw_if_index=self.src_if.sw_if_index, enable_ip4=False) + sw_if_index=self.src_if.sw_if_index, enable_ip4=False + ) super().tearDown() def show_commands_at_teardown(self): @@ -82,11 +98,14 @@ class TestIPv4Reassembly(VppTestCase): for i in range(0, packet_count): info = cls.create_packet_info(cls.src_if, cls.src_if) payload = cls.info_to_payload(info) - p = (Ether(dst=cls.src_if.local_mac, src=cls.src_if.remote_mac) / - IP(id=info.index, src=cls.src_if.remote_ip4, - dst=cls.dst_if.remote_ip4) / - UDP(sport=1234, dport=5678) / - Raw(payload)) + p = ( + Ether(dst=cls.src_if.local_mac, src=cls.src_if.remote_mac) + / IP( + id=info.index, src=cls.src_if.remote_ip4, dst=cls.dst_if.remote_ip4 + ) + / UDP(sport=1234, dport=5678) + / Raw(payload) + ) size = packet_sizes[(i // 2) % len(packet_sizes)] cls.extend_packet(p, size, cls.padding) info.data = p @@ -101,20 +120,21 @@ class TestIPv4Reassembly(VppTestCase): # p.__class__(scapy.compat.raw(p)))) fragments_400 = fragment_rfc791(p, 400) fragments_300 = fragment_rfc791(p, 300) - fragments_200 = [ - x for f in fragments_400 for x in fragment_rfc791(f, 200)] - cls.pkt_infos.append( - (index, fragments_400, fragments_300, fragments_200)) - cls.fragments_400 = [ - x for (_, frags, _, _) in cls.pkt_infos for x in frags] - cls.fragments_300 = [ - x for (_, _, frags, _) in cls.pkt_infos for x in frags] - cls.fragments_200 = [ - x for (_, _, _, frags) in cls.pkt_infos for x in frags] - cls.logger.debug("Fragmented %s packets into %s 400-byte fragments, " - "%s 300-byte fragments and %s 200-byte fragments" % - (len(infos), len(cls.fragments_400), - len(cls.fragments_300), len(cls.fragments_200))) + fragments_200 = [x for f in fragments_400 for x in fragment_rfc791(f, 200)] + cls.pkt_infos.append((index, fragments_400, fragments_300, fragments_200)) + cls.fragments_400 = [x for (_, frags, _, _) in cls.pkt_infos for x in frags] + cls.fragments_300 = [x for (_, _, frags, _) in cls.pkt_infos for x in frags] + cls.fragments_200 = [x for (_, _, _, frags) in cls.pkt_infos for x in frags] + cls.logger.debug( + "Fragmented %s packets into %s 400-byte fragments, " + "%s 300-byte fragments and %s 200-byte fragments" + % ( + len(infos), + len(cls.fragments_400), + len(cls.fragments_300), + len(cls.fragments_200), + ) + ) def verify_capture(self, capture, dropped_packet_indexes=[]): """Verify captured packet stream. @@ -132,7 +152,8 @@ class TestIPv4Reassembly(VppTestCase): packet_index = payload_info.index self.assertTrue( packet_index not in dropped_packet_indexes, - ppp("Packet received, but should be dropped:", packet)) + ppp("Packet received, but should be dropped:", packet), + ) if packet_index in seen: raise Exception(ppp("Duplicate packet received", packet)) seen.add(packet_index) @@ -148,11 +169,13 @@ class TestIPv4Reassembly(VppTestCase): self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise for index in self._packet_infos: - self.assertTrue(index in seen or index in dropped_packet_indexes, - "Packet with packet_index %d not received" % index) + self.assertTrue( + index in seen or index in dropped_packet_indexes, + "Packet with packet_index %d not received" % index, + ) def test_reassembly(self): - """ basic reassembly """ + """basic reassembly""" self.pg_enable_capture() self.src_if.add_stream(self.fragments_200) @@ -172,7 +195,7 @@ class TestIPv4Reassembly(VppTestCase): self.src_if.assert_nothing_captured() def test_verify_clear_trace_mid_reassembly(self): - """ verify clear trace works mid-reassembly """ + """verify clear trace works mid-reassembly""" self.pg_enable_capture() self.src_if.add_stream(self.fragments_200[0:-1]) @@ -187,7 +210,7 @@ class TestIPv4Reassembly(VppTestCase): self.verify_capture(packets) def test_reversed(self): - """ reverse order reassembly """ + """reverse order reassembly""" fragments = list(self.fragments_200) fragments.reverse() @@ -210,27 +233,33 @@ class TestIPv4Reassembly(VppTestCase): self.src_if.assert_nothing_captured() def test_long_fragment_chain(self): - """ long fragment chain """ + """long fragment chain""" - error_cnt_str = \ + error_cnt_str = ( "/err/ip4-full-reassembly-feature/fragment chain too long (drop)" + ) error_cnt = self.statistics.get_err_counter(error_cnt_str) - self.vapi.ip_reassembly_set(timeout_ms=100, max_reassemblies=1000, - max_reassembly_length=3, - expire_walk_interval_ms=50) - - p1 = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / - IP(id=1000, src=self.src_if.remote_ip4, - dst=self.dst_if.remote_ip4) / - UDP(sport=1234, dport=5678) / - Raw(b"X" * 1000)) - p2 = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / - IP(id=1001, src=self.src_if.remote_ip4, - dst=self.dst_if.remote_ip4) / - UDP(sport=1234, dport=5678) / - Raw(b"X" * 1000)) + self.vapi.ip_reassembly_set( + timeout_ms=100, + max_reassemblies=1000, + max_reassembly_length=3, + expire_walk_interval_ms=50, + ) + + p1 = ( + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IP(id=1000, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) + / UDP(sport=1234, dport=5678) + / Raw(b"X" * 1000) + ) + p2 = ( + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IP(id=1001, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) + / UDP(sport=1234, dport=5678) + / Raw(b"X" * 1000) + ) frags = fragment_rfc791(p1, 200) + fragment_rfc791(p2, 500) self.pg_enable_capture() @@ -241,19 +270,20 @@ class TestIPv4Reassembly(VppTestCase): self.assert_error_counter_equal(error_cnt_str, error_cnt + 1) def test_5737(self): - """ fragment length + ip header size > 65535 """ + """fragment length + ip header size > 65535""" self.vapi.cli("clear errors") - raw = b'''E\x00\x00\x88,\xf8\x1f\xfe@\x01\x98\x00\xc0\xa8\n-\xc0\xa8\n\ + raw = b"""E\x00\x00\x88,\xf8\x1f\xfe@\x01\x98\x00\xc0\xa8\n-\xc0\xa8\n\ \x01\x08\x00\xf0J\xed\xcb\xf1\xf5Test-group: IPv4.IPv4.ipv4-message.\ -Ethernet-Payload.IPv4-Packet.IPv4-Header.Fragment-Offset; Test-case: 5737''' - malformed_packet = (Ether(dst=self.src_if.local_mac, - src=self.src_if.remote_mac) / - IP(raw)) - p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / - IP(id=1000, src=self.src_if.remote_ip4, - dst=self.dst_if.remote_ip4) / - UDP(sport=1234, dport=5678) / - Raw(b"X" * 1000)) +Ethernet-Payload.IPv4-Packet.IPv4-Header.Fragment-Offset; Test-case: 5737""" + malformed_packet = Ether( + dst=self.src_if.local_mac, src=self.src_if.remote_mac + ) / IP(raw) + p = ( + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IP(id=1000, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) + / UDP(sport=1234, dport=5678) + / Raw(b"X" * 1000) + ) valid_fragments = fragment_rfc791(p, 400) counter = "/err/ip4-full-reassembly-feature/malformed packets" @@ -264,33 +294,50 @@ Ethernet-Payload.IPv4-Packet.IPv4-Header.Fragment-Offset; Test-case: 5737''' self.dst_if.get_capture(1) self.logger.debug(self.vapi.ppcli("show error")) - self.assertEqual(self.statistics.get_err_counter(counter), - error_counter + 1) + self.assertEqual(self.statistics.get_err_counter(counter), error_counter + 1) def test_44924(self): - """ compress tiny fragments """ - packets = [(Ether(dst=self.src_if.local_mac, - src=self.src_if.remote_mac) / - IP(id=24339, flags="MF", frag=0, ttl=64, - src=self.src_if.remote_ip4, - dst=self.dst_if.remote_ip4) / - ICMP(type="echo-request", code=0, id=0x1fe6, seq=0x2407) / - Raw(load='Test-group: IPv4')), - (Ether(dst=self.src_if.local_mac, - src=self.src_if.remote_mac) / - IP(id=24339, flags="MF", frag=3, ttl=64, - src=self.src_if.remote_ip4, - dst=self.dst_if.remote_ip4) / - ICMP(type="echo-request", code=0, id=0x1fe6, seq=0x2407) / - Raw(load='.IPv4.Fragmentation.vali')), - (Ether(dst=self.src_if.local_mac, - src=self.src_if.remote_mac) / - IP(id=24339, frag=6, ttl=64, - src=self.src_if.remote_ip4, - dst=self.dst_if.remote_ip4) / - ICMP(type="echo-request", code=0, id=0x1fe6, seq=0x2407) / - Raw(load='d; Test-case: 44924')) - ] + """compress tiny fragments""" + packets = [ + ( + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IP( + id=24339, + flags="MF", + frag=0, + ttl=64, + src=self.src_if.remote_ip4, + dst=self.dst_if.remote_ip4, + ) + / ICMP(type="echo-request", code=0, id=0x1FE6, seq=0x2407) + / Raw(load="Test-group: IPv4") + ), + ( + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IP( + id=24339, + flags="MF", + frag=3, + ttl=64, + src=self.src_if.remote_ip4, + dst=self.dst_if.remote_ip4, + ) + / ICMP(type="echo-request", code=0, id=0x1FE6, seq=0x2407) + / Raw(load=".IPv4.Fragmentation.vali") + ), + ( + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IP( + id=24339, + frag=6, + ttl=64, + src=self.src_if.remote_ip4, + dst=self.dst_if.remote_ip4, + ) + / ICMP(type="echo-request", code=0, id=0x1FE6, seq=0x2407) + / Raw(load="d; Test-case: 44924") + ), + ] self.pg_enable_capture() self.src_if.add_stream(packets) @@ -299,27 +346,42 @@ Ethernet-Payload.IPv4-Packet.IPv4-Header.Fragment-Offset; Test-case: 5737''' self.dst_if.get_capture(1) def test_frag_1(self): - """ fragment of size 1 """ + """fragment of size 1""" self.vapi.cli("clear errors") - malformed_packets = [(Ether(dst=self.src_if.local_mac, - src=self.src_if.remote_mac) / - IP(id=7, len=21, flags="MF", frag=0, ttl=64, - src=self.src_if.remote_ip4, - dst=self.dst_if.remote_ip4) / - ICMP(type="echo-request")), - (Ether(dst=self.src_if.local_mac, - src=self.src_if.remote_mac) / - IP(id=7, len=21, frag=1, ttl=64, - src=self.src_if.remote_ip4, - dst=self.dst_if.remote_ip4) / - Raw(load=b'\x08')), - ] - - p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / - IP(id=1000, src=self.src_if.remote_ip4, - dst=self.dst_if.remote_ip4) / - UDP(sport=1234, dport=5678) / - Raw(b"X" * 1000)) + malformed_packets = [ + ( + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IP( + id=7, + len=21, + flags="MF", + frag=0, + ttl=64, + src=self.src_if.remote_ip4, + dst=self.dst_if.remote_ip4, + ) + / ICMP(type="echo-request") + ), + ( + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IP( + id=7, + len=21, + frag=1, + ttl=64, + src=self.src_if.remote_ip4, + dst=self.dst_if.remote_ip4, + ) + / Raw(load=b"\x08") + ), + ] + + p = ( + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IP(id=1000, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) + / UDP(sport=1234, dport=5678) + / Raw(b"X" * 1000) + ) valid_fragments = fragment_rfc791(p, 400) self.pg_enable_capture() @@ -335,7 +397,7 @@ Ethernet-Payload.IPv4-Packet.IPv4-Header.Fragment-Offset; Test-case: 5737''' # "/err/ip4-full-reassembly-feature/malformed packets", 1) def test_random(self): - """ random order reassembly """ + """random order reassembly""" fragments = list(self.fragments_200) shuffle(fragments) @@ -358,10 +420,11 @@ Ethernet-Payload.IPv4-Packet.IPv4-Header.Fragment-Offset; Test-case: 5737''' self.src_if.assert_nothing_captured() def test_duplicates(self): - """ duplicate fragments """ + """duplicate fragments""" fragments = [ - x for (_, frags, _, _) in self.pkt_infos + x + for (_, frags, _, _) in self.pkt_infos for x in frags for _ in range(0, min(2, len(frags))) ] @@ -375,7 +438,7 @@ Ethernet-Payload.IPv4-Packet.IPv4-Header.Fragment-Offset; Test-case: 5737''' self.src_if.assert_nothing_captured() def test_overlap1(self): - """ overlapping fragments case #1 """ + """overlapping fragments case #1""" fragments = [] for _, _, frags_300, frags_200 in self.pkt_infos: @@ -404,7 +467,7 @@ Ethernet-Payload.IPv4-Packet.IPv4-Header.Fragment-Offset; Test-case: 5737''' self.src_if.assert_nothing_captured() def test_overlap2(self): - """ overlapping fragments case #2 """ + """overlapping fragments case #2""" fragments = [] for _, _, frags_300, frags_200 in self.pkt_infos: @@ -439,94 +502,112 @@ Ethernet-Payload.IPv4-Packet.IPv4-Header.Fragment-Offset; Test-case: 5737''' self.src_if.assert_nothing_captured() def test_timeout_inline(self): - """ timeout (inline) """ + """timeout (inline)""" dropped_packet_indexes = set( index for (index, frags, _, _) in self.pkt_infos if len(frags) > 1 ) - self.vapi.ip_reassembly_set(timeout_ms=0, max_reassemblies=1000, - max_reassembly_length=3, - expire_walk_interval_ms=10000) + self.vapi.ip_reassembly_set( + timeout_ms=0, + max_reassemblies=1000, + max_reassembly_length=3, + expire_walk_interval_ms=10000, + ) self.pg_enable_capture() self.src_if.add_stream(self.fragments_400) self.pg_start() packets = self.dst_if.get_capture( - len(self.pkt_infos) - len(dropped_packet_indexes)) + len(self.pkt_infos) - len(dropped_packet_indexes) + ) self.verify_capture(packets, dropped_packet_indexes) self.src_if.assert_nothing_captured() def test_timeout_cleanup(self): - """ timeout (cleanup) """ + """timeout (cleanup)""" # whole packets + fragmented packets sans last fragment fragments = [ - x for (_, frags_400, _, _) in self.pkt_infos - for x in frags_400[:-1 if len(frags_400) > 1 else None] + x + for (_, frags_400, _, _) in self.pkt_infos + for x in frags_400[: -1 if len(frags_400) > 1 else None] ] # last fragments for fragmented packets - fragments2 = [frags_400[-1] - for (_, frags_400, _, _) in self.pkt_infos - if len(frags_400) > 1] + fragments2 = [ + frags_400[-1] + for (_, frags_400, _, _) in self.pkt_infos + if len(frags_400) > 1 + ] dropped_packet_indexes = set( - index for (index, frags_400, _, _) in self.pkt_infos - if len(frags_400) > 1) + index for (index, frags_400, _, _) in self.pkt_infos if len(frags_400) > 1 + ) - self.vapi.ip_reassembly_set(timeout_ms=100, max_reassemblies=1000, - max_reassembly_length=1000, - expire_walk_interval_ms=50) + self.vapi.ip_reassembly_set( + timeout_ms=100, + max_reassemblies=1000, + max_reassembly_length=1000, + expire_walk_interval_ms=50, + ) self.pg_enable_capture() self.src_if.add_stream(fragments) self.pg_start() - self.virtual_sleep(.25, "wait before sending rest of fragments") + self.virtual_sleep(0.25, "wait before sending rest of fragments") self.src_if.add_stream(fragments2) self.pg_start() packets = self.dst_if.get_capture( - len(self.pkt_infos) - len(dropped_packet_indexes)) + len(self.pkt_infos) - len(dropped_packet_indexes) + ) self.verify_capture(packets, dropped_packet_indexes) self.src_if.assert_nothing_captured() def test_disabled(self): - """ reassembly disabled """ + """reassembly disabled""" dropped_packet_indexes = set( - index for (index, frags_400, _, _) in self.pkt_infos - if len(frags_400) > 1) + index for (index, frags_400, _, _) in self.pkt_infos if len(frags_400) > 1 + ) - self.vapi.ip_reassembly_set(timeout_ms=1000, max_reassemblies=0, - max_reassembly_length=3, - expire_walk_interval_ms=10000) + self.vapi.ip_reassembly_set( + timeout_ms=1000, + max_reassemblies=0, + max_reassembly_length=3, + expire_walk_interval_ms=10000, + ) self.pg_enable_capture() self.src_if.add_stream(self.fragments_400) self.pg_start() packets = self.dst_if.get_capture( - len(self.pkt_infos) - len(dropped_packet_indexes)) + len(self.pkt_infos) - len(dropped_packet_indexes) + ) self.verify_capture(packets, dropped_packet_indexes) self.src_if.assert_nothing_captured() def test_local_enable_disable(self): - """ local reassembly enabled/disable """ + """local reassembly enabled/disable""" self.vapi.ip_reassembly_enable_disable( - sw_if_index=self.src_if.sw_if_index, enable_ip4=False) + sw_if_index=self.src_if.sw_if_index, enable_ip4=False + ) self.vapi.ip_local_reass_enable_disable(enable_ip4=True) - p = (Ether(src=self.src_if.remote_mac, dst=self.src_if.local_mac) / - IP(src=self.src_if.remote_ip4, dst=self.src_if.local_ip4) / - ICMP(id=1234, type='echo-request') / - Raw('x' * 1000)) + p = ( + Ether(src=self.src_if.remote_mac, dst=self.src_if.local_mac) + / IP(src=self.src_if.remote_ip4, dst=self.src_if.local_ip4) + / ICMP(id=1234, type="echo-request") + / Raw("x" * 1000) + ) frags = fragment_rfc791(p, 400) r = self.send_and_expect(self.src_if, frags, self.src_if, n_rx=1)[0] self.assertEqual(1234, r[ICMP].id) - self.assertEqual(icmptypes[r[ICMP].type], 'echo-reply') + self.assertEqual(icmptypes[r[ICMP].type], "echo-reply") self.vapi.ip_local_reass_enable_disable() self.send_and_assert_no_replies(self.src_if, frags) @@ -534,7 +615,7 @@ Ethernet-Payload.IPv4-Packet.IPv4-Header.Fragment-Offset; Test-case: 5737''' class TestIPv4SVReassembly(VppTestCase): - """ IPv4 Shallow Virtual Reassembly """ + """IPv4 Shallow Virtual Reassembly""" @classmethod def setUpClass(cls): @@ -551,22 +632,28 @@ class TestIPv4SVReassembly(VppTestCase): i.resolve_arp() def setUp(self): - """ Test setup - force timeout on existing reassemblies """ + """Test setup - force timeout on existing reassemblies""" super().setUp() self.vapi.ip_reassembly_enable_disable( - sw_if_index=self.src_if.sw_if_index, enable_ip4=True, - type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL) + sw_if_index=self.src_if.sw_if_index, + enable_ip4=True, + type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL, + ) self.vapi.ip_reassembly_set( - timeout_ms=0, max_reassemblies=1000, + timeout_ms=0, + max_reassemblies=1000, max_reassembly_length=1000, type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL, - expire_walk_interval_ms=10) - self.virtual_sleep(.25) + expire_walk_interval_ms=10, + ) + self.virtual_sleep(0.25) self.vapi.ip_reassembly_set( - timeout_ms=1000000, max_reassemblies=1000, + timeout_ms=1000000, + max_reassemblies=1000, max_reassembly_length=1000, type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL, - expire_walk_interval_ms=10000) + expire_walk_interval_ms=10000, + ) def tearDown(self): super().tearDown() @@ -574,7 +661,7 @@ class TestIPv4SVReassembly(VppTestCase): self.logger.debug(self.vapi.ppcli("show buffers")) def test_basic(self): - """ basic reassembly """ + """basic reassembly""" payload_len = 1000 payload = "" counter = 0 @@ -582,12 +669,13 @@ class TestIPv4SVReassembly(VppTestCase): payload += "%u " % counter counter += 1 - p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / - IP(id=1, src=self.src_if.remote_ip4, - dst=self.dst_if.remote_ip4) / - UDP(sport=1234, dport=5678) / - Raw(payload)) - fragments = fragment_rfc791(p, payload_len/4) + p = ( + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IP(id=1, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) + / UDP(sport=1234, dport=5678) + / Raw(payload) + ) + fragments = fragment_rfc791(p, payload_len / 4) # send fragment #2 - should be cached inside reassembly self.pg_enable_capture() @@ -623,7 +711,7 @@ class TestIPv4SVReassembly(VppTestCase): self.assertEqual(sent[Raw].payload, recvd[Raw].payload) def test_verify_clear_trace_mid_reassembly(self): - """ verify clear trace works mid-reassembly """ + """verify clear trace works mid-reassembly""" payload_len = 1000 payload = "" counter = 0 @@ -631,12 +719,13 @@ class TestIPv4SVReassembly(VppTestCase): payload += "%u " % counter counter += 1 - p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / - IP(id=1, src=self.src_if.remote_ip4, - dst=self.dst_if.remote_ip4) / - UDP(sport=1234, dport=5678) / - Raw(payload)) - fragments = fragment_rfc791(p, payload_len/4) + p = ( + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IP(id=1, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) + / UDP(sport=1234, dport=5678) + / Raw(payload) + ) + fragments = fragment_rfc791(p, payload_len / 4) self.pg_enable_capture() self.src_if.add_stream(fragments[1]) @@ -659,7 +748,7 @@ class TestIPv4SVReassembly(VppTestCase): self.dst_if.get_capture(len(fragments[2:])) def test_timeout(self): - """ reassembly timeout """ + """reassembly timeout""" payload_len = 1000 payload = "" counter = 0 @@ -667,18 +756,21 @@ class TestIPv4SVReassembly(VppTestCase): payload += "%u " % counter counter += 1 - p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / - IP(id=1, src=self.src_if.remote_ip4, - dst=self.dst_if.remote_ip4) / - UDP(sport=1234, dport=5678) / - Raw(payload)) - fragments = fragment_rfc791(p, payload_len/4) + p = ( + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IP(id=1, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) + / UDP(sport=1234, dport=5678) + / Raw(payload) + ) + fragments = fragment_rfc791(p, payload_len / 4) self.vapi.ip_reassembly_set( - timeout_ms=100, max_reassemblies=1000, + timeout_ms=100, + max_reassemblies=1000, max_reassembly_length=1000, expire_walk_interval_ms=50, - type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL) + type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL, + ) # send fragments #2 and #1 - should be forwarded self.pg_enable_capture() @@ -694,7 +786,7 @@ class TestIPv4SVReassembly(VppTestCase): self.assertEqual(sent[Raw].payload, recvd[Raw].payload) # wait for cleanup - self.virtual_sleep(.25, "wait before sending rest of fragments") + self.virtual_sleep(0.25, "wait before sending rest of fragments") # send rest of fragments - shouldn't be forwarded self.pg_enable_capture() @@ -703,13 +795,15 @@ class TestIPv4SVReassembly(VppTestCase): self.dst_if.assert_nothing_captured() def test_lru(self): - """ reassembly reuses LRU element """ + """reassembly reuses LRU element""" self.vapi.ip_reassembly_set( - timeout_ms=1000000, max_reassemblies=1, + timeout_ms=1000000, + max_reassemblies=1, max_reassembly_length=1000, type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL, - expire_walk_interval_ms=10000) + expire_walk_interval_ms=10000, + ) payload_len = 1000 payload = "" @@ -720,15 +814,17 @@ class TestIPv4SVReassembly(VppTestCase): packet_count = 10 - fragments = [f - for i in range(packet_count) - for p in (Ether(dst=self.src_if.local_mac, - src=self.src_if.remote_mac) / - IP(id=i, src=self.src_if.remote_ip4, - dst=self.dst_if.remote_ip4) / - UDP(sport=1234, dport=5678) / - Raw(payload)) - for f in fragment_rfc791(p, payload_len/4)] + fragments = [ + f + for i in range(packet_count) + for p in ( + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IP(id=i, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) + / UDP(sport=1234, dport=5678) + / Raw(payload) + ) + for f in fragment_rfc791(p, payload_len / 4) + ] self.pg_enable_capture() self.src_if.add_stream(fragments) @@ -742,16 +838,20 @@ class TestIPv4SVReassembly(VppTestCase): def send_mixed_and_verify_capture(self, traffic): stream = [] for t in traffic: - for c in range(t['count']): + for c in range(t["count"]): stream.append( - (Ether(dst=self.src_if.local_mac, - src=self.src_if.remote_mac) / - IP(id=self.counter, - flags=t['flags'], - src=self.src_if.remote_ip4, - dst=self.dst_if.remote_ip4) / - UDP(sport=1234, dport=5678) / - Raw("abcdef"))) + ( + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IP( + id=self.counter, + flags=t["flags"], + src=self.src_if.remote_ip4, + dst=self.dst_if.remote_ip4, + ) + / UDP(sport=1234, dport=5678) + / Raw("abcdef") + ) + ) self.counter = self.counter + 1 self.pg_enable_capture() @@ -763,58 +863,89 @@ class TestIPv4SVReassembly(VppTestCase): self.dst_if.get_capture(len(stream)) def test_mixed(self): - """ mixed traffic correctly passes through SVR """ + """mixed traffic correctly passes through SVR""" self.counter = 1 - self.send_mixed_and_verify_capture([{'count': 1, 'flags': ''}]) - self.send_mixed_and_verify_capture([{'count': 2, 'flags': ''}]) - self.send_mixed_and_verify_capture([{'count': 3, 'flags': ''}]) - self.send_mixed_and_verify_capture([{'count': 8, 'flags': ''}]) - self.send_mixed_and_verify_capture([{'count': 257, 'flags': ''}]) + self.send_mixed_and_verify_capture([{"count": 1, "flags": ""}]) + self.send_mixed_and_verify_capture([{"count": 2, "flags": ""}]) + self.send_mixed_and_verify_capture([{"count": 3, "flags": ""}]) + self.send_mixed_and_verify_capture([{"count": 8, "flags": ""}]) + self.send_mixed_and_verify_capture([{"count": 257, "flags": ""}]) - self.send_mixed_and_verify_capture([{'count': 1, 'flags': 'MF'}]) - self.send_mixed_and_verify_capture([{'count': 2, 'flags': 'MF'}]) - self.send_mixed_and_verify_capture([{'count': 3, 'flags': 'MF'}]) - self.send_mixed_and_verify_capture([{'count': 8, 'flags': 'MF'}]) - self.send_mixed_and_verify_capture([{'count': 257, 'flags': 'MF'}]) + self.send_mixed_and_verify_capture([{"count": 1, "flags": "MF"}]) + self.send_mixed_and_verify_capture([{"count": 2, "flags": "MF"}]) + self.send_mixed_and_verify_capture([{"count": 3, "flags": "MF"}]) + self.send_mixed_and_verify_capture([{"count": 8, "flags": "MF"}]) + self.send_mixed_and_verify_capture([{"count": 257, "flags": "MF"}]) self.send_mixed_and_verify_capture( - [{'count': 1, 'flags': ''}, {'count': 1, 'flags': 'MF'}]) + [{"count": 1, "flags": ""}, {"count": 1, "flags": "MF"}] + ) self.send_mixed_and_verify_capture( - [{'count': 2, 'flags': ''}, {'count': 2, 'flags': 'MF'}]) + [{"count": 2, "flags": ""}, {"count": 2, "flags": "MF"}] + ) self.send_mixed_and_verify_capture( - [{'count': 3, 'flags': ''}, {'count': 3, 'flags': 'MF'}]) + [{"count": 3, "flags": ""}, {"count": 3, "flags": "MF"}] + ) self.send_mixed_and_verify_capture( - [{'count': 8, 'flags': ''}, {'count': 8, 'flags': 'MF'}]) + [{"count": 8, "flags": ""}, {"count": 8, "flags": "MF"}] + ) self.send_mixed_and_verify_capture( - [{'count': 129, 'flags': ''}, {'count': 129, 'flags': 'MF'}]) + [{"count": 129, "flags": ""}, {"count": 129, "flags": "MF"}] + ) self.send_mixed_and_verify_capture( - [{'count': 1, 'flags': ''}, {'count': 1, 'flags': 'MF'}, - {'count': 1, 'flags': ''}, {'count': 1, 'flags': 'MF'}]) + [ + {"count": 1, "flags": ""}, + {"count": 1, "flags": "MF"}, + {"count": 1, "flags": ""}, + {"count": 1, "flags": "MF"}, + ] + ) self.send_mixed_and_verify_capture( - [{'count': 2, 'flags': ''}, {'count': 2, 'flags': 'MF'}, - {'count': 2, 'flags': ''}, {'count': 2, 'flags': 'MF'}]) + [ + {"count": 2, "flags": ""}, + {"count": 2, "flags": "MF"}, + {"count": 2, "flags": ""}, + {"count": 2, "flags": "MF"}, + ] + ) self.send_mixed_and_verify_capture( - [{'count': 3, 'flags': ''}, {'count': 3, 'flags': 'MF'}, - {'count': 3, 'flags': ''}, {'count': 3, 'flags': 'MF'}]) + [ + {"count": 3, "flags": ""}, + {"count": 3, "flags": "MF"}, + {"count": 3, "flags": ""}, + {"count": 3, "flags": "MF"}, + ] + ) self.send_mixed_and_verify_capture( - [{'count': 8, 'flags': ''}, {'count': 8, 'flags': 'MF'}, - {'count': 8, 'flags': ''}, {'count': 8, 'flags': 'MF'}]) + [ + {"count": 8, "flags": ""}, + {"count": 8, "flags": "MF"}, + {"count": 8, "flags": ""}, + {"count": 8, "flags": "MF"}, + ] + ) self.send_mixed_and_verify_capture( - [{'count': 65, 'flags': ''}, {'count': 65, 'flags': 'MF'}, - {'count': 65, 'flags': ''}, {'count': 65, 'flags': 'MF'}]) + [ + {"count": 65, "flags": ""}, + {"count": 65, "flags": "MF"}, + {"count": 65, "flags": ""}, + {"count": 65, "flags": "MF"}, + ] + ) class TestIPv4MWReassembly(VppTestCase): - """ IPv4 Reassembly (multiple workers) """ + """IPv4 Reassembly (multiple workers)""" + vpp_worker_count = 3 @classmethod def setUpClass(cls): super().setUpClass() - cls.create_pg_interfaces(range(cls.vpp_worker_count+1)) + cls.create_pg_interfaces(range(cls.vpp_worker_count + 1)) cls.src_if = cls.pg0 cls.send_ifs = cls.pg_interfaces[:-1] cls.dst_if = cls.pg_interfaces[-1] @@ -828,8 +959,12 @@ class TestIPv4MWReassembly(VppTestCase): # packets sizes reduced here because we are generating packets without # Ethernet headers, which are added later (diff fragments go via # different interfaces) - cls.packet_sizes = [64-len(Ether()), 512-len(Ether()), - 1518-len(Ether()), 9018-len(Ether())] + cls.packet_sizes = [ + 64 - len(Ether()), + 512 - len(Ether()), + 1518 - len(Ether()), + 9018 - len(Ether()), + ] cls.padding = " abcdefghijklmn" cls.create_stream(cls.packet_sizes) cls.create_fragments() @@ -839,23 +974,31 @@ class TestIPv4MWReassembly(VppTestCase): super().tearDownClass() def setUp(self): - """ Test setup - force timeout on existing reassemblies """ + """Test setup - force timeout on existing reassemblies""" super().setUp() for intf in self.send_ifs: self.vapi.ip_reassembly_enable_disable( - sw_if_index=intf.sw_if_index, enable_ip4=True) - self.vapi.ip_reassembly_set(timeout_ms=0, max_reassemblies=1000, - max_reassembly_length=1000, - expire_walk_interval_ms=10) - self.virtual_sleep(.25) - self.vapi.ip_reassembly_set(timeout_ms=1000000, max_reassemblies=1000, - max_reassembly_length=1000, - expire_walk_interval_ms=10000) + sw_if_index=intf.sw_if_index, enable_ip4=True + ) + self.vapi.ip_reassembly_set( + timeout_ms=0, + max_reassemblies=1000, + max_reassembly_length=1000, + expire_walk_interval_ms=10, + ) + self.virtual_sleep(0.25) + self.vapi.ip_reassembly_set( + timeout_ms=1000000, + max_reassemblies=1000, + max_reassembly_length=1000, + expire_walk_interval_ms=10000, + ) def tearDown(self): for intf in self.send_ifs: self.vapi.ip_reassembly_enable_disable( - sw_if_index=intf.sw_if_index, enable_ip4=False) + sw_if_index=intf.sw_if_index, enable_ip4=False + ) super().tearDown() def show_commands_at_teardown(self): @@ -871,10 +1014,11 @@ class TestIPv4MWReassembly(VppTestCase): for i in range(0, packet_count): info = cls.create_packet_info(cls.src_if, cls.src_if) payload = cls.info_to_payload(info) - p = (IP(id=info.index, src=cls.src_if.remote_ip4, - dst=cls.dst_if.remote_ip4) / - UDP(sport=1234, dport=5678) / - Raw(payload)) + p = ( + IP(id=info.index, src=cls.src_if.remote_ip4, dst=cls.dst_if.remote_ip4) + / UDP(sport=1234, dport=5678) + / Raw(payload) + ) size = packet_sizes[(i // 2) % len(packet_sizes)] cls.extend_packet(p, size, cls.padding) info.data = p @@ -889,10 +1033,11 @@ class TestIPv4MWReassembly(VppTestCase): # p.__class__(scapy.compat.raw(p)))) fragments_400 = fragment_rfc791(p, 400) cls.pkt_infos.append((index, fragments_400)) - cls.fragments_400 = [ - x for (_, frags) in cls.pkt_infos for x in frags] - cls.logger.debug("Fragmented %s packets into %s 400-byte fragments, " % - (len(infos), len(cls.fragments_400))) + cls.fragments_400 = [x for (_, frags) in cls.pkt_infos for x in frags] + cls.logger.debug( + "Fragmented %s packets into %s 400-byte fragments, " + % (len(infos), len(cls.fragments_400)) + ) def verify_capture(self, capture, dropped_packet_indexes=[]): """Verify captured packet stream. @@ -910,7 +1055,8 @@ class TestIPv4MWReassembly(VppTestCase): packet_index = payload_info.index self.assertTrue( packet_index not in dropped_packet_indexes, - ppp("Packet received, but should be dropped:", packet)) + ppp("Packet received, but should be dropped:", packet), + ) if packet_index in seen: raise Exception(ppp("Duplicate packet received", packet)) seen.add(packet_index) @@ -926,8 +1072,10 @@ class TestIPv4MWReassembly(VppTestCase): self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise for index in self._packet_infos: - self.assertTrue(index in seen or index in dropped_packet_indexes, - "Packet with packet_index %d not received" % index) + self.assertTrue( + index in seen or index in dropped_packet_indexes, + "Packet with packet_index %d not received" % index, + ) def send_packets(self, packets): for counter in range(self.vpp_worker_count): @@ -935,13 +1083,16 @@ class TestIPv4MWReassembly(VppTestCase): continue send_if = self.send_ifs[counter] send_if.add_stream( - (Ether(dst=send_if.local_mac, src=send_if.remote_mac) / x - for x in packets[counter]), - worker=counter) + ( + Ether(dst=send_if.local_mac, src=send_if.remote_mac) / x + for x in packets[counter] + ), + worker=counter, + ) self.pg_start() def test_worker_conflict(self): - """ 1st and FO=0 fragments on different workers """ + """1st and FO=0 fragments on different workers""" # in first wave we send fragments which don't start at offset 0 # then we send fragments with offset 0 on a different thread @@ -988,7 +1139,7 @@ class TestIPv4MWReassembly(VppTestCase): class TestIPv6Reassembly(VppTestCase): - """ IPv6 Reassembly """ + """IPv6 Reassembly""" @classmethod def setUpClass(cls): @@ -1015,23 +1166,33 @@ class TestIPv6Reassembly(VppTestCase): super().tearDownClass() def setUp(self): - """ Test setup - force timeout on existing reassemblies """ + """Test setup - force timeout on existing reassemblies""" super().setUp() self.vapi.ip_reassembly_enable_disable( - sw_if_index=self.src_if.sw_if_index, enable_ip6=True) - self.vapi.ip_reassembly_set(timeout_ms=0, max_reassemblies=1000, - max_reassembly_length=1000, - expire_walk_interval_ms=10, is_ip6=1) - self.virtual_sleep(.25) - self.vapi.ip_reassembly_set(timeout_ms=1000000, max_reassemblies=1000, - max_reassembly_length=1000, - expire_walk_interval_ms=10000, is_ip6=1) + sw_if_index=self.src_if.sw_if_index, enable_ip6=True + ) + self.vapi.ip_reassembly_set( + timeout_ms=0, + max_reassemblies=1000, + max_reassembly_length=1000, + expire_walk_interval_ms=10, + is_ip6=1, + ) + self.virtual_sleep(0.25) + self.vapi.ip_reassembly_set( + timeout_ms=1000000, + max_reassemblies=1000, + max_reassembly_length=1000, + expire_walk_interval_ms=10000, + is_ip6=1, + ) self.logger.debug(self.vapi.ppcli("show ip6-full-reassembly details")) self.logger.debug(self.vapi.ppcli("show buffers")) def tearDown(self): self.vapi.ip_reassembly_enable_disable( - sw_if_index=self.src_if.sw_if_index, enable_ip6=False) + sw_if_index=self.src_if.sw_if_index, enable_ip6=False + ) super().tearDown() def show_commands_at_teardown(self): @@ -1047,11 +1208,12 @@ class TestIPv6Reassembly(VppTestCase): for i in range(0, packet_count): info = cls.create_packet_info(cls.src_if, cls.src_if) payload = cls.info_to_payload(info) - p = (Ether(dst=cls.src_if.local_mac, src=cls.src_if.remote_mac) / - IPv6(src=cls.src_if.remote_ip6, - dst=cls.dst_if.remote_ip6) / - UDP(sport=1234, dport=5678) / - Raw(payload)) + p = ( + Ether(dst=cls.src_if.local_mac, src=cls.src_if.remote_mac) + / IPv6(src=cls.src_if.remote_ip6, dst=cls.dst_if.remote_ip6) + / UDP(sport=1234, dport=5678) + / Raw(payload) + ) size = packet_sizes[(i // 2) % len(packet_sizes)] cls.extend_packet(p, size, cls.padding) info.data = p @@ -1067,14 +1229,13 @@ class TestIPv6Reassembly(VppTestCase): fragments_400 = fragment_rfc8200(p, info.index, 400) fragments_300 = fragment_rfc8200(p, info.index, 300) cls.pkt_infos.append((index, fragments_400, fragments_300)) - cls.fragments_400 = [ - x for _, frags, _ in cls.pkt_infos for x in frags] - cls.fragments_300 = [ - x for _, _, frags in cls.pkt_infos for x in frags] - cls.logger.debug("Fragmented %s packets into %s 400-byte fragments, " - "and %s 300-byte fragments" % - (len(infos), len(cls.fragments_400), - len(cls.fragments_300))) + cls.fragments_400 = [x for _, frags, _ in cls.pkt_infos for x in frags] + cls.fragments_300 = [x for _, _, frags in cls.pkt_infos for x in frags] + cls.logger.debug( + "Fragmented %s packets into %s 400-byte fragments, " + "and %s 300-byte fragments" + % (len(infos), len(cls.fragments_400), len(cls.fragments_300)) + ) def verify_capture(self, capture, dropped_packet_indexes=[]): """Verify captured packet strea . @@ -1092,7 +1253,8 @@ class TestIPv6Reassembly(VppTestCase): packet_index = payload_info.index self.assertTrue( packet_index not in dropped_packet_indexes, - ppp("Packet received, but should be dropped:", packet)) + ppp("Packet received, but should be dropped:", packet), + ) if packet_index in seen: raise Exception(ppp("Duplicate packet received", packet)) seen.add(packet_index) @@ -1108,11 +1270,13 @@ class TestIPv6Reassembly(VppTestCase): self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise for index in self._packet_infos: - self.assertTrue(index in seen or index in dropped_packet_indexes, - "Packet with packet_index %d not received" % index) + self.assertTrue( + index in seen or index in dropped_packet_indexes, + "Packet with packet_index %d not received" % index, + ) def test_reassembly(self): - """ basic reassembly """ + """basic reassembly""" self.pg_enable_capture() self.src_if.add_stream(self.fragments_400) @@ -1132,16 +1296,16 @@ class TestIPv6Reassembly(VppTestCase): self.src_if.assert_nothing_captured() def test_buffer_boundary(self): - """ fragment header crossing buffer boundary """ - - p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / - IPv6(src=self.src_if.remote_ip6, - dst=self.src_if.local_ip6) / - IPv6ExtHdrHopByHop( - options=[HBHOptUnknown(otype=0xff, optlen=0)] * 1000) / - IPv6ExtHdrFragment(m=1) / - UDP(sport=1234, dport=5678) / - Raw()) + """fragment header crossing buffer boundary""" + + p = ( + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IPv6(src=self.src_if.remote_ip6, dst=self.src_if.local_ip6) + / IPv6ExtHdrHopByHop(options=[HBHOptUnknown(otype=0xFF, optlen=0)] * 1000) + / IPv6ExtHdrFragment(m=1) + / UDP(sport=1234, dport=5678) + / Raw() + ) self.pg_enable_capture() self.src_if.add_stream([p]) self.pg_start() @@ -1149,7 +1313,7 @@ class TestIPv6Reassembly(VppTestCase): self.dst_if.assert_nothing_captured() def test_verify_clear_trace_mid_reassembly(self): - """ verify clear trace works mid-reassembly """ + """verify clear trace works mid-reassembly""" self.pg_enable_capture() self.src_if.add_stream(self.fragments_400[0:-1]) @@ -1164,7 +1328,7 @@ class TestIPv6Reassembly(VppTestCase): self.verify_capture(packets) def test_reversed(self): - """ reverse order reassembly """ + """reverse order reassembly""" fragments = list(self.fragments_400) fragments.reverse() @@ -1187,7 +1351,7 @@ class TestIPv6Reassembly(VppTestCase): self.src_if.assert_nothing_captured() def test_random(self): - """ random order reassembly """ + """random order reassembly""" fragments = list(self.fragments_400) shuffle(fragments) @@ -1210,10 +1374,11 @@ class TestIPv6Reassembly(VppTestCase): self.src_if.assert_nothing_captured() def test_duplicates(self): - """ duplicate fragments """ + """duplicate fragments""" fragments = [ - x for (_, frags, _) in self.pkt_infos + x + for (_, frags, _) in self.pkt_infos for x in frags for _ in range(0, min(2, len(frags))) ] @@ -1227,22 +1392,28 @@ class TestIPv6Reassembly(VppTestCase): self.src_if.assert_nothing_captured() def test_long_fragment_chain(self): - """ long fragment chain """ + """long fragment chain""" - error_cnt_str = \ + error_cnt_str = ( "/err/ip6-full-reassembly-feature/fragment chain too long (drop)" + ) error_cnt = self.statistics.get_err_counter(error_cnt_str) - self.vapi.ip_reassembly_set(timeout_ms=100, max_reassemblies=1000, - max_reassembly_length=3, - expire_walk_interval_ms=50, is_ip6=1) + self.vapi.ip_reassembly_set( + timeout_ms=100, + max_reassemblies=1000, + max_reassembly_length=3, + expire_walk_interval_ms=50, + is_ip6=1, + ) - p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / - IPv6(src=self.src_if.remote_ip6, - dst=self.dst_if.remote_ip6) / - UDP(sport=1234, dport=5678) / - Raw(b"X" * 1000)) + p = ( + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) + / UDP(sport=1234, dport=5678) + / Raw(b"X" * 1000) + ) frags = fragment_rfc8200(p, 1, 300) + fragment_rfc8200(p, 2, 500) self.pg_enable_capture() @@ -1253,7 +1424,7 @@ class TestIPv6Reassembly(VppTestCase): self.assert_error_counter_equal(error_cnt_str, error_cnt + 1) def test_overlap1(self): - """ overlapping fragments case #1 """ + """overlapping fragments case #1""" fragments = [] for _, frags_400, frags_300 in self.pkt_infos: @@ -1273,12 +1444,13 @@ class TestIPv6Reassembly(VppTestCase): self.pg_start() packets = self.dst_if.get_capture( - len(self.pkt_infos) - len(dropped_packet_indexes)) + len(self.pkt_infos) - len(dropped_packet_indexes) + ) self.verify_capture(packets, dropped_packet_indexes) self.src_if.assert_nothing_captured() def test_overlap2(self): - """ overlapping fragments case #2 """ + """overlapping fragments case #2""" fragments = [] for _, frags_400, frags_300 in self.pkt_infos: @@ -1304,27 +1476,33 @@ class TestIPv6Reassembly(VppTestCase): self.pg_start() packets = self.dst_if.get_capture( - len(self.pkt_infos) - len(dropped_packet_indexes)) + len(self.pkt_infos) - len(dropped_packet_indexes) + ) self.verify_capture(packets, dropped_packet_indexes) self.src_if.assert_nothing_captured() def test_timeout_inline(self): - """ timeout (inline) """ + """timeout (inline)""" dropped_packet_indexes = set( index for (index, frags, _) in self.pkt_infos if len(frags) > 1 ) - self.vapi.ip_reassembly_set(timeout_ms=0, max_reassemblies=1000, - max_reassembly_length=3, - expire_walk_interval_ms=10000, is_ip6=1) + self.vapi.ip_reassembly_set( + timeout_ms=0, + max_reassemblies=1000, + max_reassembly_length=3, + expire_walk_interval_ms=10000, + is_ip6=1, + ) self.pg_enable_capture() self.src_if.add_stream(self.fragments_400) self.pg_start() packets = self.dst_if.get_capture( - len(self.pkt_infos) - len(dropped_packet_indexes)) + len(self.pkt_infos) - len(dropped_packet_indexes) + ) self.verify_capture(packets, dropped_packet_indexes) pkts = self.src_if._get_capture(1) for icmp in pkts: @@ -1334,42 +1512,51 @@ class TestIPv6Reassembly(VppTestCase): dropped_packet_indexes.remove(icmp[IPv6ExtHdrFragment].id) def test_timeout_cleanup(self): - """ timeout (cleanup) """ + """timeout (cleanup)""" # whole packets + fragmented packets sans last fragment fragments = [ - x for (_, frags_400, _) in self.pkt_infos - for x in frags_400[:-1 if len(frags_400) > 1 else None] + x + for (_, frags_400, _) in self.pkt_infos + for x in frags_400[: -1 if len(frags_400) > 1 else None] ] # last fragments for fragmented packets - fragments2 = [frags_400[-1] - for (_, frags_400, _) in self.pkt_infos - if len(frags_400) > 1] + fragments2 = [ + frags_400[-1] for (_, frags_400, _) in self.pkt_infos if len(frags_400) > 1 + ] dropped_packet_indexes = set( - index for (index, frags_400, _) in self.pkt_infos - if len(frags_400) > 1) + index for (index, frags_400, _) in self.pkt_infos if len(frags_400) > 1 + ) - self.vapi.ip_reassembly_set(timeout_ms=100, max_reassemblies=1000, - max_reassembly_length=1000, - expire_walk_interval_ms=50) + self.vapi.ip_reassembly_set( + timeout_ms=100, + max_reassemblies=1000, + max_reassembly_length=1000, + expire_walk_interval_ms=50, + ) - self.vapi.ip_reassembly_set(timeout_ms=100, max_reassemblies=1000, - max_reassembly_length=1000, - expire_walk_interval_ms=50, is_ip6=1) + self.vapi.ip_reassembly_set( + timeout_ms=100, + max_reassemblies=1000, + max_reassembly_length=1000, + expire_walk_interval_ms=50, + is_ip6=1, + ) self.pg_enable_capture() self.src_if.add_stream(fragments) self.pg_start() - self.virtual_sleep(.25, "wait before sending rest of fragments") + self.virtual_sleep(0.25, "wait before sending rest of fragments") self.src_if.add_stream(fragments2) self.pg_start() packets = self.dst_if.get_capture( - len(self.pkt_infos) - len(dropped_packet_indexes)) + len(self.pkt_infos) - len(dropped_packet_indexes) + ) self.verify_capture(packets, dropped_packet_indexes) pkts = self.src_if._get_capture(1) for icmp in pkts: @@ -1379,34 +1566,41 @@ class TestIPv6Reassembly(VppTestCase): dropped_packet_indexes.remove(icmp[IPv6ExtHdrFragment].id) def test_disabled(self): - """ reassembly disabled """ + """reassembly disabled""" dropped_packet_indexes = set( - index for (index, frags_400, _) in self.pkt_infos - if len(frags_400) > 1) + index for (index, frags_400, _) in self.pkt_infos if len(frags_400) > 1 + ) - self.vapi.ip_reassembly_set(timeout_ms=1000, max_reassemblies=0, - max_reassembly_length=3, - expire_walk_interval_ms=10000, is_ip6=1) + self.vapi.ip_reassembly_set( + timeout_ms=1000, + max_reassemblies=0, + max_reassembly_length=3, + expire_walk_interval_ms=10000, + is_ip6=1, + ) self.pg_enable_capture() self.src_if.add_stream(self.fragments_400) self.pg_start() packets = self.dst_if.get_capture( - len(self.pkt_infos) - len(dropped_packet_indexes)) + len(self.pkt_infos) - len(dropped_packet_indexes) + ) self.verify_capture(packets, dropped_packet_indexes) self.src_if.assert_nothing_captured() def test_missing_upper(self): - """ missing upper layer """ - optdata = '\x00' * 100 - p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / - IPv6(src=self.src_if.remote_ip6, - dst=self.src_if.local_ip6) / - IPv6ExtHdrFragment(m=1) / - IPv6ExtHdrDestOpt(nh=17, options=PadN(optdata='\101' * 255) / - PadN(optdata='\102'*255))) + """missing upper layer""" + optdata = "\x00" * 100 + p = ( + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IPv6(src=self.src_if.remote_ip6, dst=self.src_if.local_ip6) + / IPv6ExtHdrFragment(m=1) + / IPv6ExtHdrDestOpt( + nh=17, options=PadN(optdata="\101" * 255) / PadN(optdata="\102" * 255) + ) + ) self.pg_enable_capture() self.src_if.add_stream([p]) @@ -1417,21 +1611,23 @@ class TestIPv6Reassembly(VppTestCase): self.assert_equal(icmp[ICMPv6ParamProblem].code, 3, "ICMP code") def test_truncated_fragment(self): - """ truncated fragment """ - pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6, - nh=44, plen=2) / - IPv6ExtHdrFragment(nh=6)) + """truncated fragment""" + pkt = ( + Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6, nh=44, plen=2) + / IPv6ExtHdrFragment(nh=6) + ) self.send_and_assert_no_replies(self.pg0, [pkt], self.pg0) def test_invalid_frag_size(self): - """ fragment size not a multiple of 8 """ - p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / - IPv6(src=self.src_if.remote_ip6, - dst=self.src_if.local_ip6) / - UDP(sport=1234, dport=5678) / - Raw()) + """fragment size not a multiple of 8""" + p = ( + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IPv6(src=self.src_if.remote_ip6, dst=self.src_if.local_ip6) + / UDP(sport=1234, dport=5678) + / Raw() + ) self.extend_packet(p, 1000, self.padding) fragments = fragment_rfc8200(p, 1, 500) bad_fragment = fragments[0] @@ -1445,12 +1641,13 @@ class TestIPv6Reassembly(VppTestCase): self.assert_equal(icmp[ICMPv6ParamProblem].code, 0, "ICMP code") def test_invalid_packet_size(self): - """ total packet size > 65535 """ - p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / - IPv6(src=self.src_if.remote_ip6, - dst=self.src_if.local_ip6) / - UDP(sport=1234, dport=5678) / - Raw()) + """total packet size > 65535""" + p = ( + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IPv6(src=self.src_if.remote_ip6, dst=self.src_if.local_ip6) + / UDP(sport=1234, dport=5678) + / Raw() + ) self.extend_packet(p, 1000, self.padding) fragments = fragment_rfc8200(p, 1, 500) bad_fragment = fragments[1] @@ -1464,44 +1661,56 @@ class TestIPv6Reassembly(VppTestCase): self.assert_equal(icmp[ICMPv6ParamProblem].code, 0, "ICMP code") def test_atomic_fragment(self): - """ IPv6 atomic fragment """ - pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6, - nh=44, plen=65535) / - IPv6ExtHdrFragment(offset=8191, m=1, res1=0xFF, res2=0xFF, - nh=255, id=0xffff)/('X'*1452)) + """IPv6 atomic fragment""" + pkt = ( + Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6, nh=44, plen=65535) + / IPv6ExtHdrFragment( + offset=8191, m=1, res1=0xFF, res2=0xFF, nh=255, id=0xFFFF + ) + / ("X" * 1452) + ) rx = self.send_and_expect(self.pg0, [pkt], self.pg0) self.assertIn(ICMPv6ParamProblem, rx[0]) def test_truncated_fragment(self): - """ IPv6 truncated fragment header """ - pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6, - nh=44, plen=2) / - IPv6ExtHdrFragment(nh=6)) + """IPv6 truncated fragment header""" + pkt = ( + Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6, nh=44, plen=2) + / IPv6ExtHdrFragment(nh=6) + ) self.send_and_assert_no_replies(self.pg0, [pkt]) - pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg0.remote_ip6) / - ICMPv6EchoRequest()) + pkt = ( + Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.remote_ip6) + / ICMPv6EchoRequest() + ) rx = self.send_and_expect(self.pg0, [pkt], self.pg0) def test_one_fragment(self): - """ whole packet in one fragment processed independently """ - pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) / - ICMPv6EchoRequest()/Raw('X' * 1600)) + """whole packet in one fragment processed independently""" + pkt = ( + Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) + / ICMPv6EchoRequest() + / Raw("X" * 1600) + ) frags = fragment_rfc8200(pkt, 1, 400) # send a fragment with known id self.send_and_assert_no_replies(self.pg0, [frags[0]]) # send an atomic fragment with same id - should be reassembled - pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) / - IPv6ExtHdrFragment(id=1)/ICMPv6EchoRequest()) + pkt = ( + Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) + / IPv6ExtHdrFragment(id=1) + / ICMPv6EchoRequest() + ) rx = self.send_and_expect(self.pg0, [pkt], self.pg0) self.assertNotIn(IPv6ExtHdrFragment, rx) @@ -1510,33 +1719,46 @@ class TestIPv6Reassembly(VppTestCase): self.assertNotIn(IPv6ExtHdrFragment, rx) def test_bunch_of_fragments(self): - """ valid fragments followed by rogue fragments and atomic fragment""" - pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) / - ICMPv6EchoRequest()/Raw('X' * 1600)) + """valid fragments followed by rogue fragments and atomic fragment""" + pkt = ( + Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) + / ICMPv6EchoRequest() + / Raw("X" * 1600) + ) frags = fragment_rfc8200(pkt, 1, 400) self.send_and_expect(self.pg0, frags, self.pg0, n_rx=1) - inc_frag = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) / - IPv6ExtHdrFragment(id=1, nh=58, offset=608)/Raw('X'*308)) + inc_frag = ( + Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) + / IPv6ExtHdrFragment(id=1, nh=58, offset=608) + / Raw("X" * 308) + ) - self.send_and_assert_no_replies(self.pg0, inc_frag*604) + self.send_and_assert_no_replies(self.pg0, inc_frag * 604) - pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) / - IPv6ExtHdrFragment(id=1)/ICMPv6EchoRequest()) + pkt = ( + Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) + / IPv6ExtHdrFragment(id=1) + / ICMPv6EchoRequest() + ) rx = self.send_and_expect(self.pg0, [pkt], self.pg0) self.assertNotIn(IPv6ExtHdrFragment, rx) def test_local_enable_disable(self): - """ local reassembly enabled/disable """ + """local reassembly enabled/disable""" self.vapi.ip_reassembly_enable_disable( - sw_if_index=self.src_if.sw_if_index, enable_ip6=False) + sw_if_index=self.src_if.sw_if_index, enable_ip6=False + ) self.vapi.ip_local_reass_enable_disable(enable_ip6=True) - pkt = (Ether(src=self.src_if.local_mac, dst=self.src_if.remote_mac) / - IPv6(src=self.src_if.remote_ip6, dst=self.src_if.local_ip6) / - ICMPv6EchoRequest(id=1234)/Raw('X' * 1600)) + pkt = ( + Ether(src=self.src_if.local_mac, dst=self.src_if.remote_mac) + / IPv6(src=self.src_if.remote_ip6, dst=self.src_if.local_ip6) + / ICMPv6EchoRequest(id=1234) + / Raw("X" * 1600) + ) frags = fragment_rfc8200(pkt, 1, 400) r = self.send_and_expect(self.src_if, frags, self.src_if, n_rx=1)[0] self.assertEqual(1234, r[ICMPv6EchoReply].id) @@ -1547,14 +1769,15 @@ class TestIPv6Reassembly(VppTestCase): class TestIPv6MWReassembly(VppTestCase): - """ IPv6 Reassembly (multiple workers) """ + """IPv6 Reassembly (multiple workers)""" + vpp_worker_count = 3 @classmethod def setUpClass(cls): super().setUpClass() - cls.create_pg_interfaces(range(cls.vpp_worker_count+1)) + cls.create_pg_interfaces(range(cls.vpp_worker_count + 1)) cls.src_if = cls.pg0 cls.send_ifs = cls.pg_interfaces[:-1] cls.dst_if = cls.pg_interfaces[-1] @@ -1568,8 +1791,12 @@ class TestIPv6MWReassembly(VppTestCase): # packets sizes reduced here because we are generating packets without # Ethernet headers, which are added later (diff fragments go via # different interfaces) - cls.packet_sizes = [64-len(Ether()), 512-len(Ether()), - 1518-len(Ether()), 9018-len(Ether())] + cls.packet_sizes = [ + 64 - len(Ether()), + 512 - len(Ether()), + 1518 - len(Ether()), + 9018 - len(Ether()), + ] cls.padding = " abcdefghijklmn" cls.create_stream(cls.packet_sizes) cls.create_fragments() @@ -1579,23 +1806,33 @@ class TestIPv6MWReassembly(VppTestCase): super().tearDownClass() def setUp(self): - """ Test setup - force timeout on existing reassemblies """ + """Test setup - force timeout on existing reassemblies""" super().setUp() for intf in self.send_ifs: self.vapi.ip_reassembly_enable_disable( - sw_if_index=intf.sw_if_index, enable_ip6=True) - self.vapi.ip_reassembly_set(timeout_ms=0, max_reassemblies=1000, - max_reassembly_length=1000, - expire_walk_interval_ms=10, is_ip6=1) - self.virtual_sleep(.25) - self.vapi.ip_reassembly_set(timeout_ms=1000000, max_reassemblies=1000, - max_reassembly_length=1000, - expire_walk_interval_ms=1000, is_ip6=1) + sw_if_index=intf.sw_if_index, enable_ip6=True + ) + self.vapi.ip_reassembly_set( + timeout_ms=0, + max_reassemblies=1000, + max_reassembly_length=1000, + expire_walk_interval_ms=10, + is_ip6=1, + ) + self.virtual_sleep(0.25) + self.vapi.ip_reassembly_set( + timeout_ms=1000000, + max_reassemblies=1000, + max_reassembly_length=1000, + expire_walk_interval_ms=1000, + is_ip6=1, + ) def tearDown(self): for intf in self.send_ifs: self.vapi.ip_reassembly_enable_disable( - sw_if_index=intf.sw_if_index, enable_ip6=False) + sw_if_index=intf.sw_if_index, enable_ip6=False + ) super().tearDown() def show_commands_at_teardown(self): @@ -1611,10 +1848,11 @@ class TestIPv6MWReassembly(VppTestCase): for i in range(0, packet_count): info = cls.create_packet_info(cls.src_if, cls.src_if) payload = cls.info_to_payload(info) - p = (IPv6(src=cls.src_if.remote_ip6, - dst=cls.dst_if.remote_ip6) / - UDP(sport=1234, dport=5678) / - Raw(payload)) + p = ( + IPv6(src=cls.src_if.remote_ip6, dst=cls.dst_if.remote_ip6) + / UDP(sport=1234, dport=5678) + / Raw(payload) + ) size = packet_sizes[(i // 2) % len(packet_sizes)] cls.extend_packet(p, size, cls.padding) info.data = p @@ -1629,10 +1867,11 @@ class TestIPv6MWReassembly(VppTestCase): # p.__class__(scapy.compat.raw(p)))) fragments_400 = fragment_rfc8200(p, index, 400) cls.pkt_infos.append((index, fragments_400)) - cls.fragments_400 = [ - x for (_, frags) in cls.pkt_infos for x in frags] - cls.logger.debug("Fragmented %s packets into %s 400-byte fragments, " % - (len(infos), len(cls.fragments_400))) + cls.fragments_400 = [x for (_, frags) in cls.pkt_infos for x in frags] + cls.logger.debug( + "Fragmented %s packets into %s 400-byte fragments, " + % (len(infos), len(cls.fragments_400)) + ) def verify_capture(self, capture, dropped_packet_indexes=[]): """Verify captured packet strea . @@ -1650,7 +1889,8 @@ class TestIPv6MWReassembly(VppTestCase): packet_index = payload_info.index self.assertTrue( packet_index not in dropped_packet_indexes, - ppp("Packet received, but should be dropped:", packet)) + ppp("Packet received, but should be dropped:", packet), + ) if packet_index in seen: raise Exception(ppp("Duplicate packet received", packet)) seen.add(packet_index) @@ -1666,8 +1906,10 @@ class TestIPv6MWReassembly(VppTestCase): self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise for index in self._packet_infos: - self.assertTrue(index in seen or index in dropped_packet_indexes, - "Packet with packet_index %d not received" % index) + self.assertTrue( + index in seen or index in dropped_packet_indexes, + "Packet with packet_index %d not received" % index, + ) def send_packets(self, packets): for counter in range(self.vpp_worker_count): @@ -1675,13 +1917,16 @@ class TestIPv6MWReassembly(VppTestCase): continue send_if = self.send_ifs[counter] send_if.add_stream( - (Ether(dst=send_if.local_mac, src=send_if.remote_mac) / x - for x in packets[counter]), - worker=counter) + ( + Ether(dst=send_if.local_mac, src=send_if.remote_mac) / x + for x in packets[counter] + ), + worker=counter, + ) self.pg_start() def test_worker_conflict(self): - """ 1st and FO=0 fragments on different workers """ + """1st and FO=0 fragments on different workers""" # in first wave we send fragments which don't start at offset 0 # then we send fragments with offset 0 on a different thread @@ -1728,7 +1973,7 @@ class TestIPv6MWReassembly(VppTestCase): class TestIPv6SVReassembly(VppTestCase): - """ IPv6 Shallow Virtual Reassembly """ + """IPv6 Shallow Virtual Reassembly""" @classmethod def setUpClass(cls): @@ -1745,22 +1990,30 @@ class TestIPv6SVReassembly(VppTestCase): i.resolve_ndp() def setUp(self): - """ Test setup - force timeout on existing reassemblies """ + """Test setup - force timeout on existing reassemblies""" super().setUp() self.vapi.ip_reassembly_enable_disable( - sw_if_index=self.src_if.sw_if_index, enable_ip6=True, - type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL) + sw_if_index=self.src_if.sw_if_index, + enable_ip6=True, + type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL, + ) self.vapi.ip_reassembly_set( - timeout_ms=0, max_reassemblies=1000, + timeout_ms=0, + max_reassemblies=1000, max_reassembly_length=1000, type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL, - expire_walk_interval_ms=10, is_ip6=1) - self.virtual_sleep(.25) + expire_walk_interval_ms=10, + is_ip6=1, + ) + self.virtual_sleep(0.25) self.vapi.ip_reassembly_set( - timeout_ms=1000000, max_reassemblies=1000, + timeout_ms=1000000, + max_reassemblies=1000, max_reassembly_length=1000, type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL, - expire_walk_interval_ms=10000, is_ip6=1) + expire_walk_interval_ms=10000, + is_ip6=1, + ) def tearDown(self): super().tearDown() @@ -1768,7 +2021,7 @@ class TestIPv6SVReassembly(VppTestCase): self.logger.debug(self.vapi.ppcli("show buffers")) def test_basic(self): - """ basic reassembly """ + """basic reassembly""" payload_len = 1000 payload = "" counter = 0 @@ -1776,11 +2029,13 @@ class TestIPv6SVReassembly(VppTestCase): payload += "%u " % counter counter += 1 - p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / - IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) / - UDP(sport=1234, dport=5678) / - Raw(payload)) - fragments = fragment_rfc8200(p, 1, payload_len/4) + p = ( + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) + / UDP(sport=1234, dport=5678) + / Raw(payload) + ) + fragments = fragment_rfc8200(p, 1, payload_len / 4) # send fragment #2 - should be cached inside reassembly self.pg_enable_capture() @@ -1816,7 +2071,7 @@ class TestIPv6SVReassembly(VppTestCase): self.assertEqual(sent[Raw].payload, recvd[Raw].payload) def test_verify_clear_trace_mid_reassembly(self): - """ verify clear trace works mid-reassembly """ + """verify clear trace works mid-reassembly""" payload_len = 1000 payload = "" counter = 0 @@ -1824,11 +2079,13 @@ class TestIPv6SVReassembly(VppTestCase): payload += "%u " % counter counter += 1 - p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / - IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) / - UDP(sport=1234, dport=5678) / - Raw(payload)) - fragments = fragment_rfc8200(p, 1, payload_len/4) + p = ( + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) + / UDP(sport=1234, dport=5678) + / Raw(payload) + ) + fragments = fragment_rfc8200(p, 1, payload_len / 4) self.pg_enable_capture() self.src_if.add_stream(fragments[1]) @@ -1851,7 +2108,7 @@ class TestIPv6SVReassembly(VppTestCase): self.dst_if.get_capture(len(fragments[2:])) def test_timeout(self): - """ reassembly timeout """ + """reassembly timeout""" payload_len = 1000 payload = "" counter = 0 @@ -1859,18 +2116,22 @@ class TestIPv6SVReassembly(VppTestCase): payload += "%u " % counter counter += 1 - p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / - IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) / - UDP(sport=1234, dport=5678) / - Raw(payload)) - fragments = fragment_rfc8200(p, 1, payload_len/4) + p = ( + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) + / UDP(sport=1234, dport=5678) + / Raw(payload) + ) + fragments = fragment_rfc8200(p, 1, payload_len / 4) self.vapi.ip_reassembly_set( - timeout_ms=100, max_reassemblies=1000, + timeout_ms=100, + max_reassemblies=1000, max_reassembly_length=1000, expire_walk_interval_ms=50, is_ip6=1, - type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL) + type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL, + ) # send fragments #2 and #1 - should be forwarded self.pg_enable_capture() @@ -1886,7 +2147,7 @@ class TestIPv6SVReassembly(VppTestCase): self.assertEqual(sent[Raw].payload, recvd[Raw].payload) # wait for cleanup - self.virtual_sleep(.25, "wait before sending rest of fragments") + self.virtual_sleep(0.25, "wait before sending rest of fragments") # send rest of fragments - shouldn't be forwarded self.pg_enable_capture() @@ -1895,13 +2156,16 @@ class TestIPv6SVReassembly(VppTestCase): self.dst_if.assert_nothing_captured() def test_lru(self): - """ reassembly reuses LRU element """ + """reassembly reuses LRU element""" self.vapi.ip_reassembly_set( - timeout_ms=1000000, max_reassemblies=1, + timeout_ms=1000000, + max_reassemblies=1, max_reassembly_length=1000, type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL, - is_ip6=1, expire_walk_interval_ms=10000) + is_ip6=1, + expire_walk_interval_ms=10000, + ) payload_len = 1000 payload = "" @@ -1912,15 +2176,17 @@ class TestIPv6SVReassembly(VppTestCase): packet_count = 10 - fragments = [f - for i in range(packet_count) - for p in (Ether(dst=self.src_if.local_mac, - src=self.src_if.remote_mac) / - IPv6(src=self.src_if.remote_ip6, - dst=self.dst_if.remote_ip6) / - UDP(sport=1234, dport=5678) / - Raw(payload)) - for f in fragment_rfc8200(p, i, payload_len/4)] + fragments = [ + f + for i in range(packet_count) + for p in ( + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) + / UDP(sport=1234, dport=5678) + / Raw(payload) + ) + for f in fragment_rfc8200(p, i, payload_len / 4) + ] self.pg_enable_capture() self.src_if.add_stream(fragments) @@ -1932,55 +2198,71 @@ class TestIPv6SVReassembly(VppTestCase): self.assertEqual(sent[Raw].payload, recvd[Raw].payload) def test_one_fragment(self): - """ whole packet in one fragment processed independently """ - pkt = (Ether(src=self.src_if.local_mac, dst=self.src_if.remote_mac) / - IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) / - ICMPv6EchoRequest()/Raw('X' * 1600)) + """whole packet in one fragment processed independently""" + pkt = ( + Ether(src=self.src_if.local_mac, dst=self.src_if.remote_mac) + / IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) + / ICMPv6EchoRequest() + / Raw("X" * 1600) + ) frags = fragment_rfc8200(pkt, 1, 400) # send a fragment with known id self.send_and_expect(self.src_if, [frags[0]], self.dst_if) # send an atomic fragment with same id - should be reassembled - pkt = (Ether(src=self.src_if.local_mac, dst=self.src_if.remote_mac) / - IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) / - IPv6ExtHdrFragment(id=1)/ICMPv6EchoRequest()) + pkt = ( + Ether(src=self.src_if.local_mac, dst=self.src_if.remote_mac) + / IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) + / IPv6ExtHdrFragment(id=1) + / ICMPv6EchoRequest() + ) rx = self.send_and_expect(self.src_if, [pkt], self.dst_if) # now forward packets matching original reassembly, should still work rx = self.send_and_expect(self.src_if, frags[1:], self.dst_if) def test_bunch_of_fragments(self): - """ valid fragments followed by rogue fragments and atomic fragment""" - pkt = (Ether(src=self.src_if.local_mac, dst=self.src_if.remote_mac) / - IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) / - ICMPv6EchoRequest()/Raw('X' * 1600)) + """valid fragments followed by rogue fragments and atomic fragment""" + pkt = ( + Ether(src=self.src_if.local_mac, dst=self.src_if.remote_mac) + / IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) + / ICMPv6EchoRequest() + / Raw("X" * 1600) + ) frags = fragment_rfc8200(pkt, 1, 400) rx = self.send_and_expect(self.src_if, frags, self.dst_if) - rogue = (Ether(src=self.src_if.local_mac, dst=self.src_if.remote_mac) / - IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) / - IPv6ExtHdrFragment(id=1, nh=58, offset=608)/Raw('X'*308)) + rogue = ( + Ether(src=self.src_if.local_mac, dst=self.src_if.remote_mac) + / IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) + / IPv6ExtHdrFragment(id=1, nh=58, offset=608) + / Raw("X" * 308) + ) - self.send_and_expect(self.src_if, rogue*604, self.dst_if) + self.send_and_expect(self.src_if, rogue * 604, self.dst_if) - pkt = (Ether(src=self.src_if.local_mac, dst=self.src_if.remote_mac) / - IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) / - IPv6ExtHdrFragment(id=1)/ICMPv6EchoRequest()) + pkt = ( + Ether(src=self.src_if.local_mac, dst=self.src_if.remote_mac) + / IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) + / IPv6ExtHdrFragment(id=1) + / ICMPv6EchoRequest() + ) rx = self.send_and_expect(self.src_if, [pkt], self.dst_if) def test_truncated_fragment(self): - """ truncated fragment """ - pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6, - nh=44, plen=2) / - IPv6ExtHdrFragment(nh=6)) + """truncated fragment""" + pkt = ( + Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6, nh=44, plen=2) + / IPv6ExtHdrFragment(nh=6) + ) self.send_and_assert_no_replies(self.pg0, [pkt], self.pg0) class TestIPv4ReassemblyLocalNode(VppTestCase): - """ IPv4 Reassembly for packets coming to ip4-local node """ + """IPv4 Reassembly for packets coming to ip4-local node""" @classmethod def setUpClass(cls): @@ -2004,15 +2286,21 @@ class TestIPv4ReassemblyLocalNode(VppTestCase): super().tearDownClass() def setUp(self): - """ Test setup - force timeout on existing reassemblies """ + """Test setup - force timeout on existing reassemblies""" super().setUp() - self.vapi.ip_reassembly_set(timeout_ms=0, max_reassemblies=1000, - max_reassembly_length=1000, - expire_walk_interval_ms=10) - self.virtual_sleep(.25) - self.vapi.ip_reassembly_set(timeout_ms=1000000, max_reassemblies=1000, - max_reassembly_length=1000, - expire_walk_interval_ms=10000) + self.vapi.ip_reassembly_set( + timeout_ms=0, + max_reassemblies=1000, + max_reassembly_length=1000, + expire_walk_interval_ms=10, + ) + self.virtual_sleep(0.25) + self.vapi.ip_reassembly_set( + timeout_ms=1000000, + max_reassemblies=1000, + max_reassembly_length=1000, + expire_walk_interval_ms=10000, + ) def tearDown(self): super().tearDown() @@ -2030,12 +2318,16 @@ class TestIPv4ReassemblyLocalNode(VppTestCase): for i in range(0, packet_count): info = cls.create_packet_info(cls.src_dst_if, cls.src_dst_if) payload = cls.info_to_payload(info) - p = (Ether(dst=cls.src_dst_if.local_mac, - src=cls.src_dst_if.remote_mac) / - IP(id=info.index, src=cls.src_dst_if.remote_ip4, - dst=cls.src_dst_if.local_ip4) / - ICMP(type='echo-request', id=1234) / - Raw(payload)) + p = ( + Ether(dst=cls.src_dst_if.local_mac, src=cls.src_dst_if.remote_mac) + / IP( + id=info.index, + src=cls.src_dst_if.remote_ip4, + dst=cls.src_dst_if.local_ip4, + ) + / ICMP(type="echo-request", id=1234) + / Raw(payload) + ) cls.extend_packet(p, 1518, cls.padding) info.data = p @@ -2050,8 +2342,10 @@ class TestIPv4ReassemblyLocalNode(VppTestCase): fragments_300 = fragment_rfc791(p, 300) cls.pkt_infos.append((index, fragments_300)) cls.fragments_300 = [x for (_, frags) in cls.pkt_infos for x in frags] - cls.logger.debug("Fragmented %s packets into %s 300-byte fragments" % - (len(infos), len(cls.fragments_300))) + cls.logger.debug( + "Fragmented %s packets into %s 300-byte fragments" + % (len(infos), len(cls.fragments_300)) + ) def verify_capture(self, capture): """Verify captured packet stream. @@ -2084,11 +2378,12 @@ class TestIPv4ReassemblyLocalNode(VppTestCase): self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise for index in self._packet_infos: - self.assertIn(index, seen, - "Packet with packet_index %d not received" % index) + self.assertIn( + index, seen, "Packet with packet_index %d not received" % index + ) def test_reassembly(self): - """ basic reassembly """ + """basic reassembly""" self.pg_enable_capture() self.src_dst_if.add_stream(self.fragments_300) @@ -2107,7 +2402,7 @@ class TestIPv4ReassemblyLocalNode(VppTestCase): class TestFIFReassembly(VppTestCase): - """ Fragments in fragments reassembly """ + """Fragments in fragments reassembly""" @classmethod def setUpClass(cls): @@ -2131,27 +2426,41 @@ class TestFIFReassembly(VppTestCase): super().tearDownClass() def setUp(self): - """ Test setup - force timeout on existing reassemblies """ + """Test setup - force timeout on existing reassemblies""" super().setUp() self.vapi.ip_reassembly_enable_disable( - sw_if_index=self.src_if.sw_if_index, enable_ip4=True, - enable_ip6=True) + sw_if_index=self.src_if.sw_if_index, enable_ip4=True, enable_ip6=True + ) self.vapi.ip_reassembly_enable_disable( - sw_if_index=self.dst_if.sw_if_index, enable_ip4=True, - enable_ip6=True) - self.vapi.ip_reassembly_set(timeout_ms=0, max_reassemblies=1000, - max_reassembly_length=1000, - expire_walk_interval_ms=10) - self.vapi.ip_reassembly_set(timeout_ms=0, max_reassemblies=1000, - max_reassembly_length=1000, - expire_walk_interval_ms=10, is_ip6=1) - self.virtual_sleep(.25) - self.vapi.ip_reassembly_set(timeout_ms=1000000, max_reassemblies=1000, - max_reassembly_length=1000, - expire_walk_interval_ms=10000) - self.vapi.ip_reassembly_set(timeout_ms=1000000, max_reassemblies=1000, - max_reassembly_length=1000, - expire_walk_interval_ms=10000, is_ip6=1) + sw_if_index=self.dst_if.sw_if_index, enable_ip4=True, enable_ip6=True + ) + self.vapi.ip_reassembly_set( + timeout_ms=0, + max_reassemblies=1000, + max_reassembly_length=1000, + expire_walk_interval_ms=10, + ) + self.vapi.ip_reassembly_set( + timeout_ms=0, + max_reassemblies=1000, + max_reassembly_length=1000, + expire_walk_interval_ms=10, + is_ip6=1, + ) + self.virtual_sleep(0.25) + self.vapi.ip_reassembly_set( + timeout_ms=1000000, + max_reassemblies=1000, + max_reassembly_length=1000, + expire_walk_interval_ms=10000, + ) + self.vapi.ip_reassembly_set( + timeout_ms=1000000, + max_reassemblies=1000, + max_reassembly_length=1000, + expire_walk_interval_ms=10000, + is_ip6=1, + ) def tearDown(self): super().tearDown() @@ -2177,7 +2486,8 @@ class TestFIFReassembly(VppTestCase): packet_index = payload_info.index self.assertTrue( packet_index not in dropped_packet_indexes, - ppp("Packet received, but should be dropped:", packet)) + ppp("Packet received, but should be dropped:", packet), + ) if packet_index in seen: raise Exception(ppp("Duplicate packet received", packet)) seen.add(packet_index) @@ -2193,11 +2503,13 @@ class TestFIFReassembly(VppTestCase): self.logger.error(ppp("Unexpected or invalid packet:", packet)) raise for index in self._packet_infos: - self.assertTrue(index in seen or index in dropped_packet_indexes, - "Packet with packet_index %d not received" % index) + self.assertTrue( + index in seen or index in dropped_packet_indexes, + "Packet with packet_index %d not received" % index, + ) def test_fif4(self): - """ Fragments in fragments (4o4) """ + """Fragments in fragments (4o4)""" # TODO this should be ideally in setUpClass, but then we hit a bug # with VppIpRoute incorrectly reporting it's present when it's not @@ -2211,11 +2523,15 @@ class TestFIFReassembly(VppTestCase): self.gre4.config_ip4() self.vapi.ip_reassembly_enable_disable( - sw_if_index=self.gre4.sw_if_index, enable_ip4=True) + sw_if_index=self.gre4.sw_if_index, enable_ip4=True + ) - self.route4 = VppIpRoute(self, self.tun_ip4, 32, - [VppRoutePath(self.src_if.remote_ip4, - self.src_if.sw_if_index)]) + self.route4 = VppIpRoute( + self, + self.tun_ip4, + 32, + [VppRoutePath(self.src_if.remote_ip4, self.src_if.sw_if_index)], + ) self.route4.add_vpp_config() self.reset_packet_infos() @@ -2225,28 +2541,33 @@ class TestFIFReassembly(VppTestCase): # Ethernet header here is only for size calculation, thus it # doesn't matter how it's initialized. This is to ensure that # reassembled packet is not > 9000 bytes, so that it's not dropped - p = (Ether() / - IP(id=i, src=self.src_if.remote_ip4, - dst=self.dst_if.remote_ip4) / - UDP(sport=1234, dport=5678) / - Raw(payload)) + p = ( + Ether() + / IP(id=i, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) + / UDP(sport=1234, dport=5678) + / Raw(payload) + ) size = self.packet_sizes[(i // 2) % len(self.packet_sizes)] self.extend_packet(p, size, self.padding) info.data = p[IP] # use only IP part, without ethernet header - fragments = [x for _, p in self._packet_infos.items() - for x in fragment_rfc791(p.data, 400)] + fragments = [ + x + for _, p in self._packet_infos.items() + for x in fragment_rfc791(p.data, 400) + ] - encapped_fragments = \ - [Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / - IP(src=self.tun_ip4, dst=self.src_if.local_ip4) / - GRE() / - p - for p in fragments] + encapped_fragments = [ + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IP(src=self.tun_ip4, dst=self.src_if.local_ip4) + / GRE() + / p + for p in fragments + ] - fragmented_encapped_fragments = \ - [x for p in encapped_fragments - for x in fragment_rfc791(p, 200)] + fragmented_encapped_fragments = [ + x for p in encapped_fragments for x in fragment_rfc791(p, 200) + ] self.src_if.add_stream(fragmented_encapped_fragments) @@ -2263,7 +2584,7 @@ class TestFIFReassembly(VppTestCase): self.logger.debug(self.vapi.ppcli("show interface")) def test_fif6(self): - """ Fragments in fragments (6o6) """ + """Fragments in fragments (6o6)""" # TODO this should be ideally in setUpClass, but then we hit a bug # with VppIpRoute incorrectly reporting it's present when it's not # so we need to manually remove the vpp config, thus we cannot have @@ -2276,12 +2597,15 @@ class TestFIFReassembly(VppTestCase): self.gre6.config_ip6() self.vapi.ip_reassembly_enable_disable( - sw_if_index=self.gre6.sw_if_index, enable_ip6=True) + sw_if_index=self.gre6.sw_if_index, enable_ip6=True + ) - self.route6 = VppIpRoute(self, self.tun_ip6, 128, - [VppRoutePath( - self.src_if.remote_ip6, - self.src_if.sw_if_index)]) + self.route6 = VppIpRoute( + self, + self.tun_ip6, + 128, + [VppRoutePath(self.src_if.remote_ip6, self.src_if.sw_if_index)], + ) self.route6.add_vpp_config() self.reset_packet_infos() @@ -2291,34 +2615,41 @@ class TestFIFReassembly(VppTestCase): # Ethernet header here is only for size calculation, thus it # doesn't matter how it's initialized. This is to ensure that # reassembled packet is not > 9000 bytes, so that it's not dropped - p = (Ether() / - IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) / - UDP(sport=1234, dport=5678) / - Raw(payload)) + p = ( + Ether() + / IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) + / UDP(sport=1234, dport=5678) + / Raw(payload) + ) size = self.packet_sizes[(i // 2) % len(self.packet_sizes)] self.extend_packet(p, size, self.padding) info.data = p[IPv6] # use only IPv6 part, without ethernet header - fragments = [x for _, i in self._packet_infos.items() - for x in fragment_rfc8200( - i.data, i.index, 400)] + fragments = [ + x + for _, i in self._packet_infos.items() + for x in fragment_rfc8200(i.data, i.index, 400) + ] - encapped_fragments = \ - [Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) / - IPv6(src=self.tun_ip6, dst=self.src_if.local_ip6) / - GRE() / - p - for p in fragments] + encapped_fragments = [ + Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) + / IPv6(src=self.tun_ip6, dst=self.src_if.local_ip6) + / GRE() + / p + for p in fragments + ] - fragmented_encapped_fragments = \ - [x for p in encapped_fragments for x in ( + fragmented_encapped_fragments = [ + x + for p in encapped_fragments + for x in ( fragment_rfc8200( - p, - 2 * len(self._packet_infos) + p[IPv6ExtHdrFragment].id, - 200) - if IPv6ExtHdrFragment in p else [p] + p, 2 * len(self._packet_infos) + p[IPv6ExtHdrFragment].id, 200 + ) + if IPv6ExtHdrFragment in p + else [p] ) - ] + ] self.src_if.add_stream(fragmented_encapped_fragments) @@ -2334,5 +2665,5 @@ class TestFIFReassembly(VppTestCase): self.gre6.remove_vpp_config() -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_session.py b/test/test_session.py index 6c48e5467db..699ebafc386 100644 --- a/test/test_session.py +++ b/test/test_session.py @@ -10,7 +10,7 @@ from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath @tag_fixme_vpp_workers class TestSession(VppTestCase): - """ Session Test Case """ + """Session Test Case""" @classmethod def setUpClass(cls): @@ -40,10 +40,12 @@ class TestSession(VppTestCase): table_id += 1 # Configure namespaces - self.vapi.app_namespace_add_del(namespace_id="0", - sw_if_index=self.loop0.sw_if_index) - self.vapi.app_namespace_add_del(namespace_id="1", - sw_if_index=self.loop1.sw_if_index) + self.vapi.app_namespace_add_del( + namespace_id="0", sw_if_index=self.loop0.sw_if_index + ) + self.vapi.app_namespace_add_del( + namespace_id="1", sw_if_index=self.loop1.sw_if_index + ) def tearDown(self): for i in self.lo_interfaces: @@ -55,31 +57,42 @@ class TestSession(VppTestCase): self.vapi.session_enable_disable(is_enable=1) def test_segment_manager_alloc(self): - """ Session Segment Manager Multiple Segment Allocation """ + """Session Segment Manager Multiple Segment Allocation""" # Add inter-table routes - ip_t01 = VppIpRoute(self, self.loop1.local_ip4, 32, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_table_id=1)]) - ip_t10 = VppIpRoute(self, self.loop0.local_ip4, 32, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_table_id=0)], table_id=1) + ip_t01 = VppIpRoute( + self, + self.loop1.local_ip4, + 32, + [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=1)], + ) + ip_t10 = VppIpRoute( + self, + self.loop0.local_ip4, + 32, + [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=0)], + table_id=1, + ) ip_t01.add_vpp_config() ip_t10.add_vpp_config() # Start builtin server and client with small private segments uri = "tcp://" + self.loop0.local_ip4 + "/1234" - error = self.vapi.cli("test echo server appns 0 fifo-size 64 " + - "private-segment-size 1m uri " + uri) + error = self.vapi.cli( + "test echo server appns 0 fifo-size 64 " + + "private-segment-size 1m uri " + + uri + ) if error: self.logger.critical(error) self.assertNotIn("failed", error) - error = self.vapi.cli("test echo client nclients 100 appns 1 " + - "no-output fifo-size 64 syn-timeout 2 " + - "private-segment-size 1m uri " + uri) + error = self.vapi.cli( + "test echo client nclients 100 appns 1 " + + "no-output fifo-size 64 syn-timeout 2 " + + "private-segment-size 1m uri " + + uri + ) if error: self.logger.critical(error) self.assertNotIn("failed", error) @@ -94,7 +107,7 @@ class TestSession(VppTestCase): @tag_fixme_vpp_workers class TestSessionUnitTests(VppTestCase): - """ Session Unit Tests Case """ + """Session Unit Tests Case""" @classmethod def setUpClass(cls): @@ -109,7 +122,7 @@ class TestSessionUnitTests(VppTestCase): self.vapi.session_enable_disable(is_enable=1) def test_session(self): - """ Session Unit Tests """ + """Session Unit Tests""" error = self.vapi.cli("test session all") if error: @@ -123,7 +136,7 @@ class TestSessionUnitTests(VppTestCase): @tag_run_solo class TestSegmentManagerTests(VppTestCase): - """ SVM Fifo Unit Tests Case """ + """SVM Fifo Unit Tests Case""" @classmethod def setUpClass(cls): @@ -137,7 +150,7 @@ class TestSegmentManagerTests(VppTestCase): super(TestSegmentManagerTests, self).setUp() def test_segment_manager(self): - """ Segment manager Tests """ + """Segment manager Tests""" error = self.vapi.cli("test segment-manager all") if error: @@ -150,7 +163,7 @@ class TestSegmentManagerTests(VppTestCase): @tag_run_solo class TestSvmFifoUnitTests(VppTestCase): - """ SVM Fifo Unit Tests Case """ + """SVM Fifo Unit Tests Case""" @classmethod def setUpClass(cls): @@ -164,7 +177,7 @@ class TestSvmFifoUnitTests(VppTestCase): super(TestSvmFifoUnitTests, self).setUp() def test_svm_fifo(self): - """ SVM Fifo Unit Tests """ + """SVM Fifo Unit Tests""" error = self.vapi.cli("test svm fifo all") if error: @@ -174,5 +187,6 @@ class TestSvmFifoUnitTests(VppTestCase): def tearDown(self): super(TestSvmFifoUnitTests, self).tearDown() -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_sixrd.py b/test/test_sixrd.py index 24ff74b8d1c..70ff1fc8769 100644 --- a/test/test_sixrd.py +++ b/test/test_sixrd.py @@ -18,7 +18,7 @@ from socket import AF_INET, AF_INET6, inet_pton class Test6RD(VppTestCase): - """ 6RD Test Case """ + """6RD Test Case""" @classmethod def setUpClass(cls): @@ -41,7 +41,7 @@ class Test6RD(VppTestCase): for n in range(4): i = self.pg_interfaces[n] i.admin_up() - if (n > 1): + if n > 1: i.set_table_ip4(10) i.set_table_ip6(20) i.config_ip4() @@ -82,28 +82,31 @@ class Test6RD(VppTestCase): self.assertEqual(rx[IPv6].nh, expected[IPv6].nh) def payload(self, len): - return 'x' * len + return "x" * len def test_6rd_ip6_to_ip4(self): - """ ip6 -> ip4 (encap) 6rd test """ + """ip6 -> ip4 (encap) 6rd test""" p_ether = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) - p_ip6 = IPv6(src="1::1", dst="2002:AC10:0202::1", nh='UDP') + p_ip6 = IPv6(src="1::1", dst="2002:AC10:0202::1", nh="UDP") - rv = self.vapi.ipip_6rd_add_tunnel(ip6_table_id=0, - ip4_table_id=0, - ip6_prefix='2002::/16', - ip4_prefix='0.0.0.0/0', - ip4_src=self.pg0.local_ip4, - security_check=True) + rv = self.vapi.ipip_6rd_add_tunnel( + ip6_table_id=0, + ip4_table_id=0, + ip6_prefix="2002::/16", + ip4_prefix="0.0.0.0/0", + ip4_src=self.pg0.local_ip4, + security_check=True, + ) self.tunnel_index = rv.sw_if_index self.vapi.cli("show ip6 fib") p_payload = UDP(sport=1234, dport=1234) - p = (p_ether / p_ip6 / p_payload) + p = p_ether / p_ip6 / p_payload - p_reply = (IP(src=self.pg0.local_ip4, dst=self.pg1.remote_ip4, - proto='ipv6') / p_ip6) + p_reply = ( + IP(src=self.pg0.local_ip4, dst=self.pg1.remote_ip4, proto="ipv6") / p_ip6 + ) rx = self.send_and_expect(self.pg0, p * 10, self.pg1) for p in rx: @@ -113,32 +116,37 @@ class Test6RD(VppTestCase): plen = 1481 - 40 - 8 p_ip6 = IPv6(src="1::1", dst="2002:AC10:0202::1") p_payload = UDP(sport=1234, dport=1234) / Raw(self.payload(plen)) - p = (p_ether / p_ip6 / p_payload) + p = p_ether / p_ip6 / p_payload - p_reply = (IP(src=self.pg0.local_ip4, dst=self.pg1.remote_ip4, - proto='ipv6') / p_ip6) + p_reply = ( + IP(src=self.pg0.local_ip4, dst=self.pg1.remote_ip4, proto="ipv6") / p_ip6 + ) rx = self.send_and_assert_no_replies(self.pg0, p * 10) self.vapi.ipip_6rd_del_tunnel(self.tunnel_index) def test_6rd_ip6_to_ip4_vrf(self): - """ ip6 -> ip4 (encap) 6rd VRF test """ + """ip6 -> ip4 (encap) 6rd VRF test""" p_ether = Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) - p_ip6 = IPv6(src="1::1", dst="2002:AC10:0402::1", nh='UDP') - - rv = self.vapi.ipip_6rd_add_tunnel(ip6_table_id=20, ip4_table_id=10, - ip6_prefix='2002::/16', - ip4_prefix='0.0.0.0/0', - ip4_src=self.pg2.local_ip4, - security_check=True) + p_ip6 = IPv6(src="1::1", dst="2002:AC10:0402::1", nh="UDP") + + rv = self.vapi.ipip_6rd_add_tunnel( + ip6_table_id=20, + ip4_table_id=10, + ip6_prefix="2002::/16", + ip4_prefix="0.0.0.0/0", + ip4_src=self.pg2.local_ip4, + security_check=True, + ) self.tunnel_index = rv.sw_if_index self.vapi.cli("show ip6 fib") p_payload = UDP(sport=1234, dport=1234) - p = (p_ether / p_ip6 / p_payload) + p = p_ether / p_ip6 / p_payload - p_reply = (IP(src=self.pg2.local_ip4, dst=self.pg3.remote_ip4, - proto='ipv6') / p_ip6) + p_reply = ( + IP(src=self.pg2.local_ip4, dst=self.pg3.remote_ip4, proto="ipv6") / p_ip6 + ) rx = self.send_and_expect(self.pg2, p * 10, self.pg3) for p in rx: @@ -148,40 +156,47 @@ class Test6RD(VppTestCase): plen = 1481 - 40 - 8 p_ip6 = IPv6(src="1::1", dst="2002:AC10:0402::1") p_payload = UDP(sport=1234, dport=1234) / Raw(self.payload(plen)) - p = (p_ether / p_ip6 / p_payload) + p = p_ether / p_ip6 / p_payload - p_reply = (IP(src=self.pg2.local_ip4, dst=self.pg3.remote_ip4, - proto='ipv6') / p_ip6) + p_reply = ( + IP(src=self.pg2.local_ip4, dst=self.pg3.remote_ip4, proto="ipv6") / p_ip6 + ) rx = self.send_and_assert_no_replies(self.pg0, p * 10) self.vapi.ipip_6rd_del_tunnel(self.tunnel_index) def test_6rd_ip4_to_ip6(self): - """ ip4 -> ip6 (decap) 6rd test """ - - rv = self.vapi.ipip_6rd_add_tunnel(ip6_table_id=0, - ip4_table_id=0, - ip6_prefix='2002::/16', - ip4_prefix='0.0.0.0/0', - ip4_src=self.pg0.local_ip4, - security_check=True) + """ip4 -> ip6 (decap) 6rd test""" + + rv = self.vapi.ipip_6rd_add_tunnel( + ip6_table_id=0, + ip4_table_id=0, + ip6_prefix="2002::/16", + ip4_prefix="0.0.0.0/0", + ip4_src=self.pg0.local_ip4, + security_check=True, + ) self.tunnel_index = rv.sw_if_index rv = self.vapi.ipip_6rd_del_tunnel(rv.sw_if_index) - rv = self.vapi.ipip_6rd_add_tunnel(ip6_table_id=0, - ip4_table_id=0, - ip6_prefix='2002::/16', - ip4_prefix='0.0.0.0/0', - ip4_src=self.pg0.local_ip4, - security_check=True) + rv = self.vapi.ipip_6rd_add_tunnel( + ip6_table_id=0, + ip4_table_id=0, + ip6_prefix="2002::/16", + ip4_prefix="0.0.0.0/0", + ip4_src=self.pg0.local_ip4, + security_check=True, + ) self.tunnel_index = rv.sw_if_index - p_ip6 = (IPv6(src="2002:AC10:0202::1", dst=self.pg1.remote_ip6) / - UDP(sport=1234, dport=1234)) + p_ip6 = IPv6(src="2002:AC10:0202::1", dst=self.pg1.remote_ip6) / UDP( + sport=1234, dport=1234 + ) - p = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.pg0.local_ip4) / - p_ip6) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.pg0.local_ip4) + / p_ip6 + ) p_reply = p_ip6 @@ -191,32 +206,38 @@ class Test6RD(VppTestCase): self.vapi.ipip_6rd_del_tunnel(self.tunnel_index) def test_6rd_ip4_to_ip6_vrf(self): - """ ip4 -> ip6 (decap) 6rd VRF test """ - - rv = self.vapi.ipip_6rd_add_tunnel(ip6_table_id=20, - ip4_table_id=10, - ip6_prefix='2002::/16', - ip4_prefix='0.0.0.0/0', - ip4_src=self.pg2.local_ip4, - security_check=True) + """ip4 -> ip6 (decap) 6rd VRF test""" + + rv = self.vapi.ipip_6rd_add_tunnel( + ip6_table_id=20, + ip4_table_id=10, + ip6_prefix="2002::/16", + ip4_prefix="0.0.0.0/0", + ip4_src=self.pg2.local_ip4, + security_check=True, + ) self.tunnel_index = rv.sw_if_index rv = self.vapi.ipip_6rd_del_tunnel(rv.sw_if_index) - rv = self.vapi.ipip_6rd_add_tunnel(ip6_table_id=20, - ip4_table_id=10, - ip6_prefix='2002::/16', - ip4_prefix='0.0.0.0/0', - ip4_src=self.pg2.local_ip4, - security_check=True) + rv = self.vapi.ipip_6rd_add_tunnel( + ip6_table_id=20, + ip4_table_id=10, + ip6_prefix="2002::/16", + ip4_prefix="0.0.0.0/0", + ip4_src=self.pg2.local_ip4, + security_check=True, + ) self.tunnel_index = rv.sw_if_index self.vapi.sw_interface_set_table(self.tunnel_index, 1, 20) - p_ip6 = (IPv6(src="2002:AC10:0402::1", dst=self.pg3.remote_ip6) / - UDP(sport=1234, dport=1234)) + p_ip6 = IPv6(src="2002:AC10:0402::1", dst=self.pg3.remote_ip6) / UDP( + sport=1234, dport=1234 + ) - p = (Ether(src=self.pg2.remote_mac, - dst=self.pg2.local_mac) / - IP(src=self.pg3.remote_ip4, dst=self.pg2.local_ip4) / - p_ip6) + p = ( + Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) + / IP(src=self.pg3.remote_ip4, dst=self.pg2.local_ip4) + / p_ip6 + ) p_reply = p_ip6 @@ -227,39 +248,45 @@ class Test6RD(VppTestCase): self.vapi.ipip_6rd_del_tunnel(self.tunnel_index) def test_6rd_ip4_to_ip6_multiple(self): - """ ip4 -> ip6 (decap) 6rd test """ + """ip4 -> ip6 (decap) 6rd test""" self.tunnel_index = [] - rv = self.vapi.ipip_6rd_add_tunnel(ip6_table_id=0, - ip4_table_id=0, - ip6_prefix='2002::/16', - ip4_prefix='0.0.0.0/0', - ip4_src=self.pg0.local_ip4, - security_check=True) + rv = self.vapi.ipip_6rd_add_tunnel( + ip6_table_id=0, + ip4_table_id=0, + ip6_prefix="2002::/16", + ip4_prefix="0.0.0.0/0", + ip4_src=self.pg0.local_ip4, + security_check=True, + ) self.tunnel_index.append(rv.sw_if_index) - rv = self.vapi.ipip_6rd_add_tunnel(ip6_table_id=0, - ip4_table_id=0, - ip6_prefix='2003::/16', - ip4_prefix='0.0.0.0/0', - ip4_src=self.pg1.local_ip4, - security_check=True) + rv = self.vapi.ipip_6rd_add_tunnel( + ip6_table_id=0, + ip4_table_id=0, + ip6_prefix="2003::/16", + ip4_prefix="0.0.0.0/0", + ip4_src=self.pg1.local_ip4, + security_check=True, + ) self.tunnel_index.append(rv.sw_if_index) self.vapi.cli("show ip6 fib") p_ether = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) p_ip4 = IP(src=self.pg1.remote_ip4, dst=self.pg0.local_ip4) - p_ip6_1 = (IPv6(src="2002:AC10:0202::1", dst=self.pg1.remote_ip6) / - UDP(sport=1234, dport=1234)) - p_ip6_2 = (IPv6(src="2003:AC10:0202::1", dst=self.pg1.remote_ip6) / - UDP(sport=1234, dport=1234)) - - p = (p_ether / p_ip4 / p_ip6_1) + p_ip6_1 = IPv6(src="2002:AC10:0202::1", dst=self.pg1.remote_ip6) / UDP( + sport=1234, dport=1234 + ) + p_ip6_2 = IPv6(src="2003:AC10:0202::1", dst=self.pg1.remote_ip6) / UDP( + sport=1234, dport=1234 + ) + + p = p_ether / p_ip4 / p_ip6_1 rx = self.send_and_expect(self.pg0, p * 10, self.pg1) for p in rx: self.validate_4in6(p, p_ip6_1) - p = (p_ether / p_ip4 / p_ip6_2) + p = p_ether / p_ip4 / p_ip6_2 rx = self.send_and_expect(self.pg0, p * 10, self.pg1) for p in rx: self.validate_4in6(p, p_ip6_2) @@ -267,49 +294,57 @@ class Test6RD(VppTestCase): self.vapi.ipip_6rd_del_tunnel(i) def test_6rd_ip4_to_ip6_suffix(self): - """ ip4 -> ip6 (decap) 6rd test """ - - rv = self.vapi.ipip_6rd_add_tunnel(ip6_table_id=0, - ip4_table_id=0, - ip6_prefix='2002::/16', - ip4_prefix='172.0.0.0/8', - ip4_src=self.pg0.local_ip4, - security_check=True) + """ip4 -> ip6 (decap) 6rd test""" + + rv = self.vapi.ipip_6rd_add_tunnel( + ip6_table_id=0, + ip4_table_id=0, + ip6_prefix="2002::/16", + ip4_prefix="172.0.0.0/8", + ip4_src=self.pg0.local_ip4, + security_check=True, + ) self.tunnel_index = rv.sw_if_index self.vapi.cli("show ip6 fib") p_ether = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) p_ip4 = IP(src=self.pg1.remote_ip4, dst=self.pg0.local_ip4) - p_ip6 = (IPv6(src="2002:1002:0200::1", dst=self.pg1.remote_ip6) / - UDP(sport=1234, dport=1234)) + p_ip6 = IPv6(src="2002:1002:0200::1", dst=self.pg1.remote_ip6) / UDP( + sport=1234, dport=1234 + ) - p = (p_ether / p_ip4 / p_ip6) + p = p_ether / p_ip4 / p_ip6 rx = self.send_and_expect(self.pg0, p * 10, self.pg1) for p in rx: self.validate_4in6(p, p_ip6) self.vapi.ipip_6rd_del_tunnel(self.tunnel_index) def test_6rd_ip4_to_ip6_sec_check(self): - """ ip4 -> ip6 (decap) security check 6rd test """ - - rv = self.vapi.ipip_6rd_add_tunnel(ip6_table_id=0, - ip4_table_id=0, - ip6_prefix='2002::/16', - ip4_prefix='0.0.0.0/0', - ip4_src=self.pg0.local_ip4, - security_check=True) + """ip4 -> ip6 (decap) security check 6rd test""" + + rv = self.vapi.ipip_6rd_add_tunnel( + ip6_table_id=0, + ip4_table_id=0, + ip6_prefix="2002::/16", + ip4_prefix="0.0.0.0/0", + ip4_src=self.pg0.local_ip4, + security_check=True, + ) self.tunnel_index = rv.sw_if_index self.vapi.cli("show ip6 fib") - p_ip6 = (IPv6(src="2002:AC10:0202::1", dst=self.pg1.remote_ip6) / - UDP(sport=1234, dport=1234)) - p_ip6_fail = (IPv6(src="2002:DEAD:0202::1", dst=self.pg1.remote_ip6) / - UDP(sport=1234, dport=1234)) - - p = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.pg0.local_ip4) / - p_ip6) + p_ip6 = IPv6(src="2002:AC10:0202::1", dst=self.pg1.remote_ip6) / UDP( + sport=1234, dport=1234 + ) + p_ip6_fail = IPv6(src="2002:DEAD:0202::1", dst=self.pg1.remote_ip6) / UDP( + sport=1234, dport=1234 + ) + + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.pg0.local_ip4) + / p_ip6 + ) p_reply = p_ip6 @@ -317,55 +352,62 @@ class Test6RD(VppTestCase): for p in rx: self.validate_4in6(p, p_reply) - p = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg1.remote_ip4, dst=self.pg0.local_ip4) / - p_ip6_fail) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg1.remote_ip4, dst=self.pg0.local_ip4) + / p_ip6_fail + ) rx = self.send_and_assert_no_replies(self.pg0, p * 10) self.vapi.ipip_6rd_del_tunnel(self.tunnel_index) def test_6rd_bgp_tunnel(self): - """ 6rd BGP tunnel """ + """6rd BGP tunnel""" - rv = self.vapi.ipip_6rd_add_tunnel(ip6_table_id=0, - ip4_table_id=0, - ip6_prefix='2002::/16', - ip4_prefix='0.0.0.0/0', - ip4_src=self.pg0.local_ip4, - security_check=False) + rv = self.vapi.ipip_6rd_add_tunnel( + ip6_table_id=0, + ip4_table_id=0, + ip6_prefix="2002::/16", + ip4_prefix="0.0.0.0/0", + ip4_src=self.pg0.local_ip4, + security_check=False, + ) self.tunnel_index = rv.sw_if_index - default_route = VppIpRoute(self, "DEAD::", 16, - [VppRoutePath("2002:0808:0808::", - self.tunnel_index)]) + default_route = VppIpRoute( + self, "DEAD::", 16, [VppRoutePath("2002:0808:0808::", self.tunnel_index)] + ) default_route.add_vpp_config() - ip4_route = VppIpRoute(self, "8.0.0.0", 8, - [VppRoutePath(self.pg1.remote_ip4, 0xFFFFFFFF)]) + ip4_route = VppIpRoute( + self, "8.0.0.0", 8, [VppRoutePath(self.pg1.remote_ip4, 0xFFFFFFFF)] + ) ip4_route.add_vpp_config() # Via recursive route 6 -> 4 - p = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(src="1::1", dst="DEAD:BEEF::1") / - UDP(sport=1234, dport=1234)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src="1::1", dst="DEAD:BEEF::1") + / UDP(sport=1234, dport=1234) + ) - p_reply = (IP(src=self.pg0.local_ip4, dst="8.8.8.8", - proto='ipv6') / - IPv6(src='1::1', dst='DEAD:BEEF::1', nh='UDP')) + p_reply = IP(src=self.pg0.local_ip4, dst="8.8.8.8", proto="ipv6") / IPv6( + src="1::1", dst="DEAD:BEEF::1", nh="UDP" + ) rx = self.send_and_expect(self.pg0, p * 10, self.pg1) for p in rx: self.validate_6in4(p, p_reply) # Via recursive route 4 -> 6 (Security check must be disabled) - p_ip6 = (IPv6(src="DEAD:BEEF::1", dst=self.pg1.remote_ip6) / - UDP(sport=1234, dport=1234)) - p = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src="8.8.8.8", dst=self.pg0.local_ip4) / - p_ip6) + p_ip6 = IPv6(src="DEAD:BEEF::1", dst=self.pg1.remote_ip6) / UDP( + sport=1234, dport=1234 + ) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src="8.8.8.8", dst=self.pg0.local_ip4) + / p_ip6 + ) p_reply = p_ip6 @@ -377,5 +419,5 @@ class Test6RD(VppTestCase): self.vapi.ipip_6rd_del_tunnel(self.tunnel_index) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_span.py b/test/test_span.py index ecefe153706..3572d64e79c 100644 --- a/test/test_span.py +++ b/test/test_span.py @@ -16,19 +16,19 @@ from collections import namedtuple from vpp_papi import VppEnum -Tag = namedtuple('Tag', ['dot1', 'vlan']) +Tag = namedtuple("Tag", ["dot1", "vlan"]) DOT1AD = 0x88A8 DOT1Q = 0x8100 class TestSpan(VppTestCase): - """ SPAN Test Case """ + """SPAN Test Case""" @classmethod def setUpClass(cls): super(TestSpan, cls).setUpClass() # Test variables - cls.pkts_per_burst = 257 # Number of packets per burst + cls.pkts_per_burst = 257 # Number of packets per burst # create 3 pg interfaces cls.create_pg_interfaces(range(3)) @@ -56,8 +56,9 @@ class TestSpan(VppTestCase): def setUp(self): super(TestSpan, self).setUp() - self.vxlan = VppVxlanTunnel(self, src=self.pg2.local_ip4, - dst=self.pg2.remote_ip4, vni=1111) + self.vxlan = VppVxlanTunnel( + self, src=self.pg2.local_ip4, dst=self.pg2.remote_ip4, vni=1111 + ) self.vxlan.add_vpp_config() self.reset_packet_infos() @@ -72,8 +73,9 @@ class TestSpan(VppTestCase): self.vapi.sw_interface_set_l2_xconnect(b, a, enable=is_add) def bridge(self, sw_if_index, is_add=1): - self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=sw_if_index, - bd_id=self.bd_id, enable=is_add) + self.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=sw_if_index, bd_id=self.bd_id, enable=is_add + ) def _remove_tag(self, packet, vlan, tag_type): self.assertEqual(packet.type, tag_type) @@ -145,10 +147,12 @@ class TestSpan(VppTestCase): for i in range(0, self.pkts_per_burst): payload = "span test" size = packet_sizes[int((i / 2) % len(packet_sizes))] - p = (Ether(src=src_if.local_mac, dst=dst_mac) / - IP(src=src_if.remote_ip4, dst=dst_if.remote_ip4) / - UDP(sport=10000 + src_if.sw_if_index * 1000 + i, dport=1234) / - Raw(payload)) + p = ( + Ether(src=src_if.local_mac, dst=dst_mac) + / IP(src=src_if.remote_ip4, dst=dst_if.remote_ip4) + / UDP(sport=10000 + src_if.sw_if_index * 1000 + i, dport=1234) + / Raw(payload) + ) if do_dot1: p = self.sub_if.add_dot1_layer(p) self.extend_packet(p, size) @@ -156,9 +160,12 @@ class TestSpan(VppTestCase): return pkts def verify_capture(self, cap1, cap2): - self.assertEqual(len(cap1), len(cap2), - "Different number of sent and mirrored packets :" - "%u != %u" % (len(cap1), len(cap2))) + self.assertEqual( + len(cap1), + len(cap2), + "Different number of sent and mirrored packets :" + "%u != %u" % (len(cap1), len(cap2)), + ) pkts1 = [(pkt[Ether] / pkt[IP] / pkt[UDP]) for pkt in cap1] pkts2 = [(pkt[Ether] / pkt[IP] / pkt[UDP]) for pkt in cap2] @@ -166,7 +173,7 @@ class TestSpan(VppTestCase): self.assertEqual(pkts1.sort(), pkts2.sort()) def test_device_span(self): - """ SPAN device rx mirror """ + """SPAN device rx mirror""" # Create bi-directional cross-connects between pg0 and pg1 self.xconnect(self.pg0.sw_if_index, self.pg1.sw_if_index) @@ -176,7 +183,8 @@ class TestSpan(VppTestCase): # Enable SPAN on pg0 (mirrored to pg2) self.vapi.sw_interface_span_enable_disable( - self.pg0.sw_if_index, self.pg2.sw_if_index) + self.pg0.sw_if_index, self.pg2.sw_if_index + ) self.logger.info(self.vapi.ppcli("show interface span")) # Enable packet capturing and start packet sending @@ -190,13 +198,14 @@ class TestSpan(VppTestCase): # Disable SPAN on pg0 (mirrored to pg2) self.vapi.sw_interface_span_enable_disable( - self.pg0.sw_if_index, self.pg2.sw_if_index, state=0) + self.pg0.sw_if_index, self.pg2.sw_if_index, state=0 + ) self.xconnect(self.pg0.sw_if_index, self.pg1.sw_if_index, is_add=0) self.verify_capture(pg1_pkts, pg2_pkts) def test_span_l2_rx(self): - """ SPAN l2 rx mirror """ + """SPAN l2 rx mirror""" self.sub_if.admin_up() @@ -204,13 +213,13 @@ class TestSpan(VppTestCase): # Create bi-directional cross-connects between pg0 subif and pg1 self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index) # Create incoming packet streams for packet-generator interfaces - pkts = self.create_stream( - self.pg0, self.pg_if_packet_sizes, do_dot1=True) + pkts = self.create_stream(self.pg0, self.pg_if_packet_sizes, do_dot1=True) self.pg0.add_stream(pkts) # Enable SPAN on pg0 (mirrored to pg2) self.vapi.sw_interface_span_enable_disable( - self.sub_if.sw_if_index, self.pg2.sw_if_index, is_l2=1) + self.sub_if.sw_if_index, self.pg2.sw_if_index, is_l2=1 + ) self.logger.info(self.vapi.ppcli("show interface span")) # Enable packet capturing and start packet sending @@ -225,29 +234,29 @@ class TestSpan(VppTestCase): # Disable SPAN on pg0 (mirrored to pg2) self.vapi.sw_interface_span_enable_disable( - self.sub_if.sw_if_index, self.pg2.sw_if_index, state=0, is_l2=1) + self.sub_if.sw_if_index, self.pg2.sw_if_index, state=0, is_l2=1 + ) self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index, is_add=0) self.verify_capture(pg1_pkts, pg2_pkts) def test_span_l2_rx_dst_vxlan(self): - """ SPAN l2 rx mirror into vxlan """ + """SPAN l2 rx mirror into vxlan""" self.sub_if.admin_up() - self.vapi.sw_interface_set_flags(self.vxlan.sw_if_index, - flags=1) + self.vapi.sw_interface_set_flags(self.vxlan.sw_if_index, flags=1) self.bridge(self.vxlan.sw_if_index, is_add=1) # Create bi-directional cross-connects between pg0 subif and pg1 self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index) # Create incoming packet streams for packet-generator interfaces - pkts = self.create_stream( - self.pg0, self.pg_if_packet_sizes, do_dot1=True) + pkts = self.create_stream(self.pg0, self.pg_if_packet_sizes, do_dot1=True) self.pg0.add_stream(pkts) # Enable SPAN on pg0 sub if (mirrored to vxlan) self.vapi.sw_interface_span_enable_disable( - self.sub_if.sw_if_index, self.vxlan.sw_if_index, is_l2=1) + self.sub_if.sw_if_index, self.vxlan.sw_if_index, is_l2=1 + ) self.logger.info(self.vapi.ppcli("show interface span")) # Enable packet capturing and start packet sending @@ -262,20 +271,23 @@ class TestSpan(VppTestCase): self.bridge(self.vxlan.sw_if_index, is_add=0) # Disable SPAN on pg0 sub if (mirrored to vxlan) self.vapi.sw_interface_span_enable_disable( - self.sub_if.sw_if_index, self.vxlan.sw_if_index, state=0, is_l2=1) + self.sub_if.sw_if_index, self.vxlan.sw_if_index, state=0, is_l2=1 + ) self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index, is_add=0) self.verify_capture(pg1_pkts, pg2_pkts) def test_span_l2_rx_dst_gre_erspan(self): - """ SPAN l2 rx mirror into gre-erspan """ + """SPAN l2 rx mirror into gre-erspan""" self.sub_if.admin_up() - gre_if = VppGreInterface(self, self.pg2.local_ip4, - self.pg2.remote_ip4, - session=543, - type=(VppEnum.vl_api_gre_tunnel_type_t. - GRE_API_TUNNEL_TYPE_ERSPAN)) + gre_if = VppGreInterface( + self, + self.pg2.local_ip4, + self.pg2.remote_ip4, + session=543, + type=(VppEnum.vl_api_gre_tunnel_type_t.GRE_API_TUNNEL_TYPE_ERSPAN), + ) gre_if.add_vpp_config() gre_if.admin_up() @@ -285,13 +297,13 @@ class TestSpan(VppTestCase): self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index, is_add=1) # Create incoming packet streams for packet-generator interfaces - pkts = self.create_stream( - self.pg0, self.pg_if_packet_sizes, do_dot1=True) + pkts = self.create_stream(self.pg0, self.pg_if_packet_sizes, do_dot1=True) self.pg0.add_stream(pkts) # Enable SPAN on pg0 sub if (mirrored to gre-erspan) self.vapi.sw_interface_span_enable_disable( - self.sub_if.sw_if_index, gre_if.sw_if_index, is_l2=1) + self.sub_if.sw_if_index, gre_if.sw_if_index, is_l2=1 + ) # Enable packet capturing and start packet sending self.pg_enable_capture(self.pg_interfaces) @@ -302,28 +314,33 @@ class TestSpan(VppTestCase): pg1_pkts = self.pg1.get_capture(n_pkts) pg2_pkts = self.pg2.get_capture(n_pkts) - def decap(p): return self.decap_erspan(p, session=543) + def decap(p): + return self.decap_erspan(p, session=543) + pg2_decaped = [decap(p) for p in pg2_pkts] self.bridge(gre_if.sw_if_index, is_add=0) # Disable SPAN on pg0 sub if self.vapi.sw_interface_span_enable_disable( - self.sub_if.sw_if_index, gre_if.sw_if_index, state=0, is_l2=1) + self.sub_if.sw_if_index, gre_if.sw_if_index, state=0, is_l2=1 + ) gre_if.remove_vpp_config() self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index, is_add=0) self.verify_capture(pg1_pkts, pg2_decaped) def test_span_l2_rx_dst_gre_subif_vtr(self): - """ SPAN l2 rx mirror into gre-subif+vtr """ + """SPAN l2 rx mirror into gre-subif+vtr""" self.sub_if.admin_up() - gre_if = VppGreInterface(self, self.pg2.local_ip4, - self.pg2.remote_ip4, - type=(VppEnum.vl_api_gre_tunnel_type_t. - GRE_API_TUNNEL_TYPE_TEB)) + gre_if = VppGreInterface( + self, + self.pg2.local_ip4, + self.pg2.remote_ip4, + type=(VppEnum.vl_api_gre_tunnel_type_t.GRE_API_TUNNEL_TYPE_TEB), + ) gre_if.add_vpp_config() gre_if.admin_up() @@ -337,13 +354,13 @@ class TestSpan(VppTestCase): self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index, is_add=1) # Create incoming packet streams for packet-generator interfaces - pkts = self.create_stream( - self.pg0, self.pg_if_packet_sizes, do_dot1=True) + pkts = self.create_stream(self.pg0, self.pg_if_packet_sizes, do_dot1=True) self.pg0.add_stream(pkts) # Enable SPAN on pg0 sub if (mirrored to gre sub if) self.vapi.sw_interface_span_enable_disable( - self.sub_if.sw_if_index, gre_sub_if.sw_if_index, is_l2=1) + self.sub_if.sw_if_index, gre_sub_if.sw_if_index, is_l2=1 + ) # Enable packet capturing and start packet sending self.pg_enable_capture(self.pg_interfaces) @@ -354,22 +371,24 @@ class TestSpan(VppTestCase): pg1_pkts = self.pg1.get_capture(n_pkts) pg2_pkts = self.pg2.get_capture(n_pkts) - def decap(p): return self.remove_tags( - self.decap_gre(p), [Tag(dot1=DOT1Q, vlan=500)]) + def decap(p): + return self.remove_tags(self.decap_gre(p), [Tag(dot1=DOT1Q, vlan=500)]) + pg2_decaped = [decap(p) for p in pg2_pkts] self.bridge(gre_sub_if.sw_if_index, is_add=0) # Disable SPAN on pg0 sub if self.vapi.sw_interface_span_enable_disable( - self.sub_if.sw_if_index, gre_sub_if.sw_if_index, state=0, is_l2=1) + self.sub_if.sw_if_index, gre_sub_if.sw_if_index, state=0, is_l2=1 + ) gre_if.remove_vpp_config() self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index, is_add=0) self.verify_capture(pg1_pkts, pg2_decaped) def test_span_l2_rx_dst_1q_vtr(self): - """ SPAN l2 rx mirror into 1q subif+vtr """ + """SPAN l2 rx mirror into 1q subif+vtr""" self.sub_if.admin_up() self.vlan_sub_if.admin_up() @@ -379,12 +398,12 @@ class TestSpan(VppTestCase): self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index, is_add=1) # Create incoming packet streams for packet-generator interfaces - pkts = self.create_stream( - self.pg0, self.pg_if_packet_sizes, do_dot1=True) + pkts = self.create_stream(self.pg0, self.pg_if_packet_sizes, do_dot1=True) self.pg0.add_stream(pkts) self.vapi.sw_interface_span_enable_disable( - self.sub_if.sw_if_index, self.vlan_sub_if.sw_if_index, is_l2=1) + self.sub_if.sw_if_index, self.vlan_sub_if.sw_if_index, is_l2=1 + ) # Enable packet capturing and start packet sending self.pg_enable_capture(self.pg_interfaces) @@ -394,20 +413,21 @@ class TestSpan(VppTestCase): n_pkts = len(pkts) pg1_pkts = self.pg1.get_capture(n_pkts) pg2_pkts = self.pg2.get_capture(n_pkts) - pg2_untagged = [self.remove_tags(p, [Tag(dot1=DOT1Q, vlan=300)]) - for p in pg2_pkts] + pg2_untagged = [ + self.remove_tags(p, [Tag(dot1=DOT1Q, vlan=300)]) for p in pg2_pkts + ] self.bridge(self.vlan_sub_if.sw_if_index, is_add=0) # Disable SPAN on pg0 sub if (mirrored to vxlan) self.vapi.sw_interface_span_enable_disable( - self.sub_if.sw_if_index, self.vlan_sub_if.sw_if_index, state=0, - is_l2=1) + self.sub_if.sw_if_index, self.vlan_sub_if.sw_if_index, state=0, is_l2=1 + ) self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index, is_add=0) self.verify_capture(pg1_pkts, pg2_untagged) def test_span_l2_rx_dst_1ad_vtr(self): - """ SPAN l2 rx mirror into 1ad subif+vtr """ + """SPAN l2 rx mirror into 1ad subif+vtr""" self.sub_if.admin_up() self.qinq_sub_if.admin_up() @@ -417,12 +437,12 @@ class TestSpan(VppTestCase): self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index, is_add=1) # Create incoming packet streams for packet-generator interfaces - pkts = self.create_stream( - self.pg0, self.pg_if_packet_sizes, do_dot1=True) + pkts = self.create_stream(self.pg0, self.pg_if_packet_sizes, do_dot1=True) self.pg0.add_stream(pkts) self.vapi.sw_interface_span_enable_disable( - self.sub_if.sw_if_index, self.qinq_sub_if.sw_if_index, is_l2=1) + self.sub_if.sw_if_index, self.qinq_sub_if.sw_if_index, is_l2=1 + ) # Enable packet capturing and start packet sending self.pg_enable_capture(self.pg_interfaces) @@ -432,34 +452,35 @@ class TestSpan(VppTestCase): n_pkts = len(pkts) pg1_pkts = self.pg1.get_capture(n_pkts) pg2_pkts = self.pg2.get_capture(n_pkts) - pg2_untagged = [self.remove_tags(p, [Tag(dot1=DOT1AD, vlan=400), - Tag(dot1=DOT1Q, vlan=500)]) - for p in pg2_pkts] + pg2_untagged = [ + self.remove_tags(p, [Tag(dot1=DOT1AD, vlan=400), Tag(dot1=DOT1Q, vlan=500)]) + for p in pg2_pkts + ] self.bridge(self.qinq_sub_if.sw_if_index, is_add=0) # Disable SPAN on pg0 sub if (mirrored to vxlan) self.vapi.sw_interface_span_enable_disable( - self.sub_if.sw_if_index, self.qinq_sub_if.sw_if_index, state=0, - is_l2=1) + self.sub_if.sw_if_index, self.qinq_sub_if.sw_if_index, state=0, is_l2=1 + ) self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index, is_add=0) self.verify_capture(pg1_pkts, pg2_untagged) def test_l2_tx_span(self): - """ SPAN l2 tx mirror """ + """SPAN l2 tx mirror""" self.sub_if.admin_up() self.bridge(self.pg2.sw_if_index) # Create bi-directional cross-connects between pg0 and pg1 self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index) # Create incoming packet streams for packet-generator interfaces - pkts = self.create_stream( - self.pg0, self.pg_if_packet_sizes, do_dot1=True) + pkts = self.create_stream(self.pg0, self.pg_if_packet_sizes, do_dot1=True) self.pg0.add_stream(pkts) # Enable SPAN on pg1 (mirrored to pg2) self.vapi.sw_interface_span_enable_disable( - self.pg1.sw_if_index, self.pg2.sw_if_index, is_l2=1, state=2) + self.pg1.sw_if_index, self.pg2.sw_if_index, is_l2=1, state=2 + ) self.logger.info(self.vapi.ppcli("show interface span")) # Enable packet capturing and start packet sending @@ -473,13 +494,14 @@ class TestSpan(VppTestCase): self.bridge(self.pg2.sw_if_index, is_add=0) # Disable SPAN on pg0 (mirrored to pg2) self.vapi.sw_interface_span_enable_disable( - self.pg1.sw_if_index, self.pg2.sw_if_index, state=0, is_l2=1) + self.pg1.sw_if_index, self.pg2.sw_if_index, state=0, is_l2=1 + ) self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index, is_add=0) self.verify_capture(pg1_pkts, pg2_pkts) def test_l2_rx_tx_span(self): - """ SPAN l2 rx tx mirror """ + """SPAN l2 rx tx mirror""" self.sub_if.admin_up() self.bridge(self.pg2.sw_if_index) @@ -487,16 +509,15 @@ class TestSpan(VppTestCase): self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index) # Create incoming packet streams for packet-generator interfaces - pg0_pkts = self.create_stream( - self.pg0, self.pg_if_packet_sizes, do_dot1=True) + pg0_pkts = self.create_stream(self.pg0, self.pg_if_packet_sizes, do_dot1=True) self.pg0.add_stream(pg0_pkts) - pg1_pkts = self.create_stream( - self.pg1, self.pg_if_packet_sizes, do_dot1=False) + pg1_pkts = self.create_stream(self.pg1, self.pg_if_packet_sizes, do_dot1=False) self.pg1.add_stream(pg1_pkts) # Enable SPAN on pg0 (mirrored to pg2) self.vapi.sw_interface_span_enable_disable( - self.sub_if.sw_if_index, self.pg2.sw_if_index, is_l2=1, state=3) + self.sub_if.sw_if_index, self.pg2.sw_if_index, is_l2=1, state=3 + ) self.logger.info(self.vapi.ppcli("show interface span")) # Enable packet capturing and start packet sending @@ -515,34 +536,40 @@ class TestSpan(VppTestCase): self.bridge(self.pg2.sw_if_index, is_add=0) # Disable SPAN on pg0 (mirrored to pg2) self.vapi.sw_interface_span_enable_disable( - self.sub_if.sw_if_index, self.pg2.sw_if_index, state=0, is_l2=1) + self.sub_if.sw_if_index, self.pg2.sw_if_index, state=0, is_l2=1 + ) self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index, is_add=0) self.verify_capture(pg0_pkts + pg1_pkts, pg2_pkts) def test_l2_bcast_mirror(self): - """ SPAN l2 broadcast mirror """ + """SPAN l2 broadcast mirror""" self.sub_if.admin_up() self.bridge(self.pg2.sw_if_index) # Create bi-directional cross-connects between pg0 and pg1 self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.sub_if.sw_if_index, bd_id=99, enable=1) + rx_sw_if_index=self.sub_if.sw_if_index, bd_id=99, enable=1 + ) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg1.sw_if_index, bd_id=99, enable=1) + rx_sw_if_index=self.pg1.sw_if_index, bd_id=99, enable=1 + ) # Create incoming packet streams for packet-generator interfaces pg0_pkts = self.create_stream( - self.pg0, self.pg_if_packet_sizes, do_dot1=True, bcast=True) + self.pg0, self.pg_if_packet_sizes, do_dot1=True, bcast=True + ) self.pg0.add_stream(pg0_pkts) pg1_pkts = self.create_stream( - self.pg1, self.pg_if_packet_sizes, do_dot1=False, bcast=True) + self.pg1, self.pg_if_packet_sizes, do_dot1=False, bcast=True + ) self.pg1.add_stream(pg1_pkts) # Enable SPAN on pg0 (mirrored to pg2) self.vapi.sw_interface_span_enable_disable( - self.sub_if.sw_if_index, self.pg2.sw_if_index, is_l2=1, state=3) + self.sub_if.sw_if_index, self.pg2.sw_if_index, is_l2=1, state=3 + ) self.logger.info(self.vapi.ppcli("show interface span")) # Enable packet capturing and start packet sending @@ -560,15 +587,18 @@ class TestSpan(VppTestCase): self.bridge(self.pg2.sw_if_index, is_add=0) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.sub_if.sw_if_index, bd_id=99, enable=0) + rx_sw_if_index=self.sub_if.sw_if_index, bd_id=99, enable=0 + ) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg1.sw_if_index, bd_id=99, enable=0) + rx_sw_if_index=self.pg1.sw_if_index, bd_id=99, enable=0 + ) # Disable SPAN on pg0 (mirrored to pg2) self.vapi.sw_interface_span_enable_disable( - self.sub_if.sw_if_index, self.pg2.sw_if_index, state=0, is_l2=1) + self.sub_if.sw_if_index, self.pg2.sw_if_index, state=0, is_l2=1 + ) self.verify_capture(pg0_pkts + pg1_pkts, pg2_pkts) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_sparse_vec.py b/test/test_sparse_vec.py index a683faefd57..6b1cb2885e0 100644 --- a/test/test_sparse_vec.py +++ b/test/test_sparse_vec.py @@ -7,7 +7,7 @@ from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath class TestSparseVec(VppTestCase): - """ SparseVec Test Cases """ + """SparseVec Test Cases""" @classmethod def setUpClass(cls): @@ -24,11 +24,12 @@ class TestSparseVec(VppTestCase): super(TestSparseVec, self).tearDown() def test_string_unittest(self): - """ SparseVec unit tests """ + """SparseVec unit tests""" error = self.vapi.cli("test sparse_vec") if error.find("failed") != -1: self.logger.critical("FAILURE in the sparse_vec test") self.assertNotIn("failed", error) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_srmpls.py b/test/test_srmpls.py index b9abeaeffec..bac3eff2542 100644 --- a/test/test_srmpls.py +++ b/test/test_srmpls.py @@ -5,8 +5,14 @@ import socket from framework import VppTestCase, VppTestRunner from vpp_ip import DpoProto -from vpp_ip_route import VppIpRoute, VppRoutePath, VppMplsRoute, \ - VppIpTable, VppMplsTable, VppMplsLabel +from vpp_ip_route import ( + VppIpRoute, + VppRoutePath, + VppMplsRoute, + VppIpTable, + VppMplsTable, + VppMplsLabel, +) from vpp_mpls_tunnel_interface import VppMPLSTunnelInterface from scapy.packet import Raw @@ -47,7 +53,7 @@ def verify_mpls_stack(tst, rx, mpls_labels): class TestSRMPLS(VppTestCase): - """ SR-MPLS Test Case """ + """SR-MPLS Test Case""" @classmethod def setUpClass(cls): @@ -94,17 +100,19 @@ class TestSRMPLS(VppTestCase): for i in range(0, 257): info = self.create_packet_info(src_if, src_if) payload = self.info_to_payload(info) - p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - IP(src=src_if.remote_ip4, dst=dst_ip, - ttl=ip_ttl, tos=ip_dscp) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / IP(src=src_if.remote_ip4, dst=dst_ip, ttl=ip_ttl, tos=ip_dscp) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) info.data = p.copy() pkts.append(p) return pkts - def verify_capture_labelled_ip4(self, src_if, capture, sent, - mpls_labels, ip_ttl=None): + def verify_capture_labelled_ip4( + self, src_if, capture, sent, mpls_labels, ip_ttl=None + ): try: capture = verify_filter(capture, sent) @@ -152,15 +160,21 @@ class TestSRMPLS(VppTestCase): raise def test_sr_mpls(self): - """ SR MPLS """ + """SR MPLS""" # # A simple MPLS xconnect - neos label in label out # - route_32_eos = VppMplsRoute(self, 32, 0, - [VppRoutePath(self.pg0.remote_ip4, - self.pg0.sw_if_index, - labels=[VppMplsLabel(32)])]) + route_32_eos = VppMplsRoute( + self, + 32, + 0, + [ + VppRoutePath( + self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[VppMplsLabel(32)] + ) + ], + ) route_32_eos.add_vpp_config() # @@ -171,32 +185,38 @@ class TestSRMPLS(VppTestCase): # # A labeled IP route that resolves thru the binding SID # - ip_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_via_label=999, - labels=[VppMplsLabel(55)])]) + ip_10_0_0_1 = VppIpRoute( + self, + "10.0.0.1", + 32, + [ + VppRoutePath( + "0.0.0.0", 0xFFFFFFFF, nh_via_label=999, labels=[VppMplsLabel(55)] + ) + ], + ) ip_10_0_0_1.add_vpp_config() tx = self.create_stream_ip4(self.pg1, "10.0.0.1") rx = self.send_and_expect(self.pg1, tx, self.pg0) - self.verify_capture_labelled_ip4(self.pg0, rx, tx, - [VppMplsLabel(32), - VppMplsLabel(55)]) + self.verify_capture_labelled_ip4( + self.pg0, rx, tx, [VppMplsLabel(32), VppMplsLabel(55)] + ) # # An unlabeled IP route that resolves thru the binding SID # - ip_10_0_0_1 = VppIpRoute(self, "10.0.0.2", 32, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_via_label=999)]) + ip_10_0_0_1 = VppIpRoute( + self, + "10.0.0.2", + 32, + [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_via_label=999)], + ) ip_10_0_0_1.add_vpp_config() tx = self.create_stream_ip4(self.pg1, "10.0.0.2") rx = self.send_and_expect(self.pg1, tx, self.pg0) - self.verify_capture_labelled_ip4(self.pg0, rx, tx, - [VppMplsLabel(32)]) + self.verify_capture_labelled_ip4(self.pg0, rx, tx, [VppMplsLabel(32)]) self.vapi.sr_mpls_policy_del(999) @@ -207,71 +227,89 @@ class TestSRMPLS(VppTestCase): tx = self.create_stream_ip4(self.pg1, "10.0.0.1") rx = self.send_and_expect(self.pg1, tx, self.pg0) - self.verify_capture_labelled_ip4(self.pg0, rx, tx, - [VppMplsLabel(32), - VppMplsLabel(33), - VppMplsLabel(34), - VppMplsLabel(55)]) + self.verify_capture_labelled_ip4( + self.pg0, + rx, + tx, + [VppMplsLabel(32), VppMplsLabel(33), VppMplsLabel(34), VppMplsLabel(55)], + ) tx = self.create_stream_ip4(self.pg1, "10.0.0.2") rx = self.send_and_expect(self.pg1, tx, self.pg0) - self.verify_capture_labelled_ip4(self.pg0, rx, tx, - [VppMplsLabel(32), - VppMplsLabel(33), - VppMplsLabel(34)]) + self.verify_capture_labelled_ip4( + self.pg0, rx, tx, [VppMplsLabel(32), VppMplsLabel(33), VppMplsLabel(34)] + ) # # Resolve an MPLS tunnel via the SID # mpls_tun = VppMPLSTunnelInterface( self, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_via_label=999, - labels=[VppMplsLabel(44), - VppMplsLabel(46)])]) + [ + VppRoutePath( + "0.0.0.0", + 0xFFFFFFFF, + nh_via_label=999, + labels=[VppMplsLabel(44), VppMplsLabel(46)], + ) + ], + ) mpls_tun.add_vpp_config() mpls_tun.admin_up() # # add an unlabelled route through the new tunnel # - route_10_0_0_3 = VppIpRoute(self, "10.0.0.3", 32, - [VppRoutePath("0.0.0.0", - mpls_tun._sw_if_index)]) + route_10_0_0_3 = VppIpRoute( + self, "10.0.0.3", 32, [VppRoutePath("0.0.0.0", mpls_tun._sw_if_index)] + ) route_10_0_0_3.add_vpp_config() self.logger.info(self.vapi.cli("sh mpls tun 0")) self.logger.info(self.vapi.cli("sh adj 21")) tx = self.create_stream_ip4(self.pg1, "10.0.0.3") rx = self.send_and_expect(self.pg1, tx, self.pg0) - self.verify_capture_tunneled_ip4(self.pg0, rx, tx, - [VppMplsLabel(32), - VppMplsLabel(33), - VppMplsLabel(34), - VppMplsLabel(44), - VppMplsLabel(46)]) + self.verify_capture_tunneled_ip4( + self.pg0, + rx, + tx, + [ + VppMplsLabel(32), + VppMplsLabel(33), + VppMplsLabel(34), + VppMplsLabel(44), + VppMplsLabel(46), + ], + ) # # add a labelled route through the new tunnel # - route_10_0_0_3 = VppIpRoute(self, "10.0.0.4", 32, - [VppRoutePath("0.0.0.0", - mpls_tun._sw_if_index, - labels=[VppMplsLabel(55)])]) + route_10_0_0_3 = VppIpRoute( + self, + "10.0.0.4", + 32, + [VppRoutePath("0.0.0.0", mpls_tun._sw_if_index, labels=[VppMplsLabel(55)])], + ) route_10_0_0_3.add_vpp_config() tx = self.create_stream_ip4(self.pg1, "10.0.0.4") rx = self.send_and_expect(self.pg1, tx, self.pg0) - self.verify_capture_tunneled_ip4(self.pg0, rx, tx, - [VppMplsLabel(32), - VppMplsLabel(33), - VppMplsLabel(34), - VppMplsLabel(44), - VppMplsLabel(46), - VppMplsLabel(55)]) + self.verify_capture_tunneled_ip4( + self.pg0, + rx, + tx, + [ + VppMplsLabel(32), + VppMplsLabel(33), + VppMplsLabel(34), + VppMplsLabel(44), + VppMplsLabel(46), + VppMplsLabel(55), + ], + ) self.vapi.sr_mpls_policy_del(999) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_srv6.py b/test/test_srv6.py index ec2fb6d4369..40b53375ddb 100644 --- a/test/test_srv6.py +++ b/test/test_srv6.py @@ -6,8 +6,14 @@ from socket import AF_INET6 from framework import VppTestCase, VppTestRunner from vpp_ip_route import VppIpRoute, VppRoutePath, FibPathProto, VppIpTable -from vpp_srv6 import SRv6LocalSIDBehaviors, VppSRv6LocalSID, VppSRv6Policy, \ - SRv6PolicyType, VppSRv6Steering, SRv6PolicySteeringTypes +from vpp_srv6 import ( + SRv6LocalSIDBehaviors, + VppSRv6LocalSID, + VppSRv6Policy, + SRv6PolicyType, + VppSRv6Steering, + SRv6PolicySteeringTypes, +) import scapy.compat from scapy.packet import Raw @@ -19,7 +25,7 @@ from util import ppp class TestSRv6(VppTestCase): - """ SRv6 Test Case """ + """SRv6 Test Case""" @classmethod def setUpClass(cls): @@ -30,8 +36,7 @@ class TestSRv6(VppTestCase): super(TestSRv6, cls).tearDownClass() def setUp(self): - """ Perform test setup before each test case. - """ + """Perform test setup before each test case.""" super(TestSRv6, self).setUp() # packet sizes, inclusive L2 overhead @@ -41,17 +46,15 @@ class TestSRv6(VppTestCase): self.reset_packet_infos() def tearDown(self): - """ Clean up test setup after each test case. - """ + """Clean up test setup after each test case.""" self.teardown_interfaces() super(TestSRv6, self).tearDown() - def configure_interface(self, - interface, - ipv6=False, ipv4=False, - ipv6_table_id=0, ipv4_table_id=0): - """ Configure interface. + def configure_interface( + self, interface, ipv6=False, ipv4=False, ipv6_table_id=0, ipv4_table_id=0 + ): + """Configure interface. :param ipv6: configure IPv6 on interface :param ipv4: configure IPv4 on interface :param ipv6_table_id: FIB table_id for IPv6 @@ -70,9 +73,8 @@ class TestSRv6(VppTestCase): interface.resolve_arp() interface.admin_up() - def setup_interfaces(self, ipv6=[], ipv4=[], - ipv6_table_id=[], ipv4_table_id=[]): - """ Create and configure interfaces. + def setup_interfaces(self, ipv6=[], ipv4=[], ipv6_table_id=[], ipv4_table_id=[]): + """Create and configure interfaces. :param ipv6: list of interface IPv6 capabilities :param ipv4: list of interface IPv4 capabilities @@ -107,9 +109,9 @@ class TestSRv6(VppTestCase): # setup all interfaces for i in range(count): intf = self.pg_interfaces[i] - self.configure_interface(intf, - ipv6[i], ipv4[i], - ipv6_table_id[i], ipv4_table_id[i]) + self.configure_interface( + intf, ipv6[i], ipv4[i], ipv6_table_id[i], ipv4_table_id[i] + ) if any(ipv6): self.logger.debug(self.vapi.cli("show ip6 neighbors")) @@ -121,8 +123,7 @@ class TestSRv6(VppTestCase): return self.pg_interfaces def teardown_interfaces(self): - """ Unconfigure and bring down interface. - """ + """Unconfigure and bring down interface.""" self.logger.debug("Tearing down interfaces") # tear down all interfaces # AFAIK they cannot be deleted @@ -135,16 +136,15 @@ class TestSRv6(VppTestCase): @unittest.skipUnless(0, "PC to fix") def test_SRv6_T_Encaps(self): - """ Test SRv6 Transit.Encaps behavior for IPv6. - """ + """Test SRv6 Transit.Encaps behavior for IPv6.""" # send traffic to one destination interface # source and destination are IPv6 only self.setup_interfaces(ipv6=[True, True]) # configure FIB entries - route = VppIpRoute(self, "a4::", 64, - [VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index)]) + route = VppIpRoute( + self, "a4::", 64, [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)] + ) route.add_vpp_config() # configure encaps IPv6 source address @@ -152,16 +152,19 @@ class TestSRv6(VppTestCase): # TODO: API? self.vapi.cli("set sr encaps source addr a3::") - bsid = 'a3::9999:1' + bsid = "a3::9999:1" # configure SRv6 Policy # Note: segment list order: first -> last sr_policy = VppSRv6Policy( - self, bsid=bsid, + self, + bsid=bsid, is_encap=1, sr_type=SRv6PolicyType.SR_POLICY_TYPE_DEFAULT, - weight=1, fib_table=0, - segments=['a4::', 'a5::', 'a6::c7'], - source='a3::') + weight=1, + fib_table=0, + segments=["a4::", "a5::", "a6::c7"], + source="a3::", + ) sr_policy.add_vpp_config() self.sr_policy = sr_policy @@ -171,12 +174,15 @@ class TestSRv6(VppTestCase): # steer IPv6 traffic to a7::/64 into SRv6 Policy # use the bsid of the above self.sr_policy pol_steering = VppSRv6Steering( - self, - bsid=self.sr_policy.bsid, - prefix="a7::", mask_width=64, - traffic_type=SRv6PolicySteeringTypes.SR_STEER_IPV6, - sr_policy_index=0, table_id=0, - sw_if_index=0) + self, + bsid=self.sr_policy.bsid, + prefix="a7::", + mask_width=64, + traffic_type=SRv6PolicySteeringTypes.SR_STEER_IPV6, + sr_policy_index=0, + table_id=0, + sw_if_index=0, + ) pol_steering.add_vpp_config() # log the sr steering policies @@ -184,37 +190,46 @@ class TestSRv6(VppTestCase): # create packets count = len(self.pg_packet_sizes) - dst_inner = 'a7::1234' + dst_inner = "a7::1234" pkts = [] # create IPv6 packets without SRH packet_header = self.create_packet_header_IPv6(dst_inner) # create traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count + ) + ) # create IPv6 packets with SRH # packets with segments-left 1, active segment a7:: packet_header = self.create_packet_header_IPv6_SRH( - sidlist=['a8::', 'a7::', 'a6::'], - segleft=1) + sidlist=["a8::", "a7::", "a6::"], segleft=1 + ) # create traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count + ) + ) # create IPv6 packets with SRH and IPv6 # packets with segments-left 1, active segment a7:: packet_header = self.create_packet_header_IPv6_SRH_IPv6( - dst_inner, - sidlist=['a8::', 'a7::', 'a6::'], - segleft=1) + dst_inner, sidlist=["a8::", "a7::", "a6::"], segleft=1 + ) # create traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count + ) + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg0, pkts, self.pg1, - self.compare_rx_tx_packet_T_Encaps) + self.send_and_verify_pkts( + self.pg0, pkts, self.pg1, self.compare_rx_tx_packet_T_Encaps + ) # log the localsid counters self.logger.info(self.vapi.cli("show sr localsid")) @@ -235,16 +250,15 @@ class TestSRv6(VppTestCase): @unittest.skipUnless(0, "PC to fix") def test_SRv6_T_Insert(self): - """ Test SRv6 Transit.Insert behavior (IPv6 only). - """ + """Test SRv6 Transit.Insert behavior (IPv6 only).""" # send traffic to one destination interface # source and destination are IPv6 only self.setup_interfaces(ipv6=[True, True]) # configure FIB entries - route = VppIpRoute(self, "a4::", 64, - [VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index)]) + route = VppIpRoute( + self, "a4::", 64, [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)] + ) route.add_vpp_config() # configure encaps IPv6 source address @@ -252,16 +266,19 @@ class TestSRv6(VppTestCase): # TODO: API? self.vapi.cli("set sr encaps source addr a3::") - bsid = 'a3::9999:1' + bsid = "a3::9999:1" # configure SRv6 Policy # Note: segment list order: first -> last sr_policy = VppSRv6Policy( - self, bsid=bsid, + self, + bsid=bsid, is_encap=0, sr_type=SRv6PolicyType.SR_POLICY_TYPE_DEFAULT, - weight=1, fib_table=0, - segments=['a4::', 'a5::', 'a6::c7'], - source='a3::') + weight=1, + fib_table=0, + segments=["a4::", "a5::", "a6::c7"], + source="a3::", + ) sr_policy.add_vpp_config() self.sr_policy = sr_policy @@ -271,12 +288,15 @@ class TestSRv6(VppTestCase): # steer IPv6 traffic to a7::/64 into SRv6 Policy # use the bsid of the above self.sr_policy pol_steering = VppSRv6Steering( - self, - bsid=self.sr_policy.bsid, - prefix="a7::", mask_width=64, - traffic_type=SRv6PolicySteeringTypes.SR_STEER_IPV6, - sr_policy_index=0, table_id=0, - sw_if_index=0) + self, + bsid=self.sr_policy.bsid, + prefix="a7::", + mask_width=64, + traffic_type=SRv6PolicySteeringTypes.SR_STEER_IPV6, + sr_policy_index=0, + table_id=0, + sw_if_index=0, + ) pol_steering.add_vpp_config() # log the sr steering policies @@ -284,27 +304,34 @@ class TestSRv6(VppTestCase): # create packets count = len(self.pg_packet_sizes) - dst_inner = 'a7::1234' + dst_inner = "a7::1234" pkts = [] # create IPv6 packets without SRH packet_header = self.create_packet_header_IPv6(dst_inner) # create traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count + ) + ) # create IPv6 packets with SRH # packets with segments-left 1, active segment a7:: packet_header = self.create_packet_header_IPv6_SRH( - sidlist=['a8::', 'a7::', 'a6::'], - segleft=1) + sidlist=["a8::", "a7::", "a6::"], segleft=1 + ) # create traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count + ) + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg0, pkts, self.pg1, - self.compare_rx_tx_packet_T_Insert) + self.send_and_verify_pkts( + self.pg0, pkts, self.pg1, self.compare_rx_tx_packet_T_Insert + ) # log the localsid counters self.logger.info(self.vapi.cli("show sr localsid")) @@ -325,17 +352,16 @@ class TestSRv6(VppTestCase): @unittest.skipUnless(0, "PC to fix") def test_SRv6_T_Encaps_IPv4(self): - """ Test SRv6 Transit.Encaps behavior for IPv4. - """ + """Test SRv6 Transit.Encaps behavior for IPv4.""" # send traffic to one destination interface # source interface is IPv4 only # destination interface is IPv6 only self.setup_interfaces(ipv6=[False, True], ipv4=[True, False]) # configure FIB entries - route = VppIpRoute(self, "a4::", 64, - [VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index)]) + route = VppIpRoute( + self, "a4::", 64, [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)] + ) route.add_vpp_config() # configure encaps IPv6 source address @@ -343,16 +369,19 @@ class TestSRv6(VppTestCase): # TODO: API? self.vapi.cli("set sr encaps source addr a3::") - bsid = 'a3::9999:1' + bsid = "a3::9999:1" # configure SRv6 Policy # Note: segment list order: first -> last sr_policy = VppSRv6Policy( - self, bsid=bsid, + self, + bsid=bsid, is_encap=1, sr_type=SRv6PolicyType.SR_POLICY_TYPE_DEFAULT, - weight=1, fib_table=0, - segments=['a4::', 'a5::', 'a6::c7'], - source='a3::') + weight=1, + fib_table=0, + segments=["a4::", "a5::", "a6::c7"], + source="a3::", + ) sr_policy.add_vpp_config() self.sr_policy = sr_policy @@ -362,12 +391,15 @@ class TestSRv6(VppTestCase): # steer IPv4 traffic to 7.1.1.0/24 into SRv6 Policy # use the bsid of the above self.sr_policy pol_steering = VppSRv6Steering( - self, - bsid=self.sr_policy.bsid, - prefix="7.1.1.0", mask_width=24, - traffic_type=SRv6PolicySteeringTypes.SR_STEER_IPV4, - sr_policy_index=0, table_id=0, - sw_if_index=0) + self, + bsid=self.sr_policy.bsid, + prefix="7.1.1.0", + mask_width=24, + traffic_type=SRv6PolicySteeringTypes.SR_STEER_IPV4, + sr_policy_index=0, + table_id=0, + sw_if_index=0, + ) pol_steering.add_vpp_config() # log the sr steering policies @@ -375,18 +407,22 @@ class TestSRv6(VppTestCase): # create packets count = len(self.pg_packet_sizes) - dst_inner = '7.1.1.123' + dst_inner = "7.1.1.123" pkts = [] # create IPv4 packets packet_header = self.create_packet_header_IPv4(dst_inner) # create traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count + ) + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg0, pkts, self.pg1, - self.compare_rx_tx_packet_T_Encaps_IPv4) + self.send_and_verify_pkts( + self.pg0, pkts, self.pg1, self.compare_rx_tx_packet_T_Encaps_IPv4 + ) # log the localsid counters self.logger.info(self.vapi.cli("show sr localsid")) @@ -407,17 +443,16 @@ class TestSRv6(VppTestCase): @unittest.skip("VPP crashes after running this test") def test_SRv6_T_Encaps_L2(self): - """ Test SRv6 Transit.Encaps behavior for L2. - """ + """Test SRv6 Transit.Encaps behavior for L2.""" # send traffic to one destination interface # source interface is IPv4 only TODO? # destination interface is IPv6 only self.setup_interfaces(ipv6=[False, True], ipv4=[False, False]) # configure FIB entries - route = VppIpRoute(self, "a4::", 64, - [VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index)]) + route = VppIpRoute( + self, "a4::", 64, [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)] + ) route.add_vpp_config() # configure encaps IPv6 source address @@ -425,16 +460,19 @@ class TestSRv6(VppTestCase): # TODO: API? self.vapi.cli("set sr encaps source addr a3::") - bsid = 'a3::9999:1' + bsid = "a3::9999:1" # configure SRv6 Policy # Note: segment list order: first -> last sr_policy = VppSRv6Policy( - self, bsid=bsid, + self, + bsid=bsid, is_encap=1, sr_type=SRv6PolicyType.SR_POLICY_TYPE_DEFAULT, - weight=1, fib_table=0, - segments=['a4::', 'a5::', 'a6::c7'], - source='a3::') + weight=1, + fib_table=0, + segments=["a4::", "a5::", "a6::c7"], + source="a3::", + ) sr_policy.add_vpp_config() self.sr_policy = sr_policy @@ -444,12 +482,15 @@ class TestSRv6(VppTestCase): # steer L2 traffic into SRv6 Policy # use the bsid of the above self.sr_policy pol_steering = VppSRv6Steering( - self, - bsid=self.sr_policy.bsid, - prefix="::", mask_width=0, - traffic_type=SRv6PolicySteeringTypes.SR_STEER_L2, - sr_policy_index=0, table_id=0, - sw_if_index=self.pg0.sw_if_index) + self, + bsid=self.sr_policy.bsid, + prefix="::", + mask_width=0, + traffic_type=SRv6PolicySteeringTypes.SR_STEER_L2, + sr_policy_index=0, + table_id=0, + sw_if_index=self.pg0.sw_if_index, + ) pol_steering.add_vpp_config() # log the sr steering policies @@ -462,18 +503,25 @@ class TestSRv6(VppTestCase): # create L2 packets without dot1q header packet_header = self.create_packet_header_L2() # create traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count + ) + ) # create L2 packets with dot1q header packet_header = self.create_packet_header_L2(vlan=123) # create traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count + ) + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg0, pkts, self.pg1, - self.compare_rx_tx_packet_T_Encaps_L2) + self.send_and_verify_pkts( + self.pg0, pkts, self.pg1, self.compare_rx_tx_packet_T_Encaps_L2 + ) # log the localsid counters self.logger.info(self.vapi.cli("show sr localsid")) @@ -493,27 +541,28 @@ class TestSRv6(VppTestCase): self.teardown_interfaces() def test_SRv6_End(self): - """ Test SRv6 End (without PSP) behavior. - """ + """Test SRv6 End (without PSP) behavior.""" # send traffic to one destination interface # source and destination interfaces are IPv6 only self.setup_interfaces(ipv6=[True, True]) # configure FIB entries - route = VppIpRoute(self, "a4::", 64, - [VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index)]) + route = VppIpRoute( + self, "a4::", 64, [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)] + ) route.add_vpp_config() # configure SRv6 localSID End without PSP behavior localsid = VppSRv6LocalSID( - self, localsid='A3::0', - behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_END, - nh_addr=0, - end_psp=0, - sw_if_index=0, - vlan_index=0, - fib_table=0) + self, + localsid="A3::0", + behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_END, + nh_addr=0, + end_psp=0, + sw_if_index=0, + vlan_index=0, + fib_table=0, + ) localsid.add_vpp_config() # log the localsids self.logger.debug(self.vapi.cli("show sr localsid")) @@ -522,41 +571,52 @@ class TestSRv6(VppTestCase): # send one packet per SL value per packet size # SL=0 packet with localSID End with USP needs 2nd SRH count = len(self.pg_packet_sizes) - dst_inner = 'a4::1234' + dst_inner = "a4::1234" pkts = [] # packets with segments-left 2, active segment a3:: packet_header = self.create_packet_header_IPv6_SRH_IPv6( - dst_inner, - sidlist=['a5::', 'a4::', 'a3::'], - segleft=2) + dst_inner, sidlist=["a5::", "a4::", "a3::"], segleft=2 + ) # create traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count + ) + ) # packets with segments-left 1, active segment a3:: packet_header = self.create_packet_header_IPv6_SRH_IPv6( - dst_inner, - sidlist=['a4::', 'a3::', 'a2::'], - segleft=1) + dst_inner, sidlist=["a4::", "a3::", "a2::"], segleft=1 + ) # add to traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count + ) + ) # TODO: test behavior with SL=0 packet (needs 2*SRH?) expected_count = len(pkts) # packets without SRH (should not crash) - packet_header = self.create_packet_header_IPv6('a3::') + packet_header = self.create_packet_header_IPv6("a3::") # create traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count + ) + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg0, pkts, self.pg1, - self.compare_rx_tx_packet_End, - expected_count=expected_count) + self.send_and_verify_pkts( + self.pg0, + pkts, + self.pg1, + self.compare_rx_tx_packet_End, + expected_count=expected_count, + ) # log the localsid counters self.logger.info(self.vapi.cli("show sr localsid")) @@ -571,27 +631,28 @@ class TestSRv6(VppTestCase): self.teardown_interfaces() def test_SRv6_End_with_PSP(self): - """ Test SRv6 End with PSP behavior. - """ + """Test SRv6 End with PSP behavior.""" # send traffic to one destination interface # source and destination interfaces are IPv6 only self.setup_interfaces(ipv6=[True, True]) # configure FIB entries - route = VppIpRoute(self, "a4::", 64, - [VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index)]) + route = VppIpRoute( + self, "a4::", 64, [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)] + ) route.add_vpp_config() # configure SRv6 localSID End with PSP behavior localsid = VppSRv6LocalSID( - self, localsid='A3::0', - behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_END, - nh_addr=0, - end_psp=1, - sw_if_index=0, - vlan_index=0, - fib_table=0) + self, + localsid="A3::0", + behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_END, + nh_addr=0, + end_psp=1, + sw_if_index=0, + vlan_index=0, + fib_table=0, + ) localsid.add_vpp_config() # log the localsids self.logger.debug(self.vapi.cli("show sr localsid")) @@ -600,30 +661,35 @@ class TestSRv6(VppTestCase): # send one packet per SL value per packet size # SL=0 packet with localSID End with PSP is dropped count = len(self.pg_packet_sizes) - dst_inner = 'a4::1234' + dst_inner = "a4::1234" pkts = [] # packets with segments-left 2, active segment a3:: packet_header = self.create_packet_header_IPv6_SRH_IPv6( - dst_inner, - sidlist=['a5::', 'a4::', 'a3::'], - segleft=2) + dst_inner, sidlist=["a5::", "a4::", "a3::"], segleft=2 + ) # create traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count + ) + ) # packets with segments-left 1, active segment a3:: packet_header = self.create_packet_header_IPv6_SRH_IPv6( - dst_inner, - sidlist=['a4::', 'a3::', 'a2::'], - segleft=1) + dst_inner, sidlist=["a4::", "a3::", "a2::"], segleft=1 + ) # add to traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count + ) + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg0, pkts, self.pg1, - self.compare_rx_tx_packet_End_PSP) + self.send_and_verify_pkts( + self.pg0, pkts, self.pg1, self.compare_rx_tx_packet_End_PSP + ) # log the localsid counters self.logger.info(self.vapi.cli("show sr localsid")) @@ -638,32 +704,37 @@ class TestSRv6(VppTestCase): self.teardown_interfaces() def test_SRv6_End_X(self): - """ Test SRv6 End.X (without PSP) behavior. - """ + """Test SRv6 End.X (without PSP) behavior.""" # create three interfaces (1 source, 2 destinations) # source and destination interfaces are IPv6 only self.setup_interfaces(ipv6=[True, True, True]) # configure FIB entries # a4::/64 via pg1 and pg2 - route = VppIpRoute(self, "a4::", 64, - [VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index), - VppRoutePath(self.pg2.remote_ip6, - self.pg2.sw_if_index)]) + route = VppIpRoute( + self, + "a4::", + 64, + [ + VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index), + VppRoutePath(self.pg2.remote_ip6, self.pg2.sw_if_index), + ], + ) route.add_vpp_config() self.logger.debug(self.vapi.cli("show ip6 fib")) # configure SRv6 localSID End.X without PSP behavior # End.X points to interface pg1 localsid = VppSRv6LocalSID( - self, localsid='A3::C4', - behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_X, - nh_addr=self.pg1.remote_ip6, - end_psp=0, - sw_if_index=self.pg1.sw_if_index, - vlan_index=0, - fib_table=0) + self, + localsid="A3::C4", + behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_X, + nh_addr=self.pg1.remote_ip6, + end_psp=0, + sw_if_index=self.pg1.sw_if_index, + vlan_index=0, + fib_table=0, + ) localsid.add_vpp_config() # log the localsids self.logger.debug(self.vapi.cli("show sr localsid")) @@ -672,31 +743,36 @@ class TestSRv6(VppTestCase): # send one packet per SL value per packet size # SL=0 packet with localSID End with PSP is dropped count = len(self.pg_packet_sizes) - dst_inner = 'a4::1234' + dst_inner = "a4::1234" pkts = [] # packets with segments-left 2, active segment a3::c4 packet_header = self.create_packet_header_IPv6_SRH_IPv6( - dst_inner, - sidlist=['a5::', 'a4::', 'a3::c4'], - segleft=2) + dst_inner, sidlist=["a5::", "a4::", "a3::c4"], segleft=2 + ) # create traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count + ) + ) # packets with segments-left 1, active segment a3::c4 packet_header = self.create_packet_header_IPv6_SRH_IPv6( - dst_inner, - sidlist=['a4::', 'a3::c4', 'a2::'], - segleft=1) + dst_inner, sidlist=["a4::", "a3::c4", "a2::"], segleft=1 + ) # add to traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count + ) + ) # send packets and verify received packets # using same comparison function as End (no PSP) - self.send_and_verify_pkts(self.pg0, pkts, self.pg1, - self.compare_rx_tx_packet_End) + self.send_and_verify_pkts( + self.pg0, pkts, self.pg1, self.compare_rx_tx_packet_End + ) # assert nothing was received on the other interface (pg2) self.pg2.assert_nothing_captured(remark="mis-directed packet(s)") @@ -714,31 +790,35 @@ class TestSRv6(VppTestCase): self.teardown_interfaces() def test_SRv6_End_X_with_PSP(self): - """ Test SRv6 End.X with PSP behavior. - """ + """Test SRv6 End.X with PSP behavior.""" # create three interfaces (1 source, 2 destinations) # source and destination interfaces are IPv6 only self.setup_interfaces(ipv6=[True, True, True]) # configure FIB entries # a4::/64 via pg1 and pg2 - route = VppIpRoute(self, "a4::", 64, - [VppRoutePath( - self.pg1.remote_ip6, - self.pg1.sw_if_index), - VppRoutePath(self.pg2.remote_ip6, - self.pg2.sw_if_index)]) + route = VppIpRoute( + self, + "a4::", + 64, + [ + VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index), + VppRoutePath(self.pg2.remote_ip6, self.pg2.sw_if_index), + ], + ) route.add_vpp_config() # configure SRv6 localSID End with PSP behavior localsid = VppSRv6LocalSID( - self, localsid='A3::C4', - behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_X, - nh_addr=self.pg1.remote_ip6, - end_psp=1, - sw_if_index=self.pg1.sw_if_index, - vlan_index=0, - fib_table=0) + self, + localsid="A3::C4", + behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_X, + nh_addr=self.pg1.remote_ip6, + end_psp=1, + sw_if_index=self.pg1.sw_if_index, + vlan_index=0, + fib_table=0, + ) localsid.add_vpp_config() # log the localsids self.logger.debug(self.vapi.cli("show sr localsid")) @@ -747,31 +827,36 @@ class TestSRv6(VppTestCase): # send one packet per SL value per packet size # SL=0 packet with localSID End with PSP is dropped count = len(self.pg_packet_sizes) - dst_inner = 'a4::1234' + dst_inner = "a4::1234" pkts = [] # packets with segments-left 2, active segment a3:: packet_header = self.create_packet_header_IPv6_SRH_IPv6( - dst_inner, - sidlist=['a5::', 'a4::', 'a3::c4'], - segleft=2) + dst_inner, sidlist=["a5::", "a4::", "a3::c4"], segleft=2 + ) # create traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count + ) + ) # packets with segments-left 1, active segment a3:: packet_header = self.create_packet_header_IPv6_SRH_IPv6( - dst_inner, - sidlist=['a4::', 'a3::c4', 'a2::'], - segleft=1) + dst_inner, sidlist=["a4::", "a3::c4", "a2::"], segleft=1 + ) # add to traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count + ) + ) # send packets and verify received packets # using same comparison function as End with PSP - self.send_and_verify_pkts(self.pg0, pkts, self.pg1, - self.compare_rx_tx_packet_End_PSP) + self.send_and_verify_pkts( + self.pg0, pkts, self.pg1, self.compare_rx_tx_packet_End_PSP + ) # assert nothing was received on the other interface (pg2) self.pg2.assert_nothing_captured(remark="mis-directed packet(s)") @@ -789,21 +874,22 @@ class TestSRv6(VppTestCase): self.teardown_interfaces() def test_SRv6_End_DX6(self): - """ Test SRv6 End.DX6 behavior. - """ + """Test SRv6 End.DX6 behavior.""" # send traffic to one destination interface # source and destination interfaces are IPv6 only self.setup_interfaces(ipv6=[True, True]) # configure SRv6 localSID End.DX6 behavior localsid = VppSRv6LocalSID( - self, localsid='A3::C4', - behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_DX6, - nh_addr=self.pg1.remote_ip6, - end_psp=0, - sw_if_index=self.pg1.sw_if_index, - vlan_index=0, - fib_table=0) + self, + localsid="A3::C4", + behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_DX6, + nh_addr=self.pg1.remote_ip6, + end_psp=0, + sw_if_index=self.pg1.sw_if_index, + vlan_index=0, + fib_table=0, + ) localsid.add_vpp_config() # log the localsids self.logger.debug(self.vapi.cli("show sr localsid")) @@ -811,30 +897,36 @@ class TestSRv6(VppTestCase): # create IPv6 packets with SRH (SL=0) # send one packet per packet size count = len(self.pg_packet_sizes) - dst_inner = 'a4::1234' # inner header destination address + dst_inner = "a4::1234" # inner header destination address pkts = [] # packets with SRH, segments-left 0, active segment a3::c4 packet_header = self.create_packet_header_IPv6_SRH_IPv6( - dst_inner, - sidlist=['a3::c4', 'a2::', 'a1::'], - segleft=0) + dst_inner, sidlist=["a3::c4", "a2::", "a1::"], segleft=0 + ) # add to traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count + ) + ) # packets without SRH, IPv6 in IPv6 # outer IPv6 dest addr is the localsid End.DX6 packet_header = self.create_packet_header_IPv6_IPv6( - dst_inner, - dst_outer='a3::c4') + dst_inner, dst_outer="a3::c4" + ) # add to traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count + ) + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg0, pkts, self.pg1, - self.compare_rx_tx_packet_End_DX6) + self.send_and_verify_pkts( + self.pg0, pkts, self.pg1, self.compare_rx_tx_packet_End_DX6 + ) # log the localsid counters self.logger.info(self.vapi.cli("show sr localsid")) @@ -846,8 +938,7 @@ class TestSRv6(VppTestCase): self.teardown_interfaces() def test_SRv6_End_DT6(self): - """ Test SRv6 End.DT6 behavior. - """ + """Test SRv6 End.DT6 behavior.""" # create three interfaces (1 source, 2 destinations) # all interfaces are IPv6 only # source interface in global FIB (0) @@ -855,24 +946,31 @@ class TestSRv6(VppTestCase): vrf_1 = 1 ipt = VppIpTable(self, vrf_1, is_ip6=True) ipt.add_vpp_config() - self.setup_interfaces(ipv6=[True, True, True], - ipv6_table_id=[0, 0, vrf_1]) + self.setup_interfaces(ipv6=[True, True, True], ipv6_table_id=[0, 0, vrf_1]) # configure FIB entries # a4::/64 is reachable # via pg1 in table 0 (global) # and via pg2 in table vrf_1 - route0 = VppIpRoute(self, "a4::", 64, - [VppRoutePath(self.pg1.remote_ip6, - self.pg1.sw_if_index, - nh_table_id=0)], - table_id=0) + route0 = VppIpRoute( + self, + "a4::", + 64, + [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index, nh_table_id=0)], + table_id=0, + ) route0.add_vpp_config() - route1 = VppIpRoute(self, "a4::", 64, - [VppRoutePath(self.pg2.remote_ip6, - self.pg2.sw_if_index, - nh_table_id=vrf_1)], - table_id=vrf_1) + route1 = VppIpRoute( + self, + "a4::", + 64, + [ + VppRoutePath( + self.pg2.remote_ip6, self.pg2.sw_if_index, nh_table_id=vrf_1 + ) + ], + table_id=vrf_1, + ) route1.add_vpp_config() self.logger.debug(self.vapi.cli("show ip6 fib")) @@ -881,13 +979,15 @@ class TestSRv6(VppTestCase): # fib_table: where the localsid is installed # sw_if_index: in T-variants of localsid this is the vrf table_id localsid = VppSRv6LocalSID( - self, localsid='A3::C4', - behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_DT6, - nh_addr=0, - end_psp=0, - sw_if_index=vrf_1, - vlan_index=0, - fib_table=0) + self, + localsid="A3::C4", + behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_DT6, + nh_addr=0, + end_psp=0, + sw_if_index=vrf_1, + vlan_index=0, + fib_table=0, + ) localsid.add_vpp_config() # log the localsids self.logger.debug(self.vapi.cli("show sr localsid")) @@ -895,31 +995,37 @@ class TestSRv6(VppTestCase): # create IPv6 packets with SRH (SL=0) # send one packet per packet size count = len(self.pg_packet_sizes) - dst_inner = 'a4::1234' # inner header destination address + dst_inner = "a4::1234" # inner header destination address pkts = [] # packets with SRH, segments-left 0, active segment a3::c4 packet_header = self.create_packet_header_IPv6_SRH_IPv6( - dst_inner, - sidlist=['a3::c4', 'a2::', 'a1::'], - segleft=0) + dst_inner, sidlist=["a3::c4", "a2::", "a1::"], segleft=0 + ) # add to traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg2, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg2, packet_header, self.pg_packet_sizes, count + ) + ) # packets without SRH, IPv6 in IPv6 # outer IPv6 dest addr is the localsid End.DT6 packet_header = self.create_packet_header_IPv6_IPv6( - dst_inner, - dst_outer='a3::c4') + dst_inner, dst_outer="a3::c4" + ) # add to traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg2, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg2, packet_header, self.pg_packet_sizes, count + ) + ) # send packets and verify received packets # using same comparison function as End.DX6 - self.send_and_verify_pkts(self.pg0, pkts, self.pg2, - self.compare_rx_tx_packet_End_DX6) + self.send_and_verify_pkts( + self.pg0, pkts, self.pg2, self.compare_rx_tx_packet_End_DX6 + ) # assert nothing was received on the other interface (pg2) self.pg1.assert_nothing_captured(remark="mis-directed packet(s)") @@ -937,8 +1043,7 @@ class TestSRv6(VppTestCase): self.teardown_interfaces() def test_SRv6_End_DX4(self): - """ Test SRv6 End.DX4 behavior. - """ + """Test SRv6 End.DX4 behavior.""" # send traffic to one destination interface # source interface is IPv6 only # destination interface is IPv4 only @@ -946,43 +1051,51 @@ class TestSRv6(VppTestCase): # configure SRv6 localSID End.DX4 behavior localsid = VppSRv6LocalSID( - self, localsid='A3::C4', - behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_DX4, - nh_addr=self.pg1.remote_ip4, - end_psp=0, - sw_if_index=self.pg1.sw_if_index, - vlan_index=0, - fib_table=0) + self, + localsid="A3::C4", + behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_DX4, + nh_addr=self.pg1.remote_ip4, + end_psp=0, + sw_if_index=self.pg1.sw_if_index, + vlan_index=0, + fib_table=0, + ) localsid.add_vpp_config() # log the localsids self.logger.debug(self.vapi.cli("show sr localsid")) # send one packet per packet size count = len(self.pg_packet_sizes) - dst_inner = '4.1.1.123' # inner header destination address + dst_inner = "4.1.1.123" # inner header destination address pkts = [] # packets with SRH, segments-left 0, active segment a3::c4 packet_header = self.create_packet_header_IPv6_SRH_IPv4( - dst_inner, - sidlist=['a3::c4', 'a2::', 'a1::'], - segleft=0) + dst_inner, sidlist=["a3::c4", "a2::", "a1::"], segleft=0 + ) # add to traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count + ) + ) # packets without SRH, IPv4 in IPv6 # outer IPv6 dest addr is the localsid End.DX4 packet_header = self.create_packet_header_IPv6_IPv4( - dst_inner, - dst_outer='a3::c4') + dst_inner, dst_outer="a3::c4" + ) # add to traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count + ) + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg0, pkts, self.pg1, - self.compare_rx_tx_packet_End_DX4) + self.send_and_verify_pkts( + self.pg0, pkts, self.pg1, self.compare_rx_tx_packet_End_DX4 + ) # log the localsid counters self.logger.info(self.vapi.cli("show sr localsid")) @@ -994,8 +1107,7 @@ class TestSRv6(VppTestCase): self.teardown_interfaces() def test_SRv6_End_DT4(self): - """ Test SRv6 End.DT4 behavior. - """ + """Test SRv6 End.DT4 behavior.""" # create three interfaces (1 source, 2 destinations) # source interface is IPv6-only # destination interfaces are IPv4 only @@ -1004,26 +1116,36 @@ class TestSRv6(VppTestCase): vrf_1 = 1 ipt = VppIpTable(self, vrf_1) ipt.add_vpp_config() - self.setup_interfaces(ipv6=[True, False, False], - ipv4=[False, True, True], - ipv6_table_id=[0, 0, 0], - ipv4_table_id=[0, 0, vrf_1]) + self.setup_interfaces( + ipv6=[True, False, False], + ipv4=[False, True, True], + ipv6_table_id=[0, 0, 0], + ipv4_table_id=[0, 0, vrf_1], + ) # configure FIB entries # 4.1.1.0/24 is reachable # via pg1 in table 0 (global) # and via pg2 in table vrf_1 - route0 = VppIpRoute(self, "4.1.1.0", 24, - [VppRoutePath(self.pg1.remote_ip4, - self.pg1.sw_if_index, - nh_table_id=0)], - table_id=0) + route0 = VppIpRoute( + self, + "4.1.1.0", + 24, + [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index, nh_table_id=0)], + table_id=0, + ) route0.add_vpp_config() - route1 = VppIpRoute(self, "4.1.1.0", 24, - [VppRoutePath(self.pg2.remote_ip4, - self.pg2.sw_if_index, - nh_table_id=vrf_1)], - table_id=vrf_1) + route1 = VppIpRoute( + self, + "4.1.1.0", + 24, + [ + VppRoutePath( + self.pg2.remote_ip4, self.pg2.sw_if_index, nh_table_id=vrf_1 + ) + ], + table_id=vrf_1, + ) route1.add_vpp_config() self.logger.debug(self.vapi.cli("show ip fib")) @@ -1032,13 +1154,15 @@ class TestSRv6(VppTestCase): # fib_table: where the localsid is installed # sw_if_index: in T-variants of localsid: vrf table_id localsid = VppSRv6LocalSID( - self, localsid='A3::C4', - behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_DT4, - nh_addr=0, - end_psp=0, - sw_if_index=vrf_1, - vlan_index=0, - fib_table=0) + self, + localsid="A3::C4", + behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_DT4, + nh_addr=0, + end_psp=0, + sw_if_index=vrf_1, + vlan_index=0, + fib_table=0, + ) localsid.add_vpp_config() # log the localsids self.logger.debug(self.vapi.cli("show sr localsid")) @@ -1046,31 +1170,37 @@ class TestSRv6(VppTestCase): # create IPv6 packets with SRH (SL=0) # send one packet per packet size count = len(self.pg_packet_sizes) - dst_inner = '4.1.1.123' # inner header destination address + dst_inner = "4.1.1.123" # inner header destination address pkts = [] # packets with SRH, segments-left 0, active segment a3::c4 packet_header = self.create_packet_header_IPv6_SRH_IPv4( - dst_inner, - sidlist=['a3::c4', 'a2::', 'a1::'], - segleft=0) + dst_inner, sidlist=["a3::c4", "a2::", "a1::"], segleft=0 + ) # add to traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg2, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg2, packet_header, self.pg_packet_sizes, count + ) + ) # packets without SRH, IPv6 in IPv6 # outer IPv6 dest addr is the localsid End.DX4 packet_header = self.create_packet_header_IPv6_IPv4( - dst_inner, - dst_outer='a3::c4') + dst_inner, dst_outer="a3::c4" + ) # add to traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg2, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg2, packet_header, self.pg_packet_sizes, count + ) + ) # send packets and verify received packets # using same comparison function as End.DX4 - self.send_and_verify_pkts(self.pg0, pkts, self.pg2, - self.compare_rx_tx_packet_End_DX4) + self.send_and_verify_pkts( + self.pg0, pkts, self.pg2, self.compare_rx_tx_packet_End_DX4 + ) # assert nothing was received on the other interface (pg2) self.pg1.assert_nothing_captured(remark="mis-directed packet(s)") @@ -1088,21 +1218,22 @@ class TestSRv6(VppTestCase): self.teardown_interfaces() def test_SRv6_End_DX2(self): - """ Test SRv6 End.DX2 behavior. - """ + """Test SRv6 End.DX2 behavior.""" # send traffic to one destination interface # source interface is IPv6 only self.setup_interfaces(ipv6=[True, False], ipv4=[False, False]) # configure SRv6 localSID End.DX2 behavior localsid = VppSRv6LocalSID( - self, localsid='A3::C4', - behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_DX2, - nh_addr=0, - end_psp=0, - sw_if_index=self.pg1.sw_if_index, - vlan_index=0, - fib_table=0) + self, + localsid="A3::C4", + behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_DX2, + nh_addr=0, + end_psp=0, + sw_if_index=self.pg1.sw_if_index, + vlan_index=0, + fib_table=0, + ) localsid.add_vpp_config() # log the localsids self.logger.debug(self.vapi.cli("show sr localsid")) @@ -1114,46 +1245,53 @@ class TestSRv6(VppTestCase): # packets with SRH, segments-left 0, active segment a3::c4 # L2 has no dot1q header packet_header = self.create_packet_header_IPv6_SRH_L2( - sidlist=['a3::c4', 'a2::', 'a1::'], - segleft=0, - vlan=0) + sidlist=["a3::c4", "a2::", "a1::"], segleft=0, vlan=0 + ) # add to traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count + ) + ) # packets with SRH, segments-left 0, active segment a3::c4 # L2 has dot1q header packet_header = self.create_packet_header_IPv6_SRH_L2( - sidlist=['a3::c4', 'a2::', 'a1::'], - segleft=0, - vlan=123) + sidlist=["a3::c4", "a2::", "a1::"], segleft=0, vlan=123 + ) # add to traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count + ) + ) # packets without SRH, L2 in IPv6 # outer IPv6 dest addr is the localsid End.DX2 # L2 has no dot1q header - packet_header = self.create_packet_header_IPv6_L2( - dst_outer='a3::c4', - vlan=0) + packet_header = self.create_packet_header_IPv6_L2(dst_outer="a3::c4", vlan=0) # add to traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count + ) + ) # packets without SRH, L2 in IPv6 # outer IPv6 dest addr is the localsid End.DX2 # L2 has dot1q header - packet_header = self.create_packet_header_IPv6_L2( - dst_outer='a3::c4', - vlan=123) + packet_header = self.create_packet_header_IPv6_L2(dst_outer="a3::c4", vlan=123) # add to traffic stream pg0->pg1 - pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count + ) + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg0, pkts, self.pg1, - self.compare_rx_tx_packet_End_DX2) + self.send_and_verify_pkts( + self.pg0, pkts, self.pg1, self.compare_rx_tx_packet_End_DX2 + ) # log the localsid counters self.logger.info(self.vapi.cli("show sr localsid")) @@ -1166,18 +1304,17 @@ class TestSRv6(VppTestCase): @unittest.skipUnless(0, "PC to fix") def test_SRv6_T_Insert_Classifier(self): - """ Test SRv6 Transit.Insert behavior (IPv6 only). - steer packets using the classifier + """Test SRv6 Transit.Insert behavior (IPv6 only). + steer packets using the classifier """ # send traffic to one destination interface # source and destination are IPv6 only self.setup_interfaces(ipv6=[False, False, False, True, True]) # configure FIB entries - route = VppIpRoute(self, "a4::", 64, - [VppRoutePath( - self.pg4.remote_ip6, - self.pg4.sw_if_index)]) + route = VppIpRoute( + self, "a4::", 64, [VppRoutePath(self.pg4.remote_ip6, self.pg4.sw_if_index)] + ) route.add_vpp_config() # configure encaps IPv6 source address @@ -1185,16 +1322,19 @@ class TestSRv6(VppTestCase): # TODO: API? self.vapi.cli("set sr encaps source addr a3::") - bsid = 'a3::9999:1' + bsid = "a3::9999:1" # configure SRv6 Policy # Note: segment list order: first -> last sr_policy = VppSRv6Policy( - self, bsid=bsid, + self, + bsid=bsid, is_encap=0, sr_type=SRv6PolicyType.SR_POLICY_TYPE_DEFAULT, - weight=1, fib_table=0, - segments=['a4::', 'a5::', 'a6::c7'], - source='a3::') + weight=1, + fib_table=0, + segments=["a4::", "a5::", "a6::c7"], + source="a3::", + ) sr_policy.add_vpp_config() self.sr_policy = sr_policy @@ -1203,75 +1343,79 @@ class TestSRv6(VppTestCase): # add classify table # mask on dst ip address prefix a7::/8 - mask = '{!s:0<16}'.format('ff') + mask = "{!s:0<16}".format("ff") r = self.vapi.classify_add_del_table( 1, binascii.unhexlify(mask), match_n_vectors=(len(mask) - 1) // 32 + 1, current_data_flag=1, - skip_n_vectors=2) # data offset - self.assertIsNotNone(r, 'No response msg for add_del_table') + skip_n_vectors=2, + ) # data offset + self.assertIsNotNone(r, "No response msg for add_del_table") table_index = r.new_table_index # add the source routing node as a ip6 inacl netxt node - r = self.vapi.add_node_next('ip6-inacl', - 'sr-pl-rewrite-insert') + r = self.vapi.add_node_next("ip6-inacl", "sr-pl-rewrite-insert") inacl_next_node_index = r.node_index - match = '{!s:0<16}'.format('a7') + match = "{!s:0<16}".format("a7") r = self.vapi.classify_add_del_session( 1, table_index, binascii.unhexlify(match), hit_next_index=inacl_next_node_index, action=3, - metadata=0) # sr policy index - self.assertIsNotNone(r, 'No response msg for add_del_session') + metadata=0, + ) # sr policy index + self.assertIsNotNone(r, "No response msg for add_del_session") # log the classify table used in the steering policy self.logger.info(self.vapi.cli("show classify table")) r = self.vapi.input_acl_set_interface( - is_add=1, - sw_if_index=self.pg3.sw_if_index, - ip6_table_index=table_index) - self.assertIsNotNone(r, - 'No response msg for input_acl_set_interface') + is_add=1, sw_if_index=self.pg3.sw_if_index, ip6_table_index=table_index + ) + self.assertIsNotNone(r, "No response msg for input_acl_set_interface") # log the ip6 inacl self.logger.info(self.vapi.cli("show inacl type ip6")) # create packets count = len(self.pg_packet_sizes) - dst_inner = 'a7::1234' + dst_inner = "a7::1234" pkts = [] # create IPv6 packets without SRH packet_header = self.create_packet_header_IPv6(dst_inner) # create traffic stream pg3->pg4 - pkts.extend(self.create_stream(self.pg3, self.pg4, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg3, self.pg4, packet_header, self.pg_packet_sizes, count + ) + ) # create IPv6 packets with SRH # packets with segments-left 1, active segment a7:: packet_header = self.create_packet_header_IPv6_SRH( - sidlist=['a8::', 'a7::', 'a6::'], - segleft=1) + sidlist=["a8::", "a7::", "a6::"], segleft=1 + ) # create traffic stream pg3->pg4 - pkts.extend(self.create_stream(self.pg3, self.pg4, packet_header, - self.pg_packet_sizes, count)) + pkts.extend( + self.create_stream( + self.pg3, self.pg4, packet_header, self.pg_packet_sizes, count + ) + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg3, pkts, self.pg4, - self.compare_rx_tx_packet_T_Insert) + self.send_and_verify_pkts( + self.pg3, pkts, self.pg4, self.compare_rx_tx_packet_T_Insert + ) # remove the interface l2 input feature r = self.vapi.input_acl_set_interface( - is_add=0, - sw_if_index=self.pg3.sw_if_index, - ip6_table_index=table_index) - self.assertIsNotNone(r, - 'No response msg for input_acl_set_interface') + is_add=0, sw_if_index=self.pg3.sw_if_index, ip6_table_index=table_index + ) + self.assertIsNotNone(r, "No response msg for input_acl_set_interface") # log the ip6 inacl after cleaning self.logger.info(self.vapi.cli("show inacl type ip6")) @@ -1289,16 +1433,14 @@ class TestSRv6(VppTestCase): # remove classify session and table r = self.vapi.classify_add_del_session( - 0, - table_index, - binascii.unhexlify(match)) - self.assertIsNotNone(r, 'No response msg for add_del_session') + 0, table_index, binascii.unhexlify(match) + ) + self.assertIsNotNone(r, "No response msg for add_del_session") r = self.vapi.classify_add_del_table( - 0, - binascii.unhexlify(mask), - table_index=table_index) - self.assertIsNotNone(r, 'No response msg for add_del_table') + 0, binascii.unhexlify(mask), table_index=table_index + ) + self.assertIsNotNone(r, "No response msg for add_del_table") self.logger.info(self.vapi.cli("show classify table")) @@ -1309,7 +1451,7 @@ class TestSRv6(VppTestCase): self.teardown_interfaces() def compare_rx_tx_packet_T_Encaps(self, tx_pkt, rx_pkt): - """ Compare input and output packet after passing T.Encaps + """Compare input and output packet after passing T.Encaps :param tx_pkt: transmitted packet :param rx_pkt: received packet @@ -1350,7 +1492,7 @@ class TestSRv6(VppTestCase): # rx'ed seglist should be equal to expected seglist self.assertEqual(rx_srh.addresses, tx_seglist) # segleft should be equal to size expected seglist-1 - self.assertEqual(rx_srh.segleft, len(tx_seglist)-1) + self.assertEqual(rx_srh.segleft, len(tx_seglist) - 1) # segleft should be equal to lastentry self.assertEqual(rx_srh.segleft, rx_srh.lastentry) @@ -1364,7 +1506,7 @@ class TestSRv6(VppTestCase): self.logger.debug("packet verification: SUCCESS") def compare_rx_tx_packet_T_Encaps_IPv4(self, tx_pkt, rx_pkt): - """ Compare input and output packet after passing T.Encaps for IPv4 + """Compare input and output packet after passing T.Encaps for IPv4 :param tx_pkt: transmitted packet :param rx_pkt: received packet @@ -1404,7 +1546,7 @@ class TestSRv6(VppTestCase): # rx'ed seglist should be equal to seglist self.assertEqual(rx_srh.addresses, tx_seglist) # segleft should be equal to size seglist-1 - self.assertEqual(rx_srh.segleft, len(tx_seglist)-1) + self.assertEqual(rx_srh.segleft, len(tx_seglist) - 1) # segleft should be equal to lastentry self.assertEqual(rx_srh.segleft, rx_srh.lastentry) @@ -1423,7 +1565,7 @@ class TestSRv6(VppTestCase): self.logger.debug("packet verification: SUCCESS") def compare_rx_tx_packet_T_Encaps_L2(self, tx_pkt, rx_pkt): - """ Compare input and output packet after passing T.Encaps for L2 + """Compare input and output packet after passing T.Encaps for L2 :param tx_pkt: transmitted packet :param rx_pkt: received packet @@ -1461,7 +1603,7 @@ class TestSRv6(VppTestCase): # rx'ed seglist should be equal to seglist self.assertEqual(rx_srh.addresses, tx_seglist) # segleft should be equal to size seglist-1 - self.assertEqual(rx_srh.segleft, len(tx_seglist)-1) + self.assertEqual(rx_srh.segleft, len(tx_seglist) - 1) # segleft should be equal to lastentry self.assertEqual(rx_srh.segleft, rx_srh.lastentry) # nh should be "No Next Header" (143) @@ -1473,7 +1615,7 @@ class TestSRv6(VppTestCase): self.logger.debug("packet verification: SUCCESS") def compare_rx_tx_packet_T_Insert(self, tx_pkt, rx_pkt): - """ Compare input and output packet after passing T.Insert + """Compare input and output packet after passing T.Insert :param tx_pkt: transmitted packet :param rx_pkt: received packet @@ -1529,7 +1671,7 @@ class TestSRv6(VppTestCase): # rx'ed seglist should be equal to expected seglist self.assertEqual(rx_srh.addresses, tx_seglist) # segleft should be equal to size(expected seglist)-1 - self.assertEqual(rx_srh.segleft, len(tx_seglist)-1) + self.assertEqual(rx_srh.segleft, len(tx_seglist) - 1) # segleft should be equal to lastentry self.assertEqual(rx_srh.segleft, rx_srh.lastentry) @@ -1556,7 +1698,7 @@ class TestSRv6(VppTestCase): self.logger.debug("packet verification: SUCCESS") def compare_rx_tx_packet_End(self, tx_pkt, rx_pkt): - """ Compare input and output packet after passing End (without PSP) + """Compare input and output packet after passing End (without PSP) :param tx_pkt: transmitted packet :param rx_pkt: received packet @@ -1596,7 +1738,7 @@ class TestSRv6(VppTestCase): # sidlist should be unchanged self.assertEqual(rx_srh.addresses, tx_srh.addresses) # segleft should have been decremented - self.assertEqual(rx_srh.segleft, tx_srh.segleft-1) + self.assertEqual(rx_srh.segleft, tx_srh.segleft - 1) # received ip.dst should be equal to sidlist[segleft] self.assertEqual(rx_ip.dst, rx_srh.addresses[rx_srh.segleft]) # lastentry should be unchanged @@ -1605,7 +1747,7 @@ class TestSRv6(VppTestCase): self.assertEqual(rx_ip2.src, tx_ip2.src) self.assertEqual(rx_ip2.dst, tx_ip2.dst) # else: # tx_ip.segleft == 0 - # TODO: Does this work with 2 SRHs in ingress packet? + # TODO: Does this work with 2 SRHs in ingress packet? # UDP layer should be unchanged self.assertEqual(rx_udp, tx_udp) @@ -1613,7 +1755,7 @@ class TestSRv6(VppTestCase): self.logger.debug("packet verification: SUCCESS") def compare_rx_tx_packet_End_PSP(self, tx_pkt, rx_pkt): - """ Compare input and output packet after passing End with PSP + """Compare input and output packet after passing End with PSP :param tx_pkt: transmitted packet :param rx_pkt: received packet @@ -1658,7 +1800,7 @@ class TestSRv6(VppTestCase): # sidlist should be unchanged self.assertEqual(rx_srh.addresses, tx_srh.addresses) # segleft should have been decremented - self.assertEqual(rx_srh.segleft, tx_srh.segleft-1) + self.assertEqual(rx_srh.segleft, tx_srh.segleft - 1) # received ip.dst should be equal to sidlist[segleft] self.assertEqual(rx_ip.dst, rx_srh.addresses[rx_srh.segleft]) # lastentry should be unchanged @@ -1674,7 +1816,7 @@ class TestSRv6(VppTestCase): # outer IPv6 header ip.src should be equal to tx'ed ip.src self.assertEqual(rx_ip.src, tx_ip.src) # outer IPv6 header ip.dst should be = to tx'ed sidlist[segleft-1] - self.assertEqual(rx_ip.dst, tx_srh.addresses[tx_srh.segleft-1]) + self.assertEqual(rx_ip.dst, tx_srh.addresses[tx_srh.segleft - 1]) # UDP layer should be unchanged self.assertEqual(rx_udp, tx_udp) @@ -1682,7 +1824,7 @@ class TestSRv6(VppTestCase): self.logger.debug("packet verification: SUCCESS") def compare_rx_tx_packet_End_DX6(self, tx_pkt, rx_pkt): - """ Compare input and output packet after passing End.DX6 + """Compare input and output packet after passing End.DX6 :param tx_pkt: transmitted packet :param rx_pkt: received packet @@ -1714,7 +1856,7 @@ class TestSRv6(VppTestCase): self.logger.debug("packet verification: SUCCESS") def compare_rx_tx_packet_End_DX4(self, tx_pkt, rx_pkt): - """ Compare input and output packet after passing End.DX4 + """Compare input and output packet after passing End.DX4 :param tx_pkt: transmitted packet :param rx_pkt: received packet @@ -1751,7 +1893,7 @@ class TestSRv6(VppTestCase): self.logger.debug("packet verification: SUCCESS") def compare_rx_tx_packet_End_DX2(self, tx_pkt, rx_pkt): - """ Compare input and output packet after passing End.DX2 + """Compare input and output packet after passing End.DX2 :param tx_pkt: transmitted packet :param rx_pkt: received packet @@ -1780,8 +1922,7 @@ class TestSRv6(VppTestCase): self.logger.debug("packet verification: SUCCESS") - def create_stream(self, src_if, dst_if, packet_header, packet_sizes, - count): + def create_stream(self, src_if, dst_if, packet_header, packet_sizes, count): """Create SRv6 input packet stream for defined interface. :param VppInterface src_if: Interface to create packet stream for @@ -1796,19 +1937,19 @@ class TestSRv6(VppTestCase): """ self.logger.info("Creating packets") pkts = [] - for i in range(0, count-1): + for i in range(0, count - 1): payload_info = self.create_packet_info(src_if, dst_if) - self.logger.debug( - "Creating packet with index %d" % (payload_info.index)) + self.logger.debug("Creating packet with index %d" % (payload_info.index)) payload = self.info_to_payload(payload_info) # add L2 header if not yet provided in packet_header - if packet_header.getlayer(0).name == 'Ethernet': - p = (packet_header / - Raw(payload)) + if packet_header.getlayer(0).name == "Ethernet": + p = packet_header / Raw(payload) else: - p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - packet_header / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / packet_header + / Raw(payload) + ) size = packet_sizes[i % len(packet_sizes)] self.logger.debug("Packet size %d" % (size)) self.extend_packet(p, size) @@ -1823,8 +1964,9 @@ class TestSRv6(VppTestCase): self.logger.info("Done creating packets") return pkts - def send_and_verify_pkts(self, input, pkts, output, compare_func, - expected_count=None): + def send_and_verify_pkts( + self, input, pkts, output, compare_func, expected_count=None + ): """Send packets and verify received packets using compare_func :param input: ingress interface of DUT @@ -1863,8 +2005,7 @@ class TestSRv6(VppTestCase): UDP source port and destination port are 1234 """ - p = (IPv6(src='1234::1', dst=dst) / - UDP(sport=1234, dport=1234)) + p = IPv6(src="1234::1", dst=dst) / UDP(sport=1234, dport=1234) return p def create_packet_header_IPv6_SRH(self, sidlist, segleft): @@ -1878,9 +2019,11 @@ class TestSRv6(VppTestCase): UDP source port and destination port are 1234 """ - p = (IPv6(src='1234::1', dst=sidlist[segleft]) / - IPv6ExtHdrSegmentRouting(addresses=sidlist) / - UDP(sport=1234, dport=1234)) + p = ( + IPv6(src="1234::1", dst=sidlist[segleft]) + / IPv6ExtHdrSegmentRouting(addresses=sidlist) + / UDP(sport=1234, dport=1234) + ) return p def create_packet_header_IPv6_SRH_IPv6(self, dst, sidlist, segleft): @@ -1896,11 +2039,12 @@ class TestSRv6(VppTestCase): UDP source port and destination port are 1234 """ - p = (IPv6(src='1234::1', dst=sidlist[segleft]) / - IPv6ExtHdrSegmentRouting(addresses=sidlist, - segleft=segleft, nh=41) / - IPv6(src='4321::1', dst=dst) / - UDP(sport=1234, dport=1234)) + p = ( + IPv6(src="1234::1", dst=sidlist[segleft]) + / IPv6ExtHdrSegmentRouting(addresses=sidlist, segleft=segleft, nh=41) + / IPv6(src="4321::1", dst=dst) + / UDP(sport=1234, dport=1234) + ) return p def create_packet_header_IPv6_IPv6(self, dst_inner, dst_outer): @@ -1914,13 +2058,16 @@ class TestSRv6(VppTestCase): UDP source port and destination port are 1234 """ - p = (IPv6(src='1234::1', dst=dst_outer) / - IPv6(src='4321::1', dst=dst_inner) / - UDP(sport=1234, dport=1234)) + p = ( + IPv6(src="1234::1", dst=dst_outer) + / IPv6(src="4321::1", dst=dst_inner) + / UDP(sport=1234, dport=1234) + ) return p - def create_packet_header_IPv6_SRH_SRH_IPv6(self, dst, sidlist1, segleft1, - sidlist2, segleft2): + def create_packet_header_IPv6_SRH_SRH_IPv6( + self, dst, sidlist1, segleft1, sidlist2, segleft2 + ): """Create packet header: IPv6 encapsulated in SRv6 with 2 SRH: IPv6 header with SRH, 2nd SRH, IPv6 header, UDP header @@ -1935,13 +2082,13 @@ class TestSRv6(VppTestCase): UDP source port and destination port are 1234 """ - p = (IPv6(src='1234::1', dst=sidlist1[segleft1]) / - IPv6ExtHdrSegmentRouting(addresses=sidlist1, - segleft=segleft1, nh=43) / - IPv6ExtHdrSegmentRouting(addresses=sidlist2, - segleft=segleft2, nh=41) / - IPv6(src='4321::1', dst=dst) / - UDP(sport=1234, dport=1234)) + p = ( + IPv6(src="1234::1", dst=sidlist1[segleft1]) + / IPv6ExtHdrSegmentRouting(addresses=sidlist1, segleft=segleft1, nh=43) + / IPv6ExtHdrSegmentRouting(addresses=sidlist2, segleft=segleft2, nh=41) + / IPv6(src="4321::1", dst=dst) + / UDP(sport=1234, dport=1234) + ) return p def create_packet_header_IPv4(self, dst): @@ -1953,8 +2100,7 @@ class TestSRv6(VppTestCase): UDP source port and destination port are 1234 """ - p = (IP(src='123.1.1.1', dst=dst) / - UDP(sport=1234, dport=1234)) + p = IP(src="123.1.1.1", dst=dst) / UDP(sport=1234, dport=1234) return p def create_packet_header_IPv6_IPv4(self, dst_inner, dst_outer): @@ -1969,9 +2115,11 @@ class TestSRv6(VppTestCase): UDP source port and destination port are 1234 """ - p = (IPv6(src='1234::1', dst=dst_outer) / - IP(src='123.1.1.1', dst=dst_inner) / - UDP(sport=1234, dport=1234)) + p = ( + IPv6(src="1234::1", dst=dst_outer) + / IP(src="123.1.1.1", dst=dst_inner) + / UDP(sport=1234, dport=1234) + ) return p def create_packet_header_IPv6_SRH_IPv4(self, dst, sidlist, segleft): @@ -1988,11 +2136,12 @@ class TestSRv6(VppTestCase): UDP source port and destination port are 1234 """ - p = (IPv6(src='1234::1', dst=sidlist[segleft]) / - IPv6ExtHdrSegmentRouting(addresses=sidlist, - segleft=segleft, nh=4) / - IP(src='123.1.1.1', dst=dst) / - UDP(sport=1234, dport=1234)) + p = ( + IPv6(src="1234::1", dst=sidlist[segleft]) + / IPv6ExtHdrSegmentRouting(addresses=sidlist, segleft=segleft, nh=4) + / IP(src="123.1.1.1", dst=dst) + / UDP(sport=1234, dport=1234) + ) return p def create_packet_header_L2(self, vlan=0): @@ -2003,7 +2152,7 @@ class TestSRv6(VppTestCase): # Note: the dst addr ('00:55:44:33:22:11') is used in # the compare function compare_rx_tx_packet_T_Encaps_L2 # to detect presence of L2 in SRH payload - p = Ether(src='00:11:22:33:44:55', dst='00:55:44:33:22:11') + p = Ether(src="00:11:22:33:44:55", dst="00:55:44:33:22:11") etype = 0x8137 # IPX if vlan: # add 802.1q layer @@ -2023,7 +2172,7 @@ class TestSRv6(VppTestCase): Outer IPv6 destination address is set to sidlist[segleft] IPv6 source address is 1234::1 """ - eth = Ether(src='00:11:22:33:44:55', dst='00:55:44:33:22:11') + eth = Ether(src="00:11:22:33:44:55", dst="00:55:44:33:22:11") etype = 0x8137 # IPX if vlan: # add 802.1q layer @@ -2031,10 +2180,11 @@ class TestSRv6(VppTestCase): else: eth.type = etype - p = (IPv6(src='1234::1', dst=sidlist[segleft]) / - IPv6ExtHdrSegmentRouting(addresses=sidlist, - segleft=segleft, nh=143) / - eth) + p = ( + IPv6(src="1234::1", dst=sidlist[segleft]) + / IPv6ExtHdrSegmentRouting(addresses=sidlist, segleft=segleft, nh=143) + / eth + ) return p def create_packet_header_IPv6_L2(self, dst_outer, vlan=0): @@ -2044,7 +2194,7 @@ class TestSRv6(VppTestCase): :param ipv6address dst_outer: outer IPv6 destination address :param vlan: L2 vlan; if vlan!=0 then add 802.1q header """ - eth = Ether(src='00:11:22:33:44:55', dst='00:55:44:33:22:11') + eth = Ether(src="00:11:22:33:44:55", dst="00:55:44:33:22:11") etype = 0x8137 # IPX if vlan: # add 802.1q layer @@ -2052,12 +2202,11 @@ class TestSRv6(VppTestCase): else: eth.type = etype - p = (IPv6(src='1234::1', dst=dst_outer, nh=143) / eth) + p = IPv6(src="1234::1", dst=dst_outer, nh=143) / eth return p def get_payload_info(self, packet): - """ Extract the payload_info from the packet - """ + """Extract the payload_info from the packet""" # in most cases, payload_info is in packet[Raw] # but packet[Raw] gives the complete payload # (incl L2 header) for the T.Encaps L2 case @@ -2068,8 +2217,7 @@ class TestSRv6(VppTestCase): # remote L2 header from packet[Raw]: # take packet[Raw], convert it to an Ether layer # and then extract Raw from it - payload_info = self.payload_to_info( - Ether(scapy.compat.r(packet[Raw]))[Raw]) + payload_info = self.payload_to_info(Ether(scapy.compat.r(packet[Raw]))[Raw]) return payload_info @@ -2082,8 +2230,10 @@ class TestSRv6(VppTestCase): :param capture: captured packets :param compare_func: function to compare in and out packet """ - self.logger.info("Verifying capture on interface %s using function %s" - % (dst_if.name, compare_func.__name__)) + self.logger.info( + "Verifying capture on interface %s using function %s" + % (dst_if.name, compare_func.__name__) + ) last_info = dict() for i in self.pg_interfaces: @@ -2096,19 +2246,19 @@ class TestSRv6(VppTestCase): payload_info = self.get_payload_info(packet) packet_index = payload_info.index - self.logger.debug("Verifying packet with index %d" - % (packet_index)) + self.logger.debug("Verifying packet with index %d" % (packet_index)) # packet should have arrived on the expected interface self.assertEqual(payload_info.dst, dst_sw_if_index) self.logger.debug( - "Got packet on interface %s: src=%u (idx=%u)" % - (dst_if.name, payload_info.src, packet_index)) + "Got packet on interface %s: src=%u (idx=%u)" + % (dst_if.name, payload_info.src, packet_index) + ) # search for payload_info with same src and dst if_index # this will give us the transmitted packet next_info = self.get_next_packet_info_for_interface2( - payload_info.src, dst_sw_if_index, - last_info[payload_info.src]) + payload_info.src, dst_sw_if_index, last_info[payload_info.src] + ) last_info[payload_info.src] = next_info # next_info should not be None self.assertTrue(next_info is not None) @@ -2117,8 +2267,9 @@ class TestSRv6(VppTestCase): # data field of next_info contains the tx packet txed_packet = next_info.data - self.logger.debug(ppp("Transmitted packet:", - txed_packet)) # ppp=Pretty Print Packet + self.logger.debug( + ppp("Transmitted packet:", txed_packet) + ) # ppp=Pretty Print Packet self.logger.debug(ppp("Received packet:", packet)) @@ -2143,5 +2294,5 @@ class TestSRv6(VppTestCase): # "didn't arrive" % (dst_if.name, i.name)) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_srv6_ad.py b/test/test_srv6_ad.py index dad7c186a93..88c0b1d8074 100644 --- a/test/test_srv6_ad.py +++ b/test/test_srv6_ad.py @@ -7,8 +7,14 @@ from socket import AF_INET6 from framework import VppTestCase, VppTestRunner from vpp_ip import DpoProto from vpp_ip_route import VppIpRoute, VppRoutePath, VppIpTable -from vpp_srv6 import SRv6LocalSIDBehaviors, VppSRv6LocalSID, VppSRv6Policy, \ - SRv6PolicyType, VppSRv6Steering, SRv6PolicySteeringTypes +from vpp_srv6 import ( + SRv6LocalSIDBehaviors, + VppSRv6LocalSID, + VppSRv6Policy, + SRv6PolicyType, + VppSRv6Steering, + SRv6PolicySteeringTypes, +) import scapy.compat from scapy.packet import Raw @@ -20,7 +26,7 @@ from util import ppp class TestSRv6Ad(VppTestCase): - """ SRv6 Dynamic Proxy plugin Test Case """ + """SRv6 Dynamic Proxy plugin Test Case""" @classmethod def setUpClass(self): @@ -31,8 +37,7 @@ class TestSRv6Ad(VppTestCase): super(TestSRv6Ad, cls).tearDownClass() def setUp(self): - """ Perform test setup before each test case. - """ + """Perform test setup before each test case.""" super(TestSRv6Ad, self).setUp() # packet sizes, inclusive L2 overhead @@ -42,17 +47,15 @@ class TestSRv6Ad(VppTestCase): self.reset_packet_infos() def tearDown(self): - """ Clean up test setup after each test case. - """ + """Clean up test setup after each test case.""" self.teardown_interfaces() super(TestSRv6Ad, self).tearDown() - def configure_interface(self, - interface, - ipv6=False, ipv4=False, - ipv6_table_id=0, ipv4_table_id=0): - """ Configure interface. + def configure_interface( + self, interface, ipv6=False, ipv4=False, ipv6_table_id=0, ipv4_table_id=0 + ): + """Configure interface. :param ipv6: configure IPv6 on interface :param ipv4: configure IPv4 on interface :param ipv6_table_id: FIB table_id for IPv6 @@ -71,9 +74,8 @@ class TestSRv6Ad(VppTestCase): interface.resolve_arp() interface.admin_up() - def setup_interfaces(self, ipv6=[], ipv4=[], - ipv6_table_id=[], ipv4_table_id=[]): - """ Create and configure interfaces. + def setup_interfaces(self, ipv6=[], ipv4=[], ipv6_table_id=[], ipv4_table_id=[]): + """Create and configure interfaces. :param ipv6: list of interface IPv6 capabilities :param ipv4: list of interface IPv4 capabilities @@ -108,9 +110,9 @@ class TestSRv6Ad(VppTestCase): # setup all interfaces for i in range(count): intf = self.pg_interfaces[i] - self.configure_interface(intf, - ipv6[i], ipv4[i], - ipv6_table_id[i], ipv4_table_id[i]) + self.configure_interface( + intf, ipv6[i], ipv4[i], ipv6_table_id[i], ipv4_table_id[i] + ) if any(ipv6): self.logger.debug(self.vapi.cli("show ip6 neighbors")) @@ -122,8 +124,7 @@ class TestSRv6Ad(VppTestCase): return self.pg_interfaces def teardown_interfaces(self): - """ Unconfigure and bring down interface. - """ + """Unconfigure and bring down interface.""" self.logger.debug("Tearing down interfaces") # tear down all interfaces # AFAIK they cannot be deleted @@ -135,10 +136,9 @@ class TestSRv6Ad(VppTestCase): i.set_table_ip6(0) def test_SRv6_End_AD_IPv6(self): - """ Test SRv6 End.AD behavior with IPv6 traffic. - """ - self.src_addr = 'a0::' - self.sid_list = ['a1::', 'a2::a6', 'a3::'] + """Test SRv6 End.AD behavior with IPv6 traffic.""" + self.src_addr = "a0::" + self.sid_list = ["a1::", "a2::a6", "a3::"] self.test_sid_index = 1 # send traffic to one destination interface @@ -146,19 +146,32 @@ class TestSRv6Ad(VppTestCase): self.setup_interfaces(ipv6=[True, True]) # configure route to next segment - route = VppIpRoute(self, self.sid_list[self.test_sid_index + 1], 128, - [VppRoutePath(self.pg0.remote_ip6, - self.pg0.sw_if_index, - proto=DpoProto.DPO_PROTO_IP6)]) + route = VppIpRoute( + self, + self.sid_list[self.test_sid_index + 1], + 128, + [ + VppRoutePath( + self.pg0.remote_ip6, + self.pg0.sw_if_index, + proto=DpoProto.DPO_PROTO_IP6, + ) + ], + ) route.add_vpp_config() # configure SRv6 localSID behavior - cli_str = "sr localsid address " + \ - self.sid_list[self.test_sid_index] + \ - " behavior end.ad" + \ - " nh " + self.pg1.remote_ip6 + \ - " oif " + self.pg1.name + \ - " iif " + self.pg1.name + cli_str = ( + "sr localsid address " + + self.sid_list[self.test_sid_index] + + " behavior end.ad" + + " nh " + + self.pg1.remote_ip6 + + " oif " + + self.pg1.name + + " iif " + + self.pg1.name + ) self.vapi.cli(cli_str) # log the localsids @@ -171,15 +184,18 @@ class TestSRv6Ad(VppTestCase): packet_header1 = self.create_packet_header_IPv6_SRH_IPv6( srcaddr=self.src_addr, sidlist=self.sid_list[::-1], - segleft=len(self.sid_list) - self.test_sid_index - 1) + segleft=len(self.sid_list) - self.test_sid_index - 1, + ) # generate packets (pg0->pg1) - pkts1 = self.create_stream(self.pg0, self.pg1, packet_header1, - self.pg_packet_sizes, count) + pkts1 = self.create_stream( + self.pg0, self.pg1, packet_header1, self.pg_packet_sizes, count + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg0, pkts1, self.pg1, - self.compare_rx_tx_packet_End_AD_IPv6_out) + self.send_and_verify_pkts( + self.pg0, pkts1, self.pg1, self.compare_rx_tx_packet_End_AD_IPv6_out + ) # log the localsid counters self.logger.info(self.vapi.cli("show sr localsid")) @@ -188,26 +204,27 @@ class TestSRv6Ad(VppTestCase): packet_header2 = self.create_packet_header_IPv6() # generate returning packets (pg1->pg0) - pkts2 = self.create_stream(self.pg1, self.pg0, packet_header2, - self.pg_packet_sizes, count) + pkts2 = self.create_stream( + self.pg1, self.pg0, packet_header2, self.pg_packet_sizes, count + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg1, pkts2, self.pg0, - self.compare_rx_tx_packet_End_AD_IPv6_in) + self.send_and_verify_pkts( + self.pg1, pkts2, self.pg0, self.compare_rx_tx_packet_End_AD_IPv6_in + ) # log the localsid counters self.logger.info(self.vapi.cli("show sr localsid")) # remove SRv6 localSIDs - cli_str = "sr localsid del address " + \ - self.sid_list[self.test_sid_index] + cli_str = "sr localsid del address " + self.sid_list[self.test_sid_index] self.vapi.cli(cli_str) # cleanup interfaces self.teardown_interfaces() def compare_rx_tx_packet_End_AD_IPv6_out(self, tx_pkt, rx_pkt): - """ Compare input and output packet after passing End.AD with IPv6 + """Compare input and output packet after passing End.AD with IPv6 :param tx_pkt: transmitted packet :param rx_pkt: received packet @@ -232,7 +249,7 @@ class TestSRv6Ad(VppTestCase): self.logger.debug("packet verification: SUCCESS") def compare_rx_tx_packet_End_AD_IPv6_in(self, tx_pkt, rx_pkt): - """ Compare input and output packet after passing End.AD + """Compare input and output packet after passing End.AD :param tx_pkt: transmitted packet :param rx_pkt: received packet @@ -253,8 +270,7 @@ class TestSRv6Ad(VppTestCase): # rx'ed seglist should be equal to SID-list in reversed order self.assertEqual(rx_srh.addresses, self.sid_list[::-1]) # segleft should be equal to previous segleft value minus 1 - self.assertEqual(rx_srh.segleft, - len(self.sid_list) - self.test_sid_index - 2) + self.assertEqual(rx_srh.segleft, len(self.sid_list) - self.test_sid_index - 2) # lastentry should be equal to the SID-list length minus 1 self.assertEqual(rx_srh.lastentry, len(self.sid_list) - 1) @@ -269,10 +285,9 @@ class TestSRv6Ad(VppTestCase): self.logger.debug("packet verification: SUCCESS") def test_SRv6_End_AD_IPv4(self): - """ Test SRv6 End.AD behavior with IPv4 traffic. - """ - self.src_addr = 'a0::' - self.sid_list = ['a1::', 'a2::a4', 'a3::'] + """Test SRv6 End.AD behavior with IPv4 traffic.""" + self.src_addr = "a0::" + self.sid_list = ["a1::", "a2::a4", "a3::"] self.test_sid_index = 1 # send traffic to one destination interface @@ -280,19 +295,32 @@ class TestSRv6Ad(VppTestCase): self.setup_interfaces(ipv6=[True, False], ipv4=[False, True]) # configure route to next segment - route = VppIpRoute(self, self.sid_list[self.test_sid_index + 1], 128, - [VppRoutePath(self.pg0.remote_ip6, - self.pg0.sw_if_index, - proto=DpoProto.DPO_PROTO_IP6)]) + route = VppIpRoute( + self, + self.sid_list[self.test_sid_index + 1], + 128, + [ + VppRoutePath( + self.pg0.remote_ip6, + self.pg0.sw_if_index, + proto=DpoProto.DPO_PROTO_IP6, + ) + ], + ) route.add_vpp_config() # configure SRv6 localSID behavior - cli_str = "sr localsid address " + \ - self.sid_list[self.test_sid_index] + \ - " behavior end.ad" + \ - " nh " + self.pg1.remote_ip4 + \ - " oif " + self.pg1.name + \ - " iif " + self.pg1.name + cli_str = ( + "sr localsid address " + + self.sid_list[self.test_sid_index] + + " behavior end.ad" + + " nh " + + self.pg1.remote_ip4 + + " oif " + + self.pg1.name + + " iif " + + self.pg1.name + ) self.vapi.cli(cli_str) # log the localsids @@ -305,15 +333,18 @@ class TestSRv6Ad(VppTestCase): packet_header1 = self.create_packet_header_IPv6_SRH_IPv4( srcaddr=self.src_addr, sidlist=self.sid_list[::-1], - segleft=len(self.sid_list) - self.test_sid_index - 1) + segleft=len(self.sid_list) - self.test_sid_index - 1, + ) # generate packets (pg0->pg1) - pkts1 = self.create_stream(self.pg0, self.pg1, packet_header1, - self.pg_packet_sizes, count) + pkts1 = self.create_stream( + self.pg0, self.pg1, packet_header1, self.pg_packet_sizes, count + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg0, pkts1, self.pg1, - self.compare_rx_tx_packet_End_AD_IPv4_out) + self.send_and_verify_pkts( + self.pg0, pkts1, self.pg1, self.compare_rx_tx_packet_End_AD_IPv4_out + ) # log the localsid counters self.logger.info(self.vapi.cli("show sr localsid")) @@ -322,26 +353,27 @@ class TestSRv6Ad(VppTestCase): packet_header2 = self.create_packet_header_IPv4() # generate returning packets (pg1->pg0) - pkts2 = self.create_stream(self.pg1, self.pg0, packet_header2, - self.pg_packet_sizes, count) + pkts2 = self.create_stream( + self.pg1, self.pg0, packet_header2, self.pg_packet_sizes, count + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg1, pkts2, self.pg0, - self.compare_rx_tx_packet_End_AD_IPv4_in) + self.send_and_verify_pkts( + self.pg1, pkts2, self.pg0, self.compare_rx_tx_packet_End_AD_IPv4_in + ) # log the localsid counters self.logger.info(self.vapi.cli("show sr localsid")) # remove SRv6 localSIDs - cli_str = "sr localsid del address " + \ - self.sid_list[self.test_sid_index] + cli_str = "sr localsid del address " + self.sid_list[self.test_sid_index] self.vapi.cli(cli_str) # cleanup interfaces self.teardown_interfaces() def compare_rx_tx_packet_End_AD_IPv4_out(self, tx_pkt, rx_pkt): - """ Compare input and output packet after passing End.AD with IPv4 + """Compare input and output packet after passing End.AD with IPv4 :param tx_pkt: transmitted packet :param rx_pkt: received packet @@ -371,7 +403,7 @@ class TestSRv6Ad(VppTestCase): self.logger.debug("packet verification: SUCCESS") def compare_rx_tx_packet_End_AD_IPv4_in(self, tx_pkt, rx_pkt): - """ Compare input and output packet after passing End.AD + """Compare input and output packet after passing End.AD :param tx_pkt: transmitted packet :param rx_pkt: received packet @@ -392,8 +424,7 @@ class TestSRv6Ad(VppTestCase): # rx'ed seglist should be equal to SID-list in reversed order self.assertEqual(rx_srh.addresses, self.sid_list[::-1]) # segleft should be equal to previous segleft value minus 1 - self.assertEqual(rx_srh.segleft, - len(self.sid_list) - self.test_sid_index - 2) + self.assertEqual(rx_srh.segleft, len(self.sid_list) - self.test_sid_index - 2) # lastentry should be equal to the SID-list length minus 1 self.assertEqual(rx_srh.lastentry, len(self.sid_list) - 1) @@ -411,10 +442,9 @@ class TestSRv6Ad(VppTestCase): self.logger.debug("packet verification: SUCCESS") def test_SRv6_End_AD_L2(self): - """ Test SRv6 End.AD behavior with L2 traffic. - """ - self.src_addr = 'a0::' - self.sid_list = ['a1::', 'a2::a4', 'a3::'] + """Test SRv6 End.AD behavior with L2 traffic.""" + self.src_addr = "a0::" + self.sid_list = ["a1::", "a2::a4", "a3::"] self.test_sid_index = 1 # send traffic to one destination interface @@ -422,18 +452,30 @@ class TestSRv6Ad(VppTestCase): self.setup_interfaces(ipv6=[True, False]) # configure route to next segment - route = VppIpRoute(self, self.sid_list[self.test_sid_index + 1], 128, - [VppRoutePath(self.pg0.remote_ip6, - self.pg0.sw_if_index, - proto=DpoProto.DPO_PROTO_IP6)]) + route = VppIpRoute( + self, + self.sid_list[self.test_sid_index + 1], + 128, + [ + VppRoutePath( + self.pg0.remote_ip6, + self.pg0.sw_if_index, + proto=DpoProto.DPO_PROTO_IP6, + ) + ], + ) route.add_vpp_config() # configure SRv6 localSID behavior - cli_str = "sr localsid address " + \ - self.sid_list[self.test_sid_index] + \ - " behavior end.ad" + \ - " oif " + self.pg1.name + \ - " iif " + self.pg1.name + cli_str = ( + "sr localsid address " + + self.sid_list[self.test_sid_index] + + " behavior end.ad" + + " oif " + + self.pg1.name + + " iif " + + self.pg1.name + ) self.vapi.cli(cli_str) # log the localsids @@ -447,15 +489,18 @@ class TestSRv6Ad(VppTestCase): srcaddr=self.src_addr, sidlist=self.sid_list[::-1], segleft=len(self.sid_list) - self.test_sid_index - 1, - vlan=0) + vlan=0, + ) # generate packets (pg0->pg1) - pkts1 = self.create_stream(self.pg0, self.pg1, packet_header1, - self.pg_packet_sizes, count) + pkts1 = self.create_stream( + self.pg0, self.pg1, packet_header1, self.pg_packet_sizes, count + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg0, pkts1, self.pg1, - self.compare_rx_tx_packet_End_AD_L2_out) + self.send_and_verify_pkts( + self.pg0, pkts1, self.pg1, self.compare_rx_tx_packet_End_AD_L2_out + ) # log the localsid counters self.logger.info(self.vapi.cli("show sr localsid")) @@ -464,26 +509,27 @@ class TestSRv6Ad(VppTestCase): packet_header2 = self.create_packet_header_L2() # generate returning packets (pg1->pg0) - pkts2 = self.create_stream(self.pg1, self.pg0, packet_header2, - self.pg_packet_sizes, count) + pkts2 = self.create_stream( + self.pg1, self.pg0, packet_header2, self.pg_packet_sizes, count + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg1, pkts2, self.pg0, - self.compare_rx_tx_packet_End_AD_L2_in) + self.send_and_verify_pkts( + self.pg1, pkts2, self.pg0, self.compare_rx_tx_packet_End_AD_L2_in + ) # log the localsid counters self.logger.info(self.vapi.cli("show sr localsid")) # remove SRv6 localSIDs - cli_str = "sr localsid del address " + \ - self.sid_list[self.test_sid_index] + cli_str = "sr localsid del address " + self.sid_list[self.test_sid_index] self.vapi.cli(cli_str) # cleanup interfaces self.teardown_interfaces() def compare_rx_tx_packet_End_AD_L2_out(self, tx_pkt, rx_pkt): - """ Compare input and output packet after passing End.AD with L2 + """Compare input and output packet after passing End.AD with L2 :param tx_pkt: transmitted packet :param rx_pkt: received packet @@ -506,7 +552,7 @@ class TestSRv6Ad(VppTestCase): self.logger.debug("packet verification: SUCCESS") def compare_rx_tx_packet_End_AD_L2_in(self, tx_pkt, rx_pkt): - """ Compare input and output packet after passing End.AD + """Compare input and output packet after passing End.AD :param tx_pkt: transmitted packet :param rx_pkt: received packet @@ -528,8 +574,7 @@ class TestSRv6Ad(VppTestCase): # rx'ed seglist should be equal to SID-list in reversed order self.assertEqual(rx_srh.addresses, self.sid_list[::-1]) # segleft should be equal to previous segleft value minus 1 - self.assertEqual(rx_srh.segleft, - len(self.sid_list) - self.test_sid_index - 2) + self.assertEqual(rx_srh.segleft, len(self.sid_list) - self.test_sid_index - 2) # lastentry should be equal to the SID-list length minus 1 self.assertEqual(rx_srh.lastentry, len(self.sid_list) - 1) @@ -539,8 +584,7 @@ class TestSRv6Ad(VppTestCase): self.logger.debug("packet verification: SUCCESS") - def create_stream(self, src_if, dst_if, packet_header, packet_sizes, - count): + def create_stream(self, src_if, dst_if, packet_header, packet_sizes, count): """Create SRv6 input packet stream for defined interface. :param VppInterface src_if: Interface to create packet stream for @@ -557,15 +601,17 @@ class TestSRv6Ad(VppTestCase): pkts = [] for i in range(0, count - 1): payload_info = self.create_packet_info(src_if, dst_if) - self.logger.debug( - "Creating packet with index %d" % (payload_info.index)) + self.logger.debug("Creating packet with index %d" % (payload_info.index)) payload = self.info_to_payload(payload_info) # add L2 header if not yet provided in packet_header - if packet_header.getlayer(0).name == 'Ethernet': + if packet_header.getlayer(0).name == "Ethernet": p = packet_header / Raw(payload) else: - p = Ether(dst=src_if.local_mac, src=src_if.remote_mac) / \ - packet_header / Raw(payload) + p = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / packet_header + / Raw(payload) + ) size = packet_sizes[i % len(packet_sizes)] self.logger.debug("Packet size %d" % (size)) self.extend_packet(p, size) @@ -618,7 +664,7 @@ class TestSRv6Ad(VppTestCase): UDP source port and destination port are 1234 """ - p = IPv6(src='1234::1', dst='4321::1') / UDP(sport=1234, dport=1234) + p = IPv6(src="1234::1", dst="4321::1") / UDP(sport=1234, dport=1234) return p def create_packet_header_IPv6_SRH_IPv6(self, srcaddr, sidlist, segleft): @@ -636,11 +682,12 @@ class TestSRv6Ad(VppTestCase): UDP source port and destination port are 1234 """ - p = IPv6(src=srcaddr, dst=sidlist[segleft]) / \ - IPv6ExtHdrSegmentRouting(addresses=sidlist, - segleft=segleft, nh=41) / \ - IPv6(src='1234::1', dst='4321::1') / \ - UDP(sport=1234, dport=1234) + p = ( + IPv6(src=srcaddr, dst=sidlist[segleft]) + / IPv6ExtHdrSegmentRouting(addresses=sidlist, segleft=segleft, nh=41) + / IPv6(src="1234::1", dst="4321::1") + / UDP(sport=1234, dport=1234) + ) return p def create_packet_header_IPv4(self): @@ -653,7 +700,7 @@ class TestSRv6Ad(VppTestCase): UDP source port and destination port are 1234 """ - p = IP(src='123.1.1.1', dst='124.1.1.1') / UDP(sport=1234, dport=1234) + p = IP(src="123.1.1.1", dst="124.1.1.1") / UDP(sport=1234, dport=1234) return p def create_packet_header_IPv6_SRH_IPv4(self, srcaddr, sidlist, segleft): @@ -671,11 +718,12 @@ class TestSRv6Ad(VppTestCase): UDP source port and destination port are 1234 """ - p = IPv6(src=srcaddr, dst=sidlist[segleft]) / \ - IPv6ExtHdrSegmentRouting(addresses=sidlist, - segleft=segleft, nh=4) / \ - IP(src='123.1.1.1', dst='124.1.1.1') / \ - UDP(sport=1234, dport=1234) + p = ( + IPv6(src=srcaddr, dst=sidlist[segleft]) + / IPv6ExtHdrSegmentRouting(addresses=sidlist, segleft=segleft, nh=4) + / IP(src="123.1.1.1", dst="124.1.1.1") + / UDP(sport=1234, dport=1234) + ) return p def create_packet_header_L2(self, vlan=0): @@ -686,7 +734,7 @@ class TestSRv6Ad(VppTestCase): # Note: the dst addr ('00:55:44:33:22:11') is used in # the compare function compare_rx_tx_packet_T_Encaps_L2 # to detect presence of L2 in SRH payload - p = Ether(src='00:11:22:33:44:55', dst='00:55:44:33:22:11') + p = Ether(src="00:11:22:33:44:55", dst="00:55:44:33:22:11") etype = 0x8137 # IPX if vlan: # add 802.1q layer @@ -695,8 +743,7 @@ class TestSRv6Ad(VppTestCase): p.type = etype return p - def create_packet_header_IPv6_SRH_L2(self, srcaddr, sidlist, segleft, - vlan=0): + def create_packet_header_IPv6_SRH_L2(self, srcaddr, sidlist, segleft, vlan=0): """Create packet header: L2 encapsulated in SRv6: IPv6 header with SRH, L2 @@ -708,7 +755,7 @@ class TestSRv6Ad(VppTestCase): IPv6 source address is set to srcaddr IPv6 destination address is set to sidlist[segleft] """ - eth = Ether(src='00:11:22:33:44:55', dst='00:55:44:33:22:11') + eth = Ether(src="00:11:22:33:44:55", dst="00:55:44:33:22:11") etype = 0x8137 # IPX if vlan: # add 802.1q layer @@ -716,15 +763,15 @@ class TestSRv6Ad(VppTestCase): else: eth.type = etype - p = IPv6(src=srcaddr, dst=sidlist[segleft]) / \ - IPv6ExtHdrSegmentRouting(addresses=sidlist, - segleft=segleft, nh=143) / \ - eth + p = ( + IPv6(src=srcaddr, dst=sidlist[segleft]) + / IPv6ExtHdrSegmentRouting(addresses=sidlist, segleft=segleft, nh=143) + / eth + ) return p def get_payload_info(self, packet): - """ Extract the payload_info from the packet - """ + """Extract the payload_info from the packet""" # in most cases, payload_info is in packet[Raw] # but packet[Raw] gives the complete payload # (incl L2 header) for the T.Encaps L2 case @@ -736,7 +783,8 @@ class TestSRv6Ad(VppTestCase): # take packet[Raw], convert it to an Ether layer # and then extract Raw from it payload_info = self.payload_to_info( - Ether(scapy.compat.raw(packet[Raw]))[Raw]) + Ether(scapy.compat.raw(packet[Raw]))[Raw] + ) return payload_info @@ -749,8 +797,10 @@ class TestSRv6Ad(VppTestCase): :param capture: captured packets :param compare_func: function to compare in and out packet """ - self.logger.info("Verifying capture on interface %s using function %s" - % (dst_if.name, compare_func.__name__)) + self.logger.info( + "Verifying capture on interface %s using function %s" + % (dst_if.name, compare_func.__name__) + ) last_info = dict() for i in self.pg_interfaces: @@ -763,19 +813,19 @@ class TestSRv6Ad(VppTestCase): payload_info = self.get_payload_info(packet) packet_index = payload_info.index - self.logger.debug("Verifying packet with index %d" - % (packet_index)) + self.logger.debug("Verifying packet with index %d" % (packet_index)) # packet should have arrived on the expected interface self.assertEqual(payload_info.dst, dst_sw_if_index) self.logger.debug( - "Got packet on interface %s: src=%u (idx=%u)" % - (dst_if.name, payload_info.src, packet_index)) + "Got packet on interface %s: src=%u (idx=%u)" + % (dst_if.name, payload_info.src, packet_index) + ) # search for payload_info with same src and dst if_index # this will give us the transmitted packet next_info = self.get_next_packet_info_for_interface2( - payload_info.src, dst_sw_if_index, - last_info[payload_info.src]) + payload_info.src, dst_sw_if_index, last_info[payload_info.src] + ) last_info[payload_info.src] = next_info # next_info should not be None self.assertTrue(next_info is not None) @@ -784,8 +834,9 @@ class TestSRv6Ad(VppTestCase): # data field of next_info contains the tx packet txed_packet = next_info.data - self.logger.debug(ppp("Transmitted packet:", - txed_packet)) # ppp=Pretty Print Packet + self.logger.debug( + ppp("Transmitted packet:", txed_packet) + ) # ppp=Pretty Print Packet self.logger.debug(ppp("Received packet:", packet)) @@ -799,11 +850,14 @@ class TestSRv6Ad(VppTestCase): # have all expected packets arrived? for i in self.pg_interfaces: remaining_packet = self.get_next_packet_info_for_interface2( - i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index]) - self.assertTrue(remaining_packet is None, - "Interface %s: Packet expected from interface %s " - "didn't arrive" % (dst_if.name, i.name)) + i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index] + ) + self.assertTrue( + remaining_packet is None, + "Interface %s: Packet expected from interface %s " + "didn't arrive" % (dst_if.name, i.name), + ) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_srv6_ad_flow.py b/test/test_srv6_ad_flow.py index 6b4ec19a31b..4b274c92232 100644 --- a/test/test_srv6_ad_flow.py +++ b/test/test_srv6_ad_flow.py @@ -18,7 +18,7 @@ from util import ppp class TestSRv6AdFlow(VppTestCase): - """ SRv6 Flow-based Dynamic Proxy plugin Test Case """ + """SRv6 Flow-based Dynamic Proxy plugin Test Case""" @classmethod def setUpClass(self): @@ -29,8 +29,7 @@ class TestSRv6AdFlow(VppTestCase): super(TestSRv6AdFlow, cls).tearDownClass() def setUp(self): - """ Perform test setup before each test case. - """ + """Perform test setup before each test case.""" super(TestSRv6AdFlow, self).setUp() # packet sizes, inclusive L2 overhead @@ -40,17 +39,15 @@ class TestSRv6AdFlow(VppTestCase): self.reset_packet_infos() def tearDown(self): - """ Clean up test setup after each test case. - """ + """Clean up test setup after each test case.""" self.teardown_interfaces() super(TestSRv6AdFlow, self).tearDown() - def configure_interface(self, - interface, - ipv6=False, ipv4=False, - ipv6_table_id=0, ipv4_table_id=0): - """ Configure interface. + def configure_interface( + self, interface, ipv6=False, ipv4=False, ipv6_table_id=0, ipv4_table_id=0 + ): + """Configure interface. :param ipv6: configure IPv6 on interface :param ipv4: configure IPv4 on interface :param ipv6_table_id: FIB table_id for IPv6 @@ -69,9 +66,8 @@ class TestSRv6AdFlow(VppTestCase): interface.resolve_arp() interface.admin_up() - def setup_interfaces(self, ipv6=[], ipv4=[], - ipv6_table_id=[], ipv4_table_id=[]): - """ Create and configure interfaces. + def setup_interfaces(self, ipv6=[], ipv4=[], ipv6_table_id=[], ipv4_table_id=[]): + """Create and configure interfaces. :param ipv6: list of interface IPv6 capabilities :param ipv4: list of interface IPv4 capabilities @@ -106,9 +102,9 @@ class TestSRv6AdFlow(VppTestCase): # setup all interfaces for i in range(count): intf = self.pg_interfaces[i] - self.configure_interface(intf, - ipv6[i], ipv4[i], - ipv6_table_id[i], ipv4_table_id[i]) + self.configure_interface( + intf, ipv6[i], ipv4[i], ipv6_table_id[i], ipv4_table_id[i] + ) if any(ipv6): self.logger.debug(self.vapi.cli("show ip6 neighbors")) @@ -120,8 +116,7 @@ class TestSRv6AdFlow(VppTestCase): return self.pg_interfaces def teardown_interfaces(self): - """ Unconfigure and bring down interface. - """ + """Unconfigure and bring down interface.""" self.logger.debug("Tearing down interfaces") # tear down all interfaces # AFAIK they cannot be deleted @@ -133,10 +128,9 @@ class TestSRv6AdFlow(VppTestCase): i.set_table_ip6(0) def test_SRv6_End_AD_IPv6(self): - """ Test SRv6 End.AD behavior with IPv6 traffic. - """ - self.src_addr = 'a0::' - self.sid_list = ['a1::', 'a2::a6', 'a3::'] + """Test SRv6 End.AD behavior with IPv6 traffic.""" + self.src_addr = "a0::" + self.sid_list = ["a1::", "a2::a6", "a3::"] self.test_sid_index = 1 # send traffic to one destination interface @@ -144,19 +138,32 @@ class TestSRv6AdFlow(VppTestCase): self.setup_interfaces(ipv6=[True, True]) # configure route to next segment - route = VppIpRoute(self, self.sid_list[self.test_sid_index + 1], 128, - [VppRoutePath(self.pg0.remote_ip6, - self.pg0.sw_if_index, - proto=DpoProto.DPO_PROTO_IP6)]) + route = VppIpRoute( + self, + self.sid_list[self.test_sid_index + 1], + 128, + [ + VppRoutePath( + self.pg0.remote_ip6, + self.pg0.sw_if_index, + proto=DpoProto.DPO_PROTO_IP6, + ) + ], + ) route.add_vpp_config() # configure SRv6 localSID behavior - cli_str = "sr localsid address " + \ - self.sid_list[self.test_sid_index] + \ - " behavior end.ad.flow" + \ - " nh " + self.pg1.remote_ip6 + \ - " oif " + self.pg1.name + \ - " iif " + self.pg1.name + cli_str = ( + "sr localsid address " + + self.sid_list[self.test_sid_index] + + " behavior end.ad.flow" + + " nh " + + self.pg1.remote_ip6 + + " oif " + + self.pg1.name + + " iif " + + self.pg1.name + ) self.vapi.cli(cli_str) # log the localsids @@ -169,15 +176,18 @@ class TestSRv6AdFlow(VppTestCase): packet_header1 = self.create_packet_header_IPv6_SRH_IPv6( srcaddr=self.src_addr, sidlist=self.sid_list[::-1], - segleft=len(self.sid_list) - self.test_sid_index - 1) + segleft=len(self.sid_list) - self.test_sid_index - 1, + ) # generate packets (pg0->pg1) - pkts1 = self.create_stream(self.pg0, self.pg1, packet_header1, - self.pg_packet_sizes, count) + pkts1 = self.create_stream( + self.pg0, self.pg1, packet_header1, self.pg_packet_sizes, count + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg0, pkts1, self.pg1, - self.compare_rx_tx_packet_End_AD_IPv6_out) + self.send_and_verify_pkts( + self.pg0, pkts1, self.pg1, self.compare_rx_tx_packet_End_AD_IPv6_out + ) # log the localsid counters self.logger.info(self.vapi.cli("show sr localsid")) @@ -186,26 +196,27 @@ class TestSRv6AdFlow(VppTestCase): packet_header2 = self.create_packet_header_IPv6() # generate returning packets (pg1->pg0) - pkts2 = self.create_stream(self.pg1, self.pg0, packet_header2, - self.pg_packet_sizes, count) + pkts2 = self.create_stream( + self.pg1, self.pg0, packet_header2, self.pg_packet_sizes, count + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg1, pkts2, self.pg0, - self.compare_rx_tx_packet_End_AD_IPv6_in) + self.send_and_verify_pkts( + self.pg1, pkts2, self.pg0, self.compare_rx_tx_packet_End_AD_IPv6_in + ) # log the localsid counters self.logger.info(self.vapi.cli("show sr localsid")) # remove SRv6 localSIDs - cli_str = "sr localsid del address " + \ - self.sid_list[self.test_sid_index] + cli_str = "sr localsid del address " + self.sid_list[self.test_sid_index] self.vapi.cli(cli_str) # cleanup interfaces self.teardown_interfaces() def compare_rx_tx_packet_End_AD_IPv6_out(self, tx_pkt, rx_pkt): - """ Compare input and output packet after passing End.AD with IPv6 + """Compare input and output packet after passing End.AD with IPv6 :param tx_pkt: transmitted packet :param rx_pkt: received packet @@ -230,7 +241,7 @@ class TestSRv6AdFlow(VppTestCase): self.logger.debug("packet verification: SUCCESS") def compare_rx_tx_packet_End_AD_IPv6_in(self, tx_pkt, rx_pkt): - """ Compare input and output packet after passing End.AD + """Compare input and output packet after passing End.AD :param tx_pkt: transmitted packet :param rx_pkt: received packet @@ -251,8 +262,7 @@ class TestSRv6AdFlow(VppTestCase): # rx'ed seglist should be equal to SID-list in reversed order self.assertEqual(rx_srh.addresses, self.sid_list[::-1]) # segleft should be equal to previous segleft value minus 1 - self.assertEqual(rx_srh.segleft, - len(self.sid_list) - self.test_sid_index - 2) + self.assertEqual(rx_srh.segleft, len(self.sid_list) - self.test_sid_index - 2) # lastentry should be equal to the SID-list length minus 1 self.assertEqual(rx_srh.lastentry, len(self.sid_list) - 1) @@ -267,10 +277,9 @@ class TestSRv6AdFlow(VppTestCase): self.logger.debug("packet verification: SUCCESS") def test_SRv6_End_AD_IPv4(self): - """ Test SRv6 End.AD behavior with IPv4 traffic. - """ - self.src_addr = 'a0::' - self.sid_list = ['a1::', 'a2::a4', 'a3::'] + """Test SRv6 End.AD behavior with IPv4 traffic.""" + self.src_addr = "a0::" + self.sid_list = ["a1::", "a2::a4", "a3::"] self.test_sid_index = 1 # send traffic to one destination interface @@ -278,19 +287,32 @@ class TestSRv6AdFlow(VppTestCase): self.setup_interfaces(ipv6=[True, False], ipv4=[False, True]) # configure route to next segment - route = VppIpRoute(self, self.sid_list[self.test_sid_index + 1], 128, - [VppRoutePath(self.pg0.remote_ip6, - self.pg0.sw_if_index, - proto=DpoProto.DPO_PROTO_IP6)]) + route = VppIpRoute( + self, + self.sid_list[self.test_sid_index + 1], + 128, + [ + VppRoutePath( + self.pg0.remote_ip6, + self.pg0.sw_if_index, + proto=DpoProto.DPO_PROTO_IP6, + ) + ], + ) route.add_vpp_config() # configure SRv6 localSID behavior - cli_str = "sr localsid address " + \ - self.sid_list[self.test_sid_index] + \ - " behavior end.ad.flow" + \ - " nh " + self.pg1.remote_ip4 + \ - " oif " + self.pg1.name + \ - " iif " + self.pg1.name + cli_str = ( + "sr localsid address " + + self.sid_list[self.test_sid_index] + + " behavior end.ad.flow" + + " nh " + + self.pg1.remote_ip4 + + " oif " + + self.pg1.name + + " iif " + + self.pg1.name + ) self.vapi.cli(cli_str) # log the localsids @@ -303,15 +325,18 @@ class TestSRv6AdFlow(VppTestCase): packet_header1 = self.create_packet_header_IPv6_SRH_IPv4( srcaddr=self.src_addr, sidlist=self.sid_list[::-1], - segleft=len(self.sid_list) - self.test_sid_index - 1) + segleft=len(self.sid_list) - self.test_sid_index - 1, + ) # generate packets (pg0->pg1) - pkts1 = self.create_stream(self.pg0, self.pg1, packet_header1, - self.pg_packet_sizes, count) + pkts1 = self.create_stream( + self.pg0, self.pg1, packet_header1, self.pg_packet_sizes, count + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg0, pkts1, self.pg1, - self.compare_rx_tx_packet_End_AD_IPv4_out) + self.send_and_verify_pkts( + self.pg0, pkts1, self.pg1, self.compare_rx_tx_packet_End_AD_IPv4_out + ) # log the localsid counters self.logger.info(self.vapi.cli("show sr localsid")) @@ -320,26 +345,27 @@ class TestSRv6AdFlow(VppTestCase): packet_header2 = self.create_packet_header_IPv4() # generate returning packets (pg1->pg0) - pkts2 = self.create_stream(self.pg1, self.pg0, packet_header2, - self.pg_packet_sizes, count) + pkts2 = self.create_stream( + self.pg1, self.pg0, packet_header2, self.pg_packet_sizes, count + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg1, pkts2, self.pg0, - self.compare_rx_tx_packet_End_AD_IPv4_in) + self.send_and_verify_pkts( + self.pg1, pkts2, self.pg0, self.compare_rx_tx_packet_End_AD_IPv4_in + ) # log the localsid counters self.logger.info(self.vapi.cli("show sr localsid")) # remove SRv6 localSIDs - cli_str = "sr localsid del address " + \ - self.sid_list[self.test_sid_index] + cli_str = "sr localsid del address " + self.sid_list[self.test_sid_index] self.vapi.cli(cli_str) # cleanup interfaces self.teardown_interfaces() def compare_rx_tx_packet_End_AD_IPv4_out(self, tx_pkt, rx_pkt): - """ Compare input and output packet after passing End.AD with IPv4 + """Compare input and output packet after passing End.AD with IPv4 :param tx_pkt: transmitted packet :param rx_pkt: received packet @@ -369,7 +395,7 @@ class TestSRv6AdFlow(VppTestCase): self.logger.debug("packet verification: SUCCESS") def compare_rx_tx_packet_End_AD_IPv4_in(self, tx_pkt, rx_pkt): - """ Compare input and output packet after passing End.AD + """Compare input and output packet after passing End.AD :param tx_pkt: transmitted packet :param rx_pkt: received packet @@ -390,8 +416,7 @@ class TestSRv6AdFlow(VppTestCase): # rx'ed seglist should be equal to SID-list in reversed order self.assertEqual(rx_srh.addresses, self.sid_list[::-1]) # segleft should be equal to previous segleft value minus 1 - self.assertEqual(rx_srh.segleft, - len(self.sid_list) - self.test_sid_index - 2) + self.assertEqual(rx_srh.segleft, len(self.sid_list) - self.test_sid_index - 2) # lastentry should be equal to the SID-list length minus 1 self.assertEqual(rx_srh.lastentry, len(self.sid_list) - 1) @@ -408,8 +433,7 @@ class TestSRv6AdFlow(VppTestCase): self.logger.debug("packet verification: SUCCESS") - def create_stream(self, src_if, dst_if, packet_header, packet_sizes, - count): + def create_stream(self, src_if, dst_if, packet_header, packet_sizes, count): """Create SRv6 input packet stream for defined interface. :param VppInterface src_if: Interface to create packet stream for @@ -426,15 +450,17 @@ class TestSRv6AdFlow(VppTestCase): pkts = [] for i in range(0, count - 1): payload_info = self.create_packet_info(src_if, dst_if) - self.logger.debug( - "Creating packet with index %d" % (payload_info.index)) + self.logger.debug("Creating packet with index %d" % (payload_info.index)) payload = self.info_to_payload(payload_info) # add L2 header if not yet provided in packet_header - if packet_header.getlayer(0).name == 'Ethernet': + if packet_header.getlayer(0).name == "Ethernet": p = packet_header / Raw(payload) else: - p = Ether(dst=src_if.local_mac, src=src_if.remote_mac) / \ - packet_header / Raw(payload) + p = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / packet_header + / Raw(payload) + ) size = packet_sizes[i % len(packet_sizes)] self.logger.debug("Packet size %d" % (size)) self.extend_packet(p, size) @@ -477,8 +503,9 @@ class TestSRv6AdFlow(VppTestCase): # verify captured packets self.verify_captured_pkts(output, capture, compare_func) - def create_packet_header_IPv6(self, saddr='1234::1', daddr='4321::1', - sport=1234, dport=1234): + def create_packet_header_IPv6( + self, saddr="1234::1", daddr="4321::1", sport=1234, dport=1234 + ): """Create packet header: IPv6 header, UDP header :param dst: IPv6 destination address @@ -491,9 +518,16 @@ class TestSRv6AdFlow(VppTestCase): p = IPv6(src=saddr, dst=daddr) / UDP(sport=sport, dport=dport) return p - def create_packet_header_IPv6_SRH_IPv6(self, srcaddr, sidlist, segleft, - insrc='1234::1', indst='4321::1', - sport=1234, dport=1234): + def create_packet_header_IPv6_SRH_IPv6( + self, + srcaddr, + sidlist, + segleft, + insrc="1234::1", + indst="4321::1", + sport=1234, + dport=1234, + ): """Create packet header: IPv6 encapsulated in SRv6: IPv6 header with SRH, IPv6 header, UDP header @@ -508,11 +542,12 @@ class TestSRv6AdFlow(VppTestCase): UDP source port and destination port are 1234 """ - p = IPv6(src=srcaddr, dst=sidlist[segleft]) / \ - IPv6ExtHdrSegmentRouting(addresses=sidlist, - segleft=segleft, nh=41) / \ - IPv6(src=insrc, dst=indst) / \ - UDP(sport=sport, dport=dport) + p = ( + IPv6(src=srcaddr, dst=sidlist[segleft]) + / IPv6ExtHdrSegmentRouting(addresses=sidlist, segleft=segleft, nh=41) + / IPv6(src=insrc, dst=indst) + / UDP(sport=sport, dport=dport) + ) return p def create_packet_header_IPv4(self): @@ -525,7 +560,7 @@ class TestSRv6AdFlow(VppTestCase): UDP source port and destination port are 1234 """ - p = IP(src='123.1.1.1', dst='124.1.1.1') / UDP(sport=1234, dport=1234) + p = IP(src="123.1.1.1", dst="124.1.1.1") / UDP(sport=1234, dport=1234) return p def create_packet_header_IPv6_SRH_IPv4(self, srcaddr, sidlist, segleft): @@ -543,16 +578,16 @@ class TestSRv6AdFlow(VppTestCase): UDP source port and destination port are 1234 """ - p = IPv6(src=srcaddr, dst=sidlist[segleft]) / \ - IPv6ExtHdrSegmentRouting(addresses=sidlist, - segleft=segleft, nh=4) / \ - IP(src='123.1.1.1', dst='124.1.1.1') / \ - UDP(sport=1234, dport=1234) + p = ( + IPv6(src=srcaddr, dst=sidlist[segleft]) + / IPv6ExtHdrSegmentRouting(addresses=sidlist, segleft=segleft, nh=4) + / IP(src="123.1.1.1", dst="124.1.1.1") + / UDP(sport=1234, dport=1234) + ) return p def get_payload_info(self, packet): - """ Extract the payload_info from the packet - """ + """Extract the payload_info from the packet""" # in most cases, payload_info is in packet[Raw] # but packet[Raw] gives the complete payload # (incl L2 header) for the T.Encaps L2 case @@ -564,7 +599,8 @@ class TestSRv6AdFlow(VppTestCase): # take packet[Raw], convert it to an Ether layer # and then extract Raw from it payload_info = self.payload_to_info( - Ether(scapy.compat.raw(packet[Raw]))[Raw]) + Ether(scapy.compat.raw(packet[Raw]))[Raw] + ) return payload_info @@ -577,8 +613,10 @@ class TestSRv6AdFlow(VppTestCase): :param capture: captured packets :param compare_func: function to compare in and out packet """ - self.logger.info("Verifying capture on interface %s using function %s" - % (dst_if.name, compare_func.__name__)) + self.logger.info( + "Verifying capture on interface %s using function %s" + % (dst_if.name, compare_func.__name__) + ) last_info = dict() for i in self.pg_interfaces: @@ -591,19 +629,19 @@ class TestSRv6AdFlow(VppTestCase): payload_info = self.get_payload_info(packet) packet_index = payload_info.index - self.logger.debug("Verifying packet with index %d" - % (packet_index)) + self.logger.debug("Verifying packet with index %d" % (packet_index)) # packet should have arrived on the expected interface self.assertEqual(payload_info.dst, dst_sw_if_index) self.logger.debug( - "Got packet on interface %s: src=%u (idx=%u)" % - (dst_if.name, payload_info.src, packet_index)) + "Got packet on interface %s: src=%u (idx=%u)" + % (dst_if.name, payload_info.src, packet_index) + ) # search for payload_info with same src and dst if_index # this will give us the transmitted packet next_info = self.get_next_packet_info_for_interface2( - payload_info.src, dst_sw_if_index, - last_info[payload_info.src]) + payload_info.src, dst_sw_if_index, last_info[payload_info.src] + ) last_info[payload_info.src] = next_info # next_info should not be None self.assertTrue(next_info is not None) @@ -612,8 +650,9 @@ class TestSRv6AdFlow(VppTestCase): # data field of next_info contains the tx packet txed_packet = next_info.data - self.logger.debug(ppp("Transmitted packet:", - txed_packet)) # ppp=Pretty Print Packet + self.logger.debug( + ppp("Transmitted packet:", txed_packet) + ) # ppp=Pretty Print Packet self.logger.debug(ppp("Received packet:", packet)) @@ -627,11 +666,14 @@ class TestSRv6AdFlow(VppTestCase): # have all expected packets arrived? for i in self.pg_interfaces: remaining_packet = self.get_next_packet_info_for_interface2( - i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index]) - self.assertTrue(remaining_packet is None, - "Interface %s: Packet expected from interface %s " - "didn't arrive" % (dst_if.name, i.name)) + i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index] + ) + self.assertTrue( + remaining_packet is None, + "Interface %s: Packet expected from interface %s " + "didn't arrive" % (dst_if.name, i.name), + ) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_srv6_as.py b/test/test_srv6_as.py index 947633e7fab..87cafd1e5ed 100644 --- a/test/test_srv6_as.py +++ b/test/test_srv6_as.py @@ -6,8 +6,14 @@ from socket import AF_INET6 from framework import VppTestCase, VppTestRunner from vpp_ip_route import VppIpRoute, VppRoutePath, FibPathProto, VppIpTable -from vpp_srv6 import SRv6LocalSIDBehaviors, VppSRv6LocalSID, VppSRv6Policy, \ - SRv6PolicyType, VppSRv6Steering, SRv6PolicySteeringTypes +from vpp_srv6 import ( + SRv6LocalSIDBehaviors, + VppSRv6LocalSID, + VppSRv6Policy, + SRv6PolicyType, + VppSRv6Steering, + SRv6PolicySteeringTypes, +) import scapy.compat from scapy.packet import Raw @@ -19,7 +25,7 @@ from util import ppp class TestSRv6As(VppTestCase): - """ SRv6 Static Proxy plugin Test Case """ + """SRv6 Static Proxy plugin Test Case""" @classmethod def setUpClass(self): @@ -30,8 +36,7 @@ class TestSRv6As(VppTestCase): super(TestSRv6As, cls).tearDownClass() def setUp(self): - """ Perform test setup before each test case. - """ + """Perform test setup before each test case.""" super(TestSRv6As, self).setUp() # packet sizes, inclusive L2 overhead @@ -41,17 +46,15 @@ class TestSRv6As(VppTestCase): self.reset_packet_infos() def tearDown(self): - """ Clean up test setup after each test case. - """ + """Clean up test setup after each test case.""" self.teardown_interfaces() super(TestSRv6As, self).tearDown() - def configure_interface(self, - interface, - ipv6=False, ipv4=False, - ipv6_table_id=0, ipv4_table_id=0): - """ Configure interface. + def configure_interface( + self, interface, ipv6=False, ipv4=False, ipv6_table_id=0, ipv4_table_id=0 + ): + """Configure interface. :param ipv6: configure IPv6 on interface :param ipv4: configure IPv4 on interface :param ipv6_table_id: FIB table_id for IPv6 @@ -70,9 +73,8 @@ class TestSRv6As(VppTestCase): interface.resolve_arp() interface.admin_up() - def setup_interfaces(self, ipv6=[], ipv4=[], - ipv6_table_id=[], ipv4_table_id=[]): - """ Create and configure interfaces. + def setup_interfaces(self, ipv6=[], ipv4=[], ipv6_table_id=[], ipv4_table_id=[]): + """Create and configure interfaces. :param ipv6: list of interface IPv6 capabilities :param ipv4: list of interface IPv4 capabilities @@ -107,9 +109,9 @@ class TestSRv6As(VppTestCase): # setup all interfaces for i in range(count): intf = self.pg_interfaces[i] - self.configure_interface(intf, - ipv6[i], ipv4[i], - ipv6_table_id[i], ipv4_table_id[i]) + self.configure_interface( + intf, ipv6[i], ipv4[i], ipv6_table_id[i], ipv4_table_id[i] + ) if any(ipv6): self.logger.debug(self.vapi.cli("show ip6 neighbors")) @@ -121,8 +123,7 @@ class TestSRv6As(VppTestCase): return self.pg_interfaces def teardown_interfaces(self): - """ Unconfigure and bring down interface. - """ + """Unconfigure and bring down interface.""" self.logger.debug("Tearing down interfaces") # tear down all interfaces # AFAIK they cannot be deleted @@ -134,75 +135,83 @@ class TestSRv6As(VppTestCase): i.set_table_ip6(0) def test_SRv6_End_AS_IPv6_noSRH(self): - """ Test SRv6 End.AS behavior with IPv6 traffic and no SRH rewrite. - """ + """Test SRv6 End.AS behavior with IPv6 traffic and no SRH rewrite.""" self.run_SRv6_End_AS_IPv6( - sid_list=['a1::', 'a2::a6', 'a3::'], + sid_list=["a1::", "a2::a6", "a3::"], test_sid_index=1, - rewrite_src_addr='a2::') + rewrite_src_addr="a2::", + ) def test_SRv6_End_AS_IPv6_SRH(self): - """ Test SRv6 End.AS behavior with IPv6 traffic and SRH rewrite. - """ + """Test SRv6 End.AS behavior with IPv6 traffic and SRH rewrite.""" self.run_SRv6_End_AS_IPv6( - sid_list=['a1::a6', 'a2::', 'a3::'], + sid_list=["a1::a6", "a2::", "a3::"], test_sid_index=0, - rewrite_src_addr='a1::') + rewrite_src_addr="a1::", + ) def test_SRv6_End_AS_IPv4_noSRH(self): - """ Test SRv6 End.AS behavior with IPv4 traffic and no SRH rewrite. - """ + """Test SRv6 End.AS behavior with IPv4 traffic and no SRH rewrite.""" self.run_SRv6_End_AS_IPv4( - sid_list=['a1::', 'a2::a6', 'a3::'], + sid_list=["a1::", "a2::a6", "a3::"], test_sid_index=1, - rewrite_src_addr='a2::') + rewrite_src_addr="a2::", + ) def test_SRv6_End_AS_IPv4_SRH(self): - """ Test SRv6 End.AS behavior with IPv4 traffic and SRH rewrite. - """ + """Test SRv6 End.AS behavior with IPv4 traffic and SRH rewrite.""" self.run_SRv6_End_AS_IPv4( - sid_list=['a1::a6', 'a2::', 'a3::'], + sid_list=["a1::a6", "a2::", "a3::"], test_sid_index=0, - rewrite_src_addr='a1::') + rewrite_src_addr="a1::", + ) def test_SRv6_End_AS_L2_noSRH(self): - """ Test SRv6 End.AS behavior with L2 traffic and no SRH rewrite. - """ + """Test SRv6 End.AS behavior with L2 traffic and no SRH rewrite.""" self.run_SRv6_End_AS_L2( - sid_list=['a1::', 'a2::a6', 'a3::'], + sid_list=["a1::", "a2::a6", "a3::"], test_sid_index=1, - rewrite_src_addr='a2::') + rewrite_src_addr="a2::", + ) def test_SRv6_End_AS_L2_SRH(self): - """ Test SRv6 End.AS behavior with L2 traffic and SRH rewrite. - """ + """Test SRv6 End.AS behavior with L2 traffic and SRH rewrite.""" self.run_SRv6_End_AS_L2( - sid_list=['a1::a6', 'a2::', 'a3::'], + sid_list=["a1::a6", "a2::", "a3::"], test_sid_index=0, - rewrite_src_addr='a1::') + rewrite_src_addr="a1::", + ) def run_SRv6_End_AS_L2(self, sid_list, test_sid_index, rewrite_src_addr): - """ Run SRv6 End.AS test with L2 traffic. - """ + """Run SRv6 End.AS test with L2 traffic.""" self.rewrite_src_addr = rewrite_src_addr - self.rewrite_sid_list = sid_list[test_sid_index + 1::] + self.rewrite_sid_list = sid_list[test_sid_index + 1 : :] # send traffic to one destination interface # source and destination interfaces are IPv6 only self.setup_interfaces(ipv6=[True, False]) # configure route to next segment - route = VppIpRoute(self, sid_list[test_sid_index + 1], 128, - [VppRoutePath(self.pg0.remote_ip6, - self.pg0.sw_if_index)]) + route = VppIpRoute( + self, + sid_list[test_sid_index + 1], + 128, + [VppRoutePath(self.pg0.remote_ip6, self.pg0.sw_if_index)], + ) route.add_vpp_config() # configure SRv6 localSID behavior - cli_str = "sr localsid address " + sid_list[test_sid_index] \ - + " behavior end.as" \ - + " oif " + self.pg1.name \ - + " iif " + self.pg1.name \ - + " src " + self.rewrite_src_addr + cli_str = ( + "sr localsid address " + + sid_list[test_sid_index] + + " behavior end.as" + + " oif " + + self.pg1.name + + " iif " + + self.pg1.name + + " src " + + self.rewrite_src_addr + ) for s in self.rewrite_sid_list: cli_str += " next " + s self.vapi.cli(cli_str) @@ -215,17 +224,18 @@ class TestSRv6As(VppTestCase): # prepare L2 in SRv6 headers packet_header1 = self.create_packet_header_IPv6_SRH_L2( - sidlist=sid_list[::-1], - segleft=len(sid_list) - test_sid_index - 1, - vlan=0) + sidlist=sid_list[::-1], segleft=len(sid_list) - test_sid_index - 1, vlan=0 + ) # generate packets (pg0->pg1) - pkts1 = self.create_stream(self.pg0, self.pg1, packet_header1, - self.pg_packet_sizes, count) + pkts1 = self.create_stream( + self.pg0, self.pg1, packet_header1, self.pg_packet_sizes, count + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg0, pkts1, self.pg1, - self.compare_rx_tx_packet_End_AS_L2_out) + self.send_and_verify_pkts( + self.pg0, pkts1, self.pg1, self.compare_rx_tx_packet_End_AS_L2_out + ) # log the localsid counters self.logger.info(self.vapi.cli("show sr localsid")) @@ -234,12 +244,14 @@ class TestSRv6As(VppTestCase): packet_header2 = self.create_packet_header_L2() # generate returning packets (pg1->pg0) - pkts2 = self.create_stream(self.pg1, self.pg0, packet_header2, - self.pg_packet_sizes, count) + pkts2 = self.create_stream( + self.pg1, self.pg0, packet_header2, self.pg_packet_sizes, count + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg1, pkts2, self.pg0, - self.compare_rx_tx_packet_End_AS_L2_in) + self.send_and_verify_pkts( + self.pg1, pkts2, self.pg0, self.compare_rx_tx_packet_End_AS_L2_in + ) # log the localsid counters self.logger.info(self.vapi.cli("show sr localsid")) @@ -251,28 +263,37 @@ class TestSRv6As(VppTestCase): self.teardown_interfaces() def run_SRv6_End_AS_IPv6(self, sid_list, test_sid_index, rewrite_src_addr): - """ Run SRv6 End.AS test with IPv6 traffic. - """ + """Run SRv6 End.AS test with IPv6 traffic.""" self.rewrite_src_addr = rewrite_src_addr - self.rewrite_sid_list = sid_list[test_sid_index + 1::] + self.rewrite_sid_list = sid_list[test_sid_index + 1 : :] # send traffic to one destination interface # source and destination interfaces are IPv6 only self.setup_interfaces(ipv6=[True, True]) # configure route to next segment - route = VppIpRoute(self, sid_list[test_sid_index + 1], 128, - [VppRoutePath(self.pg0.remote_ip6, - self.pg0.sw_if_index)]) + route = VppIpRoute( + self, + sid_list[test_sid_index + 1], + 128, + [VppRoutePath(self.pg0.remote_ip6, self.pg0.sw_if_index)], + ) route.add_vpp_config() # configure SRv6 localSID behavior - cli_str = "sr localsid address " + sid_list[test_sid_index] \ - + " behavior end.as" \ - + " nh " + self.pg1.remote_ip6 \ - + " oif " + self.pg1.name \ - + " iif " + self.pg1.name \ - + " src " + self.rewrite_src_addr + cli_str = ( + "sr localsid address " + + sid_list[test_sid_index] + + " behavior end.as" + + " nh " + + self.pg1.remote_ip6 + + " oif " + + self.pg1.name + + " iif " + + self.pg1.name + + " src " + + self.rewrite_src_addr + ) for s in self.rewrite_sid_list: cli_str += " next " + s self.vapi.cli(cli_str) @@ -285,16 +306,18 @@ class TestSRv6As(VppTestCase): # prepare IPv6 in SRv6 headers packet_header1 = self.create_packet_header_IPv6_SRH_IPv6( - sidlist=sid_list[::-1], - segleft=len(sid_list) - test_sid_index - 1) + sidlist=sid_list[::-1], segleft=len(sid_list) - test_sid_index - 1 + ) # generate packets (pg0->pg1) - pkts1 = self.create_stream(self.pg0, self.pg1, packet_header1, - self.pg_packet_sizes, count) + pkts1 = self.create_stream( + self.pg0, self.pg1, packet_header1, self.pg_packet_sizes, count + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg0, pkts1, self.pg1, - self.compare_rx_tx_packet_End_AS_IPv6_out) + self.send_and_verify_pkts( + self.pg0, pkts1, self.pg1, self.compare_rx_tx_packet_End_AS_IPv6_out + ) # log the localsid counters self.logger.info(self.vapi.cli("show sr localsid")) @@ -303,12 +326,14 @@ class TestSRv6As(VppTestCase): packet_header2 = self.create_packet_header_IPv6() # generate returning packets (pg1->pg0) - pkts2 = self.create_stream(self.pg1, self.pg0, packet_header2, - self.pg_packet_sizes, count) + pkts2 = self.create_stream( + self.pg1, self.pg0, packet_header2, self.pg_packet_sizes, count + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg1, pkts2, self.pg0, - self.compare_rx_tx_packet_End_AS_IPv6_in) + self.send_and_verify_pkts( + self.pg1, pkts2, self.pg0, self.compare_rx_tx_packet_End_AS_IPv6_in + ) # log the localsid counters self.logger.info(self.vapi.cli("show sr localsid")) @@ -320,28 +345,37 @@ class TestSRv6As(VppTestCase): self.teardown_interfaces() def run_SRv6_End_AS_IPv4(self, sid_list, test_sid_index, rewrite_src_addr): - """ Run SRv6 End.AS test with IPv4 traffic. - """ + """Run SRv6 End.AS test with IPv4 traffic.""" self.rewrite_src_addr = rewrite_src_addr - self.rewrite_sid_list = sid_list[test_sid_index + 1::] + self.rewrite_sid_list = sid_list[test_sid_index + 1 : :] # send traffic to one destination interface # source and destination interfaces are IPv6 only self.setup_interfaces(ipv6=[True, False], ipv4=[True, True]) # configure route to next segment - route = VppIpRoute(self, sid_list[test_sid_index + 1], 128, - [VppRoutePath(self.pg0.remote_ip6, - self.pg0.sw_if_index)]) + route = VppIpRoute( + self, + sid_list[test_sid_index + 1], + 128, + [VppRoutePath(self.pg0.remote_ip6, self.pg0.sw_if_index)], + ) route.add_vpp_config() # configure SRv6 localSID behavior - cli_str = "sr localsid address " + sid_list[test_sid_index] \ - + " behavior end.as" \ - + " nh " + self.pg1.remote_ip4 \ - + " oif " + self.pg1.name \ - + " iif " + self.pg1.name \ - + " src " + self.rewrite_src_addr + cli_str = ( + "sr localsid address " + + sid_list[test_sid_index] + + " behavior end.as" + + " nh " + + self.pg1.remote_ip4 + + " oif " + + self.pg1.name + + " iif " + + self.pg1.name + + " src " + + self.rewrite_src_addr + ) for s in self.rewrite_sid_list: cli_str += " next " + s self.vapi.cli(cli_str) @@ -354,16 +388,18 @@ class TestSRv6As(VppTestCase): # prepare IPv4 in SRv6 headers packet_header1 = self.create_packet_header_IPv6_SRH_IPv4( - sidlist=sid_list[::-1], - segleft=len(sid_list) - test_sid_index - 1) + sidlist=sid_list[::-1], segleft=len(sid_list) - test_sid_index - 1 + ) # generate packets (pg0->pg1) - pkts1 = self.create_stream(self.pg0, self.pg1, packet_header1, - self.pg_packet_sizes, count) + pkts1 = self.create_stream( + self.pg0, self.pg1, packet_header1, self.pg_packet_sizes, count + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg0, pkts1, self.pg1, - self.compare_rx_tx_packet_End_AS_IPv4_out) + self.send_and_verify_pkts( + self.pg0, pkts1, self.pg1, self.compare_rx_tx_packet_End_AS_IPv4_out + ) # log the localsid counters self.logger.info(self.vapi.cli("show sr localsid")) @@ -372,12 +408,14 @@ class TestSRv6As(VppTestCase): packet_header2 = self.create_packet_header_IPv4() # generate returning packets (pg1->pg0) - pkts2 = self.create_stream(self.pg1, self.pg0, packet_header2, - self.pg_packet_sizes, count) + pkts2 = self.create_stream( + self.pg1, self.pg0, packet_header2, self.pg_packet_sizes, count + ) # send packets and verify received packets - self.send_and_verify_pkts(self.pg1, pkts2, self.pg0, - self.compare_rx_tx_packet_End_AS_IPv4_in) + self.send_and_verify_pkts( + self.pg1, pkts2, self.pg0, self.compare_rx_tx_packet_End_AS_IPv4_in + ) # log the localsid counters self.logger.info(self.vapi.cli("show sr localsid")) @@ -389,7 +427,7 @@ class TestSRv6As(VppTestCase): self.teardown_interfaces() def compare_rx_tx_packet_End_AS_IPv6_in(self, tx_pkt, rx_pkt): - """ Compare input and output packet after passing End.AS + """Compare input and output packet after passing End.AS :param tx_pkt: transmitted packet :param rx_pkt: received packet @@ -417,7 +455,7 @@ class TestSRv6As(VppTestCase): # rx'ed seglist should be equal to expected seglist self.assertEqual(rx_srh.addresses, tx_seglist) # segleft should be equal to size expected seglist-1 - self.assertEqual(rx_srh.segleft, len(tx_seglist)-1) + self.assertEqual(rx_srh.segleft, len(tx_seglist) - 1) # segleft should be equal to lastentry self.assertEqual(rx_srh.segleft, rx_srh.lastentry) # get payload @@ -438,7 +476,7 @@ class TestSRv6As(VppTestCase): self.logger.debug("packet verification: SUCCESS") def compare_rx_tx_packet_End_AS_IPv4_in(self, tx_pkt, rx_pkt): - """ Compare input and output packet after passing End.AS + """Compare input and output packet after passing End.AS :param tx_pkt: transmitted packet :param rx_pkt: received packet @@ -467,7 +505,7 @@ class TestSRv6As(VppTestCase): # rx'ed seglist should be equal to seglist self.assertEqual(rx_srh.addresses, tx_seglist) # segleft should be equal to size seglist-1 - self.assertEqual(rx_srh.segleft, len(tx_seglist)-1) + self.assertEqual(rx_srh.segleft, len(tx_seglist) - 1) # segleft should be equal to lastentry self.assertEqual(rx_srh.segleft, rx_srh.lastentry) payload = rx_srh.payload @@ -492,7 +530,7 @@ class TestSRv6As(VppTestCase): self.logger.debug("packet verification: SUCCESS") def compare_rx_tx_packet_End_AS_L2_in(self, tx_pkt, rx_pkt): - """ Compare input and output packet after passing End.AS + """Compare input and output packet after passing End.AS :param tx_pkt: transmitted packet :param rx_pkt: received packet @@ -520,7 +558,7 @@ class TestSRv6As(VppTestCase): # rx'ed seglist should be equal to seglist self.assertEqual(rx_srh.addresses, tx_seglist) # segleft should be equal to size seglist-1 - self.assertEqual(rx_srh.segleft, len(tx_seglist)-1) + self.assertEqual(rx_srh.segleft, len(tx_seglist) - 1) # segleft should be equal to lastentry self.assertEqual(rx_srh.segleft, rx_srh.lastentry) # nh should be "No Next Header" (143) @@ -539,7 +577,7 @@ class TestSRv6As(VppTestCase): self.logger.debug("packet verification: SUCCESS") def compare_rx_tx_packet_End_AS_IPv6_out(self, tx_pkt, rx_pkt): - """ Compare input and output packet after passing End.AS with IPv6 + """Compare input and output packet after passing End.AS with IPv6 :param tx_pkt: transmitted packet :param rx_pkt: received packet @@ -564,7 +602,7 @@ class TestSRv6As(VppTestCase): self.logger.debug("packet verification: SUCCESS") def compare_rx_tx_packet_End_AS_IPv4_out(self, tx_pkt, rx_pkt): - """ Compare input and output packet after passing End.AS with IPv4 + """Compare input and output packet after passing End.AS with IPv4 :param tx_pkt: transmitted packet :param rx_pkt: received packet @@ -594,7 +632,7 @@ class TestSRv6As(VppTestCase): self.logger.debug("packet verification: SUCCESS") def compare_rx_tx_packet_End_AS_L2_out(self, tx_pkt, rx_pkt): - """ Compare input and output packet after passing End.AS with L2 + """Compare input and output packet after passing End.AS with L2 :param tx_pkt: transmitted packet :param rx_pkt: received packet @@ -616,8 +654,7 @@ class TestSRv6As(VppTestCase): self.logger.debug("packet verification: SUCCESS") - def create_stream(self, src_if, dst_if, packet_header, packet_sizes, - count): + def create_stream(self, src_if, dst_if, packet_header, packet_sizes, count): """Create SRv6 input packet stream for defined interface. :param VppInterface src_if: Interface to create packet stream for @@ -632,19 +669,19 @@ class TestSRv6As(VppTestCase): """ self.logger.info("Creating packets") pkts = [] - for i in range(0, count-1): + for i in range(0, count - 1): payload_info = self.create_packet_info(src_if, dst_if) - self.logger.debug( - "Creating packet with index %d" % (payload_info.index)) + self.logger.debug("Creating packet with index %d" % (payload_info.index)) payload = self.info_to_payload(payload_info) # add L2 header if not yet provided in packet_header - if packet_header.getlayer(0).name == 'Ethernet': - p = (packet_header / - Raw(payload)) + if packet_header.getlayer(0).name == "Ethernet": + p = packet_header / Raw(payload) else: - p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - packet_header / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / packet_header + / Raw(payload) + ) size = packet_sizes[i % len(packet_sizes)] self.logger.debug("Packet size %d" % (size)) self.extend_packet(p, size) @@ -697,8 +734,7 @@ class TestSRv6As(VppTestCase): UDP source port and destination port are 1234 """ - p = (IPv6(src='1234::1', dst='4321::1') / - UDP(sport=1234, dport=1234)) + p = IPv6(src="1234::1", dst="4321::1") / UDP(sport=1234, dport=1234) return p def create_packet_header_IPv6_SRH_IPv6(self, sidlist, segleft): @@ -715,11 +751,12 @@ class TestSRv6As(VppTestCase): UDP source port and destination port are 1234 """ - p = (IPv6(src='5678::1', dst=sidlist[segleft]) / - IPv6ExtHdrSegmentRouting(addresses=sidlist, - segleft=segleft, nh=41) / - IPv6(src='1234::1', dst='4321::1') / - UDP(sport=1234, dport=1234)) + p = ( + IPv6(src="5678::1", dst=sidlist[segleft]) + / IPv6ExtHdrSegmentRouting(addresses=sidlist, segleft=segleft, nh=41) + / IPv6(src="1234::1", dst="4321::1") + / UDP(sport=1234, dport=1234) + ) return p def create_packet_header_IPv4(self): @@ -732,8 +769,7 @@ class TestSRv6As(VppTestCase): UDP source port and destination port are 1234 """ - p = (IP(src='123.1.1.1', dst='124.1.1.1') / - UDP(sport=1234, dport=1234)) + p = IP(src="123.1.1.1", dst="124.1.1.1") / UDP(sport=1234, dport=1234) return p def create_packet_header_IPv6_SRH_IPv4(self, sidlist, segleft): @@ -751,11 +787,12 @@ class TestSRv6As(VppTestCase): UDP source port and destination port are 1234 """ - p = (IPv6(src='1234::1', dst=sidlist[segleft]) / - IPv6ExtHdrSegmentRouting(addresses=sidlist, - segleft=segleft, nh=4) / - IP(src='123.1.1.1', dst='124.1.1.1') / - UDP(sport=1234, dport=1234)) + p = ( + IPv6(src="1234::1", dst=sidlist[segleft]) + / IPv6ExtHdrSegmentRouting(addresses=sidlist, segleft=segleft, nh=4) + / IP(src="123.1.1.1", dst="124.1.1.1") + / UDP(sport=1234, dport=1234) + ) return p def create_packet_header_L2(self, vlan=0): @@ -766,7 +803,7 @@ class TestSRv6As(VppTestCase): # Note: the dst addr ('00:55:44:33:22:11') is used in # the compare function compare_rx_tx_packet_T_Encaps_L2 # to detect presence of L2 in SRH payload - p = Ether(src='00:11:22:33:44:55', dst='00:55:44:33:22:11') + p = Ether(src="00:11:22:33:44:55", dst="00:55:44:33:22:11") etype = 0x8137 # IPX if vlan: # add 802.1q layer @@ -786,7 +823,7 @@ class TestSRv6As(VppTestCase): Outer IPv6 destination address is set to sidlist[segleft] IPv6 source address is 1234::1 """ - eth = Ether(src='00:11:22:33:44:55', dst='00:55:44:33:22:11') + eth = Ether(src="00:11:22:33:44:55", dst="00:55:44:33:22:11") etype = 0x8137 # IPX if vlan: # add 802.1q layer @@ -794,15 +831,15 @@ class TestSRv6As(VppTestCase): else: eth.type = etype - p = (IPv6(src='1234::1', dst=sidlist[segleft]) / - IPv6ExtHdrSegmentRouting(addresses=sidlist, - segleft=segleft, nh=143) / - eth) + p = ( + IPv6(src="1234::1", dst=sidlist[segleft]) + / IPv6ExtHdrSegmentRouting(addresses=sidlist, segleft=segleft, nh=143) + / eth + ) return p def get_payload_info(self, packet): - """ Extract the payload_info from the packet - """ + """Extract the payload_info from the packet""" # in most cases, payload_info is in packet[Raw] # but packet[Raw] gives the complete payload # (incl L2 header) for the T.Encaps L2 case @@ -814,7 +851,8 @@ class TestSRv6As(VppTestCase): # take packet[Raw], convert it to an Ether layer # and then extract Raw from it payload_info = self.payload_to_info( - Ether(scapy.compat.raw(packet[Raw]))[Raw]) + Ether(scapy.compat.raw(packet[Raw]))[Raw] + ) return payload_info @@ -827,8 +865,10 @@ class TestSRv6As(VppTestCase): :param capture: captured packets :param compare_func: function to compare in and out packet """ - self.logger.info("Verifying capture on interface %s using function %s" - % (dst_if.name, compare_func.__name__)) + self.logger.info( + "Verifying capture on interface %s using function %s" + % (dst_if.name, compare_func.__name__) + ) last_info = dict() for i in self.pg_interfaces: @@ -841,19 +881,19 @@ class TestSRv6As(VppTestCase): payload_info = self.get_payload_info(packet) packet_index = payload_info.index - self.logger.debug("Verifying packet with index %d" - % (packet_index)) + self.logger.debug("Verifying packet with index %d" % (packet_index)) # packet should have arrived on the expected interface self.assertEqual(payload_info.dst, dst_sw_if_index) self.logger.debug( - "Got packet on interface %s: src=%u (idx=%u)" % - (dst_if.name, payload_info.src, packet_index)) + "Got packet on interface %s: src=%u (idx=%u)" + % (dst_if.name, payload_info.src, packet_index) + ) # search for payload_info with same src and dst if_index # this will give us the transmitted packet next_info = self.get_next_packet_info_for_interface2( - payload_info.src, dst_sw_if_index, - last_info[payload_info.src]) + payload_info.src, dst_sw_if_index, last_info[payload_info.src] + ) last_info[payload_info.src] = next_info # next_info should not be None self.assertTrue(next_info is not None) @@ -862,8 +902,9 @@ class TestSRv6As(VppTestCase): # data field of next_info contains the tx packet txed_packet = next_info.data - self.logger.debug(ppp("Transmitted packet:", - txed_packet)) # ppp=Pretty Print Packet + self.logger.debug( + ppp("Transmitted packet:", txed_packet) + ) # ppp=Pretty Print Packet self.logger.debug(ppp("Received packet:", packet)) @@ -877,11 +918,14 @@ class TestSRv6As(VppTestCase): # have all expected packets arrived? for i in self.pg_interfaces: remaining_packet = self.get_next_packet_info_for_interface2( - i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index]) - self.assertTrue(remaining_packet is None, - "Interface %s: Packet expected from interface %s " - "didn't arrive" % (dst_if.name, i.name)) + i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index] + ) + self.assertTrue( + remaining_packet is None, + "Interface %s: Packet expected from interface %s " + "didn't arrive" % (dst_if.name, i.name), + ) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_srv6_mobile.py b/test/test_srv6_mobile.py index e617acef9ab..33190b84ba0 100644 --- a/test/test_srv6_mobile.py +++ b/test/test_srv6_mobile.py @@ -8,7 +8,7 @@ from scapy.all import * class TestSRv6EndMGTP4E(VppTestCase): - """ SRv6 End.M.GTP4.E (SRv6 -> GTP-U) """ + """SRv6 End.M.GTP4.E (SRv6 -> GTP-U)""" @classmethod def setUpClass(cls): @@ -37,14 +37,12 @@ class TestSRv6EndMGTP4E(VppTestCase): ip4_dst = IPv4Address(str(self.ip4_dst)) # 32bit prefix + 32bit IPv4 DA + 8bit + 32bit TEID + 24bit - dst = b'\xaa' * 4 + ip4_dst.packed + \ - b'\x11' + b'\xbb' * 4 + b'\x11' * 3 + dst = b"\xaa" * 4 + ip4_dst.packed + b"\x11" + b"\xbb" * 4 + b"\x11" * 3 ip6_dst = IPv6Address(dst) ip4_src = IPv4Address(str(self.ip4_src)) # 64bit prefix + 32bit IPv4 SA + 16 bit port + 16bit - src = b'\xcc' * 8 + ip4_src.packed + \ - b'\xdd' * 2 + b'\x11' * 2 + src = b"\xcc" * 8 + ip4_src.packed + b"\xdd" * 2 + b"\x11" * 2 ip6_src = IPv6Address(src) self.logger.info("ip4 dst: {}".format(ip4_dst)) @@ -54,24 +52,26 @@ class TestSRv6EndMGTP4E(VppTestCase): pkts = list() for d, s in inner: - pkt = (Ether() / - IPv6(dst=str(ip6_dst), src=str(ip6_src)) / - IPv6ExtHdrSegmentRouting() / - IPv6(dst=d, src=s) / - UDP(sport=1000, dport=23)) + pkt = ( + Ether() + / IPv6(dst=str(ip6_dst), src=str(ip6_src)) + / IPv6ExtHdrSegmentRouting() + / IPv6(dst=d, src=s) + / UDP(sport=1000, dport=23) + ) self.logger.info(pkt.show2(dump=True)) pkts.append(pkt) return pkts def test_srv6_mobile(self): - """ test_srv6_mobile """ + """test_srv6_mobile""" pkts = self.create_packets([("A::1", "B::1"), ("C::1", "D::1")]) self.vapi.cli( - "sr localsid address {} behavior end.m.gtp4.e " - .format(pkts[0]['IPv6'].dst) + - "v4src_position 64 fib-table 0") + "sr localsid address {} behavior end.m.gtp4.e ".format(pkts[0]["IPv6"].dst) + + "v4src_position 64 fib-table 0" + ) self.logger.info(self.vapi.cli("show sr localsid")) self.vapi.cli("clear errors") @@ -89,11 +89,11 @@ class TestSRv6EndMGTP4E(VppTestCase): self.logger.info(pkt.show2(dump=True)) self.assertEqual(pkt[IP].dst, self.ip4_dst) self.assertEqual(pkt[IP].src, self.ip4_src) - self.assertEqual(pkt[GTP_U_Header].teid, 0xbbbbbbbb) + self.assertEqual(pkt[GTP_U_Header].teid, 0xBBBBBBBB) class TestSRv6TMGTP4D(VppTestCase): - """ SRv6 T.M.GTP4.D (GTP-U -> SRv6) """ + """SRv6 T.M.GTP4.D (GTP-U -> SRv6)""" @classmethod def setUpClass(cls): @@ -133,26 +133,29 @@ class TestSRv6TMGTP4D(VppTestCase): pkts = list() for d, s in inner: - pkt = (Ether() / - IP(dst=str(ip4_dst), src=str(ip4_src)) / - UDP(sport=2152, dport=2152) / - GTP_U_Header(gtp_type="g_pdu", teid=200) / - IPv6(dst=d, src=s) / - UDP(sport=1000, dport=23)) + pkt = ( + Ether() + / IP(dst=str(ip4_dst), src=str(ip4_src)) + / UDP(sport=2152, dport=2152) + / GTP_U_Header(gtp_type="g_pdu", teid=200) + / IPv6(dst=d, src=s) + / UDP(sport=1000, dport=23) + ) self.logger.info(pkt.show2(dump=True)) pkts.append(pkt) return pkts def test_srv6_mobile(self): - """ test_srv6_mobile """ + """test_srv6_mobile""" pkts = self.create_packets([("A::1", "B::1"), ("C::1", "D::1")]) self.vapi.cli("set sr encaps source addr A1::1") self.vapi.cli("sr policy add bsid D4:: next D2:: next D3::") self.vapi.cli( - "sr policy add bsid D5:: behavior t.m.gtp4.d D4::/32 " + - "v6src_prefix C1::/64 nhtype ipv6 fib-table 0 drop-in") + "sr policy add bsid D5:: behavior t.m.gtp4.d D4::/32 " + + "v6src_prefix C1::/64 nhtype ipv6 fib-table 0 drop-in" + ) self.vapi.cli("sr steer l3 {}/32 via bsid D5::".format(self.ip4_dst)) self.vapi.cli("ip route add D2::/32 via {}".format(self.ip6_dst)) @@ -172,15 +175,18 @@ class TestSRv6TMGTP4D(VppTestCase): for pkt in capture: self.logger.info(pkt.show2(dump=True)) - self.logger.info("GTP4.D Address={}".format( - str(pkt[IPv6ExtHdrSegmentRouting].addresses[0]))) + self.logger.info( + "GTP4.D Address={}".format( + str(pkt[IPv6ExtHdrSegmentRouting].addresses[0]) + ) + ) self.assertEqual( - str(pkt[IPv6ExtHdrSegmentRouting].addresses[0]), - "d4:0:101:101::c800:0") + str(pkt[IPv6ExtHdrSegmentRouting].addresses[0]), "d4:0:101:101::c800:0" + ) class TestSRv6EndMGTP6E(VppTestCase): - """ SRv6 End.M.GTP6.E """ + """SRv6 End.M.GTP6.E""" @classmethod def setUpClass(cls): @@ -205,42 +211,42 @@ class TestSRv6EndMGTP6E(VppTestCase): def create_packets(self, inner): # 64bit prefix + 8bit QFI + 32bit TEID + 24bit - dst = b'\xaa' * 8 + b'\x00' + \ - b'\xbb' * 4 + b'\x00' * 3 + dst = b"\xaa" * 8 + b"\x00" + b"\xbb" * 4 + b"\x00" * 3 ip6_dst = IPv6Address(dst) self.ip6_dst = ip6_dst - src = b'\xcc' * 8 + \ - b'\xdd' * 4 + b'\x11' * 4 + src = b"\xcc" * 8 + b"\xdd" * 4 + b"\x11" * 4 ip6_src = IPv6Address(src) self.ip6_src = ip6_src pkts = list() for d, s in inner: - pkt = (Ether() / - IPv6(dst=str(ip6_dst), - src=str(ip6_src)) / - IPv6ExtHdrSegmentRouting(segleft=1, - lastentry=0, - tag=0, - addresses=["a1::1"]) / - IPv6(dst=d, src=s) / UDP(sport=1000, dport=23)) + pkt = ( + Ether() + / IPv6(dst=str(ip6_dst), src=str(ip6_src)) + / IPv6ExtHdrSegmentRouting( + segleft=1, lastentry=0, tag=0, addresses=["a1::1"] + ) + / IPv6(dst=d, src=s) + / UDP(sport=1000, dport=23) + ) self.logger.info(pkt.show2(dump=True)) pkts.append(pkt) return pkts def test_srv6_mobile(self): - """ test_srv6_mobile """ + """test_srv6_mobile""" pkts = self.create_packets([("A::1", "B::1"), ("C::1", "D::1")]) self.vapi.cli( - "sr localsid prefix {}/64 behavior end.m.gtp6.e fib-table 0" - .format(pkts[0]['IPv6'].dst)) - self.vapi.cli( - "ip route add a1::/64 via {}".format(self.ip6_nhop)) + "sr localsid prefix {}/64 behavior end.m.gtp6.e fib-table 0".format( + pkts[0]["IPv6"].dst + ) + ) + self.vapi.cli("ip route add a1::/64 via {}".format(self.ip6_nhop)) self.logger.info(self.vapi.cli("show sr localsid")) self.vapi.cli("clear errors") @@ -258,11 +264,11 @@ class TestSRv6EndMGTP6E(VppTestCase): self.logger.info(pkt.show2(dump=True)) self.assertEqual(pkt[IPv6].dst, "a1::1") self.assertEqual(pkt[IPv6].src, str(self.ip6_src)) - self.assertEqual(pkt[GTP_U_Header].teid, 0xbbbbbbbb) + self.assertEqual(pkt[GTP_U_Header].teid, 0xBBBBBBBB) class TestSRv6EndMGTP6D(VppTestCase): - """ SRv6 End.M.GTP6.D """ + """SRv6 End.M.GTP6.D""" @classmethod def setUpClass(cls): @@ -299,26 +305,29 @@ class TestSRv6EndMGTP6D(VppTestCase): pkts = list() for d, s in inner: - pkt = (Ether() / - IPv6(dst=str(ip6_dst), src=str(ip6_src)) / - UDP(sport=2152, dport=2152) / - GTP_U_Header(gtp_type="g_pdu", teid=200) / - IPv6(dst=d, src=s) / - UDP(sport=1000, dport=23)) + pkt = ( + Ether() + / IPv6(dst=str(ip6_dst), src=str(ip6_src)) + / UDP(sport=2152, dport=2152) + / GTP_U_Header(gtp_type="g_pdu", teid=200) + / IPv6(dst=d, src=s) + / UDP(sport=1000, dport=23) + ) self.logger.info(pkt.show2(dump=True)) pkts.append(pkt) return pkts def test_srv6_mobile(self): - """ test_srv6_mobile """ + """test_srv6_mobile""" pkts = self.create_packets([("A::1", "B::1"), ("C::1", "D::1")]) self.vapi.cli("set sr encaps source addr A1::1") self.vapi.cli("sr policy add bsid D4:: next D2:: next D3::") self.vapi.cli( - "sr localsid prefix 2001::/64 behavior end.m.gtp6.d " + - "D4::/64 fib-table 0 drop-in") + "sr localsid prefix 2001::/64 behavior end.m.gtp6.d " + + "D4::/64 fib-table 0 drop-in" + ) self.vapi.cli("ip route add D2::/64 via {}".format(self.ip6_nhop)) self.logger.info(self.vapi.cli("show sr policies")) @@ -337,11 +346,13 @@ class TestSRv6EndMGTP6D(VppTestCase): for pkt in capture: self.logger.info(pkt.show2(dump=True)) - self.logger.info("GTP6.D SID0={}".format( - str(pkt[IPv6ExtHdrSegmentRouting].addresses[0]))) - self.logger.info("GTP6.D SID1={}".format( - str(pkt[IPv6ExtHdrSegmentRouting].addresses[1]))) - self.assertEqual( - str(pkt[IPv6ExtHdrSegmentRouting].addresses[0]), "2001::1") + self.logger.info( + "GTP6.D SID0={}".format(str(pkt[IPv6ExtHdrSegmentRouting].addresses[0])) + ) + self.logger.info( + "GTP6.D SID1={}".format(str(pkt[IPv6ExtHdrSegmentRouting].addresses[1])) + ) + self.assertEqual(str(pkt[IPv6ExtHdrSegmentRouting].addresses[0]), "2001::1") self.assertEqual( - str(pkt[IPv6ExtHdrSegmentRouting].addresses[1]), "d4::c800:0") + str(pkt[IPv6ExtHdrSegmentRouting].addresses[1]), "d4::c800:0" + ) diff --git a/test/test_srv6_un.py b/test/test_srv6_un.py index 73285bbac87..22a3c486584 100644 --- a/test/test_srv6_un.py +++ b/test/test_srv6_un.py @@ -8,7 +8,7 @@ from scapy.all import * class TestSRv6uSIDSRH(VppTestCase): - """ SRv6 End.uSID w/ SRH """ + """SRv6 End.uSID w/ SRH""" @classmethod def setUpClass(cls): @@ -45,30 +45,30 @@ class TestSRv6uSIDSRH(VppTestCase): pkts = list() for d, s in inner: - pkt = (Ether() / - IPv6(dst=str(ip6_dst), src=str(ip6_src)) / - IPv6ExtHdrSegmentRouting(segleft=1, - lastentry=0, - tag=0, - addresses=[ - "a1::1", - "1111:2222:aaaa:bbbb::"]) / - IPv6(dst=d, src=s) / - UDP(sport=1000, dport=23)) + pkt = ( + Ether() + / IPv6(dst=str(ip6_dst), src=str(ip6_src)) + / IPv6ExtHdrSegmentRouting( + segleft=1, + lastentry=0, + tag=0, + addresses=["a1::1", "1111:2222:aaaa:bbbb::"], + ) + / IPv6(dst=d, src=s) + / UDP(sport=1000, dport=23) + ) self.logger.info(pkt.show2(dump=True)) pkts.append(pkt) return pkts def test_srv6_usid_srh(self): - """ test_srv6_usid_srh """ + """test_srv6_usid_srh""" pkts = self.create_packets([("A::1", "B::1"), ("C::1", "D::1")]) self.vapi.cli("set sr encaps source addr A1::1") - self.vapi.cli( - "sr localsid prefix 1111:2222:aaaa::/48 behavior un 16") - self.vapi.cli( - "ip route add 1111:2222:bbbb::/48 via {}".format(self.ip6_nhop)) + self.vapi.cli("sr localsid prefix 1111:2222:aaaa::/48 behavior un 16") + self.vapi.cli("ip route add 1111:2222:bbbb::/48 via {}".format(self.ip6_nhop)) self.logger.info(self.vapi.cli("show sr localsids")) @@ -85,12 +85,11 @@ class TestSRv6uSIDSRH(VppTestCase): for pkt in capture: self.logger.info(pkt.show2(dump=True)) - self.assertEqual( - pkt[IPv6].dst, "1111:2222:bbbb:cccc:dddd:eeee:ffff:0") + self.assertEqual(pkt[IPv6].dst, "1111:2222:bbbb:cccc:dddd:eeee:ffff:0") class TestSRv6uSID(VppTestCase): - """ SRv6 End.uSID w/o SRH """ + """SRv6 End.uSID w/o SRH""" @classmethod def setUpClass(cls): @@ -127,24 +126,24 @@ class TestSRv6uSID(VppTestCase): pkts = list() for d, s in inner: - pkt = (Ether() / - IPv6(dst=str(ip6_dst), src=str(ip6_src)) / - IPv6(dst=d, src=s) / - UDP(sport=1000, dport=23)) + pkt = ( + Ether() + / IPv6(dst=str(ip6_dst), src=str(ip6_src)) + / IPv6(dst=d, src=s) + / UDP(sport=1000, dport=23) + ) self.logger.info(pkt.show2(dump=True)) pkts.append(pkt) return pkts def test_srv6_usid(self): - """ test_srv6_usid """ + """test_srv6_usid""" pkts = self.create_packets([("A::1", "B::1"), ("C::1", "D::1")]) self.vapi.cli("set sr encaps source addr A1::1") - self.vapi.cli( - "sr localsid prefix 1111:2222:aaaa::/48 behavior un 16") - self.vapi.cli( - "ip route add 1111:2222:bbbb::/48 via {}".format(self.ip6_nhop)) + self.vapi.cli("sr localsid prefix 1111:2222:aaaa::/48 behavior un 16") + self.vapi.cli("ip route add 1111:2222:bbbb::/48 via {}".format(self.ip6_nhop)) self.logger.info(self.vapi.cli("show sr localsids")) @@ -161,12 +160,11 @@ class TestSRv6uSID(VppTestCase): for pkt in capture: self.logger.info(pkt.show2(dump=True)) - self.assertEqual( - pkt[IPv6].dst, "1111:2222:bbbb:cccc:dddd:eeee:ffff:0") + self.assertEqual(pkt[IPv6].dst, "1111:2222:bbbb:cccc:dddd:eeee:ffff:0") class TestSRv6uSIDFlexSRH(VppTestCase): - """ SRv6 End.uSID.Flex w/ SRH """ + """SRv6 End.uSID.Flex w/ SRH""" @classmethod def setUpClass(cls): @@ -203,30 +201,30 @@ class TestSRv6uSIDFlexSRH(VppTestCase): pkts = list() for d, s in inner: - pkt = (Ether() / - IPv6(dst=str(ip6_dst), src=str(ip6_src)) / - IPv6ExtHdrSegmentRouting(segleft=1, - lastentry=0, - tag=0, - addresses=[ - "a1::1", - "1111:2222:aaaa:bbbb::"]) / - IPv6(dst=d, src=s) / - UDP(sport=1000, dport=23)) + pkt = ( + Ether() + / IPv6(dst=str(ip6_dst), src=str(ip6_src)) + / IPv6ExtHdrSegmentRouting( + segleft=1, + lastentry=0, + tag=0, + addresses=["a1::1", "1111:2222:aaaa:bbbb::"], + ) + / IPv6(dst=d, src=s) + / UDP(sport=1000, dport=23) + ) self.logger.info(pkt.show2(dump=True)) pkts.append(pkt) return pkts def test_srv6_usid_flex_srh(self): - """ test_srv6_usid_flex_srh """ + """test_srv6_usid_flex_srh""" pkts = self.create_packets([("A::1", "B::1"), ("C::1", "D::1")]) self.vapi.cli("set sr encaps source addr A1::1") - self.vapi.cli( - "sr localsid prefix 1111:2222:aaaa::/48 behavior un.flex 16") - self.vapi.cli( - "ip route add 1111:2222:bbbb::/48 via {}".format(self.ip6_nhop)) + self.vapi.cli("sr localsid prefix 1111:2222:aaaa::/48 behavior un.flex 16") + self.vapi.cli("ip route add 1111:2222:bbbb::/48 via {}".format(self.ip6_nhop)) self.logger.info(self.vapi.cli("show sr localsids")) @@ -243,12 +241,11 @@ class TestSRv6uSIDFlexSRH(VppTestCase): for pkt in capture: self.logger.info(pkt.show2(dump=True)) - self.assertEqual( - pkt[IPv6].dst, "1111:2222:bbbb:cccc:dddd:eeee:ffff:0") + self.assertEqual(pkt[IPv6].dst, "1111:2222:bbbb:cccc:dddd:eeee:ffff:0") class TestSRv6uSIDFlex(VppTestCase): - """ SRv6 End.uSID.Flex w/o SRH """ + """SRv6 End.uSID.Flex w/o SRH""" @classmethod def setUpClass(cls): @@ -285,24 +282,24 @@ class TestSRv6uSIDFlex(VppTestCase): pkts = list() for d, s in inner: - pkt = (Ether() / - IPv6(dst=str(ip6_dst), src=str(ip6_src)) / - IPv6(dst=d, src=s) / - UDP(sport=1000, dport=23)) + pkt = ( + Ether() + / IPv6(dst=str(ip6_dst), src=str(ip6_src)) + / IPv6(dst=d, src=s) + / UDP(sport=1000, dport=23) + ) self.logger.info(pkt.show2(dump=True)) pkts.append(pkt) return pkts def test_srv6_usid_flex(self): - """ test_srv6_usid_flex """ + """test_srv6_usid_flex""" pkts = self.create_packets([("A::1", "B::1"), ("C::1", "D::1")]) self.vapi.cli("set sr encaps source addr A1::1") - self.vapi.cli( - "sr localsid prefix 1111:2222:aaaa::/48 behavior un.flex 16") - self.vapi.cli( - "ip route add 1111:2222:bbbb::/48 via {}".format(self.ip6_nhop)) + self.vapi.cli("sr localsid prefix 1111:2222:aaaa::/48 behavior un.flex 16") + self.vapi.cli("ip route add 1111:2222:bbbb::/48 via {}".format(self.ip6_nhop)) self.logger.info(self.vapi.cli("show sr localsids")) @@ -319,5 +316,4 @@ class TestSRv6uSIDFlex(VppTestCase): for pkt in capture: self.logger.info(pkt.show2(dump=True)) - self.assertEqual( - pkt[IPv6].dst, "1111:2222:bbbb:cccc:dddd:eeee:ffff:0") + self.assertEqual(pkt[IPv6].dst, "1111:2222:bbbb:cccc:dddd:eeee:ffff:0") diff --git a/test/test_stats_client.py b/test/test_stats_client.py index f3db2ef3b2e..7b62b292853 100644 --- a/test/test_stats_client.py +++ b/test/test_stats_client.py @@ -32,7 +32,8 @@ class StatsClientTestCase(VppTestCase): """Test set errors""" self.assertEqual(self.statistics.set_errors(), {}) self.assertEqual( - self.statistics.get_counter('/err/ethernet-input/no error'), [0]) + self.statistics.get_counter("/err/ethernet-input/no error"), [0] + ) def test_client_fd_leak(self): """Test file descriptor count - VPP-1486""" @@ -46,11 +47,13 @@ class StatsClientTestCase(VppTestCase): stats.disconnect() ending_fds = p.num_fds() - self.assertEqual(initial_fds, ending_fds, - "initial client side file descriptor count: %s " - "is not equal to " - "ending client side file descriptor count: %s" % ( - initial_fds, ending_fds)) + self.assertEqual( + initial_fds, + ending_fds, + "initial client side file descriptor count: %s " + "is not equal to " + "ending client side file descriptor count: %s" % (initial_fds, ending_fds), + ) def test_symlink_values(self): """Test symlinks reported values""" @@ -63,16 +66,16 @@ class StatsClientTestCase(VppTestCase): p = list() for i in range(5): - packet = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)) + packet = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / IP( + src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4 + ) p.append(packet) self.send_and_expect(self.pg0, p, self.pg1) - pg1_tx = self.statistics.get_counter('/interfaces/pg1/tx') - if_tx = self.statistics.get_counter('/if/tx') + pg1_tx = self.statistics.get_counter("/interfaces/pg1/tx") + if_tx = self.statistics.get_counter("/if/tx") - self.assertEqual(pg1_tx[0]['bytes'], - if_tx[0][self.pg1.sw_if_index]['bytes']) + self.assertEqual(pg1_tx[0]["bytes"], if_tx[0][self.pg1.sw_if_index]["bytes"]) for i in self.pg_interfaces: i.unconfig() i.admin_down() @@ -93,31 +96,28 @@ class StatsClientTestCase(VppTestCase): p = list() bytes_to_send = 0 for i in range(5): - packet = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)) + packet = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / IP( + src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4 + ) bytes_to_send += len(packet) p.append(packet) - tx_before_sending = self.statistics.get_counter('/interfaces/pg1/tx') - rx_before_sending = self.statistics.get_counter('/interfaces/pg0/rx') + tx_before_sending = self.statistics.get_counter("/interfaces/pg1/tx") + rx_before_sending = self.statistics.get_counter("/interfaces/pg0/rx") self.send_and_expect(self.pg0, p, self.pg1) - tx = self.statistics.get_counter('/interfaces/pg1/tx') - rx = self.statistics.get_counter('/interfaces/pg0/rx') + tx = self.statistics.get_counter("/interfaces/pg1/tx") + rx = self.statistics.get_counter("/interfaces/pg0/rx") # We wait for nodes symlinks to update (interfaces created/deleted). # ... and packets to be sent self.sleep(0.1) - vectors = self.statistics.get_counter('/nodes/pg1-tx/vectors') - - self.assertEqual(tx[0]['bytes'] - tx_before_sending[0]['bytes'], - bytes_to_send) - self.assertEqual(tx[0]['packets'] - tx_before_sending[0]['packets'], - 5) - self.assertEqual(rx[0]['bytes'] - rx_before_sending[0]['bytes'], - bytes_to_send) - self.assertEqual(rx[0]['packets'] - rx_before_sending[0]['packets'], - 5) - self.assertEqual(vectors[0], rx[0]['packets']) + vectors = self.statistics.get_counter("/nodes/pg1-tx/vectors") + + self.assertEqual(tx[0]["bytes"] - tx_before_sending[0]["bytes"], bytes_to_send) + self.assertEqual(tx[0]["packets"] - tx_before_sending[0]["packets"], 5) + self.assertEqual(rx[0]["bytes"] - rx_before_sending[0]["bytes"], bytes_to_send) + self.assertEqual(rx[0]["packets"] - rx_before_sending[0]["packets"], 5) + self.assertEqual(vectors[0], rx[0]["packets"]) for i in self.pg_interfaces: i.unconfig() @@ -125,7 +125,7 @@ class StatsClientTestCase(VppTestCase): def test_index_consistency(self): """Test index consistency despite changes in the stats""" - d = self.statistics.ls(['/if/names']) + d = self.statistics.ls(["/if/names"]) self.create_loopback_interfaces(10) for i in range(10): try: @@ -142,22 +142,21 @@ class StatsClientTestCase(VppTestCase): @unittest.skip("Manual only") def test_mem_leak(self): def loop(): - print('Running loop') + print("Running loop") for i in range(50): rv = self.vapi.papi.tap_create_v2(id=i, use_random_mac=1) self.assertEqual(rv.retval, 0) rv = self.vapi.papi.tap_delete_v2(sw_if_index=rv.sw_if_index) self.assertEqual(rv.retval, 0) - before = self.statistics.get_counter('/mem/statseg/used') + before = self.statistics.get_counter("/mem/statseg/used") loop() self.vapi.cli("memory-trace on stats-segment") for j in range(100): loop() print(self.vapi.cli("show memory stats-segment verbose")) - print('AFTER', before, - self.statistics.get_counter('/mem/statseg/used')) + print("AFTER", before, self.statistics.get_counter("/mem/statseg/used")) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_string.py b/test/test_string.py index c507c7559ca..866a6597107 100644 --- a/test/test_string.py +++ b/test/test_string.py @@ -7,7 +7,7 @@ from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath class TestString(VppTestCase): - """ String Test Cases """ + """String Test Cases""" @classmethod def setUpClass(cls): @@ -24,15 +24,30 @@ class TestString(VppTestCase): super(TestString, self).tearDown() def test_string_unittest(self): - """ String unit tests """ - names = ["memcpy_s", - "clib_memcmp", "clib_memcpy", "clib_memset", - "clib_strcmp", "clib_strncmp", "clib_strncpy", - "clib_strnlen", "clib_strtok", - "memcmp_s", "memcpy_s", "memset_s ", - "strcat_s", "strcmp_s", "strcpy_s", - "strncat_s", "strncmp_s", "strncpy_s", - "strnlen_s", "strstr_s", "strtok_s"] + """String unit tests""" + names = [ + "memcpy_s", + "clib_memcmp", + "clib_memcpy", + "clib_memset", + "clib_strcmp", + "clib_strncmp", + "clib_strncpy", + "clib_strnlen", + "clib_strtok", + "memcmp_s", + "memcpy_s", + "memset_s ", + "strcat_s", + "strcmp_s", + "strcpy_s", + "strncat_s", + "strncmp_s", + "strncpy_s", + "strnlen_s", + "strstr_s", + "strtok_s", + ] for name in names: error = self.vapi.cli("test string " + name) @@ -41,5 +56,5 @@ class TestString(VppTestCase): self.assertNotIn("failed", error) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_svs.py b/test/test_svs.py index db4ad8078e0..91603966453 100644 --- a/test/test_svs.py +++ b/test/test_svs.py @@ -16,7 +16,7 @@ NUM_PKTS = 67 class TestSVS(VppTestCase): - """ SVS Test Case """ + """SVS Test Case""" @classmethod def setUpClass(cls): @@ -61,35 +61,51 @@ class TestSVS(VppTestCase): super(TestSVS, self).tearDown() def test_svs4(self): - """ Source VRF Select IP4 """ + """Source VRF Select IP4""" # # packets destined out of the 3 non-default table interfaces # - pkts_0 = [(Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src="1.1.1.1", dst=self.pg1.remote_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)), - (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src="2.2.2.2", dst=self.pg2.remote_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)), - (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src="3.3.3.3", dst=self.pg3.remote_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100))] - pkts_1 = [(Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IP(src="1.1.1.1", dst=self.pg1.remote_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)), - (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IP(src="2.2.2.2", dst=self.pg2.remote_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)), - (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IP(src="3.3.3.3", dst=self.pg3.remote_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100))] + pkts_0 = [ + ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src="1.1.1.1", dst=self.pg1.remote_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ), + ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src="2.2.2.2", dst=self.pg2.remote_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ), + ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src="3.3.3.3", dst=self.pg3.remote_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ), + ] + pkts_1 = [ + ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src="1.1.1.1", dst=self.pg1.remote_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ), + ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src="2.2.2.2", dst=self.pg2.remote_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ), + ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src="3.3.3.3", dst=self.pg3.remote_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ), + ] # # before adding the SVS config all these packets are dropped when @@ -108,7 +124,8 @@ class TestSVS(VppTestCase): self.vapi.svs_table_add_del( is_add=1, af=VppEnum.vl_api_address_family_t.ADDRESS_IP4, - table_id=table_id) + table_id=table_id, + ) # # map X.0.0.0/8 to each SVS table for lookup in table X @@ -118,7 +135,8 @@ class TestSVS(VppTestCase): is_add=1, prefix="%d.0.0.0/8" % i, table_id=table_id, - source_table_id=i) + source_table_id=i, + ) # # Enable SVS on pg0/pg1 using table 1001/1002 @@ -127,12 +145,14 @@ class TestSVS(VppTestCase): is_enable=1, af=VppEnum.vl_api_address_family_t.ADDRESS_IP4, table_id=table_ids[0], - sw_if_index=self.pg0.sw_if_index) + sw_if_index=self.pg0.sw_if_index, + ) self.vapi.svs_enable_disable( is_enable=1, af=VppEnum.vl_api_address_family_t.ADDRESS_IP4, table_id=table_ids[1], - sw_if_index=self.pg1.sw_if_index) + sw_if_index=self.pg1.sw_if_index, + ) # # now all the packets should be delivered out the respective interface @@ -148,16 +168,20 @@ class TestSVS(VppTestCase): # check that if the SVS lookup does not match a route the packet # is forwarded using the interface's routing table # - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg0.remote_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.remote_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) self.send_and_expect(self.pg0, p * NUM_PKTS, self.pg0) - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IP(src=self.pg1.remote_ip4, dst=self.pg1.remote_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src=self.pg1.remote_ip4, dst=self.pg1.remote_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) self.send_and_expect(self.pg1, p * NUM_PKTS, self.pg1) # @@ -179,12 +203,14 @@ class TestSVS(VppTestCase): is_enable=0, af=VppEnum.vl_api_address_family_t.ADDRESS_IP4, table_id=table_ids[0], - sw_if_index=self.pg0.sw_if_index) + sw_if_index=self.pg0.sw_if_index, + ) self.vapi.svs_enable_disable( is_enable=0, af=VppEnum.vl_api_address_family_t.ADDRESS_IP4, table_id=table_ids[1], - sw_if_index=self.pg1.sw_if_index) + sw_if_index=self.pg1.sw_if_index, + ) for table_id in table_ids: for i in range(1, 4): @@ -192,43 +218,61 @@ class TestSVS(VppTestCase): is_add=0, prefix="%d.0.0.0/8" % i, table_id=table_id, - source_table_id=0) + source_table_id=0, + ) self.vapi.svs_table_add_del( is_add=0, af=VppEnum.vl_api_address_family_t.ADDRESS_IP4, - table_id=table_id) + table_id=table_id, + ) def test_svs6(self): - """ Source VRF Select IP6 """ + """Source VRF Select IP6""" # # packets destined out of the 3 non-default table interfaces # - pkts_0 = [(Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src="2001:1::1", dst=self.pg1.remote_ip6) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)), - (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src="2001:2::1", dst=self.pg2.remote_ip6) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)), - (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src="2001:3::1", dst=self.pg3.remote_ip6) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100))] - pkts_1 = [(Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IPv6(src="2001:1::1", dst=self.pg1.remote_ip6) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)), - (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IPv6(src="2001:2::1", dst=self.pg2.remote_ip6) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)), - (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IPv6(src="2001:3::1", dst=self.pg3.remote_ip6) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100))] + pkts_0 = [ + ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src="2001:1::1", dst=self.pg1.remote_ip6) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ), + ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src="2001:2::1", dst=self.pg2.remote_ip6) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ), + ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src="2001:3::1", dst=self.pg3.remote_ip6) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ), + ] + pkts_1 = [ + ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(src="2001:1::1", dst=self.pg1.remote_ip6) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ), + ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(src="2001:2::1", dst=self.pg2.remote_ip6) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ), + ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(src="2001:3::1", dst=self.pg3.remote_ip6) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ), + ] # # before adding the SVS config all these packets are dropped when @@ -247,7 +291,8 @@ class TestSVS(VppTestCase): self.vapi.svs_table_add_del( is_add=1, af=VppEnum.vl_api_address_family_t.ADDRESS_IP6, - table_id=table_id) + table_id=table_id, + ) # # map X.0.0.0/8 to each SVS table for lookup in table X @@ -257,7 +302,8 @@ class TestSVS(VppTestCase): is_add=1, prefix="2001:%d::/32" % i, table_id=table_id, - source_table_id=i) + source_table_id=i, + ) # # Enable SVS on pg0/pg1 using table 1001/1002 @@ -266,12 +312,14 @@ class TestSVS(VppTestCase): is_enable=1, af=VppEnum.vl_api_address_family_t.ADDRESS_IP6, table_id=table_ids[0], - sw_if_index=self.pg0.sw_if_index) + sw_if_index=self.pg0.sw_if_index, + ) self.vapi.svs_enable_disable( is_enable=1, af=VppEnum.vl_api_address_family_t.ADDRESS_IP6, table_id=table_ids[1], - sw_if_index=self.pg1.sw_if_index) + sw_if_index=self.pg1.sw_if_index, + ) # # now all the packets should be delivered out the respective interface @@ -287,16 +335,20 @@ class TestSVS(VppTestCase): # check that if the SVS lookup does not match a route the packet # is forwarded using the interface's routing table # - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg0.remote_ip6) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.remote_ip6) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) self.send_and_expect(self.pg0, p * NUM_PKTS, self.pg0) - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IPv6(src=self.pg1.remote_ip6, dst=self.pg1.remote_ip6) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IPv6(src=self.pg1.remote_ip6, dst=self.pg1.remote_ip6) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) self.send_and_expect(self.pg1, p * NUM_PKTS, self.pg1) # @@ -318,12 +370,14 @@ class TestSVS(VppTestCase): is_enable=0, af=VppEnum.vl_api_address_family_t.ADDRESS_IP6, table_id=table_ids[0], - sw_if_index=self.pg0.sw_if_index) + sw_if_index=self.pg0.sw_if_index, + ) self.vapi.svs_enable_disable( is_enable=0, af=VppEnum.vl_api_address_family_t.ADDRESS_IP6, table_id=table_ids[1], - sw_if_index=self.pg1.sw_if_index) + sw_if_index=self.pg1.sw_if_index, + ) for table_id in table_ids: for i in range(1, 4): @@ -331,12 +385,15 @@ class TestSVS(VppTestCase): is_add=0, prefix="2001:%d::/32" % i, table_id=table_id, - source_table_id=0) + source_table_id=0, + ) self.vapi.svs_table_add_del( is_add=0, af=VppEnum.vl_api_address_family_t.ADDRESS_IP6, - table_id=table_id) + table_id=table_id, + ) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_syslog.py b/test/test_syslog.py index b084a1d1846..b84c89c57d0 100644 --- a/test/test_syslog.py +++ b/test/test_syslog.py @@ -11,7 +11,7 @@ from vpp_papi import VppEnum class TestSyslog(VppTestCase): - """ Syslog Protocol Test Cases """ + """Syslog Protocol Test Cases""" @property def SYSLOG_SEVERITY(self): @@ -22,7 +22,7 @@ class TestSyslog(VppTestCase): super(TestSyslog, cls).setUpClass() try: - cls.pg0, = cls.create_pg_interfaces(range(1)) + (cls.pg0,) = cls.create_pg_interfaces(range(1)) cls.pg0.admin_up() cls.pg0.config_ip4() cls.pg0.resolve_arp() @@ -35,8 +35,7 @@ class TestSyslog(VppTestCase): def tearDownClass(cls): super(TestSyslog, cls).tearDownClass() - def syslog_generate(self, facility, severity, appname, msgid, sd=None, - msg=None): + def syslog_generate(self, facility, severity, appname, msgid, sd=None, msg=None): """ Generate syslog message @@ -47,20 +46,50 @@ class TestSyslog(VppTestCase): :param sd: structured data (optional) :param msg: free-form message (optional) """ - facility_str = ['kernel', 'user-level', 'mail-system', - 'system-daemons', 'security-authorization', 'syslogd', - 'line-printer', 'network-news', 'uucp', 'clock-daemon', - '', 'ftp-daemon', 'ntp-subsystem', 'log-audit', - 'log-alert', '', 'local0', 'local1', 'local2', - 'local3', 'local4', 'local5', 'local6', 'local7'] - - severity_str = ['emergency', 'alert', 'critical', 'error', 'warning', - 'notice', 'informational', 'debug'] - - cli_str = "test syslog %s %s %s %s" % (facility_str[facility], - severity_str[severity], - appname, - msgid) + facility_str = [ + "kernel", + "user-level", + "mail-system", + "system-daemons", + "security-authorization", + "syslogd", + "line-printer", + "network-news", + "uucp", + "clock-daemon", + "", + "ftp-daemon", + "ntp-subsystem", + "log-audit", + "log-alert", + "", + "local0", + "local1", + "local2", + "local3", + "local4", + "local5", + "local6", + "local7", + ] + + severity_str = [ + "emergency", + "alert", + "critical", + "error", + "warning", + "notice", + "informational", + "debug", + ] + + cli_str = "test syslog %s %s %s %s" % ( + facility_str[facility], + severity_str[severity], + appname, + msgid, + ) if sd is not None: for sd_id, sd_params in sd.items(): cli_str += " sd-id %s" % (sd_id) @@ -70,8 +99,9 @@ class TestSyslog(VppTestCase): cli_str += " %s" % (msg) self.vapi.cli(cli_str) - def syslog_verify(self, data, facility, severity, appname, msgid, sd=None, - msg=None): + def syslog_verify( + self, data, facility, severity, appname, msgid, sd=None, msg=None + ): """ Verify syslog message @@ -83,7 +113,7 @@ class TestSyslog(VppTestCase): :param sd: structured data (optional) :param msg: free-form message (optional) """ - message = data.decode('utf-8') + message = data.decode("utf-8") if sd is None: sd = {} try: @@ -102,35 +132,32 @@ class TestSyslog(VppTestCase): self.assertEqual(message.hostname, self.pg0.local_ip4) def test_syslog(self): - """ Syslog Protocol test """ - self.vapi.syslog_set_sender(src_address=self.pg0.local_ip4, - collector_address=self.pg0.remote_ip4) + """Syslog Protocol test""" + self.vapi.syslog_set_sender( + src_address=self.pg0.local_ip4, collector_address=self.pg0.remote_ip4 + ) config = self.vapi.syslog_get_sender() - self.assertEqual(str(config.collector_address), - self.pg0.remote_ip4) + self.assertEqual(str(config.collector_address), self.pg0.remote_ip4) self.assertEqual(config.collector_port, 514) self.assertEqual(str(config.src_address), self.pg0.local_ip4) self.assertEqual(config.vrf_id, 0) self.assertEqual(config.max_msg_size, 480) - appname = 'test' - msgid = 'testMsg' - msg = 'this is message' - sd1 = {'exampleSDID@32473': {'iut': '3', - 'eventSource': 'App', - 'eventID': '1011'}} - sd2 = {'exampleSDID@32473': {'iut': '3', - 'eventSource': 'App', - 'eventID': '1011'}, - 'examplePriority@32473': {'class': 'high'}} + appname = "test" + msgid = "testMsg" + msg = "this is message" + sd1 = { + "exampleSDID@32473": {"iut": "3", "eventSource": "App", "eventID": "1011"} + } + sd2 = { + "exampleSDID@32473": {"iut": "3", "eventSource": "App", "eventID": "1011"}, + "examplePriority@32473": {"class": "high"}, + } self.pg_enable_capture(self.pg_interfaces) - self.syslog_generate(SyslogFacility.local7, - SyslogSeverity.info, - appname, - msgid, - None, - msg) + self.syslog_generate( + SyslogFacility.local7, SyslogSeverity.info, appname, msgid, None, msg + ) capture = self.pg0.get_capture(1) try: self.assertEqual(capture[0][IP].src, self.pg0.local_ip4) @@ -140,71 +167,66 @@ class TestSyslog(VppTestCase): except: self.logger.error(ppp("invalid packet:", capture[0])) raise - self.syslog_verify(capture[0][Raw].load, - SyslogFacility.local7, - SyslogSeverity.info, - appname, - msgid, - None, - msg) + self.syslog_verify( + capture[0][Raw].load, + SyslogFacility.local7, + SyslogSeverity.info, + appname, + msgid, + None, + msg, + ) self.pg_enable_capture(self.pg_interfaces) - self.vapi.syslog_set_filter( - self.SYSLOG_SEVERITY.SYSLOG_API_SEVERITY_WARN) + self.vapi.syslog_set_filter(self.SYSLOG_SEVERITY.SYSLOG_API_SEVERITY_WARN) filter = self.vapi.syslog_get_filter() - self.assertEqual(filter.severity, - self.SYSLOG_SEVERITY.SYSLOG_API_SEVERITY_WARN) - self.syslog_generate(SyslogFacility.local7, - SyslogSeverity.info, - appname, - msgid, - None, - msg) + self.assertEqual(filter.severity, self.SYSLOG_SEVERITY.SYSLOG_API_SEVERITY_WARN) + self.syslog_generate( + SyslogFacility.local7, SyslogSeverity.info, appname, msgid, None, msg + ) self.pg0.assert_nothing_captured() self.pg_enable_capture(self.pg_interfaces) - self.syslog_generate(SyslogFacility.local6, - SyslogSeverity.warning, - appname, - msgid, - sd1, - msg) + self.syslog_generate( + SyslogFacility.local6, SyslogSeverity.warning, appname, msgid, sd1, msg + ) capture = self.pg0.get_capture(1) - self.syslog_verify(capture[0][Raw].load, - SyslogFacility.local6, - SyslogSeverity.warning, - appname, - msgid, - sd1, - msg) - - self.vapi.syslog_set_sender(self.pg0.local_ip4, - self.pg0.remote_ip4, - collector_port=12345) + self.syslog_verify( + capture[0][Raw].load, + SyslogFacility.local6, + SyslogSeverity.warning, + appname, + msgid, + sd1, + msg, + ) + + self.vapi.syslog_set_sender( + self.pg0.local_ip4, self.pg0.remote_ip4, collector_port=12345 + ) config = self.vapi.syslog_get_sender() self.assertEqual(config.collector_port, 12345) self.pg_enable_capture(self.pg_interfaces) - self.syslog_generate(SyslogFacility.local5, - SyslogSeverity.err, - appname, - msgid, - sd2, - None) + self.syslog_generate( + SyslogFacility.local5, SyslogSeverity.err, appname, msgid, sd2, None + ) capture = self.pg0.get_capture(1) try: self.assertEqual(capture[0][UDP].dport, 12345) except: self.logger.error(ppp("invalid packet:", capture[0])) raise - self.syslog_verify(capture[0][Raw].load, - SyslogFacility.local5, - SyslogSeverity.err, - appname, - msgid, - sd2, - None) - - -if __name__ == '__main__': + self.syslog_verify( + capture[0][Raw].load, + SyslogFacility.local5, + SyslogSeverity.err, + appname, + msgid, + sd2, + None, + ) + + +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_tap.py b/test/test_tap.py index 0e5b315963e..57014e4ecb3 100644 --- a/test/test_tap.py +++ b/test/test_tap.py @@ -11,7 +11,7 @@ def check_tuntap_driver_access(): @unittest.skip("Requires root") class TestTAP(VppTestCase): - """ TAP Test Case """ + """TAP Test Case""" def test_tap_add_del(self): """Create TAP interface""" @@ -20,7 +20,7 @@ class TestTAP(VppTestCase): self.assertTrue(tap0.query_vpp_config()) def test_tap_dump(self): - """ Test api dump w/ and w/o sw_if_index filtering""" + """Test api dump w/ and w/o sw_if_index filtering""" MAX_INSTANCES = 10 tap_instances = [] for instance in range(MAX_INSTANCES): @@ -29,10 +29,9 @@ class TestTAP(VppTestCase): tap_instances.append(i) details = self.vapi.sw_interface_tap_v2_dump() self.assertEqual(MAX_INSTANCES, len(details)) - details = self.vapi.sw_interface_tap_v2_dump( - tap_instances[5].sw_if_index) + details = self.vapi.sw_interface_tap_v2_dump(tap_instances[5].sw_if_index) self.assertEqual(1, len(details)) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_tcp.py b/test/test_tcp.py index f8e51057d38..de126362107 100644 --- a/test/test_tcp.py +++ b/test/test_tcp.py @@ -7,7 +7,7 @@ from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath class TestTCP(VppTestCase): - """ TCP Test Case """ + """TCP Test Case""" @classmethod def setUpClass(cls): @@ -36,10 +36,12 @@ class TestTCP(VppTestCase): table_id += 1 # Configure namespaces - self.vapi.app_namespace_add_del(namespace_id="0", - sw_if_index=self.loop0.sw_if_index) - self.vapi.app_namespace_add_del(namespace_id="1", - sw_if_index=self.loop1.sw_if_index) + self.vapi.app_namespace_add_del( + namespace_id="0", sw_if_index=self.loop0.sw_if_index + ) + self.vapi.app_namespace_add_del( + namespace_id="1", sw_if_index=self.loop1.sw_if_index + ) def tearDown(self): for i in self.lo_interfaces: @@ -50,31 +52,38 @@ class TestTCP(VppTestCase): super(TestTCP, self).tearDown() def test_tcp_transfer(self): - """ TCP echo client/server transfer """ + """TCP echo client/server transfer""" # Add inter-table routes - ip_t01 = VppIpRoute(self, self.loop1.local_ip4, 32, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_table_id=1)]) - ip_t10 = VppIpRoute(self, self.loop0.local_ip4, 32, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_table_id=0)], table_id=1) + ip_t01 = VppIpRoute( + self, + self.loop1.local_ip4, + 32, + [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=1)], + ) + ip_t10 = VppIpRoute( + self, + self.loop0.local_ip4, + 32, + [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=0)], + table_id=1, + ) ip_t01.add_vpp_config() ip_t10.add_vpp_config() # Start builtin server and client uri = "tcp://" + self.loop0.local_ip4 + "/1234" - error = self.vapi.cli("test echo server appns 0 fifo-size 4 uri " + - uri) + error = self.vapi.cli("test echo server appns 0 fifo-size 4 uri " + uri) if error: self.logger.critical(error) self.assertNotIn("failed", error) - error = self.vapi.cli("test echo client mbytes 10 appns 1 " + - "fifo-size 4 no-output test-bytes " + - "syn-timeout 2 uri " + uri) + error = self.vapi.cli( + "test echo client mbytes 10 appns 1 " + + "fifo-size 4 no-output test-bytes " + + "syn-timeout 2 uri " + + uri + ) if error: self.logger.critical(error) self.assertNotIn("failed", error) @@ -104,12 +113,13 @@ class TestTCPUnitTests(VppTestCase): self.vapi.session_enable_disable(is_enable=0) def test_tcp_unittest(self): - """ TCP Unit Tests """ + """TCP Unit Tests""" error = self.vapi.cli("test tcp all") if error: self.logger.critical(error) self.assertNotIn("failed", error) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_tls.py b/test/test_tls.py index 2f8edd4e0e2..301cddf5082 100644 --- a/test/test_tls.py +++ b/test/test_tls.py @@ -23,8 +23,9 @@ def checkOpenSSLVersion(): r = "OPENSSL_ROOT_DIR" in os.environ if r: ssl = os.environ["OPENSSL_ROOT_DIR"] + "/bin/openssl version" - p = subprocess.Popen(ssl, stdin=subprocess.PIPE, - stdout=subprocess.PIPE, shell=True) + p = subprocess.Popen( + ssl, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True + ) p.wait() output = p.stdout.read() status = p.returncode @@ -52,7 +53,7 @@ def checkAll(): class TestTLS(VppTestCase): - """ TLS Qat Test Case. """ + """TLS Qat Test Case.""" @classmethod def setUpClass(cls): @@ -82,10 +83,12 @@ class TestTLS(VppTestCase): table_id += 1 # Configure namespaces - self.vapi.app_namespace_add_del(namespace_id="0", - sw_if_index=self.loop0.sw_if_index) - self.vapi.app_namespace_add_del(namespace_id="1", - sw_if_index=self.loop1.sw_if_index) + self.vapi.app_namespace_add_del( + namespace_id="0", sw_if_index=self.loop0.sw_if_index + ) + self.vapi.app_namespace_add_del( + namespace_id="1", sw_if_index=self.loop1.sw_if_index + ) def tearDown(self): for i in self.lo_interfaces: @@ -95,46 +98,49 @@ class TestTLS(VppTestCase): self.vapi.session_enable_disable(is_enable=0) super(TestTLS, self).tearDown() - @unittest.skipUnless(checkAll(), - "QAT or OpenSSL not satisfied,skip.") + @unittest.skipUnless(checkAll(), "QAT or OpenSSL not satisfied,skip.") def test_tls_transfer(self): - """ TLS qat echo client/server transfer """ + """TLS qat echo client/server transfer""" # Add inter-table routes - ip_t01 = VppIpRoute(self, self.loop1.local_ip4, 32, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_table_id=1)]) - - ip_t10 = VppIpRoute(self, self.loop0.local_ip4, 32, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_table_id=0)], table_id=1) + ip_t01 = VppIpRoute( + self, + self.loop1.local_ip4, + 32, + [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=1)], + ) + + ip_t10 = VppIpRoute( + self, + self.loop0.local_ip4, + 32, + [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=0)], + table_id=1, + ) ip_t01.add_vpp_config() ip_t10.add_vpp_config() # Enable QAT engine and TLS async r = self.vapi.tls_openssl_set_engine( - async_enable=1, - engine="qat", - algorithm="RSA,PKEY_CRYPTO", - ciphers="RSA") - self.assertIsNotNone(r, - 'No response msg ') + async_enable=1, engine="qat", algorithm="RSA,PKEY_CRYPTO", ciphers="RSA" + ) + self.assertIsNotNone(r, "No response msg ") # Start builtin server and client uri = "tls://" + self.loop0.local_ip4 + "/1234" - error = self.vapi.cli("test echo server appns 0 fifo-size 4 " - "tls-engine 1 uri " + - uri) + error = self.vapi.cli( + "test echo server appns 0 fifo-size 4 tls-engine 1 uri " + uri + ) if error: self.logger.critical(error) self.assertNotIn("failed", error) - error = self.vapi.cli("test echo client mbytes 10 appns 1 " - "fifo-size 4 no-output test-bytes " - "tls-engine 1 " - "syn-timeout 2 uri " + uri) + error = self.vapi.cli( + "test echo client mbytes 10 appns 1 " + "fifo-size 4 no-output test-bytes " + "tls-engine 1 " + "syn-timeout 2 uri " + uri + ) if error: self.logger.critical(error) self.assertNotIn("failed", error) @@ -144,5 +150,5 @@ class TestTLS(VppTestCase): ip_t10.remove_vpp_config() -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_trace_filter.py b/test/test_trace_filter.py index fa0d74812f5..3c1f778a0f7 100644 --- a/test/test_trace_filter.py +++ b/test/test_trace_filter.py @@ -15,7 +15,7 @@ from scapy.utils import rdpcap class TestTracefilter(VppTestCase): - """ Packet Tracer Filter Test """ + """Packet Tracer Filter Test""" @classmethod def setUpClass(cls): @@ -43,8 +43,11 @@ class TestTracefilter(VppTestCase): def cli(self, cmd): r = self.vapi.cli_return_response(cmd) if r.retval != 0: - s = "reply '%s'" % r.reply if hasattr( - r, "reply") else "retval '%s'" % r.retval + s = ( + "reply '%s'" % r.reply + if hasattr(r, "reply") + else "retval '%s'" % r.retval + ) raise RuntimeError("cli command '%s' FAIL with %s" % (cmd, s)) return r @@ -71,26 +74,34 @@ class TestTracefilter(VppTestCase): self.assertTrue(r.reply.find(s) != -1) def test_basic(self): - """ Packet Tracer Filter Test """ + """Packet Tracer Filter Test""" self.add_trace_filter( - "l3 ip4 src", - "l3 ip4 src %s" % - self.pg0.remote_hosts[5].ip4) + "l3 ip4 src", "l3 ip4 src %s" % self.pg0.remote_hosts[5].ip4 + ) self.add_trace_filter( - "l3 ip4 proto l4 src_port", - "l3 ip4 proto 17 l4 src_port 2345") + "l3 ip4 proto l4 src_port", "l3 ip4 proto 17 l4 src_port 2345" + ) # the packet we are trying to match p = list() for i in range(100): src = self.pg0.remote_hosts[i % len(self.pg0.remote_hosts)].ip4 - p.append((Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=src, dst=self.pg1.remote_ip4) / - UDP(sport=1234, dport=2345) / Raw('\xa5' * 100))) + p.append( + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=src, dst=self.pg1.remote_ip4) + / UDP(sport=1234, dport=2345) + / Raw("\xa5" * 100) + ) + ) for i in range(17): - p.append((Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_hosts[0].ip4, - dst=self.pg1.remote_ip4) / - UDP(sport=2345, dport=1234) / Raw('\xa5' * 100))) + p.append( + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_hosts[0].ip4, dst=self.pg1.remote_ip4) + / UDP(sport=2345, dport=1234) + / Raw("\xa5" * 100) + ) + ) self.send_and_expect(self.pg0, p, self.pg1, trace=False) @@ -108,21 +119,23 @@ class TestTracefilter(VppTestCase): self.del_trace_filters() def test_encap(self): - """ Packet Tracer Filter Test with encap """ + """Packet Tracer Filter Test with encap""" # the packet we are trying to match - p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / - UDP() / - VXLAN() / - Ether() / - IP() / - UDP() / - GENEVE(vni=1234) / - Ether() / - IP(src='192.168.4.167') / - UDP() / - Raw('\xa5' * 100)) + p = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / UDP() + / VXLAN() + / Ether() + / IP() + / UDP() + / GENEVE(vni=1234) + / Ether() + / IP(src="192.168.4.167") + / UDP() + / Raw("\xa5" * 100) + ) # # compute filter mask & value @@ -130,29 +143,31 @@ class TestTracefilter(VppTestCase): # we need to set checksums to 0 to make sure scapy will not recompute # them # - tmpl = (Ether() / - IP(chksum=0) / - UDP(chksum=0) / - VXLAN() / - Ether() / - IP(chksum=0) / - UDP(chksum=0) / - GENEVE(vni=0) / - Ether() / - IP(src='0.0.0.0', chksum=0)) + tmpl = ( + Ether() + / IP(chksum=0) + / UDP(chksum=0) + / VXLAN() + / Ether() + / IP(chksum=0) + / UDP(chksum=0) + / GENEVE(vni=0) + / Ether() + / IP(src="0.0.0.0", chksum=0) + ) ori = raw(tmpl) # the mask - tmpl[GENEVE].vni = 0xffffff + tmpl[GENEVE].vni = 0xFFFFFF user = tmpl[GENEVE].payload - user[IP].src = '255.255.255.255' + user[IP].src = "255.255.255.255" new = raw(tmpl) mask = "".join(("{:02x}".format(o ^ n) for o, n in zip(ori, new))) # this does not match (wrong vni) tmpl[GENEVE].vni = 1 user = tmpl[GENEVE].payload - user[IP].src = '192.168.4.167' + user[IP].src = "192.168.4.167" new = raw(tmpl) match = "".join(("{:02x}".format(o ^ n) for o, n in zip(ori, new))) self.assert_classify(mask, match, [p] * 11, 0) @@ -164,29 +179,41 @@ class TestTracefilter(VppTestCase): self.assert_classify(mask, match, [p] * 17) def test_pcap(self): - """ Packet Capture Filter Test """ + """Packet Capture Filter Test""" self.cli( - "classify filter pcap mask l3 ip4 src match l3 ip4 src %s" % - self.pg0.remote_hosts[5].ip4) + "classify filter pcap mask l3 ip4 src match l3 ip4 src %s" + % self.pg0.remote_hosts[5].ip4 + ) self.cli( "classify filter pcap " "mask l3 ip4 proto l4 src_port " - "match l3 ip4 proto 17 l4 src_port 2345") + "match l3 ip4 proto 17 l4 src_port 2345" + ) self.cli( "pcap trace rx tx max 1000 intfc pg0 " - "file vpp_test_trace_filter_test_pcap.pcap filter") + "file vpp_test_trace_filter_test_pcap.pcap filter" + ) # the packet we are trying to match p = list() for i in range(100): src = self.pg0.remote_hosts[i % len(self.pg0.remote_hosts)].ip4 - p.append((Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=src, dst=self.pg1.remote_ip4) / - UDP(sport=1234, dport=2345) / Raw('\xa5' * 100))) + p.append( + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=src, dst=self.pg1.remote_ip4) + / UDP(sport=1234, dport=2345) + / Raw("\xa5" * 100) + ) + ) for i in range(17): - p.append((Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_hosts[0].ip4, - dst=self.pg1.remote_ip4) / - UDP(sport=2345, dport=1234) / Raw('\xa5' * 100))) + p.append( + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_hosts[0].ip4, dst=self.pg1.remote_ip4) + / UDP(sport=2345, dport=1234) + / Raw("\xa5" * 100) + ) + ) self.send_and_expect(self.pg0, p, self.pg1, trace=False) @@ -208,28 +235,42 @@ class TestTracefilter(VppTestCase): self.assertEqual(str(pcap[i]), p_) def test_pcap_drop(self): - """ Drop Packet Capture Filter Test """ + """Drop Packet Capture Filter Test""" self.cli( "pcap trace drop max 1000 " "error {ip4-udp-lookup}.{no_listener} " - "file vpp_test_trace_filter_test_pcap_drop.pcap") + "file vpp_test_trace_filter_test_pcap_drop.pcap" + ) # the packet we are trying to match p = list() for i in range(17): # this packet should be forwarded - p.append((Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_hosts[0].ip4, - dst=self.pg1.remote_ip4) / - UDP(sport=2345, dport=1234) / Raw('\xa5' * 100))) + p.append( + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_hosts[0].ip4, dst=self.pg1.remote_ip4) + / UDP(sport=2345, dport=1234) + / Raw("\xa5" * 100) + ) + ) # this packet should be captured (no listener) - p.append((Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_hosts[0].ip4, - dst=self.pg0.local_ip4) / - UDP(sport=2345, dport=1234) / Raw('\xa5' * 100))) + p.append( + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_hosts[0].ip4, dst=self.pg0.local_ip4) + / UDP(sport=2345, dport=1234) + / Raw("\xa5" * 100) + ) + ) # this packet will be blackholed but not captured - p.append((Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_hosts[0].ip4, dst="0.0.0.0") / - UDP(sport=2345, dport=1234) / Raw('\xa5' * 100))) + p.append( + ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_hosts[0].ip4, dst="0.0.0.0") + / UDP(sport=2345, dport=1234) + / Raw("\xa5" * 100) + ) + ) self.send_and_expect(self.pg0, p, self.pg1, n_rx=17, trace=False) @@ -240,5 +281,5 @@ class TestTracefilter(VppTestCase): self.assertEqual(len(pcap), 17) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_udp.py b/test/test_udp.py index 031867cf63d..c7e97c641b8 100644 --- a/test/test_udp.py +++ b/test/test_udp.py @@ -5,8 +5,16 @@ from framework import VppTestCase, VppTestRunner from vpp_udp_encap import find_udp_encap, VppUdpEncap from vpp_udp_decap import VppUdpDecap -from vpp_ip_route import VppIpRoute, VppRoutePath, VppIpTable, VppMplsLabel, \ - VppMplsTable, VppMplsRoute, FibPathType, FibPathProto +from vpp_ip_route import ( + VppIpRoute, + VppRoutePath, + VppIpTable, + VppMplsLabel, + VppMplsTable, + VppMplsRoute, + FibPathType, + FibPathProto, +) from vpp_neighbor import VppNeighbor from vpp_papi import VppEnum @@ -21,7 +29,7 @@ NUM_PKTS = 67 @tag_fixme_vpp_workers class TestUdpEncap(VppTestCase): - """ UDP Encap Test Case """ + """UDP Encap Test Case""" @classmethod def setUpClass(cls): @@ -99,8 +107,7 @@ class TestUdpEncap(VppTestCase): self.assertEqual(rx.hlim, tx[IPv6].hlim) def test_udp_encap(self): - """ UDP Encap test - """ + """UDP Encap test""" # # construct a UDP encap object through each of the peers @@ -109,29 +116,21 @@ class TestUdpEncap(VppTestCase): # where 2 different udp encap objects are processed at the # same time # - udp_encap_0 = VppUdpEncap(self, - self.pg0.local_ip4, - self.pg0.remote_ip4, - 330, 440) - udp_encap_1 = VppUdpEncap(self, - self.pg1.local_ip4, - self.pg1.remote_ip4, - 331, 441, - table_id=1) - udp_encap_2 = VppUdpEncap(self, - self.pg2.local_ip6, - self.pg2.remote_ip6, - 332, 442, - table_id=2) - udp_encap_3 = VppUdpEncap(self, - self.pg3.local_ip6, - self.pg3.remote_ip6, - 333, 443, - table_id=3) - udp_encap_4 = VppUdpEncap(self, - self.pg0.local_ip4, - self.pg0.remote_ip4, - 334, 444) + udp_encap_0 = VppUdpEncap( + self, self.pg0.local_ip4, self.pg0.remote_ip4, 330, 440 + ) + udp_encap_1 = VppUdpEncap( + self, self.pg1.local_ip4, self.pg1.remote_ip4, 331, 441, table_id=1 + ) + udp_encap_2 = VppUdpEncap( + self, self.pg2.local_ip6, self.pg2.remote_ip6, 332, 442, table_id=2 + ) + udp_encap_3 = VppUdpEncap( + self, self.pg3.local_ip6, self.pg3.remote_ip6, 333, 443, table_id=3 + ) + udp_encap_4 = VppUdpEncap( + self, self.pg0.local_ip4, self.pg0.remote_ip4, 334, 444 + ) udp_encap_0.add_vpp_config() udp_encap_1.add_vpp_config() udp_encap_2.add_vpp_config() @@ -150,44 +149,79 @@ class TestUdpEncap(VppTestCase): # Routes via each UDP encap object - all combinations of v4 and v6. # route_4o4 = VppIpRoute( - self, "1.1.0.1", 24, - [VppRoutePath("0.0.0.0", - 0xFFFFFFFF, - type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP, - next_hop_id=udp_encap_0.id, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP4)], - table_id=1) + self, + "1.1.0.1", + 24, + [ + VppRoutePath( + "0.0.0.0", + 0xFFFFFFFF, + type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP, + next_hop_id=udp_encap_0.id, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP4, + ) + ], + table_id=1, + ) # specific route to match encap4, to test encap of 2 packets using 2 # different encap route_4o4_2 = VppIpRoute( - self, "1.1.0.2", 32, - [VppRoutePath("0.0.0.0", - 0xFFFFFFFF, - type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP, - next_hop_id=udp_encap_4.id, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP4)], - table_id=1) + self, + "1.1.0.2", + 32, + [ + VppRoutePath( + "0.0.0.0", + 0xFFFFFFFF, + type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP, + next_hop_id=udp_encap_4.id, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP4, + ) + ], + table_id=1, + ) route_4o6 = VppIpRoute( - self, "1.1.2.1", 32, - [VppRoutePath("0.0.0.0", - 0xFFFFFFFF, - type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP, - next_hop_id=udp_encap_2.id, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP4)]) + self, + "1.1.2.1", + 32, + [ + VppRoutePath( + "0.0.0.0", + 0xFFFFFFFF, + type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP, + next_hop_id=udp_encap_2.id, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP4, + ) + ], + ) route_6o4 = VppIpRoute( - self, "2001::1", 128, - [VppRoutePath("0.0.0.0", - 0xFFFFFFFF, - type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP, - next_hop_id=udp_encap_1.id, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)]) + self, + "2001::1", + 128, + [ + VppRoutePath( + "0.0.0.0", + 0xFFFFFFFF, + type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP, + next_hop_id=udp_encap_1.id, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ) + ], + ) route_6o6 = VppIpRoute( - self, "2001::3", 128, - [VppRoutePath("0.0.0.0", - 0xFFFFFFFF, - type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP, - next_hop_id=udp_encap_3.id, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)]) + self, + "2001::3", + 128, + [ + VppRoutePath( + "0.0.0.0", + 0xFFFFFFFF, + type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP, + next_hop_id=udp_encap_3.id, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP6, + ) + ], + ) route_4o6.add_vpp_config() route_6o6.add_vpp_config() route_6o4.add_vpp_config() @@ -200,104 +234,117 @@ class TestUdpEncap(VppTestCase): # the packet vector so that we encap 2 packets with different udp # encap object at the same time # - p_4o4 = (Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) / - IP(src="2.2.2.2", dst="1.1.0.1") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - p_4o4_2 = (Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) / - IP(src="2.2.2.2", dst="1.1.0.2") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) + p_4o4 = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src="2.2.2.2", dst="1.1.0.1") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + p_4o4_2 = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IP(src="2.2.2.2", dst="1.1.0.2") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) rx = self.send_and_expect( - self.pg1, p_4o4_2 * 1 + p_4o4 * (NUM_PKTS - 1), self.pg0) + self.pg1, p_4o4_2 * 1 + p_4o4 * (NUM_PKTS - 1), self.pg0 + ) # checking encap4 magic packet p = rx.pop(0) self.validate_outer4(p, udp_encap_4) p = IP(p["UDP"].payload.load) self.validate_inner4(p, p_4o4_2) - self.assertEqual(udp_encap_4.get_stats()['packets'], 1) + self.assertEqual(udp_encap_4.get_stats()["packets"], 1) # checking remaining packets for encap0 for p in rx: self.validate_outer4(p, udp_encap_0) p = IP(p["UDP"].payload.load) self.validate_inner4(p, p_4o4) - self.assertEqual(udp_encap_0.get_stats()['packets'], NUM_PKTS - 1) + self.assertEqual(udp_encap_0.get_stats()["packets"], NUM_PKTS - 1) # # 4o6 encap # - p_4o6 = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src="2.2.2.2", dst="1.1.2.1") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - rx = self.send_and_expect(self.pg0, p_4o6*NUM_PKTS, self.pg2) + p_4o6 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src="2.2.2.2", dst="1.1.2.1") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + rx = self.send_and_expect(self.pg0, p_4o6 * NUM_PKTS, self.pg2) for p in rx: self.validate_outer6(p, udp_encap_2) p = IP(p["UDP"].payload.load) self.validate_inner4(p, p_4o6) - self.assertEqual(udp_encap_2.get_stats()['packets'], NUM_PKTS) + self.assertEqual(udp_encap_2.get_stats()["packets"], NUM_PKTS) # # 6o4 encap # - p_6o4 = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(src="2001::100", dst="2001::1") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - rx = self.send_and_expect(self.pg0, p_6o4*NUM_PKTS, self.pg1) + p_6o4 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src="2001::100", dst="2001::1") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + rx = self.send_and_expect(self.pg0, p_6o4 * NUM_PKTS, self.pg1) for p in rx: self.validate_outer4(p, udp_encap_1) p = IPv6(p["UDP"].payload.load) self.validate_inner6(p, p_6o4) - self.assertEqual(udp_encap_1.get_stats()['packets'], NUM_PKTS) + self.assertEqual(udp_encap_1.get_stats()["packets"], NUM_PKTS) # # 6o6 encap # - p_6o6 = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IPv6(src="2001::100", dst="2001::3") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - rx = self.send_and_expect(self.pg0, p_6o6*NUM_PKTS, self.pg3) + p_6o6 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src="2001::100", dst="2001::3") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + rx = self.send_and_expect(self.pg0, p_6o6 * NUM_PKTS, self.pg3) for p in rx: self.validate_outer6(p, udp_encap_3) p = IPv6(p["UDP"].payload.load) self.validate_inner6(p, p_6o6) - self.assertEqual(udp_encap_3.get_stats()['packets'], NUM_PKTS) + self.assertEqual(udp_encap_3.get_stats()["packets"], NUM_PKTS) # # A route with an output label # the TTL of the inner packet is decremented on LSP ingress # route_4oMPLSo4 = VppIpRoute( - self, "1.1.2.22", 32, - [VppRoutePath("0.0.0.0", - 0xFFFFFFFF, - type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP, - next_hop_id=1, - labels=[VppMplsLabel(66)])]) + self, + "1.1.2.22", + 32, + [ + VppRoutePath( + "0.0.0.0", + 0xFFFFFFFF, + type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP, + next_hop_id=1, + labels=[VppMplsLabel(66)], + ) + ], + ) route_4oMPLSo4.add_vpp_config() - p_4omo4 = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src="2.2.2.2", dst="1.1.2.22") / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) - rx = self.send_and_expect(self.pg0, p_4omo4*NUM_PKTS, self.pg1) + p_4omo4 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src="2.2.2.2", dst="1.1.2.22") + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) + rx = self.send_and_expect(self.pg0, p_4omo4 * NUM_PKTS, self.pg1) for p in rx: self.validate_outer4(p, udp_encap_1) p = MPLS(p["UDP"].payload.load) self.validate_inner4(p, p_4omo4, ttl=63) - self.assertEqual(udp_encap_1.get_stats()['packets'], 2*NUM_PKTS) + self.assertEqual(udp_encap_1.get_stats()["packets"], 2 * NUM_PKTS) def test_udp_decap(self): - """ UDP Decap test - """ + """UDP Decap test""" # # construct a UDP decap object for each type of protocol # @@ -323,19 +370,24 @@ class TestUdpEncap(VppTestCase): # Routes via the corresponding pg after the UDP decap # route_4 = VppIpRoute( - self, "1.1.1.1", 32, + self, + "1.1.1.1", + 32, [VppRoutePath("0.0.0.0", self.pg0.sw_if_index)], - table_id=0) + table_id=0, + ) route_6 = VppIpRoute( - self, "2001::1", 128, - [VppRoutePath("::", self.pg1.sw_if_index)], - table_id=1) + self, "2001::1", 128, [VppRoutePath("::", self.pg1.sw_if_index)], table_id=1 + ) route_mo4 = VppIpRoute( - self, "3.3.3.3", 32, + self, + "3.3.3.3", + 32, [VppRoutePath("0.0.0.0", self.pg2.sw_if_index)], - table_id=2) + table_id=2, + ) route_4.add_vpp_config() route_6.add_vpp_config() @@ -344,18 +396,9 @@ class TestUdpEncap(VppTestCase): # # Adding neighbors to route the packets # - n_4 = VppNeighbor(self, - self.pg0.sw_if_index, - "00:11:22:33:44:55", - "1.1.1.1") - n_6 = VppNeighbor(self, - self.pg1.sw_if_index, - "11:22:33:44:55:66", - "2001::1") - n_mo4 = VppNeighbor(self, - self.pg2.sw_if_index, - "22:33:44:55:66:77", - "3.3.3.3") + n_4 = VppNeighbor(self, self.pg0.sw_if_index, "00:11:22:33:44:55", "1.1.1.1") + n_6 = VppNeighbor(self, self.pg1.sw_if_index, "11:22:33:44:55:66", "2001::1") + n_mo4 = VppNeighbor(self, self.pg2.sw_if_index, "22:33:44:55:66:77", "3.3.3.3") n_4.add_vpp_config() n_6.add_vpp_config() @@ -367,25 +410,33 @@ class TestUdpEncap(VppTestCase): mpls_table = VppMplsTable(self, 0) mpls_table.add_vpp_config() mpls_route = VppMplsRoute( - self, 77, 1, - [VppRoutePath("0.0.0.0", - 0xFFFFFFFF, - nh_table_id=2, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP4)]) + self, + 77, + 1, + [ + VppRoutePath( + "0.0.0.0", + 0xFFFFFFFF, + nh_table_id=2, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP4, + ) + ], + ) mpls_route.add_vpp_config() # # UDP over ipv4 decap # - p_4 = (Ether(src=self.pg0.remote_mac, - dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / - UDP(sport=1111, dport=220) / - IP(src="2.2.2.2", dst="1.1.1.1") / - UDP(sport=1234, dport=4321) / - Raw(b'\xa5' * 100)) - - rx = self.send_and_expect(self.pg0, p_4*NUM_PKTS, self.pg0) + p_4 = ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / UDP(sport=1111, dport=220) + / IP(src="2.2.2.2", dst="1.1.1.1") + / UDP(sport=1234, dport=4321) + / Raw(b"\xa5" * 100) + ) + + rx = self.send_and_expect(self.pg0, p_4 * NUM_PKTS, self.pg0) p_4 = IP(p_4["UDP"].payload) for p in rx: p = IP(p["Ether"].payload) @@ -394,15 +445,16 @@ class TestUdpEncap(VppTestCase): # # UDP over ipv6 decap # - p_6 = (Ether(src=self.pg1.remote_mac, - dst=self.pg1.local_mac) / - IPv6(src=self.pg1.remote_ip6, dst=self.pg1.local_ip6) / - UDP(sport=2222, dport=221) / - IPv6(src="2001::100", dst="2001::1") / - UDP(sport=1234, dport=4321) / - Raw(b'\xa5' * 100)) - - rx = self.send_and_expect(self.pg1, p_6*NUM_PKTS, self.pg1) + p_6 = ( + Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) + / IPv6(src=self.pg1.remote_ip6, dst=self.pg1.local_ip6) + / UDP(sport=2222, dport=221) + / IPv6(src="2001::100", dst="2001::1") + / UDP(sport=1234, dport=4321) + / Raw(b"\xa5" * 100) + ) + + rx = self.send_and_expect(self.pg1, p_6 * NUM_PKTS, self.pg1) p_6 = IPv6(p_6["UDP"].payload) p = IPv6(rx[0]["Ether"].payload) for p in rx: @@ -412,17 +464,18 @@ class TestUdpEncap(VppTestCase): # # UDP over mpls decap # - p_mo4 = (Ether(src=self.pg2.remote_mac, - dst=self.pg2.local_mac) / - IP(src=self.pg2.remote_ip4, dst=self.pg2.local_ip4) / - UDP(sport=3333, dport=222) / - MPLS(label=77, ttl=1) / - IP(src="4.4.4.4", dst="3.3.3.3") / - UDP(sport=1234, dport=4321) / - Raw(b'\xa5' * 100)) + p_mo4 = ( + Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) + / IP(src=self.pg2.remote_ip4, dst=self.pg2.local_ip4) + / UDP(sport=3333, dport=222) + / MPLS(label=77, ttl=1) + / IP(src="4.4.4.4", dst="3.3.3.3") + / UDP(sport=1234, dport=4321) + / Raw(b"\xa5" * 100) + ) self.pg2.enable_mpls() - rx = self.send_and_expect(self.pg2, p_mo4*NUM_PKTS, self.pg2) + rx = self.send_and_expect(self.pg2, p_mo4 * NUM_PKTS, self.pg2) self.pg2.disable_mpls() p_mo4 = IP(MPLS(p_mo4["UDP"].payload).payload) for p in rx: @@ -432,7 +485,7 @@ class TestUdpEncap(VppTestCase): @tag_fixme_vpp_workers class TestUDP(VppTestCase): - """ UDP Test Case """ + """UDP Test Case""" @classmethod def setUpClass(cls): @@ -461,10 +514,12 @@ class TestUDP(VppTestCase): table_id += 1 # Configure namespaces - self.vapi.app_namespace_add_del(namespace_id="0", - sw_if_index=self.loop0.sw_if_index) - self.vapi.app_namespace_add_del(namespace_id="1", - sw_if_index=self.loop1.sw_if_index) + self.vapi.app_namespace_add_del( + namespace_id="0", sw_if_index=self.loop0.sw_if_index + ) + self.vapi.app_namespace_add_del( + namespace_id="1", sw_if_index=self.loop1.sw_if_index + ) def tearDown(self): for i in self.lo_interfaces: @@ -475,31 +530,40 @@ class TestUDP(VppTestCase): super(TestUDP, self).tearDown() def test_udp_transfer(self): - """ UDP echo client/server transfer """ + """UDP echo client/server transfer""" # Add inter-table routes - ip_t01 = VppIpRoute(self, self.loop1.local_ip4, 32, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_table_id=1)]) - ip_t10 = VppIpRoute(self, self.loop0.local_ip4, 32, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_table_id=0)], table_id=1) + ip_t01 = VppIpRoute( + self, + self.loop1.local_ip4, + 32, + [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=1)], + ) + ip_t10 = VppIpRoute( + self, + self.loop0.local_ip4, + 32, + [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=0)], + table_id=1, + ) ip_t01.add_vpp_config() ip_t10.add_vpp_config() # Start builtin server and client uri = "udp://" + self.loop0.local_ip4 + "/1234" - error = self.vapi.cli("test echo server appns 0 fifo-size 4 no-echo" + - "uri " + uri) + error = self.vapi.cli( + "test echo server appns 0 fifo-size 4 no-echo" + "uri " + uri + ) if error: self.logger.critical(error) self.assertNotIn("failed", error) - error = self.vapi.cli("test echo client mbytes 10 appns 1 " + - "fifo-size 4 no-output test-bytes " + - "syn-timeout 2 no-return uri " + uri) + error = self.vapi.cli( + "test echo client mbytes 10 appns 1 " + + "fifo-size 4 no-output test-bytes " + + "syn-timeout 2 no-return uri " + + uri + ) if error: self.logger.critical(error) self.assertNotIn("failed", error) @@ -511,5 +575,5 @@ class TestUDP(VppTestCase): ip_t10.remove_vpp_config() -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_urpf.py b/test/test_urpf.py index 8f4e563f8bc..e0dc1210bfc 100644 --- a/test/test_urpf.py +++ b/test/test_urpf.py @@ -15,7 +15,7 @@ N_PKTS = 63 class TestURPF(VppTestCase): - """ Unicast Reverse Path Forwarding Test Case """ + """Unicast Reverse Path Forwarding Test Case""" @classmethod def setUpClass(cls): @@ -47,26 +47,27 @@ class TestURPF(VppTestCase): super(TestURPF, self).tearDown() def test_urpf4(self): - """ uRPF IP4 """ + """uRPF IP4""" e = VppEnum - p_spoof_loose = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IP(src="3.3.3.3", dst=self.pg1.remote_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) * N_PKTS - p_spoof_strict = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IP(src=self.pg2.remote_ip4, - dst=self.pg1.remote_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) * N_PKTS - p_good = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, - dst=self.pg1.remote_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) * N_PKTS + p_spoof_loose = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src="3.3.3.3", dst=self.pg1.remote_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) * N_PKTS + p_spoof_strict = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg2.remote_ip4, dst=self.pg1.remote_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) * N_PKTS + p_good = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) * N_PKTS # # before adding the uRPF, ensure all packets are forwarded @@ -78,10 +79,12 @@ class TestURPF(VppTestCase): # # apply loose uRPF check on pg0 rx # - self.vapi.urpf_update(is_input=True, - mode=e.vl_api_urpf_mode_t.URPF_API_MODE_LOOSE, - af=e.vl_api_address_family_t.ADDRESS_IP4, - sw_if_index=self.pg0.sw_if_index) + self.vapi.urpf_update( + is_input=True, + mode=e.vl_api_urpf_mode_t.URPF_API_MODE_LOOSE, + af=e.vl_api_address_family_t.ADDRESS_IP4, + sw_if_index=self.pg0.sw_if_index, + ) # good packets still pass self.send_and_expect(self.pg0, p_good, self.pg1) @@ -90,16 +93,17 @@ class TestURPF(VppTestCase): # packets from address to which there is no route are dropped self.send_and_assert_no_replies(self.pg0, p_spoof_loose) - self.assert_error_counter_equal("/err/ip4-rx-urpf-loose/uRPF Drop", - N_PKTS) + self.assert_error_counter_equal("/err/ip4-rx-urpf-loose/uRPF Drop", N_PKTS) # # crank it up to strict mode # - self.vapi.urpf_update(is_input=True, - mode=e.vl_api_urpf_mode_t.URPF_API_MODE_STRICT, - af=e.vl_api_address_family_t.ADDRESS_IP4, - sw_if_index=self.pg0.sw_if_index) + self.vapi.urpf_update( + is_input=True, + mode=e.vl_api_urpf_mode_t.URPF_API_MODE_STRICT, + af=e.vl_api_address_family_t.ADDRESS_IP4, + sw_if_index=self.pg0.sw_if_index, + ) # good packets still pass self.send_and_expect(self.pg0, p_good, self.pg1) @@ -107,16 +111,17 @@ class TestURPF(VppTestCase): self.send_and_assert_no_replies(self.pg0, p_spoof_strict) self.send_and_assert_no_replies(self.pg0, p_spoof_loose) - self.assert_error_counter_equal("/err/ip4-rx-urpf-strict/uRPF Drop", - 2 * N_PKTS) + self.assert_error_counter_equal("/err/ip4-rx-urpf-strict/uRPF Drop", 2 * N_PKTS) # # disable uRPF, all traffic should pass # - self.vapi.urpf_update(is_input=True, - mode=e.vl_api_urpf_mode_t.URPF_API_MODE_OFF, - af=e.vl_api_address_family_t.ADDRESS_IP4, - sw_if_index=self.pg0.sw_if_index) + self.vapi.urpf_update( + is_input=True, + mode=e.vl_api_urpf_mode_t.URPF_API_MODE_OFF, + af=e.vl_api_address_family_t.ADDRESS_IP4, + sw_if_index=self.pg0.sw_if_index, + ) self.send_and_expect(self.pg0, p_good, self.pg1) self.send_and_expect(self.pg0, p_spoof_strict, self.pg1) @@ -129,22 +134,25 @@ class TestURPF(VppTestCase): # for strict they should not be forwarded if they would be # forwarded thru that interface. # - self.vapi.urpf_update(is_input=False, - mode=e.vl_api_urpf_mode_t.URPF_API_MODE_LOOSE, - af=e.vl_api_address_family_t.ADDRESS_IP4, - sw_if_index=self.pg1.sw_if_index) + self.vapi.urpf_update( + is_input=False, + mode=e.vl_api_urpf_mode_t.URPF_API_MODE_LOOSE, + af=e.vl_api_address_family_t.ADDRESS_IP4, + sw_if_index=self.pg1.sw_if_index, + ) self.send_and_expect(self.pg0, p_good, self.pg1) self.send_and_expect(self.pg0, p_spoof_strict, self.pg1) self.send_and_assert_no_replies(self.pg0, p_spoof_loose) - self.assert_error_counter_equal("/err/ip4-tx-urpf-loose/uRPF Drop", - N_PKTS) + self.assert_error_counter_equal("/err/ip4-tx-urpf-loose/uRPF Drop", N_PKTS) - self.vapi.urpf_update(is_input=False, - mode=e.vl_api_urpf_mode_t.URPF_API_MODE_STRICT, - af=e.vl_api_address_family_t.ADDRESS_IP4, - sw_if_index=self.pg1.sw_if_index) + self.vapi.urpf_update( + is_input=False, + mode=e.vl_api_urpf_mode_t.URPF_API_MODE_STRICT, + af=e.vl_api_address_family_t.ADDRESS_IP4, + sw_if_index=self.pg1.sw_if_index, + ) self.send_and_expect(self.pg0, p_good, self.pg1) # the strict packet, from a peer is allowed, since it does @@ -152,48 +160,49 @@ class TestURPF(VppTestCase): self.send_and_expect(self.pg0, p_spoof_strict, self.pg1) self.send_and_assert_no_replies(self.pg0, p_spoof_loose) - self.assert_error_counter_equal("/err/ip4-tx-urpf-strict/uRPF Drop", - N_PKTS) + self.assert_error_counter_equal("/err/ip4-tx-urpf-strict/uRPF Drop", N_PKTS) # change the strict packet so that it would forward through pg1 - p_spoof_strict = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IP(src=self.pg1.remote_ip4, - dst=self.pg1.remote_ip4) / - UDP(sport=1234, dport=1234) / - Raw(b'\xa5' * 100)) * N_PKTS + p_spoof_strict = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg1.remote_ip4, dst=self.pg1.remote_ip4) + / UDP(sport=1234, dport=1234) + / Raw(b"\xa5" * 100) + ) * N_PKTS self.send_and_assert_no_replies(self.pg0, p_spoof_strict) - self.assert_error_counter_equal("/err/ip4-tx-urpf-strict/uRPF Drop", - 2 * N_PKTS) + self.assert_error_counter_equal("/err/ip4-tx-urpf-strict/uRPF Drop", 2 * N_PKTS) # cleanup - self.vapi.urpf_update(is_input=False, - mode=e.vl_api_urpf_mode_t.URPF_API_MODE_OFF, - af=e.vl_api_address_family_t.ADDRESS_IP4, - sw_if_index=self.pg1.sw_if_index) + self.vapi.urpf_update( + is_input=False, + mode=e.vl_api_urpf_mode_t.URPF_API_MODE_OFF, + af=e.vl_api_address_family_t.ADDRESS_IP4, + sw_if_index=self.pg1.sw_if_index, + ) def test_urpf6(self): - """ uRPF IP6 """ + """uRPF IP6""" e = VppEnum - p_spoof_loose = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IPv6(src="3::3", dst=self.pg1.remote_ip6) / - UDP(sport=1236, dport=1236) / - Raw(b'\xa5' * 100)) * N_PKTS - p_spoof_strict = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IPv6(src=self.pg2.remote_ip6, - dst=self.pg1.remote_ip6) / - UDP(sport=1236, dport=1236) / - Raw(b'\xa5' * 100)) * N_PKTS - p_good = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, - dst=self.pg1.remote_ip6) / - UDP(sport=1236, dport=1236) / - Raw(b'\xa5' * 100)) * N_PKTS + p_spoof_loose = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src="3::3", dst=self.pg1.remote_ip6) + / UDP(sport=1236, dport=1236) + / Raw(b"\xa5" * 100) + ) * N_PKTS + p_spoof_strict = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg2.remote_ip6, dst=self.pg1.remote_ip6) + / UDP(sport=1236, dport=1236) + / Raw(b"\xa5" * 100) + ) * N_PKTS + p_good = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6) + / UDP(sport=1236, dport=1236) + / Raw(b"\xa5" * 100) + ) * N_PKTS # # before adding the uRPF, ensure all packets are forwarded @@ -205,10 +214,12 @@ class TestURPF(VppTestCase): # # apply loose uRPF check on pg0 rx # - self.vapi.urpf_update(is_input=True, - mode=e.vl_api_urpf_mode_t.URPF_API_MODE_LOOSE, - af=e.vl_api_address_family_t.ADDRESS_IP6, - sw_if_index=self.pg0.sw_if_index) + self.vapi.urpf_update( + is_input=True, + mode=e.vl_api_urpf_mode_t.URPF_API_MODE_LOOSE, + af=e.vl_api_address_family_t.ADDRESS_IP6, + sw_if_index=self.pg0.sw_if_index, + ) # good packets still pass self.send_and_expect(self.pg0, p_good, self.pg1) @@ -217,16 +228,17 @@ class TestURPF(VppTestCase): # packets from address to which there is no route are dropped self.send_and_assert_no_replies(self.pg0, p_spoof_loose) - self.assert_error_counter_equal("/err/ip6-rx-urpf-loose/uRPF Drop", - N_PKTS) + self.assert_error_counter_equal("/err/ip6-rx-urpf-loose/uRPF Drop", N_PKTS) # # crank it up to strict mode # - self.vapi.urpf_update(is_input=True, - mode=e.vl_api_urpf_mode_t.URPF_API_MODE_STRICT, - af=e.vl_api_address_family_t.ADDRESS_IP6, - sw_if_index=self.pg0.sw_if_index) + self.vapi.urpf_update( + is_input=True, + mode=e.vl_api_urpf_mode_t.URPF_API_MODE_STRICT, + af=e.vl_api_address_family_t.ADDRESS_IP6, + sw_if_index=self.pg0.sw_if_index, + ) # good packets still pass self.send_and_expect(self.pg0, p_good, self.pg1) @@ -234,16 +246,17 @@ class TestURPF(VppTestCase): self.send_and_assert_no_replies(self.pg0, p_spoof_strict) self.send_and_assert_no_replies(self.pg0, p_spoof_loose) - self.assert_error_counter_equal("/err/ip6-rx-urpf-strict/uRPF Drop", - 2 * N_PKTS) + self.assert_error_counter_equal("/err/ip6-rx-urpf-strict/uRPF Drop", 2 * N_PKTS) # # disable uRPF, all traffic should pass # - self.vapi.urpf_update(is_input=True, - mode=e.vl_api_urpf_mode_t.URPF_API_MODE_OFF, - af=e.vl_api_address_family_t.ADDRESS_IP6, - sw_if_index=self.pg0.sw_if_index) + self.vapi.urpf_update( + is_input=True, + mode=e.vl_api_urpf_mode_t.URPF_API_MODE_OFF, + af=e.vl_api_address_family_t.ADDRESS_IP6, + sw_if_index=self.pg0.sw_if_index, + ) self.send_and_expect(self.pg0, p_good, self.pg1) self.send_and_expect(self.pg0, p_spoof_strict, self.pg1) @@ -256,22 +269,25 @@ class TestURPF(VppTestCase): # for strict they should not be forwarded if they would be # forwarded thru that interface. # - self.vapi.urpf_update(is_input=False, - mode=e.vl_api_urpf_mode_t.URPF_API_MODE_LOOSE, - af=e.vl_api_address_family_t.ADDRESS_IP6, - sw_if_index=self.pg1.sw_if_index) + self.vapi.urpf_update( + is_input=False, + mode=e.vl_api_urpf_mode_t.URPF_API_MODE_LOOSE, + af=e.vl_api_address_family_t.ADDRESS_IP6, + sw_if_index=self.pg1.sw_if_index, + ) self.send_and_expect(self.pg0, p_good, self.pg1) self.send_and_expect(self.pg0, p_spoof_strict, self.pg1) self.send_and_assert_no_replies(self.pg0, p_spoof_loose) - self.assert_error_counter_equal("/err/ip6-tx-urpf-loose/uRPF Drop", - N_PKTS) + self.assert_error_counter_equal("/err/ip6-tx-urpf-loose/uRPF Drop", N_PKTS) - self.vapi.urpf_update(is_input=False, - mode=e.vl_api_urpf_mode_t.URPF_API_MODE_STRICT, - af=e.vl_api_address_family_t.ADDRESS_IP6, - sw_if_index=self.pg1.sw_if_index) + self.vapi.urpf_update( + is_input=False, + mode=e.vl_api_urpf_mode_t.URPF_API_MODE_STRICT, + af=e.vl_api_address_family_t.ADDRESS_IP6, + sw_if_index=self.pg1.sw_if_index, + ) self.send_and_expect(self.pg0, p_good, self.pg1) # the strict packet, from a peer is allowed, since it does @@ -279,27 +295,27 @@ class TestURPF(VppTestCase): self.send_and_expect(self.pg0, p_spoof_strict, self.pg1) self.send_and_assert_no_replies(self.pg0, p_spoof_loose) - self.assert_error_counter_equal("/err/ip6-tx-urpf-strict/uRPF Drop", - N_PKTS) + self.assert_error_counter_equal("/err/ip6-tx-urpf-strict/uRPF Drop", N_PKTS) # change the strict packet so that it would forward through pg1 - p_spoof_strict = (Ether(dst=self.pg0.local_mac, - src=self.pg0.remote_mac) / - IPv6(src=self.pg1.remote_ip6, - dst=self.pg1.remote_ip6) / - UDP(sport=1236, dport=1236) / - Raw(b'\xa5' * 100)) * N_PKTS + p_spoof_strict = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg1.remote_ip6, dst=self.pg1.remote_ip6) + / UDP(sport=1236, dport=1236) + / Raw(b"\xa5" * 100) + ) * N_PKTS self.send_and_assert_no_replies(self.pg0, p_spoof_strict) - self.assert_error_counter_equal("/err/ip6-tx-urpf-strict/uRPF Drop", - 2 * N_PKTS) + self.assert_error_counter_equal("/err/ip6-tx-urpf-strict/uRPF Drop", 2 * N_PKTS) # cleanup - self.vapi.urpf_update(is_input=False, - mode=e.vl_api_urpf_mode_t.URPF_API_MODE_OFF, - af=e.vl_api_address_family_t.ADDRESS_IP6, - sw_if_index=self.pg1.sw_if_index) + self.vapi.urpf_update( + is_input=False, + mode=e.vl_api_urpf_mode_t.URPF_API_MODE_OFF, + af=e.vl_api_address_family_t.ADDRESS_IP6, + sw_if_index=self.pg1.sw_if_index, + ) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_util.py b/test/test_util.py index 3a61d64b28f..52aeeb1691e 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -6,17 +6,17 @@ from framework import VppTestRunner, CPUInterface from vpp_papi import mac_pton, mac_ntop -class TestUtil (CPUInterface, unittest.TestCase): - """ Test framework utility tests """ +class TestUtil(CPUInterface, unittest.TestCase): + """Test framework utility tests""" @classmethod def is_tagged_run_solo(cls): - """ if the test case class is timing-sensitive - return true """ + """if the test case class is timing-sensitive - return true""" return False @classmethod def has_tag(cls, tag): - """ if the test case has a given tag - return true """ + """if the test case has a given tag - return true""" try: return tag in cls.test_tags except AttributeError: @@ -28,13 +28,13 @@ class TestUtil (CPUInterface, unittest.TestCase): return 0 def test_mac_to_binary(self): - """ MAC to binary and back """ - mac = 'aa:bb:cc:dd:ee:ff' + """MAC to binary and back""" + mac = "aa:bb:cc:dd:ee:ff" b = mac_pton(mac) mac2 = mac_ntop(b) self.assertEqual(type(mac), type(mac2)) self.assertEqual(mac2, mac) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_vapi.py b/test/test_vapi.py index 5a04abe4de7..6817fae6498 100644 --- a/test/test_vapi.py +++ b/test/test_vapi.py @@ -9,7 +9,7 @@ from framework import VppTestCase, VppTestRunner, Worker class VAPITestCase(VppTestCase): - """ VAPI test """ + """VAPI test""" @classmethod def setUpClass(cls): @@ -20,10 +20,11 @@ class VAPITestCase(VppTestCase): super(VAPITestCase, cls).tearDownClass() def test_vapi_c(self): - """ run C VAPI tests """ + """run C VAPI tests""" executable = f"{config.vpp_build_dir}/vpp/bin/vapi_c_test" - worker = Worker([executable, "vapi client", - self.get_api_segment_prefix()], self.logger) + worker = Worker( + [executable, "vapi client", self.get_api_segment_prefix()], self.logger + ) worker.start() timeout = 60 worker.join(timeout) @@ -32,23 +33,22 @@ class VAPITestCase(VppTestCase): if worker.result is None: try: error = True - self.logger.error( - "Timeout! Worker did not finish in %ss" % timeout) + self.logger.error("Timeout! Worker did not finish in %ss" % timeout) os.killpg(os.getpgid(worker.process.pid), signal.SIGTERM) worker.join() except: self.logger.debug("Couldn't kill worker-spawned process") raise if error: - raise Exception( - "Timeout! Worker did not finish in %ss" % timeout) + raise Exception("Timeout! Worker did not finish in %ss" % timeout) self.assert_equal(worker.result, 0, "Binary test return code") def test_vapi_cpp(self): - """ run C++ VAPI tests """ + """run C++ VAPI tests""" executable = f"{config.vpp_build_dir}/vpp/bin/vapi_cpp_test" - worker = Worker([executable, "vapi client", - self.get_api_segment_prefix()], self.logger) + worker = Worker( + [executable, "vapi client", self.get_api_segment_prefix()], self.logger + ) worker.start() timeout = 120 worker.join(timeout) @@ -57,17 +57,15 @@ class VAPITestCase(VppTestCase): if worker.result is None: try: error = True - self.logger.error( - "Timeout! Worker did not finish in %ss" % timeout) + self.logger.error("Timeout! Worker did not finish in %ss" % timeout) os.killpg(os.getpgid(worker.process.pid), signal.SIGTERM) worker.join() except: raise Exception("Couldn't kill worker-spawned process") if error: - raise Exception( - "Timeout! Worker did not finish in %ss" % timeout) + raise Exception("Timeout! Worker did not finish in %ss" % timeout) self.assert_equal(worker.result, 0, "Binary test return code") -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_vcl.py b/test/test_vcl.py index 3875114c3b2..bf139fe0537 100644 --- a/test/test_vcl.py +++ b/test/test_vcl.py @@ -10,12 +10,12 @@ from config import config from framework import VppTestCase, VppTestRunner, Worker from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath, FibPathProto -iperf3 = '/usr/bin/iperf3' +iperf3 = "/usr/bin/iperf3" def have_app(app): try: - subprocess.check_output([app, '-v']) + subprocess.check_output([app, "-v"]) except (subprocess.CalledProcessError, OSError): return False return True @@ -25,22 +25,22 @@ _have_iperf3 = have_app(iperf3) class VCLAppWorker(Worker): - """ VCL Test Application Worker """ + """VCL Test Application Worker""" libname = "libvcl_ldpreload.so" class LibraryNotFound(Exception): pass - def __init__(self, appname, executable_args, logger, env=None, - role=None, *args, **kwargs): + def __init__( + self, appname, executable_args, logger, env=None, role=None, *args, **kwargs + ): self.role = role vcl_ldpreload_glob = f"{config.vpp_install_dir}/**/{self.libname}" vcl_ldpreload_so = glob.glob(vcl_ldpreload_glob, recursive=True) if len(vcl_ldpreload_so) < 1: - raise LibraryNotFound("cannot locate library: {}".format( - self.libname)) + raise LibraryNotFound("cannot locate library: {}".format(self.libname)) vcl_ldpreload_so = vcl_ldpreload_so[0] @@ -48,19 +48,19 @@ class VCLAppWorker(Worker): env = {} if "iperf" in appname: app = appname - env.update({'LD_PRELOAD': vcl_ldpreload_so}) + env.update({"LD_PRELOAD": vcl_ldpreload_so}) elif "sock" in appname: app = f"{config.vpp_build_dir}/vpp/bin/{appname}" - env.update({'LD_PRELOAD': vcl_ldpreload_so}) + env.update({"LD_PRELOAD": vcl_ldpreload_so}) else: app = f"{config.vpp_build_dir}/vpp/bin/{appname}" self.args = [app] + executable_args - super(VCLAppWorker, self).__init__(self.args, logger, env, - *args, **kwargs) + super(VCLAppWorker, self).__init__(self.args, logger, env, *args, **kwargs) class VCLTestCase(VppTestCase): - """ VCL Test Class """ + """VCL Test Class""" + session_startup = ["poll-main"] @classmethod @@ -75,7 +75,7 @@ class VCLTestCase(VppTestCase): super(VCLTestCase, cls).tearDownClass() def setUp(self): - self.vppDebug = 'vpp_debug' in config.vpp_install_dir + self.vppDebug = "vpp_debug" in config.vpp_install_dir self.server_addr = "127.0.0.1" self.server_port = "22000" self.server_args = [self.server_port] @@ -95,26 +95,26 @@ class VCLTestCase(VppTestCase): def update_vcl_app_env(self, ns_id, ns_secret, attach_sock): if not ns_id: - if 'VCL_APP_NAMESPACE_ID' in self.vcl_app_env: - del self.vcl_app_env['VCL_APP_NAMESPACE_ID'] + if "VCL_APP_NAMESPACE_ID" in self.vcl_app_env: + del self.vcl_app_env["VCL_APP_NAMESPACE_ID"] else: - self.vcl_app_env['VCL_APP_NAMESPACE_ID'] = ns_id + self.vcl_app_env["VCL_APP_NAMESPACE_ID"] = ns_id if not ns_secret: - if 'VCL_APP_NAMESPACE_SECRET' in self.vcl_app_env: - del self.vcl_app_env['VCL_APP_NAMESPACE_SECRET'] + if "VCL_APP_NAMESPACE_SECRET" in self.vcl_app_env: + del self.vcl_app_env["VCL_APP_NAMESPACE_SECRET"] else: - self.vcl_app_env['VCL_APP_NAMESPACE_SECRET'] = ns_secret + self.vcl_app_env["VCL_APP_NAMESPACE_SECRET"] = ns_secret if not attach_sock: - self.vcl_app_env['VCL_VPP_API_SOCKET'] = self.get_api_sock_path() - if 'VCL_VPP_SAPI_SOCKET' in self.vcl_app_env: - del self.vcl_app_env['VCL_VPP_SAPI_SOCKET'] + self.vcl_app_env["VCL_VPP_API_SOCKET"] = self.get_api_sock_path() + if "VCL_VPP_SAPI_SOCKET" in self.vcl_app_env: + del self.vcl_app_env["VCL_VPP_SAPI_SOCKET"] else: sapi_sock = "%s/app_ns_sockets/%s" % (self.tempdir, attach_sock) - self.vcl_app_env['VCL_VPP_SAPI_SOCKET'] = sapi_sock - if 'VCL_VPP_API_SOCKET' in self.vcl_app_env: - del self.vcl_app_env['VCL_VPP_API_SOCKET'] + self.vcl_app_env["VCL_VPP_SAPI_SOCKET"] = sapi_sock + if "VCL_VPP_API_SOCKET" in self.vcl_app_env: + del self.vcl_app_env["VCL_VPP_API_SOCKET"] def cut_thru_setup(self): self.vapi.session_enable_disable(is_enable=1) @@ -123,17 +123,19 @@ class VCLTestCase(VppTestCase): self.vapi.session_enable_disable(is_enable=0) def cut_thru_test(self, server_app, server_args, client_app, client_args): - self.vcl_app_env = {'VCL_APP_SCOPE_LOCAL': "true"} + self.vcl_app_env = {"VCL_APP_SCOPE_LOCAL": "true"} self.update_vcl_app_env("", "", self.sapi_server_sock) - worker_server = VCLAppWorker(server_app, server_args, - self.logger, self.vcl_app_env, "server") + worker_server = VCLAppWorker( + server_app, server_args, self.logger, self.vcl_app_env, "server" + ) worker_server.start() self.sleep(self.pre_test_sleep) self.update_vcl_app_env("", "", self.sapi_client_sock) - worker_client = VCLAppWorker(client_app, client_args, - self.logger, self.vcl_app_env, "client") + worker_client = VCLAppWorker( + client_app, client_args, self.logger, self.vcl_app_env, "client" + ) worker_client.start() worker_client.join(self.timeout) try: @@ -160,20 +162,28 @@ class VCLTestCase(VppTestCase): table_id += 1 # Configure namespaces - self.vapi.app_namespace_add_del(namespace_id="1", secret=1234, - sw_if_index=self.loop0.sw_if_index) - self.vapi.app_namespace_add_del(namespace_id="2", secret=5678, - sw_if_index=self.loop1.sw_if_index) + self.vapi.app_namespace_add_del( + namespace_id="1", secret=1234, sw_if_index=self.loop0.sw_if_index + ) + self.vapi.app_namespace_add_del( + namespace_id="2", secret=5678, sw_if_index=self.loop1.sw_if_index + ) # Add inter-table routes - ip_t01 = VppIpRoute(self, self.loop1.local_ip4, 32, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_table_id=2)], table_id=1) - ip_t10 = VppIpRoute(self, self.loop0.local_ip4, 32, - [VppRoutePath("0.0.0.0", - 0xffffffff, - nh_table_id=1)], table_id=2) + ip_t01 = VppIpRoute( + self, + self.loop1.local_ip4, + 32, + [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=2)], + table_id=1, + ) + ip_t10 = VppIpRoute( + self, + self.loop0.local_ip4, + 32, + [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=1)], + table_id=2, + ) ip_t01.add_vpp_config() ip_t10.add_vpp_config() self.logger.debug(self.vapi.cli("show ip fib")) @@ -201,20 +211,28 @@ class VCLTestCase(VppTestCase): table_id += 1 # Configure namespaces - self.vapi.app_namespace_add_del(namespace_id="1", secret=1234, - sw_if_index=self.loop0.sw_if_index) - self.vapi.app_namespace_add_del(namespace_id="2", secret=5678, - sw_if_index=self.loop1.sw_if_index) + self.vapi.app_namespace_add_del( + namespace_id="1", secret=1234, sw_if_index=self.loop0.sw_if_index + ) + self.vapi.app_namespace_add_del( + namespace_id="2", secret=5678, sw_if_index=self.loop1.sw_if_index + ) # Add inter-table routes - ip_t01 = VppIpRoute(self, self.loop1.local_ip6, 128, - [VppRoutePath("::0", 0xffffffff, - nh_table_id=2)], - table_id=1) - ip_t10 = VppIpRoute(self, self.loop0.local_ip6, 128, - [VppRoutePath("::0", 0xffffffff, - nh_table_id=1)], - table_id=2) + ip_t01 = VppIpRoute( + self, + self.loop1.local_ip6, + 128, + [VppRoutePath("::0", 0xFFFFFFFF, nh_table_id=2)], + table_id=1, + ) + ip_t10 = VppIpRoute( + self, + self.loop0.local_ip6, + 128, + [VppRoutePath("::0", 0xFFFFFFFF, nh_table_id=1)], + table_id=2, + ) ip_t01.add_vpp_config() ip_t10.add_vpp_config() self.logger.debug(self.vapi.cli("show interface addr")) @@ -229,19 +247,20 @@ class VCLTestCase(VppTestCase): self.vapi.session_enable_disable(is_enable=0) @unittest.skipUnless(_have_iperf3, "'%s' not found, Skipping.") - def thru_host_stack_test(self, server_app, server_args, - client_app, client_args): - self.vcl_app_env = {'VCL_APP_SCOPE_GLOBAL': "true"} + def thru_host_stack_test(self, server_app, server_args, client_app, client_args): + self.vcl_app_env = {"VCL_APP_SCOPE_GLOBAL": "true"} self.update_vcl_app_env("1", "1234", self.sapi_server_sock) - worker_server = VCLAppWorker(server_app, server_args, - self.logger, self.vcl_app_env, "server") + worker_server = VCLAppWorker( + server_app, server_args, self.logger, self.vcl_app_env, "server" + ) worker_server.start() self.sleep(self.pre_test_sleep) self.update_vcl_app_env("2", "5678", self.sapi_client_sock) - worker_client = VCLAppWorker(client_app, client_args, - self.logger, self.vcl_app_env, "client") + worker_client = VCLAppWorker( + client_app, client_args, self.logger, self.vcl_app_env, "client" + ) worker_client.start() worker_client.join(self.timeout) @@ -253,10 +272,11 @@ class VCLTestCase(VppTestCase): def validateResults(self, worker_client, worker_server, timeout): if worker_server.process is None: - raise RuntimeError('worker_server is not running.') - if os.path.isdir('/proc/{}'.format(worker_server.process.pid)): - self.logger.info("Killing server worker process (pid %d)" % - worker_server.process.pid) + raise RuntimeError("worker_server is not running.") + if os.path.isdir("/proc/{}".format(worker_server.process.pid)): + self.logger.info( + "Killing server worker process (pid %d)" % worker_server.process.pid + ) os.killpg(os.getpgid(worker_server.process.pid), signal.SIGTERM) worker_server.join() self.logger.info("Client worker result is `%s'" % worker_client.result) @@ -265,23 +285,21 @@ class VCLTestCase(VppTestCase): try: error = True self.logger.error( - "Timeout: %ss! Killing client worker process (pid %d)" % - (timeout, worker_client.process.pid)) - os.killpg(os.getpgid(worker_client.process.pid), - signal.SIGKILL) + "Timeout: %ss! Killing client worker process (pid %d)" + % (timeout, worker_client.process.pid) + ) + os.killpg(os.getpgid(worker_client.process.pid), signal.SIGKILL) worker_client.join() except OSError: - self.logger.debug( - "Couldn't kill client worker process") + self.logger.debug("Couldn't kill client worker process") raise if error: - raise RuntimeError( - "Timeout! Client worker did not finish in %ss" % timeout) + raise RuntimeError("Timeout! Client worker did not finish in %ss" % timeout) self.assert_equal(worker_client.result, 0, "Binary test return code") class LDPCutThruTestCase(VCLTestCase): - """ LDP Cut Thru Tests """ + """LDP Cut Thru Tests""" @classmethod def setUpClass(cls): @@ -296,21 +314,38 @@ class LDPCutThruTestCase(VCLTestCase): super(LDPCutThruTestCase, self).setUp() self.cut_thru_setup() - self.client_echo_test_args = ["-E", self.echo_phrase, "-X", - self.server_addr, self.server_port] + self.client_echo_test_args = [ + "-E", + self.echo_phrase, + "-X", + self.server_addr, + self.server_port, + ] self.client_iperf3_timeout = 20 self.client_iperf3_args = ["-4", "-t 2", "-c", self.server_addr] self.server_iperf3_args = ["-4", "-s"] self.client_uni_dir_nsock_timeout = 20 - self.client_uni_dir_nsock_test_args = ["-N", "1000", "-U", "-X", - "-I", "2", - self.server_addr, - self.server_port] + self.client_uni_dir_nsock_test_args = [ + "-N", + "1000", + "-U", + "-X", + "-I", + "2", + self.server_addr, + self.server_port, + ] self.client_bi_dir_nsock_timeout = 20 - self.client_bi_dir_nsock_test_args = ["-N", "1000", "-B", "-X", - "-I", "2", - self.server_addr, - self.server_port] + self.client_bi_dir_nsock_test_args = [ + "-N", + "1000", + "-B", + "-X", + "-I", + "2", + self.server_addr, + self.server_port, + ] self.sapi_client_sock = "default" self.sapi_server_sock = "default" @@ -324,40 +359,51 @@ class LDPCutThruTestCase(VCLTestCase): @unittest.skipUnless(config.extended, "part of extended tests") def test_ldp_cut_thru_echo(self): - """ run LDP cut thru echo test """ + """run LDP cut thru echo test""" - self.cut_thru_test("sock_test_server", self.server_args, - "sock_test_client", self.client_echo_test_args) + self.cut_thru_test( + "sock_test_server", + self.server_args, + "sock_test_client", + self.client_echo_test_args, + ) def test_ldp_cut_thru_iperf3(self): - """ run LDP cut thru iperf3 test """ + """run LDP cut thru iperf3 test""" self.timeout = self.client_iperf3_timeout - self.cut_thru_test(iperf3, self.server_iperf3_args, - iperf3, self.client_iperf3_args) + self.cut_thru_test( + iperf3, self.server_iperf3_args, iperf3, self.client_iperf3_args + ) @unittest.skipUnless(config.extended, "part of extended tests") def test_ldp_cut_thru_uni_dir_nsock(self): - """ run LDP cut thru uni-directional (multiple sockets) test """ + """run LDP cut thru uni-directional (multiple sockets) test""" self.timeout = self.client_uni_dir_nsock_timeout - self.cut_thru_test("sock_test_server", self.server_args, - "sock_test_client", - self.client_uni_dir_nsock_test_args) + self.cut_thru_test( + "sock_test_server", + self.server_args, + "sock_test_client", + self.client_uni_dir_nsock_test_args, + ) @unittest.skipUnless(config.extended, "part of extended tests") @unittest.skip("sock test apps need to be improved") def test_ldp_cut_thru_bi_dir_nsock(self): - """ run LDP cut thru bi-directional (multiple sockets) test """ + """run LDP cut thru bi-directional (multiple sockets) test""" self.timeout = self.client_bi_dir_nsock_timeout - self.cut_thru_test("sock_test_server", self.server_args, - "sock_test_client", - self.client_bi_dir_nsock_test_args) + self.cut_thru_test( + "sock_test_server", + self.server_args, + "sock_test_client", + self.client_bi_dir_nsock_test_args, + ) class VCLCutThruTestCase(VCLTestCase): - """ VCL Cut Thru Tests """ + """VCL Cut Thru Tests""" @classmethod def setUpClass(cls): @@ -371,19 +417,36 @@ class VCLCutThruTestCase(VCLTestCase): super(VCLCutThruTestCase, self).setUp() self.cut_thru_setup() - self.client_echo_test_args = ["-E", self.echo_phrase, "-X", - self.server_addr, self.server_port] + self.client_echo_test_args = [ + "-E", + self.echo_phrase, + "-X", + self.server_addr, + self.server_port, + ] self.client_uni_dir_nsock_timeout = 20 - self.client_uni_dir_nsock_test_args = ["-N", "1000", "-U", "-X", - "-I", "2", - self.server_addr, - self.server_port] + self.client_uni_dir_nsock_test_args = [ + "-N", + "1000", + "-U", + "-X", + "-I", + "2", + self.server_addr, + self.server_port, + ] self.client_bi_dir_nsock_timeout = 20 - self.client_bi_dir_nsock_test_args = ["-N", "1000", "-B", "-X", - "-I", "2", - self.server_addr, - self.server_port] + self.client_bi_dir_nsock_test_args = [ + "-N", + "1000", + "-B", + "-X", + "-I", + "2", + self.server_addr, + self.server_port, + ] def tearDown(self): super(VCLCutThruTestCase, self).tearDown() @@ -393,30 +456,40 @@ class VCLCutThruTestCase(VCLTestCase): self.logger.debug(self.vapi.cli("show app mq")) def test_vcl_cut_thru_echo(self): - """ run VCL cut thru echo test """ + """run VCL cut thru echo test""" - self.cut_thru_test("vcl_test_server", self.server_args, - "vcl_test_client", self.client_echo_test_args) + self.cut_thru_test( + "vcl_test_server", + self.server_args, + "vcl_test_client", + self.client_echo_test_args, + ) def test_vcl_cut_thru_uni_dir_nsock(self): - """ run VCL cut thru uni-directional (multiple sockets) test """ + """run VCL cut thru uni-directional (multiple sockets) test""" self.timeout = self.client_uni_dir_nsock_timeout - self.cut_thru_test("vcl_test_server", self.server_args, - "vcl_test_client", - self.client_uni_dir_nsock_test_args) + self.cut_thru_test( + "vcl_test_server", + self.server_args, + "vcl_test_client", + self.client_uni_dir_nsock_test_args, + ) def test_vcl_cut_thru_bi_dir_nsock(self): - """ run VCL cut thru bi-directional (multiple sockets) test """ + """run VCL cut thru bi-directional (multiple sockets) test""" self.timeout = self.client_bi_dir_nsock_timeout - self.cut_thru_test("vcl_test_server", self.server_args, - "vcl_test_client", - self.client_bi_dir_nsock_test_args) + self.cut_thru_test( + "vcl_test_server", + self.server_args, + "vcl_test_client", + self.client_bi_dir_nsock_test_args, + ) class VCLThruHostStackEcho(VCLTestCase): - """ VCL Thru Host Stack Echo """ + """VCL Thru Host Stack Echo""" @classmethod def setUpClass(cls): @@ -431,25 +504,37 @@ class VCLThruHostStackEcho(VCLTestCase): self.thru_host_stack_setup() self.client_bi_dir_nsock_timeout = 20 - self.client_bi_dir_nsock_test_args = ["-N", "1000", "-B", "-X", - "-I", "2", - self.loop0.local_ip4, - self.server_port] - self.client_echo_test_args = ["-E", self.echo_phrase, "-X", - self.loop0.local_ip4, - self.server_port] + self.client_bi_dir_nsock_test_args = [ + "-N", + "1000", + "-B", + "-X", + "-I", + "2", + self.loop0.local_ip4, + self.server_port, + ] + self.client_echo_test_args = [ + "-E", + self.echo_phrase, + "-X", + self.loop0.local_ip4, + self.server_port, + ] def tearDown(self): self.thru_host_stack_tear_down() super(VCLThruHostStackEcho, self).tearDown() def test_vcl_thru_host_stack_echo(self): - """ run VCL IPv4 thru host stack echo test """ + """run VCL IPv4 thru host stack echo test""" - self.thru_host_stack_test("vcl_test_server", - self.server_args, - "vcl_test_client", - self.client_echo_test_args) + self.thru_host_stack_test( + "vcl_test_server", + self.server_args, + "vcl_test_client", + self.client_echo_test_args, + ) def show_commands_at_teardown(self): self.logger.debug(self.vapi.cli("show app server")) @@ -458,7 +543,7 @@ class VCLThruHostStackEcho(VCLTestCase): class VCLThruHostStackTLS(VCLTestCase): - """ VCL Thru Host Stack TLS """ + """VCL Thru Host Stack TLS""" @classmethod def setUpClass(cls): @@ -475,19 +560,28 @@ class VCLThruHostStackTLS(VCLTestCase): self.thru_host_stack_setup() self.client_uni_dir_tls_timeout = 20 self.server_tls_args = ["-L", self.server_port] - self.client_uni_dir_tls_test_args = ["-N", "1000", "-U", "-X", "-L", - self.loop0.local_ip4, - self.server_port] + self.client_uni_dir_tls_test_args = [ + "-N", + "1000", + "-U", + "-X", + "-L", + self.loop0.local_ip4, + self.server_port, + ] self.sapi_server_sock = "1" self.sapi_client_sock = "2" def test_vcl_thru_host_stack_tls_uni_dir(self): - """ run VCL thru host stack uni-directional TLS test """ + """run VCL thru host stack uni-directional TLS test""" self.timeout = self.client_uni_dir_tls_timeout - self.thru_host_stack_test("vcl_test_server", self.server_tls_args, - "vcl_test_client", - self.client_uni_dir_tls_test_args) + self.thru_host_stack_test( + "vcl_test_server", + self.server_tls_args, + "vcl_test_client", + self.client_uni_dir_tls_test_args, + ) def tearDown(self): self.thru_host_stack_tear_down() @@ -500,7 +594,7 @@ class VCLThruHostStackTLS(VCLTestCase): class VCLThruHostStackDTLS(VCLTestCase): - """ VCL Thru Host Stack DTLS """ + """VCL Thru Host Stack DTLS""" @classmethod def setUpClass(cls): @@ -516,18 +610,28 @@ class VCLThruHostStackDTLS(VCLTestCase): self.thru_host_stack_setup() self.client_uni_dir_dtls_timeout = 20 self.server_dtls_args = ["-p", "dtls", self.server_port] - self.client_uni_dir_dtls_test_args = ["-N", "1000", "-U", "-X", - "-p", "dtls", "-T 1400", - self.loop0.local_ip4, - self.server_port] + self.client_uni_dir_dtls_test_args = [ + "-N", + "1000", + "-U", + "-X", + "-p", + "dtls", + "-T 1400", + self.loop0.local_ip4, + self.server_port, + ] def test_vcl_thru_host_stack_dtls_uni_dir(self): - """ run VCL thru host stack uni-directional DTLS test """ + """run VCL thru host stack uni-directional DTLS test""" self.timeout = self.client_uni_dir_dtls_timeout - self.thru_host_stack_test("vcl_test_server", self.server_dtls_args, - "vcl_test_client", - self.client_uni_dir_dtls_test_args) + self.thru_host_stack_test( + "vcl_test_server", + self.server_dtls_args, + "vcl_test_client", + self.client_uni_dir_dtls_test_args, + ) def tearDown(self): self.thru_host_stack_tear_down() @@ -540,7 +644,7 @@ class VCLThruHostStackDTLS(VCLTestCase): class VCLThruHostStackQUIC(VCLTestCase): - """ VCL Thru Host Stack QUIC """ + """VCL Thru Host Stack QUIC""" @classmethod def setUpClass(cls): @@ -557,19 +661,28 @@ class VCLThruHostStackQUIC(VCLTestCase): self.thru_host_stack_setup() self.client_uni_dir_quic_timeout = 20 self.server_quic_args = ["-p", "quic", self.server_port] - self.client_uni_dir_quic_test_args = ["-N", "1000", "-U", "-X", - "-p", "quic", - self.loop0.local_ip4, - self.server_port] + self.client_uni_dir_quic_test_args = [ + "-N", + "1000", + "-U", + "-X", + "-p", + "quic", + self.loop0.local_ip4, + self.server_port, + ] @unittest.skipUnless(config.extended, "part of extended tests") def test_vcl_thru_host_stack_quic_uni_dir(self): - """ run VCL thru host stack uni-directional QUIC test """ + """run VCL thru host stack uni-directional QUIC test""" self.timeout = self.client_uni_dir_quic_timeout - self.thru_host_stack_test("vcl_test_server", self.server_quic_args, - "vcl_test_client", - self.client_uni_dir_quic_test_args) + self.thru_host_stack_test( + "vcl_test_server", + self.server_quic_args, + "vcl_test_client", + self.client_uni_dir_quic_test_args, + ) def tearDown(self): self.thru_host_stack_tear_down() @@ -582,7 +695,7 @@ class VCLThruHostStackQUIC(VCLTestCase): class VCLThruHostStackBidirNsock(VCLTestCase): - """ VCL Thru Host Stack Bidir Nsock """ + """VCL Thru Host Stack Bidir Nsock""" @classmethod def setUpClass(cls): @@ -597,13 +710,23 @@ class VCLThruHostStackBidirNsock(VCLTestCase): self.thru_host_stack_setup() self.client_bi_dir_nsock_timeout = 20 - self.client_bi_dir_nsock_test_args = ["-N", "1000", "-B", "-X", - "-I", "2", - self.loop0.local_ip4, - self.server_port] - self.client_echo_test_args = ["-E", self.echo_phrase, "-X", - self.loop0.local_ip4, - self.server_port] + self.client_bi_dir_nsock_test_args = [ + "-N", + "1000", + "-B", + "-X", + "-I", + "2", + self.loop0.local_ip4, + self.server_port, + ] + self.client_echo_test_args = [ + "-E", + self.echo_phrase, + "-X", + self.loop0.local_ip4, + self.server_port, + ] def tearDown(self): self.thru_host_stack_tear_down() @@ -614,16 +737,19 @@ class VCLThruHostStackBidirNsock(VCLTestCase): self.logger.debug(self.vapi.cli("show app mq")) def test_vcl_thru_host_stack_bi_dir_nsock(self): - """ run VCL thru host stack bi-directional (multiple sockets) test """ + """run VCL thru host stack bi-directional (multiple sockets) test""" self.timeout = self.client_bi_dir_nsock_timeout - self.thru_host_stack_test("vcl_test_server", self.server_args, - "vcl_test_client", - self.client_bi_dir_nsock_test_args) + self.thru_host_stack_test( + "vcl_test_server", + self.server_args, + "vcl_test_client", + self.client_bi_dir_nsock_test_args, + ) class LDPThruHostStackBidirNsock(VCLTestCase): - """ LDP Thru Host Stack Bidir Nsock """ + """LDP Thru Host Stack Bidir Nsock""" @classmethod def setUpClass(cls): @@ -638,14 +764,19 @@ class LDPThruHostStackBidirNsock(VCLTestCase): self.thru_host_stack_setup() self.client_bi_dir_nsock_timeout = 20 - self.client_bi_dir_nsock_test_args = ["-N", "1000", "-B", "-X", - # OUCH! Host Stack Bug? - # Only fails when running - # 'make test TEST_JOBS=auto' - # or TEST_JOBS > 1 - # "-I", "2", - self.loop0.local_ip4, - self.server_port] + self.client_bi_dir_nsock_test_args = [ + "-N", + "1000", + "-B", + "-X", + # OUCH! Host Stack Bug? + # Only fails when running + # 'make test TEST_JOBS=auto' + # or TEST_JOBS > 1 + # "-I", "2", + self.loop0.local_ip4, + self.server_port, + ] def tearDown(self): self.thru_host_stack_tear_down() @@ -656,16 +787,19 @@ class LDPThruHostStackBidirNsock(VCLTestCase): self.logger.debug(self.vapi.cli("show app mq")) def test_ldp_thru_host_stack_bi_dir_nsock(self): - """ run LDP thru host stack bi-directional (multiple sockets) test """ + """run LDP thru host stack bi-directional (multiple sockets) test""" self.timeout = self.client_bi_dir_nsock_timeout - self.thru_host_stack_test("sock_test_server", self.server_args, - "sock_test_client", - self.client_bi_dir_nsock_test_args) + self.thru_host_stack_test( + "sock_test_server", + self.server_args, + "sock_test_client", + self.client_bi_dir_nsock_test_args, + ) class LDPThruHostStackNsock(VCLTestCase): - """ LDP Thru Host Stack Nsock """ + """LDP Thru Host Stack Nsock""" @classmethod def setUpClass(cls): @@ -686,26 +820,35 @@ class LDPThruHostStackNsock(VCLTestCase): self.client_uni_dir_nsock_timeout = 20 self.numSockets = "5" - self.client_uni_dir_nsock_test_args = ["-N", "1000", "-U", "-X", - "-I", self.numSockets, - self.loop0.local_ip4, - self.server_port] + self.client_uni_dir_nsock_test_args = [ + "-N", + "1000", + "-U", + "-X", + "-I", + self.numSockets, + self.loop0.local_ip4, + self.server_port, + ] def tearDown(self): self.thru_host_stack_tear_down() super(LDPThruHostStackNsock, self).tearDown() def test_ldp_thru_host_stack_uni_dir_nsock(self): - """ run LDP thru host stack uni-directional (multiple sockets) test """ + """run LDP thru host stack uni-directional (multiple sockets) test""" self.timeout = self.client_uni_dir_nsock_timeout - self.thru_host_stack_test("sock_test_server", self.server_args, - "sock_test_client", - self.client_uni_dir_nsock_test_args) + self.thru_host_stack_test( + "sock_test_server", + self.server_args, + "sock_test_client", + self.client_uni_dir_nsock_test_args, + ) class VCLThruHostStackNsock(VCLTestCase): - """ VCL Thru Host Stack Nsock """ + """VCL Thru Host Stack Nsock""" @classmethod def setUpClass(cls): @@ -726,26 +869,35 @@ class VCLThruHostStackNsock(VCLTestCase): self.client_uni_dir_nsock_timeout = 20 self.numSockets = "5" - self.client_uni_dir_nsock_test_args = ["-N", "1000", "-U", "-X", - "-I", self.numSockets, - self.loop0.local_ip4, - self.server_port] + self.client_uni_dir_nsock_test_args = [ + "-N", + "1000", + "-U", + "-X", + "-I", + self.numSockets, + self.loop0.local_ip4, + self.server_port, + ] def tearDown(self): self.thru_host_stack_tear_down() super(VCLThruHostStackNsock, self).tearDown() def test_vcl_thru_host_stack_uni_dir_nsock(self): - """ run VCL thru host stack uni-directional (multiple sockets) test """ + """run VCL thru host stack uni-directional (multiple sockets) test""" self.timeout = self.client_uni_dir_nsock_timeout - self.thru_host_stack_test("vcl_test_server", self.server_args, - "vcl_test_client", - self.client_uni_dir_nsock_test_args) + self.thru_host_stack_test( + "vcl_test_server", + self.server_args, + "vcl_test_client", + self.client_uni_dir_nsock_test_args, + ) class LDPThruHostStackIperf(VCLTestCase): - """ LDP Thru Host Stack Iperf """ + """LDP Thru Host Stack Iperf""" @classmethod def setUpClass(cls): @@ -773,15 +925,16 @@ class LDPThruHostStackIperf(VCLTestCase): @unittest.skipUnless(_have_iperf3, "'%s' not found, Skipping.") def test_ldp_thru_host_stack_iperf3(self): - """ run LDP thru host stack iperf3 test """ + """run LDP thru host stack iperf3 test""" self.timeout = self.client_iperf3_timeout - self.thru_host_stack_test(iperf3, self.server_iperf3_args, - iperf3, self.client_iperf3_args) + self.thru_host_stack_test( + iperf3, self.server_iperf3_args, iperf3, self.client_iperf3_args + ) class LDPThruHostStackIperfUdp(VCLTestCase): - """ LDP Thru Host Stack Iperf UDP """ + """LDP Thru Host Stack Iperf UDP""" @classmethod def setUpClass(cls): @@ -796,8 +949,14 @@ class LDPThruHostStackIperfUdp(VCLTestCase): self.thru_host_stack_setup() self.client_iperf3_timeout = 20 - self.client_iperf3_args = ["-4", "-t 2", "-u", "-l 1400", - "-c", self.loop0.local_ip4] + self.client_iperf3_args = [ + "-4", + "-t 2", + "-u", + "-l 1400", + "-c", + self.loop0.local_ip4, + ] self.server_iperf3_args = ["-4", "-s"] def tearDown(self): @@ -810,15 +969,16 @@ class LDPThruHostStackIperfUdp(VCLTestCase): @unittest.skipUnless(_have_iperf3, "'%s' not found, Skipping.") def test_ldp_thru_host_stack_iperf3_udp(self): - """ run LDP thru host stack iperf3 UDP test """ + """run LDP thru host stack iperf3 UDP test""" self.timeout = self.client_iperf3_timeout - self.thru_host_stack_test(iperf3, self.server_iperf3_args, - iperf3, self.client_iperf3_args) + self.thru_host_stack_test( + iperf3, self.server_iperf3_args, iperf3, self.client_iperf3_args + ) class LDPIpv6CutThruTestCase(VCLTestCase): - """ LDP IPv6 Cut Thru Tests """ + """LDP IPv6 Cut Thru Tests""" @classmethod def setUpClass(cls): @@ -839,22 +999,38 @@ class LDPIpv6CutThruTestCase(VCLTestCase): self.client_iperf3_timeout = 20 self.client_uni_dir_nsock_timeout = 20 self.client_bi_dir_nsock_timeout = 20 - self.client_ipv6_echo_test_args = ["-6", "-E", self.echo_phrase, "-X", - self.server_ipv6_addr, - self.server_port] - self.client_ipv6_iperf3_args = ["-6", "-t 2", "-c", - self.server_ipv6_addr] + self.client_ipv6_echo_test_args = [ + "-6", + "-E", + self.echo_phrase, + "-X", + self.server_ipv6_addr, + self.server_port, + ] + self.client_ipv6_iperf3_args = ["-6", "-t 2", "-c", self.server_ipv6_addr] self.server_ipv6_iperf3_args = ["-6", "-s"] - self.client_ipv6_uni_dir_nsock_test_args = ["-N", "1000", "-U", "-X", - "-6", - "-I", "2", - self.server_ipv6_addr, - self.server_port] - self.client_ipv6_bi_dir_nsock_test_args = ["-N", "1000", "-B", "-X", - "-6", - "-I", "2", - self.server_ipv6_addr, - self.server_port] + self.client_ipv6_uni_dir_nsock_test_args = [ + "-N", + "1000", + "-U", + "-X", + "-6", + "-I", + "2", + self.server_ipv6_addr, + self.server_port, + ] + self.client_ipv6_bi_dir_nsock_test_args = [ + "-N", + "1000", + "-B", + "-X", + "-6", + "-I", + "2", + self.server_ipv6_addr, + self.server_port, + ] def tearDown(self): super(LDPIpv6CutThruTestCase, self).tearDown() @@ -862,43 +1038,52 @@ class LDPIpv6CutThruTestCase(VCLTestCase): @unittest.skipUnless(config.extended, "part of extended tests") def test_ldp_ipv6_cut_thru_echo(self): - """ run LDP IPv6 cut thru echo test """ + """run LDP IPv6 cut thru echo test""" - self.cut_thru_test("sock_test_server", - self.server_ipv6_args, - "sock_test_client", - self.client_ipv6_echo_test_args) + self.cut_thru_test( + "sock_test_server", + self.server_ipv6_args, + "sock_test_client", + self.client_ipv6_echo_test_args, + ) @unittest.skipUnless(_have_iperf3, "'%s' not found, Skipping.") def test_ldp_ipv6_cut_thru_iperf3(self): - """ run LDP IPv6 cut thru iperf3 test """ + """run LDP IPv6 cut thru iperf3 test""" self.timeout = self.client_iperf3_timeout - self.cut_thru_test(iperf3, self.server_ipv6_iperf3_args, - iperf3, self.client_ipv6_iperf3_args) + self.cut_thru_test( + iperf3, self.server_ipv6_iperf3_args, iperf3, self.client_ipv6_iperf3_args + ) @unittest.skipUnless(config.extended, "part of extended tests") def test_ldp_ipv6_cut_thru_uni_dir_nsock(self): - """ run LDP IPv6 cut thru uni-directional (multiple sockets) test """ + """run LDP IPv6 cut thru uni-directional (multiple sockets) test""" self.timeout = self.client_uni_dir_nsock_timeout - self.cut_thru_test("sock_test_server", self.server_ipv6_args, - "sock_test_client", - self.client_ipv6_uni_dir_nsock_test_args) + self.cut_thru_test( + "sock_test_server", + self.server_ipv6_args, + "sock_test_client", + self.client_ipv6_uni_dir_nsock_test_args, + ) @unittest.skipUnless(config.extended, "part of extended tests") @unittest.skip("sock test apps need to be improved") def test_ldp_ipv6_cut_thru_bi_dir_nsock(self): - """ run LDP IPv6 cut thru bi-directional (multiple sockets) test """ + """run LDP IPv6 cut thru bi-directional (multiple sockets) test""" self.timeout = self.client_bi_dir_nsock_timeout - self.cut_thru_test("sock_test_server", self.server_ipv6_args, - "sock_test_client", - self.client_ipv6_bi_dir_nsock_test_args) + self.cut_thru_test( + "sock_test_server", + self.server_ipv6_args, + "sock_test_client", + self.client_ipv6_bi_dir_nsock_test_args, + ) class VCLIpv6CutThruTestCase(VCLTestCase): - """ VCL IPv6 Cut Thru Tests """ + """VCL IPv6 Cut Thru Tests""" @classmethod def setUpClass(cls): @@ -918,19 +1103,36 @@ class VCLIpv6CutThruTestCase(VCLTestCase): self.cut_thru_setup() self.client_uni_dir_nsock_timeout = 20 self.client_bi_dir_nsock_timeout = 20 - self.client_ipv6_echo_test_args = ["-6", "-E", self.echo_phrase, "-X", - self.server_ipv6_addr, - self.server_port] - self.client_ipv6_uni_dir_nsock_test_args = ["-N", "1000", "-U", "-X", - "-6", - "-I", "2", - self.server_ipv6_addr, - self.server_port] - self.client_ipv6_bi_dir_nsock_test_args = ["-N", "1000", "-B", "-X", - "-6", - "-I", "2", - self.server_ipv6_addr, - self.server_port] + self.client_ipv6_echo_test_args = [ + "-6", + "-E", + self.echo_phrase, + "-X", + self.server_ipv6_addr, + self.server_port, + ] + self.client_ipv6_uni_dir_nsock_test_args = [ + "-N", + "1000", + "-U", + "-X", + "-6", + "-I", + "2", + self.server_ipv6_addr, + self.server_port, + ] + self.client_ipv6_bi_dir_nsock_test_args = [ + "-N", + "1000", + "-B", + "-X", + "-6", + "-I", + "2", + self.server_ipv6_addr, + self.server_port, + ] def tearDown(self): super(VCLIpv6CutThruTestCase, self).tearDown() @@ -941,34 +1143,42 @@ class VCLIpv6CutThruTestCase(VCLTestCase): self.logger.debug(self.vapi.cli("show app mq")) def test_vcl_ipv6_cut_thru_echo(self): - """ run VCL IPv6 cut thru echo test """ + """run VCL IPv6 cut thru echo test""" - self.cut_thru_test("vcl_test_server", - self.server_ipv6_args, - "vcl_test_client", - self.client_ipv6_echo_test_args) + self.cut_thru_test( + "vcl_test_server", + self.server_ipv6_args, + "vcl_test_client", + self.client_ipv6_echo_test_args, + ) @unittest.skipUnless(config.extended, "part of extended tests") def test_vcl_ipv6_cut_thru_uni_dir_nsock(self): - """ run VCL IPv6 cut thru uni-directional (multiple sockets) test """ + """run VCL IPv6 cut thru uni-directional (multiple sockets) test""" self.timeout = self.client_uni_dir_nsock_timeout - self.cut_thru_test("vcl_test_server", self.server_ipv6_args, - "vcl_test_client", - self.client_ipv6_uni_dir_nsock_test_args) + self.cut_thru_test( + "vcl_test_server", + self.server_ipv6_args, + "vcl_test_client", + self.client_ipv6_uni_dir_nsock_test_args, + ) @unittest.skipUnless(config.extended, "part of extended tests") def test_vcl_ipv6_cut_thru_bi_dir_nsock(self): - """ run VCL IPv6 cut thru bi-directional (multiple sockets) test """ + """run VCL IPv6 cut thru bi-directional (multiple sockets) test""" self.timeout = self.client_bi_dir_nsock_timeout - self.cut_thru_test("vcl_test_server", self.server_ipv6_args, - "vcl_test_client", - self.client_ipv6_bi_dir_nsock_test_args) + self.cut_thru_test( + "vcl_test_server", + self.server_ipv6_args, + "vcl_test_client", + self.client_ipv6_bi_dir_nsock_test_args, + ) class VCLIpv6ThruHostStackEcho(VCLTestCase): - """ VCL IPv6 Thru Host Stack Echo """ + """VCL IPv6 Thru Host Stack Echo""" @classmethod def setUpClass(cls): @@ -982,22 +1192,29 @@ class VCLIpv6ThruHostStackEcho(VCLTestCase): super(VCLIpv6ThruHostStackEcho, self).setUp() self.thru_host_stack_ipv6_setup() - self.client_ipv6_echo_test_args = ["-6", "-E", self.echo_phrase, "-X", - self.loop0.local_ip6, - self.server_port] + self.client_ipv6_echo_test_args = [ + "-6", + "-E", + self.echo_phrase, + "-X", + self.loop0.local_ip6, + self.server_port, + ] def tearDown(self): self.thru_host_stack_ipv6_tear_down() super(VCLIpv6ThruHostStackEcho, self).tearDown() def test_vcl_ipv6_thru_host_stack_echo(self): - """ run VCL IPv6 thru host stack echo test """ + """run VCL IPv6 thru host stack echo test""" - self.thru_host_stack_test("vcl_test_server", - self.server_ipv6_args, - "vcl_test_client", - self.client_ipv6_echo_test_args) + self.thru_host_stack_test( + "vcl_test_server", + self.server_ipv6_args, + "vcl_test_client", + self.client_ipv6_echo_test_args, + ) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_vhost.py b/test/test_vhost.py index aefae90f2f6..01e2151e67f 100644 --- a/test/test_vhost.py +++ b/test/test_vhost.py @@ -8,9 +8,8 @@ from vpp_vhost_interface import VppVhostInterface class TesVhostInterface(VppTestCase): - """Vhost User Test Case + """Vhost User Test Case""" - """ @classmethod def setUpClass(cls): super(TesVhostInterface, cls).setUpClass() @@ -27,23 +26,23 @@ class TesVhostInterface(VppTestCase): self.vapi.delete_vhost_user_if(ifc.sw_if_index) def test_vhost(self): - """ Vhost User add/delete interface test """ + """Vhost User add/delete interface test""" self.logger.info("Vhost User add interfaces") # create interface 1 (VirtualEthernet0/0/0) - vhost_if1 = VppVhostInterface(self, sock_filename='/tmp/sock1') + vhost_if1 = VppVhostInterface(self, sock_filename="/tmp/sock1") vhost_if1.add_vpp_config() vhost_if1.admin_up() # create interface 2 (VirtualEthernet0/0/1) - vhost_if2 = VppVhostInterface(self, sock_filename='/tmp/sock2') + vhost_if2 = VppVhostInterface(self, sock_filename="/tmp/sock2") vhost_if2.add_vpp_config() vhost_if2.admin_up() # verify both interfaces in the show ifs = self.vapi.cli("show interface") - self.assertIn('VirtualEthernet0/0/0', ifs) - self.assertIn('VirtualEthernet0/0/1', ifs) + self.assertIn("VirtualEthernet0/0/0", ifs) + self.assertIn("VirtualEthernet0/0/1", ifs) # verify they are in the dump also if_dump = self.vapi.sw_interface_vhost_user_dump() @@ -58,10 +57,10 @@ class TesVhostInterface(VppTestCase): ifs = self.vapi.cli("show interface") # verify VirtualEthernet0/0/0 still in the show - self.assertIn('VirtualEthernet0/0/0', ifs) + self.assertIn("VirtualEthernet0/0/0", ifs) # verify VirtualEthernet0/0/1 not in the show - self.assertNotIn('VirtualEthernet0/0/1', ifs) + self.assertNotIn("VirtualEthernet0/0/1", ifs) # verify VirtualEthernet0/0/1 is not in the dump if_dump = self.vapi.sw_interface_vhost_user_dump() @@ -78,14 +77,14 @@ class TesVhostInterface(VppTestCase): # verify VirtualEthernet0/0/0 not in the show ifs = self.vapi.cli("show interface") - self.assertNotIn('VirtualEthernet0/0/0', ifs) + self.assertNotIn("VirtualEthernet0/0/0", ifs) # verify VirtualEthernet0/0/0 is not in the dump if_dump = self.vapi.sw_interface_vhost_user_dump() self.assertFalse(vhost_if1.is_interface_config_in_dump(if_dump)) def test_vhost_interface_state(self): - """ Vhost User interface states and events test """ + """Vhost User interface states and events test""" self.vapi.want_interface_events() @@ -93,7 +92,7 @@ class TesVhostInterface(VppTestCase): # (like delete interface events from other tests) self.vapi.collect_events() - vhost_if = VppVhostInterface(self, sock_filename='/tmp/sock1') + vhost_if = VppVhostInterface(self, sock_filename="/tmp/sock1") # create vhost interface vhost_if.add_vpp_config() @@ -111,8 +110,7 @@ class TesVhostInterface(VppTestCase): # delete vhost interface vhost_if.remove_vpp_config() event = self.vapi.wait_for_event(timeout=1) - self.assert_equal(event.sw_if_index, vhost_if.sw_if_index, - "sw_if_index") + self.assert_equal(event.sw_if_index, vhost_if.sw_if_index, "sw_if_index") self.assert_equal(event.deleted, 1, "deleted flag") # verify there are no more events @@ -120,32 +118,28 @@ class TesVhostInterface(VppTestCase): self.assert_equal(len(events), 0, "number of events") def test_vhost_interface_custom_mac_addr(self): - """ Vhost User interface custom mac address test """ + """Vhost User interface custom mac address test""" mac_addr = "aa:bb:cc:dd:ee:ff" - vhost_if = VppVhostInterface(self, - sock_filename='/tmp/sock1', - use_custom_mac=1, - mac_address=mac_addr) + vhost_if = VppVhostInterface( + self, sock_filename="/tmp/sock1", use_custom_mac=1, mac_address=mac_addr + ) # create vhost interface vhost_if.add_vpp_config() self.sleep(0.1) # verify mac in the dump - if_dump_list = self.vapi.sw_interface_dump( - sw_if_index=vhost_if.sw_if_index - ) + if_dump_list = self.vapi.sw_interface_dump(sw_if_index=vhost_if.sw_if_index) self.assert_equal(len(if_dump_list), 1, "if dump length") [if_dump] = if_dump_list - self.assert_equal( - if_dump.l2_address.mac_string, mac_addr, "MAC Address" - ) + self.assert_equal(if_dump.l2_address.mac_string, mac_addr, "MAC Address") # delete VirtualEthernet self.logger.info("Deleting VirtualEthernet") vhost_if.remove_vpp_config() -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_vlib.py b/test/test_vlib.py index 242acab4594..76a55e65a03 100644 --- a/test/test_vlib.py +++ b/test/test_vlib.py @@ -11,7 +11,8 @@ from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath @unittest.skipUnless(config.gcov, "part of code coverage tests") class TestVlib(VppTestCase): - """ Vlib Unit Test Cases """ + """Vlib Unit Test Cases""" + vpp_worker_count = 1 @classmethod @@ -29,171 +30,174 @@ class TestVlib(VppTestCase): super(TestVlib, self).tearDown() def test_vlib_main_unittest(self): - """ Vlib main.c Code Coverage Test """ - - cmds = ["loopback create", - "packet-generator new {\n" - " name vlib\n" - " limit 15\n" - " size 128-128\n" - " interface loop0\n" - " node ethernet-input\n" - " data {\n" - " IP6: 00:d0:2d:5e:86:85 -> 00:0d:ea:d0:00:00\n" - " ICMP: db00::1 -> db00::2\n" - " incrementing 30\n" - " }\n" - "}\n", - "event-logger trace dispatch", - "event-logger stop", - "event-logger clear", - "event-logger resize 102400", - "event-logger restart", - "pcap dispatch trace on max 100 buffer-trace pg-input 15", - "pa en", - "show event-log 100 all", - "event-log save", - "event-log save foo", - "pcap dispatch trace", - "pcap dispatch trace status", - "pcap dispatch trace off", - "show vlib frame-allocation", - ] + """Vlib main.c Code Coverage Test""" + + cmds = [ + "loopback create", + "packet-generator new {\n" + " name vlib\n" + " limit 15\n" + " size 128-128\n" + " interface loop0\n" + " node ethernet-input\n" + " data {\n" + " IP6: 00:d0:2d:5e:86:85 -> 00:0d:ea:d0:00:00\n" + " ICMP: db00::1 -> db00::2\n" + " incrementing 30\n" + " }\n" + "}\n", + "event-logger trace dispatch", + "event-logger stop", + "event-logger clear", + "event-logger resize 102400", + "event-logger restart", + "pcap dispatch trace on max 100 buffer-trace pg-input 15", + "pa en", + "show event-log 100 all", + "event-log save", + "event-log save foo", + "pcap dispatch trace", + "pcap dispatch trace status", + "pcap dispatch trace off", + "show vlib frame-allocation", + ] for cmd in cmds: r = self.vapi.cli_return_response(cmd) if r.retval != 0: - if hasattr(r, 'reply'): + if hasattr(r, "reply"): self.logger.info(cmd + " FAIL reply " + r.reply) else: self.logger.info(cmd + " FAIL retval " + str(r.retval)) def test_vlib_node_cli_unittest(self): - """ Vlib node_cli.c Code Coverage Test """ - - cmds = ["loopback create", - "packet-generator new {\n" - " name vlib\n" - " limit 15\n" - " size 128-128\n" - " interface loop0\n" - " node ethernet-input\n" - " data {\n" - " IP6: 00:d0:2d:5e:86:85 -> 00:0d:ea:d0:00:00\n" - " ICMP: db00::1 -> db00::2\n" - " incrementing 30\n" - " }\n" - "}\n", - "show vlib graph", - "show vlib graph ethernet-input", - "show vlib graphviz", - "show vlib graphviz graphviz.dot", - "pa en", - "show runtime ethernet-input", - "show runtime brief verbose max summary", - "clear runtime", - "show node index 1", - "show node ethernet-input", - "show node pg-input", - "set node function", - "set node function no-such-node", - "set node function cdp-input default", - "set node function ethernet-input default", - "set node function ethernet-input bozo", - "set node function ethernet-input", - "show \t", - ] + """Vlib node_cli.c Code Coverage Test""" + + cmds = [ + "loopback create", + "packet-generator new {\n" + " name vlib\n" + " limit 15\n" + " size 128-128\n" + " interface loop0\n" + " node ethernet-input\n" + " data {\n" + " IP6: 00:d0:2d:5e:86:85 -> 00:0d:ea:d0:00:00\n" + " ICMP: db00::1 -> db00::2\n" + " incrementing 30\n" + " }\n" + "}\n", + "show vlib graph", + "show vlib graph ethernet-input", + "show vlib graphviz", + "show vlib graphviz graphviz.dot", + "pa en", + "show runtime ethernet-input", + "show runtime brief verbose max summary", + "clear runtime", + "show node index 1", + "show node ethernet-input", + "show node pg-input", + "set node function", + "set node function no-such-node", + "set node function cdp-input default", + "set node function ethernet-input default", + "set node function ethernet-input bozo", + "set node function ethernet-input", + "show \t", + ] for cmd in cmds: r = self.vapi.cli_return_response(cmd) if r.retval != 0: - if hasattr(r, 'reply'): + if hasattr(r, "reply"): self.logger.info(cmd + " FAIL reply " + r.reply) else: self.logger.info(cmd + " FAIL retval " + str(r.retval)) def test_vlib_buffer_c_unittest(self): - """ Vlib buffer.c Code Coverage Test """ - - cmds = ["loopback create", - "packet-generator new {\n" - " name vlib\n" - " limit 15\n" - " size 128-128\n" - " interface loop0\n" - " node ethernet-input\n" - " data {\n" - " IP6: 00:d0:2d:5e:86:85 -> 00:0d:ea:d0:00:00\n" - " ICMP: db00::1 -> db00::2\n" - " incrementing 30\n" - " }\n" - "}\n", - "event-logger trace", - "event-logger trace enable", - "event-logger trace api cli barrier", - "pa en", - "show interface bogus", - "event-logger trace disable api cli barrier", - "event-logger trace circuit-node ethernet-input", - "event-logger trace circuit-node ethernet-input disable", - "clear interfaces", - "test vlib", - "test vlib2", - "show memory api-segment stats-segment main-heap verbose", - "leak-check { show memory }", - "show cpu", - "memory-trace main-heap", - "memory-trace main-heap api-segment stats-segment", - "leak-check { show version }", - "show version ?", - "comment { show version }", - "uncomment { show version }", - "show memory main-heap", - "show memory bogus", - "choices", - "test heap-validate", - "memory-trace main-heap disable", - "show buffers", - "show eve", - "show help", - "show ip ", - ] + """Vlib buffer.c Code Coverage Test""" + + cmds = [ + "loopback create", + "packet-generator new {\n" + " name vlib\n" + " limit 15\n" + " size 128-128\n" + " interface loop0\n" + " node ethernet-input\n" + " data {\n" + " IP6: 00:d0:2d:5e:86:85 -> 00:0d:ea:d0:00:00\n" + " ICMP: db00::1 -> db00::2\n" + " incrementing 30\n" + " }\n" + "}\n", + "event-logger trace", + "event-logger trace enable", + "event-logger trace api cli barrier", + "pa en", + "show interface bogus", + "event-logger trace disable api cli barrier", + "event-logger trace circuit-node ethernet-input", + "event-logger trace circuit-node ethernet-input disable", + "clear interfaces", + "test vlib", + "test vlib2", + "show memory api-segment stats-segment main-heap verbose", + "leak-check { show memory }", + "show cpu", + "memory-trace main-heap", + "memory-trace main-heap api-segment stats-segment", + "leak-check { show version }", + "show version ?", + "comment { show version }", + "uncomment { show version }", + "show memory main-heap", + "show memory bogus", + "choices", + "test heap-validate", + "memory-trace main-heap disable", + "show buffers", + "show eve", + "show help", + "show ip ", + ] for cmd in cmds: r = self.vapi.cli_return_response(cmd) if r.retval != 0: - if hasattr(r, 'reply'): + if hasattr(r, "reply"): self.logger.info(cmd + " FAIL reply " + r.reply) else: self.logger.info(cmd + " FAIL retval " + str(r.retval)) def test_vlib_format_unittest(self): - """ Vlib format.c Code Coverage Test """ + """Vlib format.c Code Coverage Test""" - cmds = ["loopback create", - "classify filter pcap mask l2 proto match l2 proto 0x86dd", - "classify filter pcap del", - "test format-vlib", - ] + cmds = [ + "loopback create", + "classify filter pcap mask l2 proto match l2 proto 0x86dd", + "classify filter pcap del", + "test format-vlib", + ] for cmd in cmds: r = self.vapi.cli_return_response(cmd) if r.retval != 0: - if hasattr(r, 'reply'): + if hasattr(r, "reply"): self.logger.info(cmd + " FAIL reply " + r.reply) else: self.logger.info(cmd + " FAIL retval " + str(r.retval)) def test_vlib_main_unittest(self): - """ Private Binary API Segment Test (takes 70 seconds) """ + """Private Binary API Segment Test (takes 70 seconds)""" - vat_path = config.vpp + '_api_test' - vat = pexpect.spawn(vat_path, ['socket-name', - self.get_api_sock_path()]) + vat_path = config.vpp + "_api_test" + vat = pexpect.spawn(vat_path, ["socket-name", self.get_api_sock_path()]) vat.expect("vat# ", timeout=10) - vat.sendline('sock_init_shm') + vat.sendline("sock_init_shm") vat.expect("vat# ", timeout=10) - vat.sendline('sh api cli') + vat.sendline("sh api cli") vat.kill(signal.SIGKILL) vat.wait() self.logger.info("vat terminated, 70 second wait for the Reaper") @@ -201,18 +205,20 @@ class TestVlib(VppTestCase): self.logger.info("Reaper should be complete...") def test_pool(self): - """ Fixed-size Pool Test """ + """Fixed-size Pool Test""" - cmds = ["test pool", - ] + cmds = [ + "test pool", + ] for cmd in cmds: r = self.vapi.cli_return_response(cmd) if r.retval != 0: - if hasattr(r, 'reply'): + if hasattr(r, "reply"): self.logger.info(cmd + " FAIL reply " + r.reply) else: self.logger.info(cmd + " FAIL retval " + str(r.retval)) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_vpe_api.py b/test/test_vpe_api.py index 54f7e41151b..d7d4cc72ff7 100644 --- a/test/test_vpe_api.py +++ b/test/test_vpe_api.py @@ -23,33 +23,33 @@ class TestVpeApi(VppTestCase): """TestVpeApi""" def test_log_dump_default(self): - rv = self.vapi.cli('test log notice fib entry this is a test') + rv = self.vapi.cli("test log notice fib entry this is a test") rv = self.vapi.log_dump() if enable_print: - print('\n'.join([str(v) for v in rv])) + print("\n".join([str(v) for v in rv])) self.assertTrue(rv) def test_log_dump_timestamp_0(self): - rv = self.vapi.cli('test log notice fib entry this is a test') + rv = self.vapi.cli("test log notice fib entry this is a test") rv = self.vapi.log_dump(start_timestamp=0.0) if enable_print: - print('\n'.join([str(v) for v in rv])) + print("\n".join([str(v) for v in rv])) self.assertTrue(rv) def test_log_dump_timestamp_future(self): - rv = self.vapi.cli('test log debug fib entry test') + rv = self.vapi.cli("test log debug fib entry test") rv = self.vapi.log_dump(start_timestamp=time.time() + 60.0) if enable_print: - print('\n'.join([str(v) for v in rv])) + print("\n".join([str(v) for v in rv])) self.assertFalse(rv) def test_show_vpe_system_time(self): local_start_time = datetime.datetime.now() rv = self.vapi.show_vpe_system_time() - self.assertTrue(rv.vpe_system_time > local_start_time - - datetime.timedelta(hours=1.0), - 'system times differ by more than an hour.') + self.assertTrue( + rv.vpe_system_time > local_start_time - datetime.timedelta(hours=1.0), + "system times differ by more than an hour.", + ) if enable_print: - print('\n'.join([str(v) for v in rv])) - print('%r %s' % (rv.vpe_system_time, - rv.vpe_system_time)) + print("\n".join([str(v) for v in rv])) + print("%r %s" % (rv.vpe_system_time, rv.vpe_system_time)) diff --git a/test/test_vppinfra.py b/test/test_vppinfra.py index 36cd55b3550..3a8f8e96fee 100644 --- a/test/test_vppinfra.py +++ b/test/test_vppinfra.py @@ -6,7 +6,8 @@ from framework import VppTestCase, VppTestRunner class TestVppinfra(VppTestCase): - """ Vppinfra Unit Test Cases """ + """Vppinfra Unit Test Cases""" + vpp_worker_count = 1 @classmethod @@ -24,16 +25,17 @@ class TestVppinfra(VppTestCase): super(TestVppinfra, self).tearDown() def test_bitmap_unittest(self): - """ Bitmap Code Coverage Test """ + """Bitmap Code Coverage Test""" cmds = ["test bitmap"] for cmd in cmds: r = self.vapi.cli_return_response(cmd) if r.retval != 0: - if hasattr(r, 'reply'): + if hasattr(r, "reply"): self.logger.info(cmd + " FAIL reply " + r.reply) else: self.logger.info(cmd + " FAIL retval " + str(r.retval)) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_vrrp.py b/test/test_vrrp.py index 6a62a88c2a1..9319b0fa6da 100644 --- a/test/test_vrrp.py +++ b/test/test_vrrp.py @@ -17,9 +17,18 @@ from vpp_papi import VppEnum from scapy.packet import raw from scapy.layers.l2 import Ether, ARP from scapy.layers.inet import IP, ICMP, icmptypes -from scapy.layers.inet6 import IPv6, ipv6nh, IPv6ExtHdrHopByHop, \ - ICMPv6MLReport2, ICMPv6ND_NA, ICMPv6ND_NS, ICMPv6NDOptDstLLAddr, \ - ICMPv6NDOptSrcLLAddr, ICMPv6EchoRequest, ICMPv6EchoReply +from scapy.layers.inet6 import ( + IPv6, + ipv6nh, + IPv6ExtHdrHopByHop, + ICMPv6MLReport2, + ICMPv6ND_NA, + ICMPv6ND_NS, + ICMPv6NDOptDstLLAddr, + ICMPv6NDOptSrcLLAddr, + ICMPv6EchoRequest, + ICMPv6EchoReply, +) from scapy.contrib.igmpv3 import IGMPv3, IGMPv3mr, IGMPv3gr from scapy.layers.vrrp import IPPROTO_VRRP, VRRPv3 from scapy.utils6 import in6_getnsma, in6_getnsmac @@ -37,11 +46,11 @@ VRRP_VR_STATE_BACKUP = 1 VRRP_VR_STATE_MASTER = 2 VRRP_VR_STATE_INTF_DOWN = 3 -VRRP_INDEX_INVALID = 0xffffffff +VRRP_INDEX_INVALID = 0xFFFFFFFF def is_non_arp(p): - """ Want to filter out advertisements, igmp, etc""" + """Want to filter out advertisements, igmp, etc""" if p.haslayer(ARP): return False @@ -49,7 +58,7 @@ def is_non_arp(p): def is_not_adv(p): - """ Filter out everything but advertisements. E.g. multicast RD/ND """ + """Filter out everything but advertisements. E.g. multicast RD/ND""" if p.haslayer(VRRPv3): return False @@ -57,7 +66,7 @@ def is_not_adv(p): def is_not_echo_reply(p): - """ filter out advertisements and other while waiting for echo reply """ + """filter out advertisements and other while waiting for echo reply""" if p.haslayer(IP) and p.haslayer(ICMP): if icmptypes[p[ICMP].type] == "echo-reply": return False @@ -68,15 +77,16 @@ def is_not_echo_reply(p): class VppVRRPVirtualRouter(VppObject): - - def __init__(self, - test, - intf, - vr_id, - prio=100, - intvl=100, - flags=VRRP_VR_FLAG_PREEMPT, - vips=None): + def __init__( + self, + test, + intf, + vr_id, + prio=100, + intvl=100, + flags=VRRP_VR_FLAG_PREEMPT, + vips=None, + ): self._test = test self._intf = intf self._sw_if_index = self._intf.sw_if_index @@ -84,40 +94,44 @@ class VppVRRPVirtualRouter(VppObject): self._prio = prio self._intvl = intvl self._flags = flags - if (flags & VRRP_VR_FLAG_IPV6): + if flags & VRRP_VR_FLAG_IPV6: self._is_ipv6 = 1 self._adv_dest_mac = "33:33:00:00:00:12" self._virtual_mac = "00:00:5e:00:02:%02x" % vr_id self._adv_dest_ip = "ff02::12" - self._vips = ([intf.local_ip6] if vips is None else vips) + self._vips = [intf.local_ip6] if vips is None else vips else: self._is_ipv6 = 0 self._adv_dest_mac = "01:00:5e:00:00:12" self._virtual_mac = "00:00:5e:00:01:%02x" % vr_id self._adv_dest_ip = "224.0.0.18" - self._vips = ([intf.local_ip4] if vips is None else vips) + self._vips = [intf.local_ip4] if vips is None else vips self._tracked_ifs = [] self._vrrp_index = VRRP_INDEX_INVALID def add_vpp_config(self): - self._test.vapi.vrrp_vr_add_del(is_add=1, - sw_if_index=self._intf.sw_if_index, - vr_id=self._vr_id, - priority=self._prio, - interval=self._intvl, - flags=self._flags, - n_addrs=len(self._vips), - addrs=self._vips) + self._test.vapi.vrrp_vr_add_del( + is_add=1, + sw_if_index=self._intf.sw_if_index, + vr_id=self._vr_id, + priority=self._prio, + interval=self._intvl, + flags=self._flags, + n_addrs=len(self._vips), + addrs=self._vips, + ) def update_vpp_config(self): - r = self._test.vapi.vrrp_vr_update(vrrp_index=self._vrrp_index, - sw_if_index=self._intf.sw_if_index, - vr_id=self._vr_id, - priority=self._prio, - interval=self._intvl, - flags=self._flags, - n_addrs=len(self._vips), - addrs=self._vips) + r = self._test.vapi.vrrp_vr_update( + vrrp_index=self._vrrp_index, + sw_if_index=self._intf.sw_if_index, + vr_id=self._vr_id, + priority=self._prio, + interval=self._intvl, + flags=self._flags, + n_addrs=len(self._vips), + addrs=self._vips, + ) self._vrrp_index = r.vrrp_index def delete_vpp_config(self): @@ -129,7 +143,7 @@ class VppVRRPVirtualRouter(VppObject): if vr.config.vr_id != self._vr_id: continue - is_ipv6 = (1 if (vr.config.flags & VRRP_VR_FLAG_IPV6) else 0) + is_ipv6 = 1 if (vr.config.flags & VRRP_VR_FLAG_IPV6) else 0 if is_ipv6 != self._is_ipv6: continue @@ -138,41 +152,45 @@ class VppVRRPVirtualRouter(VppObject): return None def remove_vpp_config(self): - self._test.vapi.vrrp_vr_add_del(is_add=0, - sw_if_index=self._intf.sw_if_index, - vr_id=self._vr_id, - priority=self._prio, - interval=self._intvl, - flags=self._flags, - n_addrs=len(self._vips), - addrs=self._vips) + self._test.vapi.vrrp_vr_add_del( + is_add=0, + sw_if_index=self._intf.sw_if_index, + vr_id=self._vr_id, + priority=self._prio, + interval=self._intvl, + flags=self._flags, + n_addrs=len(self._vips), + addrs=self._vips, + ) def start_stop(self, is_start): - self._test.vapi.vrrp_vr_start_stop(is_start=is_start, - sw_if_index=self._intf.sw_if_index, - vr_id=self._vr_id, - is_ipv6=self._is_ipv6) - self._start_time = (time.time() if is_start else None) + self._test.vapi.vrrp_vr_start_stop( + is_start=is_start, + sw_if_index=self._intf.sw_if_index, + vr_id=self._vr_id, + is_ipv6=self._is_ipv6, + ) + self._start_time = time.time() if is_start else None def add_del_tracked_interface(self, is_add, sw_if_index, prio): args = { - 'sw_if_index': self._intf.sw_if_index, - 'is_ipv6': self._is_ipv6, - 'vr_id': self._vr_id, - 'is_add': is_add, - 'n_ifs': 1, - 'ifs': [{'sw_if_index': sw_if_index, 'priority': prio}] + "sw_if_index": self._intf.sw_if_index, + "is_ipv6": self._is_ipv6, + "vr_id": self._vr_id, + "is_add": is_add, + "n_ifs": 1, + "ifs": [{"sw_if_index": sw_if_index, "priority": prio}], } self._test.vapi.vrrp_vr_track_if_add_del(**args) - self._tracked_ifs.append(args['ifs'][0]) + self._tracked_ifs.append(args["ifs"][0]) def set_unicast_peers(self, addrs): args = { - 'sw_if_index': self._intf.sw_if_index, - 'is_ipv6': self._is_ipv6, - 'vr_id': self._vr_id, - 'n_addrs': len(addrs), - 'addrs': addrs + "sw_if_index": self._intf.sw_if_index, + "is_ipv6": self._is_ipv6, + "vr_id": self._vr_id, + "n_addrs": len(addrs), + "addrs": addrs, } self._test.vapi.vrrp_vr_set_peers(**args) self._unicast_peers = addrs @@ -210,21 +228,22 @@ class VppVRRPVirtualRouter(VppObject): def master_down_seconds(self): vr_details = self.query_vpp_config() - return (vr_details.runtime.master_down_int * 0.01) + return vr_details.runtime.master_down_int * 0.01 def vrrp_adv_packet(self, prio=None, src_ip=None): dst_ip = self._adv_dest_ip if prio is None: prio = self._prio eth = Ether(dst=self._adv_dest_mac, src=self._virtual_mac) - vrrp = VRRPv3(vrid=self._vr_id, priority=prio, - ipcount=len(self._vips), adv=self._intvl) + vrrp = VRRPv3( + vrid=self._vr_id, priority=prio, ipcount=len(self._vips), adv=self._intvl + ) if self._is_ipv6: - src_ip = (self._intf.local_ip6_ll if src_ip is None else src_ip) + src_ip = self._intf.local_ip6_ll if src_ip is None else src_ip ip = IPv6(src=src_ip, dst=dst_ip, nh=IPPROTO_VRRP, hlim=255) vrrp.addrlist = self._vips else: - src_ip = (self._intf.local_ip4 if src_ip is None else src_ip) + src_ip = self._intf.local_ip4 if src_ip is None else src_ip ip = IP(src=src_ip, dst=dst_ip, proto=IPPROTO_VRRP, ttl=255, id=0) vrrp.addrlist = self._vips @@ -234,7 +253,7 @@ class VppVRRPVirtualRouter(VppObject): class TestVRRP4(VppTestCase): - """ IPv4 VRRP Test Case """ + """IPv4 VRRP Test Case""" @classmethod def setUpClass(cls): @@ -284,8 +303,7 @@ class TestVRRP4(VppTestCase): self.assertEqual(ip.proto, 2) igmp = pkt[IGMPv3] - self.assertEqual(IGMPv3.igmpv3types[igmp.type], - "Version 3 Membership Report") + self.assertEqual(IGMPv3.igmpv3types[igmp.type], "Version 3 Membership Report") igmpmr = pkt[IGMPv3mr] self.assertEqual(igmpmr.numgrp, 1) @@ -330,15 +348,15 @@ class TestVRRP4(VppTestCase): # become master and start advertising immediately. @unittest.skipUnless(config.extended, "part of extended tests") def test_vrrp4_master_adv(self): - """ IPv4 Master VR advertises """ + """IPv4 Master VR advertises""" self.pg_enable_capture(self.pg_interfaces) self.pg_start() prio = 255 intvl = self._default_adv - vr = VppVRRPVirtualRouter(self, self.pg0, 100, - prio=prio, intvl=intvl, - flags=self._default_flags) + vr = VppVRRPVirtualRouter( + self, self.pg0, 100, prio=prio, intvl=intvl, flags=self._default_flags + ) vr.add_vpp_config() vr.start_stop(is_start=1) @@ -362,25 +380,30 @@ class TestVRRP4(VppTestCase): # of parameters to test that too @unittest.skipUnless(config.extended, "part of extended tests") def test_vrrp4_master_adv_update(self): - """ IPv4 Master VR adv + Update to Backup """ + """IPv4 Master VR adv + Update to Backup""" self.pg_enable_capture(self.pg_interfaces) self.pg_start() prio = 255 intvl = self._default_adv - vr = VppVRRPVirtualRouter(self, self.pg0, 100, - prio=prio, intvl=intvl, - flags=self._default_flags) + vr = VppVRRPVirtualRouter( + self, self.pg0, 100, prio=prio, intvl=intvl, flags=self._default_flags + ) vr.update_vpp_config() vr.start_stop(is_start=1) self.logger.info(self.vapi.cli("show vrrp vr")) # Update VR with lower prio and larger interval # we need to keep old VR for the adv checks - upd_vr = VppVRRPVirtualRouter(self, self.pg0, 100, - prio=100, intvl=2*intvl, - flags=self._default_flags, - vips=[self.pg0.remote_ip4]) + upd_vr = VppVRRPVirtualRouter( + self, + self.pg0, + 100, + prio=100, + intvl=2 * intvl, + flags=self._default_flags, + vips=[self.pg0.remote_ip4], + ) upd_vr._vrrp_index = vr._vrrp_index upd_vr.update_vpp_config() start_time = time.time() @@ -403,7 +426,7 @@ class TestVRRP4(VppTestCase): src_ip = self.pg0.remote_ip4 pkts = [upd_vr.vrrp_adv_packet(prio=110, src_ip=src_ip)] while time.time() < end_time: - self.send_and_assert_no_replies(self.pg0, pkts, timeout=intvl*0.01) + self.send_and_assert_no_replies(self.pg0, pkts, timeout=intvl * 0.01) self.logger.info(self.vapi.cli("show trace")) upd_vr.start_stop(is_start=0) @@ -413,7 +436,7 @@ class TestVRRP4(VppTestCase): # long as it receives higher priority advertisements @unittest.skipUnless(config.extended, "part of extended tests") def test_vrrp4_backup_noadv(self): - """ IPv4 Backup VR does not advertise """ + """IPv4 Backup VR does not advertise""" self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -421,10 +444,15 @@ class TestVRRP4(VppTestCase): prio = 100 intvl = self._default_adv intvl_s = intvl * 0.01 - vr = VppVRRPVirtualRouter(self, self.pg0, vr_id, - prio=prio, intvl=intvl, - flags=self._default_flags, - vips=[self.pg0.remote_ip4]) + vr = VppVRRPVirtualRouter( + self, + self.pg0, + vr_id, + prio=prio, + intvl=intvl, + flags=self._default_flags, + vips=[self.pg0.remote_ip4], + ) self._vrs.append(vr) vr.add_vpp_config() @@ -440,7 +468,7 @@ class TestVRRP4(VppTestCase): # send higher prio advertisements, should not receive any src_ip = self.pg0.remote_ip4 - pkts = [vr.vrrp_adv_packet(prio=prio+10, src_ip=src_ip)] + pkts = [vr.vrrp_adv_packet(prio=prio + 10, src_ip=src_ip)] while time.time() < end_time: self.send_and_assert_no_replies(self.pg0, pkts, timeout=intvl_s) self.logger.info(self.vapi.cli("show trace")) @@ -451,16 +479,16 @@ class TestVRRP4(VppTestCase): self._vrs = [] def test_vrrp4_master_arp(self): - """ IPv4 Master VR replies to ARP """ + """IPv4 Master VR replies to ARP""" self.pg_start() # VR virtual IP is the default, which is the pg local IP vr_id = 100 prio = 255 intvl = self._default_adv - vr = VppVRRPVirtualRouter(self, self.pg0, 100, - prio=prio, intvl=intvl, - flags=self._default_flags) + vr = VppVRRPVirtualRouter( + self, self.pg0, 100, prio=prio, intvl=intvl, flags=self._default_flags + ) self._vrs.append(vr) vr.add_vpp_config() @@ -484,7 +512,7 @@ class TestVRRP4(VppTestCase): @unittest.skipUnless(config.extended, "part of extended tests") def test_vrrp4_backup_noarp(self): - """ IPv4 Backup VR ignores ARP """ + """IPv4 Backup VR ignores ARP""" # We need an address for a virtual IP that is not the IP that # ARP requests will originate from @@ -492,16 +520,24 @@ class TestVRRP4(VppTestCase): prio = 100 intvl = self._default_adv vip = self.pg0.remote_hosts[1].ip4 - vr = VppVRRPVirtualRouter(self, self.pg0, vr_id, - prio=prio, intvl=intvl, - flags=self._default_flags, - vips=[vip]) + vr = VppVRRPVirtualRouter( + self, + self.pg0, + vr_id, + prio=prio, + intvl=intvl, + flags=self._default_flags, + vips=[vip], + ) self._vrs.append(vr) vr.add_vpp_config() - arp_req = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / - ARP(op=ARP.who_has, pdst=vip, - psrc=self.pg0.remote_ip4, hwsrc=self.pg0.remote_mac)) + arp_req = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / ARP( + op=ARP.who_has, + pdst=vip, + psrc=self.pg0.remote_ip4, + hwsrc=self.pg0.remote_mac, + ) # Before the VR is started make sure no reply to request for VIP self.pg_start() @@ -510,7 +546,7 @@ class TestVRRP4(VppTestCase): # VR should start in backup state and still should not reply to ARP # send a higher priority adv to make sure it does not become master - adv = vr.vrrp_adv_packet(prio=prio+10, src_ip=self.pg0.remote_ip4) + adv = vr.vrrp_adv_packet(prio=prio + 10, src_ip=self.pg0.remote_ip4) vr.start_stop(is_start=1) self.send_and_assert_no_replies(self.pg0, [adv, arp_req], timeout=1) @@ -520,17 +556,22 @@ class TestVRRP4(VppTestCase): @unittest.skipUnless(config.extended, "part of extended tests") def test_vrrp4_election(self): - """ IPv4 Backup VR becomes master if no advertisements received """ + """IPv4 Backup VR becomes master if no advertisements received""" vr_id = 100 prio = 100 intvl = self._default_adv intvl_s = intvl * 0.01 vip = self.pg0.remote_ip4 - vr = VppVRRPVirtualRouter(self, self.pg0, vr_id, - prio=prio, intvl=intvl, - flags=self._default_flags, - vips=[vip]) + vr = VppVRRPVirtualRouter( + self, + self.pg0, + vr_id, + prio=prio, + intvl=intvl, + flags=self._default_flags, + vips=[vip], + ) self._vrs.append(vr) vr.add_vpp_config() @@ -557,17 +598,22 @@ class TestVRRP4(VppTestCase): @unittest.skipUnless(config.extended, "part of extended tests") def test_vrrp4_backup_preempts(self): - """ IPv4 Backup VR preempts lower priority master """ + """IPv4 Backup VR preempts lower priority master""" vr_id = 100 prio = 100 intvl = self._default_adv intvl_s = intvl * 0.01 vip = self.pg0.remote_ip4 - vr = VppVRRPVirtualRouter(self, self.pg0, vr_id, - prio=prio, intvl=intvl, - flags=self._default_flags, - vips=[vip]) + vr = VppVRRPVirtualRouter( + self, + self.pg0, + vr_id, + prio=prio, + intvl=intvl, + flags=self._default_flags, + vips=[vip], + ) self._vrs.append(vr) vr.add_vpp_config() @@ -583,7 +629,7 @@ class TestVRRP4(VppTestCase): # send lower prio advertisements until timer expires src_ip = self.pg0.remote_ip4 - pkts = [vr.vrrp_adv_packet(prio=prio-10, src_ip=src_ip)] + pkts = [vr.vrrp_adv_packet(prio=prio - 10, src_ip=src_ip)] while time.time() + intvl_s < end_time: self.send_and_assert_no_replies(self.pg0, pkts, timeout=intvl_s) self.logger.info(self.vapi.cli("show trace")) @@ -595,7 +641,7 @@ class TestVRRP4(VppTestCase): @unittest.skipUnless(config.extended, "part of extended tests") def test_vrrp4_master_preempted(self): - """ IPv4 Master VR preempted by higher priority backup """ + """IPv4 Master VR preempted by higher priority backup""" # A prio 255 VR cannot be preempted so the prio has to be lower and # we have to wait for it to take over @@ -603,10 +649,15 @@ class TestVRRP4(VppTestCase): prio = 100 intvl = self._default_adv vip = self.pg0.remote_ip4 - vr = VppVRRPVirtualRouter(self, self.pg0, vr_id, - prio=prio, intvl=intvl, - flags=self._default_flags, - vips=[vip]) + vr = VppVRRPVirtualRouter( + self, + self.pg0, + vr_id, + prio=prio, + intvl=intvl, + flags=self._default_flags, + vips=[vip], + ) self._vrs.append(vr) vr.add_vpp_config() @@ -632,7 +683,7 @@ class TestVRRP4(VppTestCase): @unittest.skipUnless(config.extended, "part of extended tests") def test_vrrp4_accept_mode_disabled(self): - """ IPv4 Master VR does not reply for VIP w/ accept mode off """ + """IPv4 Master VR does not reply for VIP w/ accept mode off""" # accept mode only matters when prio < 255, so it will have to # come up as a backup and take over as master after the timeout @@ -640,10 +691,15 @@ class TestVRRP4(VppTestCase): prio = 100 intvl = self._default_adv vip = self.pg0.remote_hosts[4].ip4 - vr = VppVRRPVirtualRouter(self, self.pg0, vr_id, - prio=prio, intvl=intvl, - flags=self._default_flags, - vips=[vip]) + vr = VppVRRPVirtualRouter( + self, + self.pg0, + vr_id, + prio=prio, + intvl=intvl, + flags=self._default_flags, + vips=[vip], + ) self._vrs.append(vr) vr.add_vpp_config() @@ -661,9 +717,11 @@ class TestVRRP4(VppTestCase): vr.assert_state_equals(VRRP_VR_STATE_MASTER) # send an ICMP echo to the VR virtual IP address - echo = (Ether(dst=vr.virtual_mac(), src=self.pg0.remote_mac) / - IP(dst=vip, src=self.pg0.remote_ip4) / - ICMP(seq=1, id=self.pg0.sw_if_index, type='echo-request')) + echo = ( + Ether(dst=vr.virtual_mac(), src=self.pg0.remote_mac) + / IP(dst=vip, src=self.pg0.remote_ip4) + / ICMP(seq=1, id=self.pg0.sw_if_index, type="echo-request") + ) self.pg_send(self.pg0, [echo]) # wait for an echo reply. none should be received @@ -672,7 +730,7 @@ class TestVRRP4(VppTestCase): @unittest.skipUnless(config.extended, "part of extended tests") def test_vrrp4_accept_mode_enabled(self): - """ IPv4 Master VR replies for VIP w/ accept mode on """ + """IPv4 Master VR replies for VIP w/ accept mode on""" # A prio 255 VR cannot be preempted so the prio has to be lower and # we have to wait for it to take over @@ -680,11 +738,10 @@ class TestVRRP4(VppTestCase): prio = 100 intvl = self._default_adv vip = self.pg0.remote_hosts[4].ip4 - flags = (VRRP_VR_FLAG_PREEMPT | VRRP_VR_FLAG_ACCEPT) - vr = VppVRRPVirtualRouter(self, self.pg0, vr_id, - prio=prio, intvl=intvl, - flags=flags, - vips=[vip]) + flags = VRRP_VR_FLAG_PREEMPT | VRRP_VR_FLAG_ACCEPT + vr = VppVRRPVirtualRouter( + self, self.pg0, vr_id, prio=prio, intvl=intvl, flags=flags, vips=[vip] + ) self._vrs.append(vr) vr.add_vpp_config() @@ -702,15 +759,18 @@ class TestVRRP4(VppTestCase): vr.assert_state_equals(VRRP_VR_STATE_MASTER) # send an ICMP echo to the VR virtual IP address - echo = (Ether(dst=vr.virtual_mac(), src=self.pg0.remote_mac) / - IP(dst=vip, src=self.pg0.remote_ip4) / - ICMP(seq=1, id=self.pg0.sw_if_index, type='echo-request')) + echo = ( + Ether(dst=vr.virtual_mac(), src=self.pg0.remote_mac) + / IP(dst=vip, src=self.pg0.remote_ip4) + / ICMP(seq=1, id=self.pg0.sw_if_index, type="echo-request") + ) self.pg_send(self.pg0, [echo]) # wait for an echo reply. time.sleep(1) - rx_pkts = self.pg0.get_capture(expected_count=1, timeout=1, - filter_out_fn=is_not_echo_reply) + rx_pkts = self.pg0.get_capture( + expected_count=1, timeout=1, filter_out_fn=is_not_echo_reply + ) self.assertEqual(rx_pkts[0][IP].src, vip) self.assertEqual(rx_pkts[0][IP].dst, self.pg0.remote_ip4) @@ -720,17 +780,22 @@ class TestVRRP4(VppTestCase): @unittest.skipUnless(config.extended, "part of extended tests") def test_vrrp4_intf_tracking(self): - """ IPv4 Master VR adjusts priority based on tracked interface """ + """IPv4 Master VR adjusts priority based on tracked interface""" vr_id = 100 prio = 255 intvl = self._default_adv intvl_s = intvl * 0.01 vip = self.pg0.local_ip4 - vr = VppVRRPVirtualRouter(self, self.pg0, vr_id, - prio=prio, intvl=intvl, - flags=self._default_flags, - vips=[vip]) + vr = VppVRRPVirtualRouter( + self, + self.pg0, + vr_id, + prio=prio, + intvl=intvl, + flags=self._default_flags, + vips=[vip], + ) self._vrs.append(vr) vr.add_vpp_config() @@ -740,9 +805,9 @@ class TestVRRP4(VppTestCase): # add pg1 as a tracked interface and start the VR adjustment = 50 adjusted_prio = prio - adjustment - vr.add_del_tracked_interface(is_add=1, - sw_if_index=self.pg1.sw_if_index, - prio=adjustment) + vr.add_del_tracked_interface( + is_add=1, sw_if_index=self.pg1.sw_if_index, prio=adjustment + ) vr.start_stop(is_start=1) vr.assert_state_equals(VRRP_VR_STATE_MASTER) @@ -751,53 +816,47 @@ class TestVRRP4(VppTestCase): # tracked intf is up -> advertised priority == configured priority self.pg0.enable_capture() - rx = self.pg0.wait_for_packet(timeout=intvl_s, - filter_out_fn=is_not_adv) + rx = self.pg0.wait_for_packet(timeout=intvl_s, filter_out_fn=is_not_adv) self.assertEqual(rx, adv_configured) # take down pg1, verify priority is now being adjusted self.pg1.admin_down() self.pg0.enable_capture() - rx = self.pg0.wait_for_packet(timeout=intvl_s, - filter_out_fn=is_not_adv) + rx = self.pg0.wait_for_packet(timeout=intvl_s, filter_out_fn=is_not_adv) self.assertEqual(rx, adv_adjusted) # bring up pg1, verify priority now matches configured value self.pg1.admin_up() self.pg0.enable_capture() - rx = self.pg0.wait_for_packet(timeout=intvl_s, - filter_out_fn=is_not_adv) + rx = self.pg0.wait_for_packet(timeout=intvl_s, filter_out_fn=is_not_adv) self.assertEqual(rx, adv_configured) # remove IP address from pg1, verify priority now being adjusted self.pg1.unconfig_ip4() self.pg0.enable_capture() - rx = self.pg0.wait_for_packet(timeout=intvl_s, - filter_out_fn=is_not_adv) + rx = self.pg0.wait_for_packet(timeout=intvl_s, filter_out_fn=is_not_adv) self.assertEqual(rx, adv_adjusted) # add IP address to pg1, verify priority now matches configured value self.pg1.config_ip4() self.pg0.enable_capture() - rx = self.pg0.wait_for_packet(timeout=intvl_s, - filter_out_fn=is_not_adv) + rx = self.pg0.wait_for_packet(timeout=intvl_s, filter_out_fn=is_not_adv) self.assertEqual(rx, adv_configured) @unittest.skipUnless(config.extended, "part of extended tests") def test_vrrp4_master_adv_unicast(self): - """ IPv4 Master VR advertises (unicast) """ + """IPv4 Master VR advertises (unicast)""" vr_id = 100 prio = 255 intvl = self._default_adv intvl_s = intvl * 0.01 vip = self.pg0.local_ip4 - flags = (self._default_flags | VRRP_VR_FLAG_UNICAST) + flags = self._default_flags | VRRP_VR_FLAG_UNICAST unicast_peer = self.pg0.remote_hosts[4] - vr = VppVRRPVirtualRouter(self, self.pg0, vr_id, - prio=prio, intvl=intvl, - flags=flags, - vips=[vip]) + vr = VppVRRPVirtualRouter( + self, self.pg0, vr_id, prio=prio, intvl=intvl, flags=flags, vips=[vip] + ) self._vrs.append(vr) vr.add_vpp_config() vr.set_unicast_peers([unicast_peer.ip4]) @@ -810,8 +869,7 @@ class TestVRRP4(VppTestCase): vr.assert_state_equals(VRRP_VR_STATE_MASTER) self.pg0.enable_capture() - rx = self.pg0.wait_for_packet(timeout=intvl_s, - filter_out_fn=is_not_adv) + rx = self.pg0.wait_for_packet(timeout=intvl_s, filter_out_fn=is_not_adv) self.assertTrue(rx.haslayer(Ether)) self.assertTrue(rx.haslayer(IP)) @@ -827,7 +885,7 @@ class TestVRRP4(VppTestCase): class TestVRRP6(VppTestCase): - """ IPv6 VRRP Test Case """ + """IPv6 VRRP Test Case""" @classmethod def setUpClass(cls): @@ -849,7 +907,7 @@ class TestVRRP6(VppTestCase): i.configure_ipv6_neighbors() self._vrs = [] - self._default_flags = (VRRP_VR_FLAG_IPV6 | VRRP_VR_FLAG_PREEMPT) + self._default_flags = VRRP_VR_FLAG_IPV6 | VRRP_VR_FLAG_PREEMPT self._default_adv = 100 def tearDown(self): @@ -922,15 +980,15 @@ class TestVRRP6(VppTestCase): # become master and start advertising immediately. @unittest.skipUnless(config.extended, "part of extended tests") def test_vrrp6_master_adv(self): - """ IPv6 Master VR advertises """ + """IPv6 Master VR advertises""" self.pg_enable_capture(self.pg_interfaces) self.pg_start() prio = 255 intvl = self._default_adv - vr = VppVRRPVirtualRouter(self, self.pg0, 100, - prio=prio, intvl=intvl, - flags=self._default_flags) + vr = VppVRRPVirtualRouter( + self, self.pg0, 100, prio=prio, intvl=intvl, flags=self._default_flags + ) self._vrs.append(vr) vr.add_vpp_config() @@ -956,25 +1014,30 @@ class TestVRRP6(VppTestCase): # of parameters to test that too @unittest.skipUnless(config.extended, "part of extended tests") def test_vrrp6_master_adv_update(self): - """ IPv6 Master VR adv + Update to Backup """ + """IPv6 Master VR adv + Update to Backup""" self.pg_enable_capture(self.pg_interfaces) self.pg_start() prio = 255 intvl = self._default_adv - vr = VppVRRPVirtualRouter(self, self.pg0, 100, - prio=prio, intvl=intvl, - flags=self._default_flags) + vr = VppVRRPVirtualRouter( + self, self.pg0, 100, prio=prio, intvl=intvl, flags=self._default_flags + ) vr.update_vpp_config() vr.start_stop(is_start=1) self.logger.info(self.vapi.cli("show vrrp vr")) # Update VR with lower prio and larger interval # we need to keep old VR for the adv checks - upd_vr = VppVRRPVirtualRouter(self, self.pg0, 100, - prio=100, intvl=2*intvl, - flags=self._default_flags, - vips=[self.pg0.remote_ip6]) + upd_vr = VppVRRPVirtualRouter( + self, + self.pg0, + 100, + prio=100, + intvl=2 * intvl, + flags=self._default_flags, + vips=[self.pg0.remote_ip6], + ) upd_vr._vrrp_index = vr._vrrp_index upd_vr.update_vpp_config() start_time = time.time() @@ -1000,7 +1063,8 @@ class TestVRRP6(VppTestCase): end_time = start_time + 2 * upd_vr.master_down_seconds() while time.time() < end_time: self.send_and_assert_no_replies( - self.pg0, pkts, timeout=0.01*upd_vr._intvl) + self.pg0, pkts, timeout=0.01 * upd_vr._intvl + ) self.logger.info(self.vapi.cli("show trace")) vr.start_stop(is_start=0) @@ -1010,7 +1074,7 @@ class TestVRRP6(VppTestCase): # long as it receives higher priority advertisements @unittest.skipUnless(config.extended, "part of extended tests") def test_vrrp6_backup_noadv(self): - """ IPv6 Backup VR does not advertise """ + """IPv6 Backup VR does not advertise""" self.pg_enable_capture(self.pg_interfaces) self.pg_start() @@ -1018,10 +1082,15 @@ class TestVRRP6(VppTestCase): prio = 100 intvl = self._default_adv intvl_s = intvl * 0.01 - vr = VppVRRPVirtualRouter(self, self.pg0, vr_id, - prio=prio, intvl=intvl, - flags=self._default_flags, - vips=[self.pg0.remote_ip6]) + vr = VppVRRPVirtualRouter( + self, + self.pg0, + vr_id, + prio=prio, + intvl=intvl, + flags=self._default_flags, + vips=[self.pg0.remote_ip6], + ) vr.add_vpp_config() self._vrs.append(vr) @@ -1037,7 +1106,7 @@ class TestVRRP6(VppTestCase): # send higher prio advertisements, should not see VPP send any src_ip = self.pg0.remote_ip6_ll num_advs = 5 - pkts = [vr.vrrp_adv_packet(prio=prio+10, src_ip=src_ip)] + pkts = [vr.vrrp_adv_packet(prio=prio + 10, src_ip=src_ip)] self.logger.info(self.vapi.cli("show vlib graph")) while time.time() < end_time: self.send_and_assert_no_replies(self.pg0, pkts, timeout=intvl_s) @@ -1050,16 +1119,16 @@ class TestVRRP6(VppTestCase): self._vrs = [] def test_vrrp6_master_nd(self): - """ IPv6 Master VR replies to NDP """ + """IPv6 Master VR replies to NDP""" self.pg_start() # VR virtual IP is the default, which is the pg local IP vr_id = 100 prio = 255 intvl = self._default_adv - vr = VppVRRPVirtualRouter(self, self.pg0, 100, - prio=prio, intvl=intvl, - flags=self._default_flags) + vr = VppVRRPVirtualRouter( + self, self.pg0, 100, prio=prio, intvl=intvl, flags=self._default_flags + ) vr.add_vpp_config() self._vrs.append(vr) @@ -1082,7 +1151,7 @@ class TestVRRP6(VppTestCase): @unittest.skipUnless(config.extended, "part of extended tests") def test_vrrp6_backup_nond(self): - """ IPv6 Backup VR ignores NDP """ + """IPv6 Backup VR ignores NDP""" # We need an address for a virtual IP that is not the IP that # ARP requests will originate from @@ -1091,10 +1160,15 @@ class TestVRRP6(VppTestCase): intvl = self._default_adv intvl_s = intvl * 0.01 vip = self.pg0.remote_hosts[1].ip6 - vr = VppVRRPVirtualRouter(self, self.pg0, vr_id, - prio=prio, intvl=intvl, - flags=self._default_flags, - vips=[vip]) + vr = VppVRRPVirtualRouter( + self, + self.pg0, + vr_id, + prio=prio, + intvl=intvl, + flags=self._default_flags, + vips=[vip], + ) vr.add_vpp_config() self._vrs.append(vr) @@ -1102,36 +1176,43 @@ class TestVRRP6(VppTestCase): dmac = in6_getnsmac(nsma) dst_ip = inet_ntop(socket.AF_INET6, nsma) - ndp_req = (Ether(dst=dmac, src=self.pg0.remote_mac) / - IPv6(dst=dst_ip, src=self.pg0.remote_ip6) / - ICMPv6ND_NS(tgt=vip) / - ICMPv6NDOptSrcLLAddr(lladdr=self.pg0.remote_mac)) + ndp_req = ( + Ether(dst=dmac, src=self.pg0.remote_mac) + / IPv6(dst=dst_ip, src=self.pg0.remote_ip6) + / ICMPv6ND_NS(tgt=vip) + / ICMPv6NDOptSrcLLAddr(lladdr=self.pg0.remote_mac) + ) # Before the VR is started make sure no reply to request for VIP self.send_and_assert_no_replies(self.pg0, [ndp_req], timeout=1) # VR should start in backup state and still should not reply to NDP # send a higher priority adv to make sure it does not become master - adv = vr.vrrp_adv_packet(prio=prio+10, src_ip=self.pg0.remote_ip6) + adv = vr.vrrp_adv_packet(prio=prio + 10, src_ip=self.pg0.remote_ip6) pkts = [adv, ndp_req] vr.start_stop(is_start=1) - self.send_and_assert_no_replies(self.pg0, pkts, timeout=intvl_s) + self.send_and_assert_no_replies(self.pg0, pkts, timeout=intvl_s) vr.start_stop(is_start=0) @unittest.skipUnless(config.extended, "part of extended tests") def test_vrrp6_election(self): - """ IPv6 Backup VR becomes master if no advertisements received """ + """IPv6 Backup VR becomes master if no advertisements received""" vr_id = 100 prio = 100 intvl = self._default_adv intvl_s = intvl * 0.01 vip = self.pg0.remote_ip6 - vr = VppVRRPVirtualRouter(self, self.pg0, vr_id, - prio=prio, intvl=intvl, - flags=self._default_flags, - vips=[vip]) + vr = VppVRRPVirtualRouter( + self, + self.pg0, + vr_id, + prio=prio, + intvl=intvl, + flags=self._default_flags, + vips=[vip], + ) self._vrs.append(vr) vr.add_vpp_config() @@ -1158,17 +1239,22 @@ class TestVRRP6(VppTestCase): @unittest.skipUnless(config.extended, "part of extended tests") def test_vrrp6_backup_preempts(self): - """ IPv6 Backup VR preempts lower priority master """ + """IPv6 Backup VR preempts lower priority master""" vr_id = 100 prio = 100 intvl = self._default_adv intvl_s = intvl * 0.01 vip = self.pg0.remote_ip6 - vr = VppVRRPVirtualRouter(self, self.pg0, vr_id, - prio=prio, intvl=intvl, - flags=self._default_flags, - vips=[vip]) + vr = VppVRRPVirtualRouter( + self, + self.pg0, + vr_id, + prio=prio, + intvl=intvl, + flags=self._default_flags, + vips=[vip], + ) self._vrs.append(vr) vr.add_vpp_config() @@ -1184,7 +1270,7 @@ class TestVRRP6(VppTestCase): # send lower prio advertisements until timer expires src_ip = self.pg0.remote_ip6 - pkts = [vr.vrrp_adv_packet(prio=prio-10, src_ip=src_ip)] + pkts = [vr.vrrp_adv_packet(prio=prio - 10, src_ip=src_ip)] while (time.time() + intvl_s) < end_time: self.send_and_assert_no_replies(self.pg0, pkts, timeout=intvl_s) self.logger.info(self.vapi.cli("show trace")) @@ -1196,7 +1282,7 @@ class TestVRRP6(VppTestCase): @unittest.skipUnless(config.extended, "part of extended tests") def test_vrrp6_master_preempted(self): - """ IPv6 Master VR preempted by higher priority backup """ + """IPv6 Master VR preempted by higher priority backup""" # A prio 255 VR cannot be preempted so the prio has to be lower and # we have to wait for it to take over @@ -1204,10 +1290,15 @@ class TestVRRP6(VppTestCase): prio = 100 intvl = self._default_adv vip = self.pg0.remote_ip6 - vr = VppVRRPVirtualRouter(self, self.pg0, vr_id, - prio=prio, intvl=intvl, - flags=self._default_flags, - vips=[vip]) + vr = VppVRRPVirtualRouter( + self, + self.pg0, + vr_id, + prio=prio, + intvl=intvl, + flags=self._default_flags, + vips=[vip], + ) self._vrs.append(vr) vr.add_vpp_config() @@ -1233,7 +1324,7 @@ class TestVRRP6(VppTestCase): @unittest.skipUnless(config.extended, "part of extended tests") def test_vrrp6_accept_mode_disabled(self): - """ IPv6 Master VR does not reply for VIP w/ accept mode off """ + """IPv6 Master VR does not reply for VIP w/ accept mode off""" # accept mode only matters when prio < 255, so it will have to # come up as a backup and take over as master after the timeout @@ -1241,10 +1332,15 @@ class TestVRRP6(VppTestCase): prio = 100 intvl = self._default_adv vip = self.pg0.remote_hosts[4].ip6 - vr = VppVRRPVirtualRouter(self, self.pg0, vr_id, - prio=prio, intvl=intvl, - flags=self._default_flags, - vips=[vip]) + vr = VppVRRPVirtualRouter( + self, + self.pg0, + vr_id, + prio=prio, + intvl=intvl, + flags=self._default_flags, + vips=[vip], + ) self._vrs.append(vr) vr.add_vpp_config() @@ -1262,9 +1358,11 @@ class TestVRRP6(VppTestCase): vr.assert_state_equals(VRRP_VR_STATE_MASTER) # send an ICMPv6 echo to the VR virtual IP address - echo = (Ether(dst=vr.virtual_mac(), src=self.pg0.remote_mac) / - IPv6(dst=vip, src=self.pg0.remote_ip6) / - ICMPv6EchoRequest(seq=1, id=self.pg0.sw_if_index)) + echo = ( + Ether(dst=vr.virtual_mac(), src=self.pg0.remote_mac) + / IPv6(dst=vip, src=self.pg0.remote_ip6) + / ICMPv6EchoRequest(seq=1, id=self.pg0.sw_if_index) + ) self.pg_send(self.pg0, [echo]) # wait for an echo reply. none should be received @@ -1273,7 +1371,7 @@ class TestVRRP6(VppTestCase): @unittest.skipUnless(config.extended, "part of extended tests") def test_vrrp6_accept_mode_enabled(self): - """ IPv6 Master VR replies for VIP w/ accept mode on """ + """IPv6 Master VR replies for VIP w/ accept mode on""" # A prio 255 VR cannot be preempted so the prio has to be lower and # we have to wait for it to take over @@ -1281,11 +1379,10 @@ class TestVRRP6(VppTestCase): prio = 100 intvl = self._default_adv vip = self.pg0.remote_hosts[4].ip6 - flags = (self._default_flags | VRRP_VR_FLAG_ACCEPT) - vr = VppVRRPVirtualRouter(self, self.pg0, vr_id, - prio=prio, intvl=intvl, - flags=flags, - vips=[vip]) + flags = self._default_flags | VRRP_VR_FLAG_ACCEPT + vr = VppVRRPVirtualRouter( + self, self.pg0, vr_id, prio=prio, intvl=intvl, flags=flags, vips=[vip] + ) self._vrs.append(vr) vr.add_vpp_config() @@ -1303,15 +1400,18 @@ class TestVRRP6(VppTestCase): vr.assert_state_equals(VRRP_VR_STATE_MASTER) # send an ICMP echo to the VR virtual IP address - echo = (Ether(dst=vr.virtual_mac(), src=self.pg0.remote_mac) / - IPv6(dst=vip, src=self.pg0.remote_ip6) / - ICMPv6EchoRequest(seq=1, id=self.pg0.sw_if_index)) + echo = ( + Ether(dst=vr.virtual_mac(), src=self.pg0.remote_mac) + / IPv6(dst=vip, src=self.pg0.remote_ip6) + / ICMPv6EchoRequest(seq=1, id=self.pg0.sw_if_index) + ) self.pg_send(self.pg0, [echo]) # wait for an echo reply. time.sleep(1) - rx_pkts = self.pg0.get_capture(expected_count=1, timeout=1, - filter_out_fn=is_not_echo_reply) + rx_pkts = self.pg0.get_capture( + expected_count=1, timeout=1, filter_out_fn=is_not_echo_reply + ) self.assertEqual(rx_pkts[0][IPv6].src, vip) self.assertEqual(rx_pkts[0][IPv6].dst, self.pg0.remote_ip6) @@ -1320,17 +1420,22 @@ class TestVRRP6(VppTestCase): @unittest.skipUnless(config.extended, "part of extended tests") def test_vrrp6_intf_tracking(self): - """ IPv6 Master VR adjusts priority based on tracked interface """ + """IPv6 Master VR adjusts priority based on tracked interface""" vr_id = 100 prio = 255 intvl = self._default_adv intvl_s = intvl * 0.01 vip = self.pg0.local_ip6 - vr = VppVRRPVirtualRouter(self, self.pg0, vr_id, - prio=prio, intvl=intvl, - flags=self._default_flags, - vips=[vip]) + vr = VppVRRPVirtualRouter( + self, + self.pg0, + vr_id, + prio=prio, + intvl=intvl, + flags=self._default_flags, + vips=[vip], + ) self._vrs.append(vr) vr.add_vpp_config() @@ -1340,9 +1445,9 @@ class TestVRRP6(VppTestCase): # add pg1 as a tracked interface and start the VR adjustment = 50 adjusted_prio = prio - adjustment - vr.add_del_tracked_interface(is_add=1, - sw_if_index=self.pg1.sw_if_index, - prio=adjustment) + vr.add_del_tracked_interface( + is_add=1, sw_if_index=self.pg1.sw_if_index, prio=adjustment + ) vr.start_stop(is_start=1) vr.assert_state_equals(VRRP_VR_STATE_MASTER) @@ -1351,53 +1456,47 @@ class TestVRRP6(VppTestCase): # tracked intf is up -> advertised priority == configured priority self.pg0.enable_capture() - rx = self.pg0.wait_for_packet(timeout=intvl_s, - filter_out_fn=is_not_adv) + rx = self.pg0.wait_for_packet(timeout=intvl_s, filter_out_fn=is_not_adv) self.assertEqual(rx, adv_configured) # take down pg1, verify priority is now being adjusted self.pg1.admin_down() self.pg0.enable_capture() - rx = self.pg0.wait_for_packet(timeout=intvl_s, - filter_out_fn=is_not_adv) + rx = self.pg0.wait_for_packet(timeout=intvl_s, filter_out_fn=is_not_adv) self.assertEqual(rx, adv_adjusted) # bring up pg1, verify priority now matches configured value self.pg1.admin_up() self.pg0.enable_capture() - rx = self.pg0.wait_for_packet(timeout=intvl_s, - filter_out_fn=is_not_adv) + rx = self.pg0.wait_for_packet(timeout=intvl_s, filter_out_fn=is_not_adv) self.assertEqual(rx, adv_configured) # remove IP address from pg1, verify priority now being adjusted self.pg1.unconfig_ip6() self.pg0.enable_capture() - rx = self.pg0.wait_for_packet(timeout=intvl_s, - filter_out_fn=is_not_adv) + rx = self.pg0.wait_for_packet(timeout=intvl_s, filter_out_fn=is_not_adv) self.assertEqual(rx, adv_adjusted) # add IP address to pg1, verify priority now matches configured value self.pg1.config_ip6() self.pg0.enable_capture() - rx = self.pg0.wait_for_packet(timeout=intvl_s, - filter_out_fn=is_not_adv) + rx = self.pg0.wait_for_packet(timeout=intvl_s, filter_out_fn=is_not_adv) self.assertEqual(rx, adv_configured) @unittest.skipUnless(config.extended, "part of extended tests") def test_vrrp6_master_adv_unicast(self): - """ IPv6 Master VR advertises (unicast) """ + """IPv6 Master VR advertises (unicast)""" vr_id = 100 prio = 255 intvl = self._default_adv intvl_s = intvl * 0.01 vip = self.pg0.local_ip6 - flags = (self._default_flags | VRRP_VR_FLAG_UNICAST) + flags = self._default_flags | VRRP_VR_FLAG_UNICAST unicast_peer = self.pg0.remote_hosts[4] - vr = VppVRRPVirtualRouter(self, self.pg0, vr_id, - prio=prio, intvl=intvl, - flags=flags, - vips=[vip]) + vr = VppVRRPVirtualRouter( + self, self.pg0, vr_id, prio=prio, intvl=intvl, flags=flags, vips=[vip] + ) self._vrs.append(vr) vr.add_vpp_config() vr.set_unicast_peers([unicast_peer.ip6]) @@ -1410,23 +1509,22 @@ class TestVRRP6(VppTestCase): vr.assert_state_equals(VRRP_VR_STATE_MASTER) self.pg0.enable_capture() - rx = self.pg0.wait_for_packet(timeout=intvl_s, - filter_out_fn=is_not_adv) + rx = self.pg0.wait_for_packet(timeout=intvl_s, filter_out_fn=is_not_adv) self.assertTrue(rx.haslayer(Ether)) self.assertTrue(rx.haslayer(IPv6)) self.assertTrue(rx.haslayer(VRRPv3)) self.assertEqual(rx[Ether].src, self.pg0.local_mac) self.assertEqual(rx[Ether].dst, unicast_peer.mac) - self.assertEqual(ip6_normalize(rx[IPv6].src), - ip6_normalize(self.pg0.local_ip6_ll)) - self.assertEqual(ip6_normalize(rx[IPv6].dst), - ip6_normalize(unicast_peer.ip6)) + self.assertEqual( + ip6_normalize(rx[IPv6].src), ip6_normalize(self.pg0.local_ip6_ll) + ) + self.assertEqual(ip6_normalize(rx[IPv6].dst), ip6_normalize(unicast_peer.ip6)) self.assertEqual(rx[VRRPv3].vrid, vr_id) self.assertEqual(rx[VRRPv3].priority, prio) self.assertEqual(rx[VRRPv3].ipcount, 1) self.assertEqual(rx[VRRPv3].addrlist, [vip]) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_vtr.py b/test/test_vtr.py index c3704f1e7b6..b33dcb66541 100644 --- a/test/test_vtr.py +++ b/test/test_vtr.py @@ -12,13 +12,13 @@ from framework import VppTestCase, VppTestRunner from vpp_sub_interface import L2_VTR_OP, VppDot1QSubint, VppDot1ADSubint from collections import namedtuple -Tag = namedtuple('Tag', ['dot1', 'vlan']) +Tag = namedtuple("Tag", ["dot1", "vlan"]) DOT1AD = 0x88A8 DOT1Q = 0x8100 class TestVtr(VppTestCase): - """ VTR Test Case """ + """VTR Test Case""" @classmethod def setUpClass(cls): @@ -36,9 +36,9 @@ class TestVtr(VppTestCase): cls.create_pg_interfaces(ifs) cls.sub_interfaces = [ - VppDot1ADSubint(cls, cls.pg1, cls.dot1ad_sub_id, - cls.Btag, cls.Atag), - VppDot1QSubint(cls, cls.pg2, cls.Btag)] + VppDot1ADSubint(cls, cls.pg1, cls.dot1ad_sub_id, cls.Btag, cls.Atag), + VppDot1QSubint(cls, cls.pg2, cls.Btag), + ] interfaces = list(cls.pg_interfaces) interfaces.extend(cls.sub_interfaces) @@ -46,10 +46,14 @@ class TestVtr(VppTestCase): # Create BD with MAC learning enabled and put interfaces and # sub-interfaces to this BD for pg_if in cls.pg_interfaces: - sw_if_index = pg_if.sub_if.sw_if_index \ - if hasattr(pg_if, 'sub_if') else pg_if.sw_if_index - cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=sw_if_index, - bd_id=cls.bd_id) + sw_if_index = ( + pg_if.sub_if.sw_if_index + if hasattr(pg_if, "sub_if") + else pg_if.sw_if_index + ) + cls.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=sw_if_index, bd_id=cls.bd_id + ) # setup all interfaces for i in interfaces: @@ -86,8 +90,7 @@ class TestVtr(VppTestCase): def show_commands_at_teardown(self): self.logger.info(self.vapi.ppcli("show l2fib verbose")) - self.logger.info(self.vapi.ppcli("show bridge-domain %s detail" % - self.bd_id)) + self.logger.info(self.vapi.ppcli("show bridge-domain %s detail" % self.bd_id)) @classmethod def create_hosts_and_learn(cls, count): @@ -98,10 +101,11 @@ class TestVtr(VppTestCase): for j in range(1, count + 1): host = Host( "00:00:00:ff:%02x:%02x" % (pg_if.sw_if_index, j), - "172.17.1%02x.%u" % (pg_if.sw_if_index, j)) - packet = (Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac)) + "172.17.1%02x.%u" % (pg_if.sw_if_index, j), + ) + packet = Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac) hosts.append(host) - if hasattr(pg_if, 'sub_if'): + if hasattr(pg_if, "sub_if"): packet = pg_if.sub_if.add_dot1_layer(packet) packets.append(packet) pg_if.add_stream(packets) @@ -115,12 +119,14 @@ class TestVtr(VppTestCase): src_host = random.choice(self.hosts_by_pg_idx[src_if.sw_if_index]) pkt_info = self.create_packet_info(src_if, dst_if) payload = self.info_to_payload(pkt_info) - p = (Ether(dst=dst_host.mac, src=src_host.mac) / - IP(src=src_host.ip4, dst=dst_host.ip4) / - UDP(sport=1234, dport=1234) / - Raw(payload)) + p = ( + Ether(dst=dst_host.mac, src=src_host.mac) + / IP(src=src_host.ip4, dst=dst_host.ip4) + / UDP(sport=1234, dport=1234) + / Raw(payload) + ) pkt_info.data = p.copy() - if do_dot1 and hasattr(src_if, 'sub_if'): + if do_dot1 and hasattr(src_if, "sub_if"): p = src_if.sub_if.add_dot1_layer(p) size = random.choice(packet_sizes) self.extend_packet(p, size) @@ -172,8 +178,9 @@ class TestVtr(VppTestCase): return i = VppDot1QSubint(self, self.pg0, tags[0].vlan) - self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=i.sw_if_index, - bd_id=self.bd_id, enable=1) + self.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=i.sw_if_index, bd_id=self.bd_id, enable=1 + ) i.admin_up() p = self.create_packet(self.pg0, swif, do_dot1=False) @@ -185,202 +192,217 @@ class TestVtr(VppTestCase): swif.sub_if.remove_dot1_layer(rx[0]) self.assertTrue(Dot1Q not in rx[0]) - self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=i.sw_if_index, - bd_id=self.bd_id, enable=0) + self.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=i.sw_if_index, bd_id=self.bd_id, enable=0 + ) i.remove_vpp_config() def test_1ad_vtr_pop_1(self): - """ 1AD VTR pop 1 test - """ + """1AD VTR pop 1 test""" self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_POP_1) self.vtr_test(self.pg1, [Tag(dot1=DOT1Q, vlan=100)]) def test_1ad_vtr_pop_2(self): - """ 1AD VTR pop 2 test - """ + """1AD VTR pop 2 test""" self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_POP_2) self.vtr_test(self.pg1, []) def test_1ad_vtr_push_1ad(self): - """ 1AD VTR push 1 1AD test - """ + """1AD VTR push 1 1AD test""" self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_PUSH_1, tag=300) - self.vtr_test(self.pg1, [Tag(dot1=DOT1AD, vlan=300), - Tag(dot1=DOT1AD, vlan=200), - Tag(dot1=DOT1Q, vlan=100)]) + self.vtr_test( + self.pg1, + [ + Tag(dot1=DOT1AD, vlan=300), + Tag(dot1=DOT1AD, vlan=200), + Tag(dot1=DOT1Q, vlan=100), + ], + ) def test_1ad_vtr_push_2ad(self): - """ 1AD VTR push 2 1AD test - """ + """1AD VTR push 2 1AD test""" self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_PUSH_2, outer=400, inner=300) - self.vtr_test(self.pg1, [Tag(dot1=DOT1AD, vlan=400), - Tag(dot1=DOT1Q, vlan=300), - Tag(dot1=DOT1AD, vlan=200), - Tag(dot1=DOT1Q, vlan=100)]) + self.vtr_test( + self.pg1, + [ + Tag(dot1=DOT1AD, vlan=400), + Tag(dot1=DOT1Q, vlan=300), + Tag(dot1=DOT1AD, vlan=200), + Tag(dot1=DOT1Q, vlan=100), + ], + ) def test_1ad_vtr_push_1q(self): - """ 1AD VTR push 1 1Q test - """ + """1AD VTR push 1 1Q test""" self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_PUSH_1, tag=300, push1q=1) - self.vtr_test(self.pg1, [Tag(dot1=DOT1Q, vlan=300), - Tag(dot1=DOT1AD, vlan=200), - Tag(dot1=DOT1Q, vlan=100)]) + self.vtr_test( + self.pg1, + [ + Tag(dot1=DOT1Q, vlan=300), + Tag(dot1=DOT1AD, vlan=200), + Tag(dot1=DOT1Q, vlan=100), + ], + ) def test_1ad_vtr_push_2q(self): - """ 1AD VTR push 2 1Q test - """ - self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_PUSH_2, - outer=400, inner=300, push1q=1) - self.vtr_test(self.pg1, [Tag(dot1=DOT1Q, vlan=400), - Tag(dot1=DOT1Q, vlan=300), - Tag(dot1=DOT1AD, vlan=200), - Tag(dot1=DOT1Q, vlan=100)]) + """1AD VTR push 2 1Q test""" + self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_PUSH_2, outer=400, inner=300, push1q=1) + self.vtr_test( + self.pg1, + [ + Tag(dot1=DOT1Q, vlan=400), + Tag(dot1=DOT1Q, vlan=300), + Tag(dot1=DOT1AD, vlan=200), + Tag(dot1=DOT1Q, vlan=100), + ], + ) def test_1ad_vtr_translate_1_1ad(self): - """ 1AD VTR translate 1 -> 1 1AD test - """ + """1AD VTR translate 1 -> 1 1AD test""" self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_TRANSLATE_1_1, tag=300) - self.vtr_test(self.pg1, [Tag(dot1=DOT1AD, vlan=300), - Tag(dot1=DOT1Q, vlan=100)]) + self.vtr_test(self.pg1, [Tag(dot1=DOT1AD, vlan=300), Tag(dot1=DOT1Q, vlan=100)]) def test_1ad_vtr_translate_1_2ad(self): - """ 1AD VTR translate 1 -> 2 1AD test - """ - self.pg1.sub_if.set_vtr( - L2_VTR_OP.L2_TRANSLATE_1_2, inner=300, outer=400) - self.vtr_test(self.pg1, [Tag(dot1=DOT1AD, vlan=400), - Tag(dot1=DOT1Q, vlan=300), - Tag(dot1=DOT1Q, vlan=100)]) + """1AD VTR translate 1 -> 2 1AD test""" + self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_TRANSLATE_1_2, inner=300, outer=400) + self.vtr_test( + self.pg1, + [ + Tag(dot1=DOT1AD, vlan=400), + Tag(dot1=DOT1Q, vlan=300), + Tag(dot1=DOT1Q, vlan=100), + ], + ) def test_1ad_vtr_translate_2_1ad(self): - """ 1AD VTR translate 2 -> 1 1AD test - """ + """1AD VTR translate 2 -> 1 1AD test""" self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_TRANSLATE_2_1, tag=300) self.vtr_test(self.pg1, [Tag(dot1=DOT1AD, vlan=300)]) def test_1ad_vtr_translate_2_2ad(self): - """ 1AD VTR translate 2 -> 2 1AD test - """ - self.pg1.sub_if.set_vtr( - L2_VTR_OP.L2_TRANSLATE_2_2, inner=300, outer=400) - self.vtr_test(self.pg1, [Tag(dot1=DOT1AD, vlan=400), - Tag(dot1=DOT1Q, vlan=300)]) + """1AD VTR translate 2 -> 2 1AD test""" + self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_TRANSLATE_2_2, inner=300, outer=400) + self.vtr_test(self.pg1, [Tag(dot1=DOT1AD, vlan=400), Tag(dot1=DOT1Q, vlan=300)]) def test_1ad_vtr_translate_1_1q(self): - """ 1AD VTR translate 1 -> 1 1Q test - """ + """1AD VTR translate 1 -> 1 1Q test""" self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_TRANSLATE_1_1, tag=300, push1q=1) - self.vtr_test(self.pg1, [Tag(dot1=DOT1Q, vlan=300), - Tag(dot1=DOT1Q, vlan=100)]) + self.vtr_test(self.pg1, [Tag(dot1=DOT1Q, vlan=300), Tag(dot1=DOT1Q, vlan=100)]) def test_1ad_vtr_translate_1_2q(self): - """ 1AD VTR translate 1 -> 2 1Q test - """ + """1AD VTR translate 1 -> 2 1Q test""" self.pg1.sub_if.set_vtr( - L2_VTR_OP.L2_TRANSLATE_1_2, inner=300, outer=400, push1q=1) - self.vtr_test(self.pg1, [Tag(dot1=DOT1Q, vlan=400), - Tag(dot1=DOT1Q, vlan=300), - Tag(dot1=DOT1Q, vlan=100)]) + L2_VTR_OP.L2_TRANSLATE_1_2, inner=300, outer=400, push1q=1 + ) + self.vtr_test( + self.pg1, + [ + Tag(dot1=DOT1Q, vlan=400), + Tag(dot1=DOT1Q, vlan=300), + Tag(dot1=DOT1Q, vlan=100), + ], + ) def test_1ad_vtr_translate_2_1q(self): - """ 1AD VTR translate 2 -> 1 1Q test - """ + """1AD VTR translate 2 -> 1 1Q test""" self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_TRANSLATE_2_1, tag=300, push1q=1) self.vtr_test(self.pg1, [Tag(dot1=DOT1Q, vlan=300)]) def test_1ad_vtr_translate_2_2q(self): - """ 1AD VTR translate 2 -> 2 1Q test - """ + """1AD VTR translate 2 -> 2 1Q test""" self.pg1.sub_if.set_vtr( - L2_VTR_OP.L2_TRANSLATE_2_2, inner=300, outer=400, push1q=1) - self.vtr_test(self.pg1, [Tag(dot1=DOT1Q, vlan=400), - Tag(dot1=DOT1Q, vlan=300)]) + L2_VTR_OP.L2_TRANSLATE_2_2, inner=300, outer=400, push1q=1 + ) + self.vtr_test(self.pg1, [Tag(dot1=DOT1Q, vlan=400), Tag(dot1=DOT1Q, vlan=300)]) def test_1q_vtr_pop_1(self): - """ 1Q VTR pop 1 test - """ + """1Q VTR pop 1 test""" self.pg2.sub_if.set_vtr(L2_VTR_OP.L2_POP_1) self.vtr_test(self.pg2, []) def test_1q_vtr_push_1(self): - """ 1Q VTR push 1 test - """ + """1Q VTR push 1 test""" self.pg2.sub_if.set_vtr(L2_VTR_OP.L2_PUSH_1, tag=300) - self.vtr_test(self.pg2, [Tag(dot1=DOT1AD, vlan=300), - Tag(dot1=DOT1Q, vlan=200)]) + self.vtr_test(self.pg2, [Tag(dot1=DOT1AD, vlan=300), Tag(dot1=DOT1Q, vlan=200)]) def test_1q_vtr_push_2(self): - """ 1Q VTR push 2 test - """ + """1Q VTR push 2 test""" self.pg2.sub_if.set_vtr(L2_VTR_OP.L2_PUSH_2, outer=400, inner=300) - self.vtr_test(self.pg2, [Tag(dot1=DOT1AD, vlan=400), - Tag(dot1=DOT1Q, vlan=300), - Tag(dot1=DOT1Q, vlan=200)]) + self.vtr_test( + self.pg2, + [ + Tag(dot1=DOT1AD, vlan=400), + Tag(dot1=DOT1Q, vlan=300), + Tag(dot1=DOT1Q, vlan=200), + ], + ) def test_1q_vtr_translate_1_1(self): - """ 1Q VTR translate 1 -> 1 test - """ + """1Q VTR translate 1 -> 1 test""" self.pg2.sub_if.set_vtr(L2_VTR_OP.L2_TRANSLATE_1_1, tag=300) self.vtr_test(self.pg2, [Tag(dot1=DOT1AD, vlan=300)]) def test_1q_vtr_translate_1_2(self): - """ 1Q VTR translate 1 -> 2 test - """ - self.pg2.sub_if.set_vtr( - L2_VTR_OP.L2_TRANSLATE_1_2, inner=300, outer=400) - self.vtr_test(self.pg2, [Tag(dot1=DOT1AD, vlan=400), - Tag(dot1=DOT1Q, vlan=300)]) + """1Q VTR translate 1 -> 2 test""" + self.pg2.sub_if.set_vtr(L2_VTR_OP.L2_TRANSLATE_1_2, inner=300, outer=400) + self.vtr_test(self.pg2, [Tag(dot1=DOT1AD, vlan=400), Tag(dot1=DOT1Q, vlan=300)]) def test_if_vtr_disable(self): - """ Disable VTR on non-sub-interfaces - """ + """Disable VTR on non-sub-interfaces""" # First set the VTR fields to junk self.vapi.l2_interface_vlan_tag_rewrite( - sw_if_index=self.pg0.sw_if_index, vtr_op=L2_VTR_OP.L2_PUSH_2, - push_dot1q=1, tag1=19, tag2=630) - - if_state = self.vapi.sw_interface_dump( - sw_if_index=self.pg0.sw_if_index) + sw_if_index=self.pg0.sw_if_index, + vtr_op=L2_VTR_OP.L2_PUSH_2, + push_dot1q=1, + tag1=19, + tag2=630, + ) + + if_state = self.vapi.sw_interface_dump(sw_if_index=self.pg0.sw_if_index) self.assertEqual(if_state[0].sw_if_index, self.pg0.sw_if_index) self.assertNotEqual(if_state[0].vtr_op, L2_VTR_OP.L2_DISABLED) # Then ensure that a request to disable VTR is honored. self.vapi.l2_interface_vlan_tag_rewrite( - sw_if_index=self.pg0.sw_if_index, vtr_op=L2_VTR_OP.L2_DISABLED) + sw_if_index=self.pg0.sw_if_index, vtr_op=L2_VTR_OP.L2_DISABLED + ) - if_state = self.vapi.sw_interface_dump( - sw_if_index=self.pg0.sw_if_index) + if_state = self.vapi.sw_interface_dump(sw_if_index=self.pg0.sw_if_index) self.assertEqual(if_state[0].sw_if_index, self.pg0.sw_if_index) self.assertEqual(if_state[0].vtr_op, L2_VTR_OP.L2_DISABLED) def test_if_vtr_push_1q(self): - """ 1Q VTR push 1 on non-sub-interfaces - """ + """1Q VTR push 1 on non-sub-interfaces""" self.vapi.l2_interface_vlan_tag_rewrite( - sw_if_index=self.pg0.sw_if_index, vtr_op=L2_VTR_OP.L2_PUSH_1, - push_dot1q=1, tag1=150) + sw_if_index=self.pg0.sw_if_index, + vtr_op=L2_VTR_OP.L2_PUSH_1, + push_dot1q=1, + tag1=150, + ) - if_state = self.vapi.sw_interface_dump( - sw_if_index=self.pg0.sw_if_index) + if_state = self.vapi.sw_interface_dump(sw_if_index=self.pg0.sw_if_index) self.assertEqual(if_state[0].sw_if_index, self.pg0.sw_if_index) self.assertEqual(if_state[0].vtr_op, L2_VTR_OP.L2_PUSH_1) self.assertEqual(if_state[0].vtr_tag1, 150) self.assertNotEqual(if_state[0].vtr_push_dot1q, 0) def test_if_vtr_push_2ad(self): - """ 1AD VTR push 2 on non-sub-interfaces - """ + """1AD VTR push 2 on non-sub-interfaces""" self.vapi.l2_interface_vlan_tag_rewrite( - sw_if_index=self.pg0.sw_if_index, vtr_op=L2_VTR_OP.L2_PUSH_2, - push_dot1q=0, tag1=450, tag2=350) - - if_state = self.vapi.sw_interface_dump( - sw_if_index=self.pg0.sw_if_index) + sw_if_index=self.pg0.sw_if_index, + vtr_op=L2_VTR_OP.L2_PUSH_2, + push_dot1q=0, + tag1=450, + tag2=350, + ) + + if_state = self.vapi.sw_interface_dump(sw_if_index=self.pg0.sw_if_index) self.assertEqual(if_state[0].sw_if_index, self.pg0.sw_if_index) self.assertEqual(if_state[0].vtr_op, L2_VTR_OP.L2_PUSH_2) - self.assertEqual(if_state[0].vtr_tag1, 450) # outer - self.assertEqual(if_state[0].vtr_tag2, 350) # inner + self.assertEqual(if_state[0].vtr_tag1, 450) # outer + self.assertEqual(if_state[0].vtr_tag2, 350) # inner self.assertEqual(if_state[0].vtr_push_dot1q, 0) -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_vxlan.py b/test/test_vxlan.py index 4247a396d24..913fc4018e0 100644 --- a/test/test_vxlan.py +++ b/test/test_vxlan.py @@ -20,7 +20,7 @@ from vpp_neighbor import VppNeighbor class TestVxlan(BridgeDomain, VppTestCase): - """ VXLAN Test Case """ + """VXLAN Test Case""" def __init__(self, *args): BridgeDomain.__init__(self) @@ -31,14 +31,16 @@ class TestVxlan(BridgeDomain, VppTestCase): Encapsulate the original payload frame by adding VXLAN header with its UDP, IP and Ethernet fields """ - return (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / - UDP(sport=self.dport, dport=self.dport, chksum=0) / - VXLAN(vni=vni, flags=self.flags) / - pkt) + return ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / UDP(sport=self.dport, dport=self.dport, chksum=0) + / VXLAN(vni=vni, flags=self.flags) + / pkt + ) def ip_range(self, start, end): - """ range of remote ip's """ + """range of remote ip's""" return ip4_range(self.pg0.remote_ip4, start, end) def encap_mcast(self, pkt, src_ip, src_mac, vni): @@ -46,18 +48,20 @@ class TestVxlan(BridgeDomain, VppTestCase): Encapsulate the original payload frame by adding VXLAN header with its UDP, IP and Ethernet fields """ - return (Ether(src=src_mac, dst=self.mcast_mac) / - IP(src=src_ip, dst=self.mcast_ip4) / - UDP(sport=self.dport, dport=self.dport, chksum=0) / - VXLAN(vni=vni, flags=self.flags) / - pkt) + return ( + Ether(src=src_mac, dst=self.mcast_mac) + / IP(src=src_ip, dst=self.mcast_ip4) + / UDP(sport=self.dport, dport=self.dport, chksum=0) + / VXLAN(vni=vni, flags=self.flags) + / pkt + ) def decapsulate(self, pkt): """ Decapsulate the original payload frame by removing VXLAN header """ # check if is set I flag - self.assertEqual(pkt[VXLAN].flags, int('0x8', 16)) + self.assertEqual(pkt[VXLAN].flags, int("0x8", 16)) return pkt[VXLAN].payload # Method for checking VXLAN encapsulation. @@ -93,18 +97,25 @@ class TestVxlan(BridgeDomain, VppTestCase): ip_range_start = 10 ip_range_end = ip_range_start + n_ucast_tunnels next_hop_address = cls.pg0.remote_ip4 - for dest_ip4 in ip4_range(next_hop_address, ip_range_start, - ip_range_end): + for dest_ip4 in ip4_range(next_hop_address, ip_range_start, ip_range_end): # add host route so dest_ip4 will not be resolved - rip = VppIpRoute(cls, dest_ip4, 32, - [VppRoutePath(next_hop_address, - INVALID_INDEX)], - register=False) + rip = VppIpRoute( + cls, + dest_ip4, + 32, + [VppRoutePath(next_hop_address, INVALID_INDEX)], + register=False, + ) rip.add_vpp_config() - r = VppVxlanTunnel(cls, src=cls.pg0.local_ip4, - src_port=port, dst_port=port, - dst=dest_ip4, vni=vni) + r = VppVxlanTunnel( + cls, + src=cls.pg0.local_ip4, + src_port=port, + dst_port=port, + dst=dest_ip4, + vni=vni, + ) r.add_vpp_config() cls.vapi.sw_interface_set_l2_bridge(r.sw_if_index, bd_id=vni) @@ -118,12 +129,18 @@ class TestVxlan(BridgeDomain, VppTestCase): vni_start = 10000 vni_end = vni_start + n_shared_dst_tunnels for vni in range(vni_start, vni_end): - r = VppVxlanTunnel(cls, src=cls.pg0.local_ip4, - src_port=port, dst_port=port, - dst=cls.mcast_ip4, mcast_sw_if_index=1, vni=vni) + r = VppVxlanTunnel( + cls, + src=cls.pg0.local_ip4, + src_port=port, + dst_port=port, + dst=cls.mcast_ip4, + mcast_sw_if_index=1, + vni=vni, + ) if is_add: r.add_vpp_config() - if r.sw_if_index == 0xffffffff: + if r.sw_if_index == 0xFFFFFFFF: raise ValueError("bad sw_if_index: ~0") else: r.remove_vpp_config() @@ -144,12 +161,17 @@ class TestVxlan(BridgeDomain, VppTestCase): n_distinct_dst_tunnels = 200 ip_range_start = 10 ip_range_end = ip_range_start + n_distinct_dst_tunnels - for dest_ip4 in ip4_range(cls.mcast_ip4, ip_range_start, - ip_range_end): + for dest_ip4 in ip4_range(cls.mcast_ip4, ip_range_start, ip_range_end): vni = bytearray(socket.inet_pton(socket.AF_INET, dest_ip4))[3] - r = VppVxlanTunnel(cls, src=cls.pg0.local_ip4, - src_port=port, dst_port=port, - dst=dest_ip4, mcast_sw_if_index=1, vni=vni) + r = VppVxlanTunnel( + cls, + src=cls.pg0.local_ip4, + src_port=port, + dst_port=port, + dst=dest_ip4, + mcast_sw_if_index=1, + vni=vni, + ) if is_add: r.add_vpp_config() else: @@ -187,7 +209,7 @@ class TestVxlan(BridgeDomain, VppTestCase): cls.pg0.resolve_arp() # Our Multicast address - cls.mcast_ip4 = '239.1.1.1' + cls.mcast_ip4 = "239.1.1.1" cls.mcast_mac = util.mcast_ip_to_mac(cls.mcast_ip4) except Exception: cls.tearDownClass() @@ -207,30 +229,44 @@ class TestVxlan(BridgeDomain, VppTestCase): self.single_tunnel_vni = 0x12345 self.single_tunnel_bd = 1 - r = VppVxlanTunnel(self, src=self.pg0.local_ip4, - dst=self.pg0.remote_ip4, - src_port=self.dport, dst_port=self.dport, - vni=self.single_tunnel_vni) + r = VppVxlanTunnel( + self, + src=self.pg0.local_ip4, + dst=self.pg0.remote_ip4, + src_port=self.dport, + dst_port=self.dport, + vni=self.single_tunnel_vni, + ) r.add_vpp_config() - self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index, - bd_id=self.single_tunnel_bd) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg1.sw_if_index, bd_id=self.single_tunnel_bd) + rx_sw_if_index=r.sw_if_index, bd_id=self.single_tunnel_bd + ) + self.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=self.pg1.sw_if_index, bd_id=self.single_tunnel_bd + ) # Setup vni 2 to test multicast flooding self.n_ucast_tunnels = 10 self.mcast_flood_bd = 2 - self.create_vxlan_flood_test_bd(self.mcast_flood_bd, - self.n_ucast_tunnels, - self.dport) - r = VppVxlanTunnel(self, src=self.pg0.local_ip4, dst=self.mcast_ip4, - src_port=self.dport, dst_port=self.dport, - mcast_sw_if_index=1, vni=self.mcast_flood_bd) + self.create_vxlan_flood_test_bd( + self.mcast_flood_bd, self.n_ucast_tunnels, self.dport + ) + r = VppVxlanTunnel( + self, + src=self.pg0.local_ip4, + dst=self.mcast_ip4, + src_port=self.dport, + dst_port=self.dport, + mcast_sw_if_index=1, + vni=self.mcast_flood_bd, + ) r.add_vpp_config() - self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index, - bd_id=self.mcast_flood_bd) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg2.sw_if_index, bd_id=self.mcast_flood_bd) + rx_sw_if_index=r.sw_if_index, bd_id=self.mcast_flood_bd + ) + self.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=self.pg2.sw_if_index, bd_id=self.mcast_flood_bd + ) # Add and delete mcast tunnels to check stability self.add_shared_mcast_dst_load(self.dport) @@ -240,11 +276,12 @@ class TestVxlan(BridgeDomain, VppTestCase): # Setup vni 3 to test unicast flooding self.ucast_flood_bd = 3 - self.create_vxlan_flood_test_bd(self.ucast_flood_bd, - self.n_ucast_tunnels, - self.dport) + self.create_vxlan_flood_test_bd( + self.ucast_flood_bd, self.n_ucast_tunnels, self.dport + ) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg3.sw_if_index, bd_id=self.ucast_flood_bd) + rx_sw_if_index=self.pg3.sw_if_index, bd_id=self.ucast_flood_bd + ) # Set scapy listen custom port for VxLAN bind_layers(UDP, VXLAN, dport=self.dport) @@ -252,10 +289,12 @@ class TestVxlan(BridgeDomain, VppTestCase): def encap_big_packet(self): self.vapi.sw_interface_set_mtu(self.pg0.sw_if_index, [1500, 0, 0, 0]) - frame = (Ether(src='00:00:00:00:00:02', dst='00:00:00:00:00:01') / - IP(src='4.3.2.1', dst='1.2.3.4') / - UDP(sport=20000, dport=10000) / - Raw(b'\xa5' * 1450)) + frame = ( + Ether(src="00:00:00:00:00:02", dst="00:00:00:00:00:01") + / IP(src="4.3.2.1", dst="1.2.3.4") + / UDP(sport=20000, dport=10000) + / Raw(b"\xa5" * 1450) + ) self.pg1.add_stream([frame]) @@ -277,43 +316,44 @@ class TestVxlan(BridgeDomain, VppTestCase): """ Tests with default port (4789) """ + def test_decap(self): - """ Decapsulation test + """Decapsulation test from BridgeDoman """ self.createVxLANInterfaces() super(TestVxlan, self).test_decap() def test_encap(self): - """ Encapsulation test + """Encapsulation test from BridgeDoman """ self.createVxLANInterfaces() super(TestVxlan, self).test_encap() def test_encap_big_packet(self): - """ Encapsulation test send big frame from pg1 + """Encapsulation test send big frame from pg1 Verify receipt of encapsulated frames on pg0 """ self.createVxLANInterfaces() self.encap_big_packet() def test_ucast_flood(self): - """ Unicast flood test + """Unicast flood test from BridgeDoman """ self.createVxLANInterfaces() super(TestVxlan, self).test_ucast_flood() def test_mcast_flood(self): - """ Multicast flood test + """Multicast flood test from BridgeDoman """ self.createVxLANInterfaces() super(TestVxlan, self).test_mcast_flood() def test_mcast_rcv(self): - """ Multicast receive test + """Multicast receive test from BridgeDoman """ self.createVxLANInterfaces() @@ -322,36 +362,37 @@ class TestVxlan(BridgeDomain, VppTestCase): """ Tests with custom port """ + def test_decap_custom_port(self): - """ Decapsulation test custom port + """Decapsulation test custom port from BridgeDoman """ self.createVxLANInterfaces(1111) super(TestVxlan, self).test_decap() def test_encap_custom_port(self): - """ Encapsulation test custom port + """Encapsulation test custom port from BridgeDoman """ self.createVxLANInterfaces(1111) super(TestVxlan, self).test_encap() def test_ucast_flood_custom_port(self): - """ Unicast flood test custom port + """Unicast flood test custom port from BridgeDoman """ self.createVxLANInterfaces(1111) super(TestVxlan, self).test_ucast_flood() def test_mcast_flood_custom_port(self): - """ Multicast flood test custom port + """Multicast flood test custom port from BridgeDoman """ self.createVxLANInterfaces(1111) super(TestVxlan, self).test_mcast_flood() def test_mcast_rcv_custom_port(self): - """ Multicast receive test custom port + """Multicast receive test custom port from BridgeDoman """ self.createVxLANInterfaces(1111) @@ -372,7 +413,8 @@ class TestVxlan(BridgeDomain, VppTestCase): class TestVxlan2(VppTestCase): - """ VXLAN Test Case """ + """VXLAN Test Case""" + def setUp(self): super(TestVxlan2, self).setUp() @@ -389,38 +431,37 @@ class TestVxlan2(VppTestCase): super(TestVxlan2, self).tearDown() def test_xconnect(self): - """ VXLAN source address not local """ + """VXLAN source address not local""" # # test the broken configuration of a VXLAN tunnel whose # source address is not local ot the box. packets sent # through the tunnel should be dropped # - t = VppVxlanTunnel(self, - src="10.0.0.5", - dst=self.pg0.local_ip4, - vni=1000) + t = VppVxlanTunnel(self, src="10.0.0.5", dst=self.pg0.local_ip4, vni=1000) t.add_vpp_config() t.admin_up() - self.vapi.sw_interface_set_l2_xconnect(t.sw_if_index, - self.pg1.sw_if_index, - enable=1) - self.vapi.sw_interface_set_l2_xconnect(self.pg1.sw_if_index, - t.sw_if_index, - enable=1) + self.vapi.sw_interface_set_l2_xconnect( + t.sw_if_index, self.pg1.sw_if_index, enable=1 + ) + self.vapi.sw_interface_set_l2_xconnect( + self.pg1.sw_if_index, t.sw_if_index, enable=1 + ) - p = (Ether(src="00:11:22:33:44:55", - dst="00:00:00:11:22:33") / - IP(src="4.3.2.1", dst="1.2.3.4") / - UDP(sport=20000, dport=10000) / - Raw(b'\xa5' * 1450)) + p = ( + Ether(src="00:11:22:33:44:55", dst="00:00:00:11:22:33") + / IP(src="4.3.2.1", dst="1.2.3.4") + / UDP(sport=20000, dport=10000) + / Raw(b"\xa5" * 1450) + ) rx = self.send_and_assert_no_replies(self.pg1, [p]) class TestVxlanL2Mode(VppTestCase): - """ VXLAN Test Case """ + """VXLAN Test Case""" + def setUp(self): super(TestVxlanL2Mode, self).setUp() @@ -440,11 +481,10 @@ class TestVxlanL2Mode(VppTestCase): super(TestVxlanL2Mode, self).tearDown() def test_l2_mode(self): - """ VXLAN L2 mode """ - t = VppVxlanTunnel(self, - src=self.pg0.local_ip4, - dst=self.pg0.remote_ip4, - vni=1000, is_l3=False) + """VXLAN L2 mode""" + t = VppVxlanTunnel( + self, src=self.pg0.local_ip4, dst=self.pg0.remote_ip4, vni=1000, is_l3=False + ) t.add_vpp_config() t.config_ip4() t.admin_up() @@ -452,10 +492,12 @@ class TestVxlanL2Mode(VppTestCase): dstIP = t.local_ip4[:-1] + "2" # Create a packet to send - p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / - IP(src=self.pg1.local_ip4, dst=dstIP) / - UDP(sport=555, dport=556) / - Raw(b'\x00' * 80)) + p = ( + Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) + / IP(src=self.pg1.local_ip4, dst=dstIP) + / UDP(sport=555, dport=556) + / Raw(b"\x00" * 80) + ) # Expect ARP request rx = self.send_and_expect(self.pg1, [p], self.pg0) @@ -466,9 +508,7 @@ class TestVxlanL2Mode(VppTestCase): self.assertEqual(p[ARP].pdst, dstIP) # Resolve ARP - VppNeighbor(self, t.sw_if_index, - self.pg1.remote_mac, - dstIP).add_vpp_config() + VppNeighbor(self, t.sw_if_index, self.pg1.remote_mac, dstIP).add_vpp_config() # Send packets NUM_PKTS = 128 @@ -476,5 +516,5 @@ class TestVxlanL2Mode(VppTestCase): self.assertEqual(NUM_PKTS, len(rx)) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_vxlan6.py b/test/test_vxlan6.py index 123cce9b7ba..0f9c5121f6d 100644 --- a/test/test_vxlan6.py +++ b/test/test_vxlan6.py @@ -17,7 +17,7 @@ from vpp_ip import INVALID_INDEX class TestVxlan6(BridgeDomain, VppTestCase): - """ VXLAN over IPv6 Test Case """ + """VXLAN over IPv6 Test Case""" def __init__(self, *args): BridgeDomain.__init__(self) @@ -28,16 +28,18 @@ class TestVxlan6(BridgeDomain, VppTestCase): Encapsulate the original payload frame by adding VXLAN header with its UDP, IP and Ethernet fields """ - return (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) / - UDP(sport=self.dport, dport=self.dport, chksum=0) / - VXLAN(vni=vni, flags=self.flags) / - pkt) + return ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) + / UDP(sport=self.dport, dport=self.dport, chksum=0) + / VXLAN(vni=vni, flags=self.flags) + / pkt + ) @classmethod def ip_range(cls, s, e): - """ range of remote ip's """ - tmp = cls.pg0.remote_ip6.rsplit(':', 1)[0] + """range of remote ip's""" + tmp = cls.pg0.remote_ip6.rsplit(":", 1)[0] return ("%s:%x" % (tmp, i) for i in range(s, e)) def encap_mcast(self, pkt, src_ip, src_mac, vni): @@ -45,18 +47,20 @@ class TestVxlan6(BridgeDomain, VppTestCase): Encapsulate the original payload frame by adding VXLAN header with its UDP, IP and Ethernet fields """ - return (Ether(src=src_mac, dst=self.mcast_mac) / - IPv6(src=src_ip, dst=self.mcast_ip6) / - UDP(sport=self.dport, dport=self.dport, chksum=0) / - VXLAN(vni=vni, flags=self.flags) / - pkt) + return ( + Ether(src=src_mac, dst=self.mcast_mac) + / IPv6(src=src_ip, dst=self.mcast_ip6) + / UDP(sport=self.dport, dport=self.dport, chksum=0) + / VXLAN(vni=vni, flags=self.flags) + / pkt + ) def decapsulate(self, pkt): """ Decapsulate the original payload frame by removing VXLAN header """ # check if is set I flag - self.assertEqual(pkt[VXLAN].flags, int('0x8', 16)) + self.assertEqual(pkt[VXLAN].flags, int("0x8", 16)) return pkt[VXLAN].payload # Method for checking VXLAN encapsulation. @@ -93,13 +97,22 @@ class TestVxlan6(BridgeDomain, VppTestCase): end = start + n_ucast_tunnels for dest_ip6 in cls.ip_range(start, end): # add host route so dest ip will not be resolved - rip = VppIpRoute(cls, dest_ip6, 128, - [VppRoutePath(cls.pg0.remote_ip6, INVALID_INDEX)], - register=False) + rip = VppIpRoute( + cls, + dest_ip6, + 128, + [VppRoutePath(cls.pg0.remote_ip6, INVALID_INDEX)], + register=False, + ) rip.add_vpp_config() - r = VppVxlanTunnel(cls, src=cls.pg0.local_ip6, - src_port=port, dst_port=port, - dst=dest_ip6, vni=vni) + r = VppVxlanTunnel( + cls, + src=cls.pg0.local_ip6, + src_port=port, + dst_port=port, + dst=dest_ip6, + vni=vni, + ) r.add_vpp_config() cls.vapi.sw_interface_set_l2_bridge(r.sw_if_index, bd_id=vni) @@ -135,7 +148,7 @@ class TestVxlan6(BridgeDomain, VppTestCase): cls.pg0.resolve_ndp() # Our Multicast address - cls.mcast_ip6 = 'ff0e::1' + cls.mcast_ip6 = "ff0e::1" cls.mcast_mac = util.mcast_ip_to_mac(cls.mcast_ip6) except Exception: super(TestVxlan6, cls).tearDownClass() @@ -155,38 +168,53 @@ class TestVxlan6(BridgeDomain, VppTestCase): self.single_tunnel_vni = 0x12345 self.single_tunnel_bd = 1 - r = VppVxlanTunnel(self, src=self.pg0.local_ip6, - dst=self.pg0.remote_ip6, - src_port=self.dport, dst_port=self.dport, - vni=self.single_tunnel_vni) + r = VppVxlanTunnel( + self, + src=self.pg0.local_ip6, + dst=self.pg0.remote_ip6, + src_port=self.dport, + dst_port=self.dport, + vni=self.single_tunnel_vni, + ) r.add_vpp_config() - self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index, - bd_id=self.single_tunnel_bd) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg1.sw_if_index, bd_id=self.single_tunnel_bd) + rx_sw_if_index=r.sw_if_index, bd_id=self.single_tunnel_bd + ) + self.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=self.pg1.sw_if_index, bd_id=self.single_tunnel_bd + ) # Setup vni 2 to test multicast flooding self.n_ucast_tunnels = 10 self.mcast_flood_bd = 2 - self.create_vxlan_flood_test_bd(self.mcast_flood_bd, - self.n_ucast_tunnels, - self.dport) - r = VppVxlanTunnel(self, src=self.pg0.local_ip6, dst=self.mcast_ip6, - src_port=self.dport, dst_port=self.dport, - mcast_sw_if_index=1, vni=self.mcast_flood_bd) + self.create_vxlan_flood_test_bd( + self.mcast_flood_bd, self.n_ucast_tunnels, self.dport + ) + r = VppVxlanTunnel( + self, + src=self.pg0.local_ip6, + dst=self.mcast_ip6, + src_port=self.dport, + dst_port=self.dport, + mcast_sw_if_index=1, + vni=self.mcast_flood_bd, + ) r.add_vpp_config() - self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index, - bd_id=self.mcast_flood_bd) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg2.sw_if_index, bd_id=self.mcast_flood_bd) + rx_sw_if_index=r.sw_if_index, bd_id=self.mcast_flood_bd + ) + self.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=self.pg2.sw_if_index, bd_id=self.mcast_flood_bd + ) # Setup vni 3 to test unicast flooding self.ucast_flood_bd = 3 - self.create_vxlan_flood_test_bd(self.ucast_flood_bd, - self.n_ucast_tunnels, - self.dport) + self.create_vxlan_flood_test_bd( + self.ucast_flood_bd, self.n_ucast_tunnels, self.dport + ) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg3.sw_if_index, bd_id=self.ucast_flood_bd) + rx_sw_if_index=self.pg3.sw_if_index, bd_id=self.ucast_flood_bd + ) # Set scapy listen custom port for VxLAN bind_layers(UDP, VXLAN, dport=self.dport) @@ -204,10 +232,12 @@ class TestVxlan6(BridgeDomain, VppTestCase): self.logger.info(self.vapi.cli("show vxlan tunnel")) def encap_fragmented_packet(self): - frame = (Ether(src='00:00:00:00:00:02', dst='00:00:00:00:00:01') / - IP(src='4.3.2.1', dst='1.2.3.4') / - UDP(sport=20000, dport=10000) / - Raw(b'\xa5' * 1000)) + frame = ( + Ether(src="00:00:00:00:00:02", dst="00:00:00:00:00:01") + / IP(src="4.3.2.1", dst="1.2.3.4") + / UDP(sport=20000, dport=10000) + / Raw(b"\xa5" * 1000) + ) frags = util.fragment_rfc791(frame, 400) @@ -231,43 +261,44 @@ class TestVxlan6(BridgeDomain, VppTestCase): """ Tests with default port (4789) """ + def test_decap(self): - """ Decapsulation test + """Decapsulation test from BridgeDoman """ self.createVxLANInterfaces() super(TestVxlan6, self).test_decap() def test_encap(self): - """ Encapsulation test + """Encapsulation test from BridgeDoman """ self.createVxLANInterfaces() super(TestVxlan6, self).test_encap() def test_encap_fragmented_packet(self): - """ Encapsulation test send fragments from pg1 + """Encapsulation test send fragments from pg1 Verify receipt of encapsulated frames on pg0 """ self.createVxLANInterfaces() self.encap_fragmented_packet() def test_ucast_flood(self): - """ Unicast flood test + """Unicast flood test from BridgeDoman """ self.createVxLANInterfaces() super(TestVxlan6, self).test_ucast_flood() def test_mcast_flood(self): - """ Multicast flood test + """Multicast flood test from BridgeDoman """ self.createVxLANInterfaces() super(TestVxlan6, self).test_mcast_flood() def test_mcast_rcv(self): - """ Multicast receive test + """Multicast receive test from BridgeDoman """ self.createVxLANInterfaces() @@ -276,41 +307,42 @@ class TestVxlan6(BridgeDomain, VppTestCase): """ Tests with custom port """ + def test_decap_custom_port(self): - """ Decapsulation test custom port + """Decapsulation test custom port from BridgeDoman """ self.createVxLANInterfaces(1111) super(TestVxlan6, self).test_decap() def test_encap_custom_port(self): - """ Encapsulation test custom port + """Encapsulation test custom port from BridgeDoman """ self.createVxLANInterfaces(1111) super(TestVxlan6, self).test_encap() def test_ucast_flood_custom_port(self): - """ Unicast flood test custom port + """Unicast flood test custom port from BridgeDoman """ self.createVxLANInterfaces(1111) super(TestVxlan6, self).test_ucast_flood() def test_mcast_flood_custom_port(self): - """ Multicast flood test custom port + """Multicast flood test custom port from BridgeDoman """ self.createVxLANInterfaces(1111) super(TestVxlan6, self).test_mcast_flood() def test_mcast_rcv_custom_port(self): - """ Multicast receive test custom port + """Multicast receive test custom port from BridgeDoman """ self.createVxLANInterfaces(1111) super(TestVxlan6, self).test_mcast_rcv() -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_vxlan_gpe.py b/test/test_vxlan_gpe.py index 828b5fc30cd..f432becfce3 100644 --- a/test/test_vxlan_gpe.py +++ b/test/test_vxlan_gpe.py @@ -20,7 +20,7 @@ from vpp_ip import INVALID_INDEX @unittest.skipUnless(config.extended, "part of extended tests") class TestVxlanGpe(BridgeDomain, VppTestCase): - """ VXLAN-GPE Test Case """ + """VXLAN-GPE Test Case""" def __init__(self, *args): BridgeDomain.__init__(self) @@ -31,14 +31,16 @@ class TestVxlanGpe(BridgeDomain, VppTestCase): Encapsulate the original payload frame by adding VXLAN-GPE header with its UDP, IP and Ethernet fields """ - return (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / - IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / - UDP(sport=self.dport, dport=self.dport, chksum=0) / - VXLAN(vni=vni, flags=self.flags) / - pkt) + return ( + Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) + / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) + / UDP(sport=self.dport, dport=self.dport, chksum=0) + / VXLAN(vni=vni, flags=self.flags) + / pkt + ) def ip_range(self, start, end): - """ range of remote ip's """ + """range of remote ip's""" return ip4_range(self.pg0.remote_ip4, start, end) def encap_mcast(self, pkt, src_ip, src_mac, vni): @@ -46,18 +48,20 @@ class TestVxlanGpe(BridgeDomain, VppTestCase): Encapsulate the original payload frame by adding VXLAN-GPE header with its UDP, IP and Ethernet fields """ - return (Ether(src=src_mac, dst=self.mcast_mac) / - IP(src=src_ip, dst=self.mcast_ip4) / - UDP(sport=self.dport, dport=self.dport, chksum=0) / - VXLAN(vni=vni, flags=self.flags) / - pkt) + return ( + Ether(src=src_mac, dst=self.mcast_mac) + / IP(src=src_ip, dst=self.mcast_ip4) + / UDP(sport=self.dport, dport=self.dport, chksum=0) + / VXLAN(vni=vni, flags=self.flags) + / pkt + ) def decapsulate(self, pkt): """ Decapsulate the original payload frame by removing VXLAN-GPE header """ # check if is set I and P flag - self.assertEqual(pkt[VXLAN].flags, 0x0c) + self.assertEqual(pkt[VXLAN].flags, 0x0C) return pkt[VXLAN].payload # Method for checking VXLAN-GPE encapsulation. @@ -92,24 +96,27 @@ class TestVxlanGpe(BridgeDomain, VppTestCase): ip_range_start = 10 ip_range_end = ip_range_start + n_ucast_tunnels next_hop_address = cls.pg0.remote_ip4 - for dest_ip4 in ip4_range(next_hop_address, ip_range_start, - ip_range_end): + for dest_ip4 in ip4_range(next_hop_address, ip_range_start, ip_range_end): # add host route so dest_ip4n will not be resolved - rip = VppIpRoute(cls, dest_ip4, 32, - [VppRoutePath(next_hop_address, - INVALID_INDEX)], - register=False) + rip = VppIpRoute( + cls, + dest_ip4, + 32, + [VppRoutePath(next_hop_address, INVALID_INDEX)], + register=False, + ) rip.add_vpp_config() - r = VppVxlanGpeTunnel(cls, - src_addr=cls.pg0.local_ip4, - dst_addr=dest_ip4, - src_port=port, - dst_port=port, - vni=vni) + r = VppVxlanGpeTunnel( + cls, + src_addr=cls.pg0.local_ip4, + dst_addr=dest_ip4, + src_port=port, + dst_port=port, + vni=vni, + ) r.add_vpp_config() - cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index, - bd_id=vni) + cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index, bd_id=vni) @classmethod def add_del_shared_mcast_dst_load(cls, port, is_add): @@ -121,16 +128,18 @@ class TestVxlanGpe(BridgeDomain, VppTestCase): vni_start = 1000 vni_end = vni_start + n_shared_dst_tunnels for vni in range(vni_start, vni_end): - r = VppVxlanGpeTunnel(cls, - src_addr=cls.pg0.local_ip4, - dst_addr=cls.mcast_ip4, - src_port=port, - dst_port=port, - mcast_sw_if_index=1, - vni=vni) + r = VppVxlanGpeTunnel( + cls, + src_addr=cls.pg0.local_ip4, + dst_addr=cls.mcast_ip4, + src_port=port, + dst_port=port, + mcast_sw_if_index=1, + vni=vni, + ) if is_add: r.add_vpp_config() - if r.sw_if_index == 0xffffffff: + if r.sw_if_index == 0xFFFFFFFF: raise ValueError("bad sw_if_index: ~0") else: r.remove_vpp_config() @@ -151,16 +160,17 @@ class TestVxlanGpe(BridgeDomain, VppTestCase): n_distinct_dst_tunnels = 20 ip_range_start = 10 ip_range_end = ip_range_start + n_distinct_dst_tunnels - for dest_ip4 in ip4_range(cls.mcast_ip4, ip_range_start, - ip_range_end): + for dest_ip4 in ip4_range(cls.mcast_ip4, ip_range_start, ip_range_end): vni = int(dest_ip4.split(".")[3]) - r = VppVxlanGpeTunnel(cls, - src_addr=cls.pg0.local_ip4, - dst_addr=dest_ip4, - src_port=port, - dst_port=port, - mcast_sw_if_index=1, - vni=vni) + r = VppVxlanGpeTunnel( + cls, + src_addr=cls.pg0.local_ip4, + dst_addr=dest_ip4, + src_port=port, + dst_port=port, + mcast_sw_if_index=1, + vni=vni, + ) if is_add: r.add_vpp_config() else: @@ -184,7 +194,7 @@ class TestVxlanGpe(BridgeDomain, VppTestCase): super(TestVxlanGpe, cls).setUpClass() try: - cls.flags = 0x0c + cls.flags = 0x0C # Create 2 pg interfaces. cls.create_pg_interfaces(range(4)) @@ -198,7 +208,7 @@ class TestVxlanGpe(BridgeDomain, VppTestCase): cls.pg0.resolve_arp() # Our Multicast address - cls.mcast_ip4 = '239.1.1.1' + cls.mcast_ip4 = "239.1.1.1" cls.mcast_mac = util.mcast_ip_to_mac(cls.mcast_ip4) except Exception: cls.tearDownClass() @@ -216,38 +226,46 @@ class TestVxlanGpe(BridgeDomain, VppTestCase): # and pg1 into BD. self.dport = port - self.single_tunnel_vni = 0xabcde + self.single_tunnel_vni = 0xABCDE self.single_tunnel_bd = 11 - r = VppVxlanGpeTunnel(self, - src_addr=self.pg0.local_ip4, - dst_addr=self.pg0.remote_ip4, - src_port=port, - dst_port=port, - vni=self.single_tunnel_vni) + r = VppVxlanGpeTunnel( + self, + src_addr=self.pg0.local_ip4, + dst_addr=self.pg0.remote_ip4, + src_port=port, + dst_port=port, + vni=self.single_tunnel_vni, + ) r.add_vpp_config() - self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index, - bd_id=self.single_tunnel_bd) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg1.sw_if_index, bd_id=self.single_tunnel_bd) + rx_sw_if_index=r.sw_if_index, bd_id=self.single_tunnel_bd + ) + self.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=self.pg1.sw_if_index, bd_id=self.single_tunnel_bd + ) # Setup vni 2 to test multicast flooding self.n_ucast_tunnels = 10 self.mcast_flood_bd = 12 - self.create_vxlan_gpe_flood_test_bd(self.mcast_flood_bd, - self.n_ucast_tunnels, - self.dport) - r = VppVxlanGpeTunnel(self, - src_addr=self.pg0.local_ip4, - dst_addr=self.mcast_ip4, - src_port=port, - dst_port=port, - mcast_sw_if_index=1, - vni=self.mcast_flood_bd) + self.create_vxlan_gpe_flood_test_bd( + self.mcast_flood_bd, self.n_ucast_tunnels, self.dport + ) + r = VppVxlanGpeTunnel( + self, + src_addr=self.pg0.local_ip4, + dst_addr=self.mcast_ip4, + src_port=port, + dst_port=port, + mcast_sw_if_index=1, + vni=self.mcast_flood_bd, + ) r.add_vpp_config() - self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index, - bd_id=self.mcast_flood_bd) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg2.sw_if_index, bd_id=self.mcast_flood_bd) + rx_sw_if_index=r.sw_if_index, bd_id=self.mcast_flood_bd + ) + self.vapi.sw_interface_set_l2_bridge( + rx_sw_if_index=self.pg2.sw_if_index, bd_id=self.mcast_flood_bd + ) # Add and delete mcast tunnels to check stability self.add_shared_mcast_dst_load(self.dport) @@ -257,11 +275,12 @@ class TestVxlanGpe(BridgeDomain, VppTestCase): # Setup vni 3 to test unicast flooding self.ucast_flood_bd = 13 - self.create_vxlan_gpe_flood_test_bd(self.ucast_flood_bd, - self.n_ucast_tunnels, - self.dport) + self.create_vxlan_gpe_flood_test_bd( + self.ucast_flood_bd, self.n_ucast_tunnels, self.dport + ) self.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.pg3.sw_if_index, bd_id=self.ucast_flood_bd) + rx_sw_if_index=self.pg3.sw_if_index, bd_id=self.ucast_flood_bd + ) # Set scapy listen custom port for VxLAN bind_layers(UDP, VXLAN, dport=self.dport) @@ -269,22 +288,23 @@ class TestVxlanGpe(BridgeDomain, VppTestCase): """ Tests with default port (4790) """ + def test_decap(self): - """ Decapsulation test + """Decapsulation test from BridgeDoman """ self.createVxLANInterfaces() super(TestVxlanGpe, self).test_decap() def test_encap(self): - """ Encapsulation test + """Encapsulation test from BridgeDoman """ self.createVxLANInterfaces() super(TestVxlanGpe, self).test_encap() def test_ucast_flood(self): - """ Unicast flood test + """Unicast flood test from BridgeDoman """ self.createVxLANInterfaces() @@ -293,22 +313,23 @@ class TestVxlanGpe(BridgeDomain, VppTestCase): """ Tests with custom port (1112) """ + def test_decap_custom_port(self): - """ Decapsulation test custom port + """Decapsulation test custom port from BridgeDoman """ self.createVxLANInterfaces(1112) super(TestVxlanGpe, self).test_decap() def test_encap_custom_port(self): - """ Encapsulation test custom port + """Encapsulation test custom port from BridgeDoman """ self.createVxLANInterfaces(1112) super(TestVxlanGpe, self).test_encap() def test_ucast_flood_custom_port(self): - """ Unicast flood test custom port + """Unicast flood test custom port from BridgeDoman """ self.createVxLANInterfaces(1112) @@ -316,12 +337,12 @@ class TestVxlanGpe(BridgeDomain, VppTestCase): @unittest.skip("test disabled for vxlan-gpe") def test_mcast_flood(self): - """ inherited from BridgeDomain """ + """inherited from BridgeDomain""" pass @unittest.skip("test disabled for vxlan-gpe") def test_mcast_rcv(self): - """ inherited from BridgeDomain """ + """inherited from BridgeDomain""" pass # Method to define VPP actions before tear down of the test case. @@ -339,5 +360,5 @@ class TestVxlanGpe(BridgeDomain, VppTestCase): self.logger.info(self.vapi.cli("show trace")) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(testRunner=VppTestRunner) diff --git a/test/test_wireguard.py b/test/test_wireguard.py index e844b1d5c0a..1a955b162f1 100644 --- a/test/test_wireguard.py +++ b/test/test_wireguard.py @@ -11,12 +11,22 @@ from scapy.packet import Raw from scapy.layers.l2 import Ether, ARP from scapy.layers.inet import IP, UDP from scapy.layers.inet6 import IPv6 -from scapy.contrib.wireguard import Wireguard, WireguardResponse, \ - WireguardInitiation, WireguardTransport -from cryptography.hazmat.primitives.asymmetric.x25519 import \ - X25519PrivateKey, X25519PublicKey -from cryptography.hazmat.primitives.serialization import Encoding, \ - PrivateFormat, PublicFormat, NoEncryption +from scapy.contrib.wireguard import ( + Wireguard, + WireguardResponse, + WireguardInitiation, + WireguardTransport, +) +from cryptography.hazmat.primitives.asymmetric.x25519 import ( + X25519PrivateKey, + X25519PublicKey, +) +from cryptography.hazmat.primitives.serialization import ( + Encoding, + PrivateFormat, + PublicFormat, + NoEncryption, +) from cryptography.hazmat.primitives.hashes import BLAKE2s, Hash from cryptography.hazmat.primitives.hmac import HMAC from cryptography.hazmat.backends import default_backend @@ -39,14 +49,11 @@ Wg test. def private_key_bytes(k): - return k.private_bytes(Encoding.Raw, - PrivateFormat.Raw, - NoEncryption()) + return k.private_bytes(Encoding.Raw, PrivateFormat.Raw, NoEncryption()) def public_key_bytes(k): - return k.public_bytes(Encoding.Raw, - PublicFormat.Raw) + return k.public_bytes(Encoding.Raw, PublicFormat.Raw) class VppWgInterface(VppInterface): @@ -69,37 +76,41 @@ class VppWgInterface(VppInterface): return private_key_bytes(self.private_key) def add_vpp_config(self): - r = self.test.vapi.wireguard_interface_create(interface={ - 'user_instance': 0xffffffff, - 'port': self.port, - 'src_ip': self.src, - 'private_key': private_key_bytes(self.private_key), - 'generate_key': False - }) + r = self.test.vapi.wireguard_interface_create( + interface={ + "user_instance": 0xFFFFFFFF, + "port": self.port, + "src_ip": self.src, + "private_key": private_key_bytes(self.private_key), + "generate_key": False, + } + ) self.set_sw_if_index(r.sw_if_index) self.test.registry.register(self, self.test.logger) return self def remove_vpp_config(self): - self.test.vapi.wireguard_interface_delete( - sw_if_index=self._sw_if_index) + self.test.vapi.wireguard_interface_delete(sw_if_index=self._sw_if_index) def query_vpp_config(self): - ts = self.test.vapi.wireguard_interface_dump(sw_if_index=0xffffffff) + ts = self.test.vapi.wireguard_interface_dump(sw_if_index=0xFFFFFFFF) for t in ts: - if t.interface.sw_if_index == self._sw_if_index and \ - str(t.interface.src_ip) == self.src and \ - t.interface.port == self.port and \ - t.interface.private_key == private_key_bytes(self.private_key): + if ( + t.interface.sw_if_index == self._sw_if_index + and str(t.interface.src_ip) == self.src + and t.interface.port == self.port + and t.interface.private_key == private_key_bytes(self.private_key) + ): return True return False - def want_events(self, peer_index=0xffffffff): + def want_events(self, peer_index=0xFFFFFFFF): self.test.vapi.want_wireguard_peer_events( enable_disable=1, pid=os.getpid(), sw_if_index=self._sw_if_index, - peer_index=peer_index) + peer_index=peer_index, + ) def wait_events(self, expect, peers, timeout=5): for i in range(len(peers)): @@ -118,8 +129,7 @@ def find_route(test, prefix, is_ip6, table_id=0): routes = test.vapi.ip_route_dump(table_id, is_ip6) for e in routes: - if table_id == e.route.table_id \ - and str(e.route.prefix) == str(prefix): + if table_id == e.route.table_id and str(e.route.prefix) == str(prefix): return True return False @@ -129,14 +139,7 @@ NOISE_IDENTIFIER_NAME = b"WireGuard v1 zx2c4 Jason@zx2c4.com" class VppWgPeer(VppObject): - - def __init__(self, - test, - itf, - endpoint, - port, - allowed_ips, - persistent_keepalive=15): + def __init__(self, test, itf, endpoint, port, allowed_ips, persistent_keepalive=15): self._test = test self.itf = itf self.endpoint = endpoint @@ -153,13 +156,15 @@ class VppWgPeer(VppObject): def add_vpp_config(self, is_ip6=False): rv = self._test.vapi.wireguard_peer_add( peer={ - 'public_key': self.public_key_bytes(), - 'port': self.port, - 'endpoint': self.endpoint, - 'n_allowed_ips': len(self.allowed_ips), - 'allowed_ips': self.allowed_ips, - 'sw_if_index': self.itf.sw_if_index, - 'persistent_keepalive': self.persistent_keepalive}) + "public_key": self.public_key_bytes(), + "port": self.port, + "endpoint": self.endpoint, + "n_allowed_ips": len(self.allowed_ips), + "allowed_ips": self.allowed_ips, + "sw_if_index": self.itf.sw_if_index, + "persistent_keepalive": self.persistent_keepalive, + } + ) self.index = rv.peer_index self.receiver_index = self.index + 1 self._test.registry.register(self, self._test.logger) @@ -169,7 +174,7 @@ class VppWgPeer(VppObject): self._test.vapi.wireguard_peer_remove(peer_index=self.index) def object_id(self): - return ("wireguard-peer-%s" % self.index) + return "wireguard-peer-%s" % self.index def public_key_bytes(self): return public_key_bytes(self.public_key) @@ -178,11 +183,13 @@ class VppWgPeer(VppObject): peers = self._test.vapi.wireguard_peers_dump() for p in peers: - if p.peer.public_key == self.public_key_bytes() and \ - p.peer.port == self.port and \ - str(p.peer.endpoint) == self.endpoint and \ - p.peer.sw_if_index == self.itf.sw_if_index and \ - len(self.allowed_ips) == p.peer.n_allowed_ips: + if ( + p.peer.public_key == self.public_key_bytes() + and p.peer.port == self.port + and str(p.peer.endpoint) == self.endpoint + and p.peer.sw_if_index == self.itf.sw_if_index + and len(self.allowed_ips) == p.peer.n_allowed_ips + ): self.allowed_ips.sort() p.peer.allowed_ips.sort() @@ -197,13 +204,17 @@ class VppWgPeer(VppObject): def mk_tunnel_header(self, tx_itf, is_ip6=False): if is_ip6 is False: - return (Ether(dst=tx_itf.local_mac, src=tx_itf.remote_mac) / - IP(src=self.endpoint, dst=self.itf.src) / - UDP(sport=self.port, dport=self.itf.port)) + return ( + Ether(dst=tx_itf.local_mac, src=tx_itf.remote_mac) + / IP(src=self.endpoint, dst=self.itf.src) + / UDP(sport=self.port, dport=self.itf.port) + ) else: - return (Ether(dst=tx_itf.local_mac, src=tx_itf.remote_mac) / - IPv6(src=self.endpoint, dst=self.itf.src) / - UDP(sport=self.port, dport=self.itf.port)) + return ( + Ether(dst=tx_itf.local_mac, src=tx_itf.remote_mac) + / IPv6(src=self.endpoint, dst=self.itf.src) + / UDP(sport=self.port, dport=self.itf.port) + ) def noise_init(self, public_key=None): self.noise.set_prologue(NOISE_IDENTIFIER_NAME) @@ -214,12 +225,12 @@ class VppWgPeer(VppObject): # local/this private self.noise.set_keypair_from_private_bytes( - Keypair.STATIC, - private_key_bytes(self.private_key)) + Keypair.STATIC, private_key_bytes(self.private_key) + ) # remote's public self.noise.set_keypair_from_public_bytes( - Keypair.REMOTE_STATIC, - public_key_bytes(public_key)) + Keypair.REMOTE_STATIC, public_key_bytes(public_key) + ) self.noise.start_handshake() @@ -227,7 +238,7 @@ class VppWgPeer(VppObject): self.noise.set_as_initiator() self.noise_init(public_key) - p = (Wireguard() / WireguardInitiation()) + p = Wireguard() / WireguardInitiation() p[Wireguard].message_type = 1 p[Wireguard].reserved_zero = 0 @@ -236,8 +247,11 @@ class VppWgPeer(VppObject): # some random data for the message # lifted from the noise protocol's wireguard example now = datetime.datetime.now() - tai = struct.pack('!qi', 4611686018427387914 + int(now.timestamp()), - int(now.microsecond * 1e3)) + tai = struct.pack( + "!qi", + 4611686018427387914 + int(now.timestamp()), + int(now.microsecond * 1e3), + ) b = self.noise.write_message(payload=tai) # load noise into init message @@ -246,14 +260,13 @@ class VppWgPeer(VppObject): p[WireguardInitiation].encrypted_timestamp = b[80:108] # generate the mac1 hash - mac_key = blake2s(b'mac1----' + - self.itf.public_key_bytes()).digest() - p[WireguardInitiation].mac1 = blake2s(bytes(p)[0:116], - digest_size=16, - key=mac_key).digest() + mac_key = blake2s(b"mac1----" + self.itf.public_key_bytes()).digest() + p[WireguardInitiation].mac1 = blake2s( + bytes(p)[0:116], digest_size=16, key=mac_key + ).digest() p[WireguardInitiation].mac2 = bytearray(16) - p = (self.mk_tunnel_header(tx_itf, is_ip6) / p) + p = self.mk_tunnel_header(tx_itf, is_ip6) / p return p @@ -281,11 +294,8 @@ class VppWgPeer(VppObject): self.sender = init[WireguardInitiation].sender_index # validate the hash - mac_key = blake2s(b'mac1----' + - public_key_bytes(self.public_key)).digest() - mac1 = blake2s(bytes(init)[0:-32], - digest_size=16, - key=mac_key).digest() + mac_key = blake2s(b"mac1----" + public_key_bytes(self.public_key)).digest() + mac1 = blake2s(bytes(init)[0:-32], digest_size=16, key=mac_key).digest() self._test.assertEqual(init[WireguardInitiation].mac1, mac1) # this passes only unencrypted_ephemeral, encrypted_static, @@ -294,19 +304,17 @@ class VppWgPeer(VppObject): # build the response b = self.noise.write_message() - mac_key = blake2s(b'mac1----' + - public_key_bytes(self.itf.public_key)).digest() - resp = (Wireguard(message_type=2, reserved_zero=0) / - WireguardResponse(sender_index=self.receiver_index, - receiver_index=self.sender, - unencrypted_ephemeral=b[0:32], - encrypted_nothing=b[32:])) - mac1 = blake2s(bytes(resp)[:-32], - digest_size=16, - key=mac_key).digest() + mac_key = blake2s(b"mac1----" + public_key_bytes(self.itf.public_key)).digest() + resp = Wireguard(message_type=2, reserved_zero=0) / WireguardResponse( + sender_index=self.receiver_index, + receiver_index=self.sender, + unencrypted_ephemeral=b[0:32], + encrypted_nothing=b[32:], + ) + mac1 = blake2s(bytes(resp)[:-32], digest_size=16, key=mac_key).digest() resp[WireguardResponse].mac1 = mac1 - resp = (self.mk_tunnel_header(tx_itf, is_ip6) / resp) + resp = self.mk_tunnel_header(tx_itf, is_ip6) / resp self._test.assertTrue(self.noise.handshake_finished) return resp @@ -318,13 +326,14 @@ class VppWgPeer(VppObject): self._test.assertEqual(resp[Wireguard].message_type, 2) self._test.assertEqual(resp[Wireguard].reserved_zero, 0) - self._test.assertEqual(resp[WireguardResponse].receiver_index, - self.receiver_index) + self._test.assertEqual( + resp[WireguardResponse].receiver_index, self.receiver_index + ) self.sender = resp[Wireguard].sender_index payload = self.noise.read_message(bytes(resp)[12:60]) - self._test.assertEqual(payload, b'') + self._test.assertEqual(payload, b"") self._test.assertTrue(self.noise.handshake_finished) def decrypt_transport(self, p, is_ip6=False): @@ -333,11 +342,11 @@ class VppWgPeer(VppObject): p = Wireguard(p[Raw]) self._test.assertEqual(p[Wireguard].message_type, 4) self._test.assertEqual(p[Wireguard].reserved_zero, 0) - self._test.assertEqual(p[WireguardTransport].receiver_index, - self.receiver_index) + self._test.assertEqual( + p[WireguardTransport].receiver_index, self.receiver_index + ) - d = self.noise.decrypt( - p[WireguardTransport].encrypted_encapsulated_packet) + d = self.noise.decrypt(p[WireguardTransport].encrypted_encapsulated_packet) return d def encrypt_transport(self, p): @@ -350,20 +359,21 @@ class VppWgPeer(VppObject): # chech the oringial packet is present self._test.assertEqual(rx[IP].dst, tx[IP].dst) - self._test.assertEqual(rx[IP].ttl, tx[IP].ttl-1) + self._test.assertEqual(rx[IP].ttl, tx[IP].ttl - 1) else: rx = IPv6(self.decrypt_transport(rx)) # chech the oringial packet is present self._test.assertEqual(rx[IPv6].dst, tx[IPv6].dst) - self._test.assertEqual(rx[IPv6].ttl, tx[IPv6].ttl-1) + self._test.assertEqual(rx[IPv6].ttl, tx[IPv6].ttl - 1) def want_events(self): self._test.vapi.want_wireguard_peer_events( enable_disable=1, pid=os.getpid(), peer_index=self.index, - sw_if_index=self.itf.sw_if_index) + sw_if_index=self.itf.sw_if_index, + ) def wait_event(self, expect, timeout=5): rv = self._test.vapi.wait_for_event(timeout, "wireguard_peer_event") @@ -372,14 +382,14 @@ class VppWgPeer(VppObject): class TestWg(VppTestCase): - """ Wireguard Test Case """ + """Wireguard Test Case""" error_str = compile(r"Error") - wg4_output_node_name = '/err/wg4-output-tun/' - wg4_input_node_name = '/err/wg4-input/' - wg6_output_node_name = '/err/wg6-output-tun/' - wg6_input_node_name = '/err/wg6-input/' + wg4_output_node_name = "/err/wg4-output-tun/" + wg4_input_node_name = "/err/wg4-input/" + wg6_output_node_name = "/err/wg6-output-tun/" + wg6_input_node_name = "/err/wg6-input/" kp4_error = wg4_output_node_name + "Keypair error" mac4_error = wg4_input_node_name + "Invalid MAC handshake" peer4_error = wg4_input_node_name + "Peer error" @@ -417,13 +427,11 @@ class TestWg(VppTestCase): self.base_peer6_err = self.statistics.get_err_counter(self.peer6_error) def test_wg_interface(self): - """ Simple interface creation """ + """Simple interface creation""" port = 12312 # Create interface - wg0 = VppWgInterface(self, - self.pg1.local_ip4, - port).add_vpp_config() + wg0 = VppWgInterface(self, self.pg1.local_ip4, port).add_vpp_config() self.logger.info(self.vapi.cli("sh int")) @@ -431,27 +439,29 @@ class TestWg(VppTestCase): wg0.remove_vpp_config() def test_handshake_hash(self): - """ test hashing an init message """ + """test hashing an init message""" # a init packet generated by linux given the key below - h = "0100000098b9032b" \ - "55cc4b39e73c3d24" \ - "a2a1ab884b524a81" \ - "1808bb86640fb70d" \ - "e93154fec1879125" \ - "ab012624a27f0b75" \ - "c0a2582f438ddb5f" \ - "8e768af40b4ab444" \ - "02f9ff473e1b797e" \ - "80d39d93c5480c82" \ - "a3d4510f70396976" \ - "586fb67300a5167b" \ - "ae6ca3ff3dfd00eb" \ - "59be198810f5aa03" \ - "6abc243d2155ee4f" \ - "2336483900aef801" \ - "08752cd700000000" \ - "0000000000000000" \ + h = ( + "0100000098b9032b" + "55cc4b39e73c3d24" + "a2a1ab884b524a81" + "1808bb86640fb70d" + "e93154fec1879125" + "ab012624a27f0b75" + "c0a2582f438ddb5f" + "8e768af40b4ab444" + "02f9ff473e1b797e" + "80d39d93c5480c82" + "a3d4510f70396976" + "586fb67300a5167b" + "ae6ca3ff3dfd00eb" + "59be198810f5aa03" + "6abc243d2155ee4f" + "2336483900aef801" + "08752cd700000000" + "0000000000000000" "00000000" + ) b = bytearray.fromhex(h) tgt = Wireguard(b) @@ -463,40 +473,34 @@ class TestWg(VppTestCase): # strip the macs and build a new packet init = b[0:-32] - mac_key = blake2s(b'mac1----' + public_key_bytes(pub)).digest() - init += blake2s(init, - digest_size=16, - key=mac_key).digest() - init += b'\x00' * 16 + mac_key = blake2s(b"mac1----" + public_key_bytes(pub)).digest() + init += blake2s(init, digest_size=16, key=mac_key).digest() + init += b"\x00" * 16 act = Wireguard(init) self.assertEqual(tgt, act) def test_wg_peer_resp(self): - """ Send handshake response """ + """Send handshake response""" port = 12323 # Create interfaces - wg0 = VppWgInterface(self, - self.pg1.local_ip4, - port).add_vpp_config() + wg0 = VppWgInterface(self, self.pg1.local_ip4, port).add_vpp_config() wg0.admin_up() wg0.config_ip4() self.pg_enable_capture(self.pg_interfaces) self.pg_start() - peer_1 = VppWgPeer(self, - wg0, - self.pg1.remote_ip4, - port+1, - ["10.11.3.0/24"]).add_vpp_config() + peer_1 = VppWgPeer( + self, wg0, self.pg1.remote_ip4, port + 1, ["10.11.3.0/24"] + ).add_vpp_config() self.assertEqual(len(self.vapi.wireguard_peers_dump()), 1) - r1 = VppIpRoute(self, "10.11.3.0", 24, - [VppRoutePath("10.11.3.1", - wg0.sw_if_index)]).add_vpp_config() + r1 = VppIpRoute( + self, "10.11.3.0", 24, [VppRoutePath("10.11.3.1", wg0.sw_if_index)] + ).add_vpp_config() # wait for the peer to send a handshake rx = self.pg1.get_capture(1, timeout=2) @@ -513,10 +517,12 @@ class TestWg(VppTestCase): self.assertEqual(0, len(b)) # send a packets that are routed into the tunnel - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst="10.11.3.2") / - UDP(sport=555, dport=556) / - Raw(b'\x00' * 80)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst="10.11.3.2") + / UDP(sport=555, dport=556) + / Raw(b"\x00" * 80) + ) rxs = self.send_and_expect(self.pg0, p * 255, self.pg1) @@ -524,15 +530,24 @@ class TestWg(VppTestCase): # send packets into the tunnel, expect to receive them on # the other side - p = [(peer_1.mk_tunnel_header(self.pg1) / - Wireguard(message_type=4, reserved_zero=0) / - WireguardTransport( - receiver_index=peer_1.sender, - counter=ii, - encrypted_encapsulated_packet=peer_1.encrypt_transport( - (IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20) / - UDP(sport=222, dport=223) / - Raw())))) for ii in range(255)] + p = [ + ( + peer_1.mk_tunnel_header(self.pg1) + / Wireguard(message_type=4, reserved_zero=0) + / WireguardTransport( + receiver_index=peer_1.sender, + counter=ii, + encrypted_encapsulated_packet=peer_1.encrypt_transport( + ( + IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20) + / UDP(sport=222, dport=223) + / Raw() + ) + ), + ) + ) + for ii in range(255) + ] rxs = self.send_and_expect(self.pg1, p, self.pg0) @@ -545,53 +560,54 @@ class TestWg(VppTestCase): wg0.remove_vpp_config() def test_wg_peer_v4o4(self): - """ Test v4o4""" + """Test v4o4""" port = 12333 # Create interfaces - wg0 = VppWgInterface(self, - self.pg1.local_ip4, - port).add_vpp_config() + wg0 = VppWgInterface(self, self.pg1.local_ip4, port).add_vpp_config() wg0.admin_up() wg0.config_ip4() - peer_1 = VppWgPeer(self, - wg0, - self.pg1.remote_ip4, - port+1, - ["10.11.3.0/24"]).add_vpp_config() + peer_1 = VppWgPeer( + self, wg0, self.pg1.remote_ip4, port + 1, ["10.11.3.0/24"] + ).add_vpp_config() self.assertEqual(len(self.vapi.wireguard_peers_dump()), 1) - r1 = VppIpRoute(self, "10.11.3.0", 24, - [VppRoutePath("10.11.3.1", - wg0.sw_if_index)]).add_vpp_config() + r1 = VppIpRoute( + self, "10.11.3.0", 24, [VppRoutePath("10.11.3.1", wg0.sw_if_index)] + ).add_vpp_config() # route a packet into the wg interface # use the allowed-ip prefix # this is dropped because the peer is not initiated - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst="10.11.3.2") / - UDP(sport=555, dport=556) / - Raw()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst="10.11.3.2") + / UDP(sport=555, dport=556) + / Raw() + ) self.send_and_assert_no_replies(self.pg0, [p]) - self.assertEqual(self.base_kp4_err + 1, - self.statistics.get_err_counter(self.kp4_error)) + self.assertEqual( + self.base_kp4_err + 1, self.statistics.get_err_counter(self.kp4_error) + ) # send a handsake from the peer with an invalid MAC p = peer_1.mk_handshake(self.pg1) - p[WireguardInitiation].mac1 = b'foobar' + p[WireguardInitiation].mac1 = b"foobar" self.send_and_assert_no_replies(self.pg1, [p]) - self.assertEqual(self.base_mac4_err + 1, - self.statistics.get_err_counter(self.mac4_error)) + self.assertEqual( + self.base_mac4_err + 1, self.statistics.get_err_counter(self.mac4_error) + ) # send a handsake from the peer but signed by the wrong key. - p = peer_1.mk_handshake(self.pg1, - False, - X25519PrivateKey.generate().public_key()) + p = peer_1.mk_handshake( + self.pg1, False, X25519PrivateKey.generate().public_key() + ) self.send_and_assert_no_replies(self.pg1, [p]) - self.assertEqual(self.base_peer4_err + 1, - self.statistics.get_err_counter(self.peer4_error)) + self.assertEqual( + self.base_peer4_err + 1, self.statistics.get_err_counter(self.peer4_error) + ) # send a valid handsake init for which we expect a response p = peer_1.mk_handshake(self.pg1) @@ -602,25 +618,31 @@ class TestWg(VppTestCase): # route a packet into the wg interface # this is dropped because the peer is still not initiated - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst="10.11.3.2") / - UDP(sport=555, dport=556) / - Raw()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst="10.11.3.2") + / UDP(sport=555, dport=556) + / Raw() + ) self.send_and_assert_no_replies(self.pg0, [p]) - self.assertEqual(self.base_kp4_err + 2, - self.statistics.get_err_counter(self.kp4_error)) + self.assertEqual( + self.base_kp4_err + 2, self.statistics.get_err_counter(self.kp4_error) + ) # send a data packet from the peer through the tunnel # this completes the handshake - p = (IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20) / - UDP(sport=222, dport=223) / - Raw()) + p = ( + IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20) + / UDP(sport=222, dport=223) + / Raw() + ) d = peer_1.encrypt_transport(p) - p = (peer_1.mk_tunnel_header(self.pg1) / - (Wireguard(message_type=4, reserved_zero=0) / - WireguardTransport(receiver_index=peer_1.sender, - counter=0, - encrypted_encapsulated_packet=d))) + p = peer_1.mk_tunnel_header(self.pg1) / ( + Wireguard(message_type=4, reserved_zero=0) + / WireguardTransport( + receiver_index=peer_1.sender, counter=0, encrypted_encapsulated_packet=d + ) + ) rxs = self.send_and_expect(self.pg1, [p], self.pg0) for rx in rxs: @@ -628,10 +650,12 @@ class TestWg(VppTestCase): self.assertEqual(rx[IP].ttl, 19) # send a packets that are routed into the tunnel - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst="10.11.3.2") / - UDP(sport=555, dport=556) / - Raw(b'\x00' * 80)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst="10.11.3.2") + / UDP(sport=555, dport=556) + / Raw(b"\x00" * 80) + ) rxs = self.send_and_expect(self.pg0, p * 255, self.pg1) @@ -640,19 +664,28 @@ class TestWg(VppTestCase): # chech the oringial packet is present self.assertEqual(rx[IP].dst, p[IP].dst) - self.assertEqual(rx[IP].ttl, p[IP].ttl-1) + self.assertEqual(rx[IP].ttl, p[IP].ttl - 1) # send packets into the tunnel, expect to receive them on # the other side - p = [(peer_1.mk_tunnel_header(self.pg1) / - Wireguard(message_type=4, reserved_zero=0) / - WireguardTransport( - receiver_index=peer_1.sender, - counter=ii+1, - encrypted_encapsulated_packet=peer_1.encrypt_transport( - (IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20) / - UDP(sport=222, dport=223) / - Raw())))) for ii in range(255)] + p = [ + ( + peer_1.mk_tunnel_header(self.pg1) + / Wireguard(message_type=4, reserved_zero=0) + / WireguardTransport( + receiver_index=peer_1.sender, + counter=ii + 1, + encrypted_encapsulated_packet=peer_1.encrypt_transport( + ( + IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20) + / UDP(sport=222, dport=223) + / Raw() + ) + ), + ) + ) + for ii in range(255) + ] rxs = self.send_and_expect(self.pg1, p, self.pg0) @@ -665,56 +698,57 @@ class TestWg(VppTestCase): wg0.remove_vpp_config() def test_wg_peer_v6o6(self): - """ Test v6o6""" + """Test v6o6""" port = 12343 # Create interfaces - wg0 = VppWgInterface(self, - self.pg1.local_ip6, - port).add_vpp_config() + wg0 = VppWgInterface(self, self.pg1.local_ip6, port).add_vpp_config() wg0.admin_up() wg0.config_ip6() - peer_1 = VppWgPeer(self, - wg0, - self.pg1.remote_ip6, - port+1, - ["1::3:0/112"]).add_vpp_config(True) + peer_1 = VppWgPeer( + self, wg0, self.pg1.remote_ip6, port + 1, ["1::3:0/112"] + ).add_vpp_config(True) self.assertEqual(len(self.vapi.wireguard_peers_dump()), 1) - r1 = VppIpRoute(self, "1::3:0", 112, - [VppRoutePath("1::3:1", - wg0.sw_if_index)]).add_vpp_config() + r1 = VppIpRoute( + self, "1::3:0", 112, [VppRoutePath("1::3:1", wg0.sw_if_index)] + ).add_vpp_config() # route a packet into the wg interface # use the allowed-ip prefix # this is dropped because the peer is not initiated - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst="1::3:2") / - UDP(sport=555, dport=556) / - Raw()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst="1::3:2") + / UDP(sport=555, dport=556) + / Raw() + ) self.send_and_assert_no_replies(self.pg0, [p]) - self.assertEqual(self.base_kp6_err + 1, - self.statistics.get_err_counter(self.kp6_error)) + self.assertEqual( + self.base_kp6_err + 1, self.statistics.get_err_counter(self.kp6_error) + ) # send a handsake from the peer with an invalid MAC p = peer_1.mk_handshake(self.pg1, True) - p[WireguardInitiation].mac1 = b'foobar' + p[WireguardInitiation].mac1 = b"foobar" self.send_and_assert_no_replies(self.pg1, [p]) - self.assertEqual(self.base_mac6_err + 1, - self.statistics.get_err_counter(self.mac6_error)) + self.assertEqual( + self.base_mac6_err + 1, self.statistics.get_err_counter(self.mac6_error) + ) # send a handsake from the peer but signed by the wrong key. - p = peer_1.mk_handshake(self.pg1, - True, - X25519PrivateKey.generate().public_key()) + p = peer_1.mk_handshake( + self.pg1, True, X25519PrivateKey.generate().public_key() + ) self.send_and_assert_no_replies(self.pg1, [p]) - self.assertEqual(self.base_peer6_err + 1, - self.statistics.get_err_counter(self.peer6_error)) + self.assertEqual( + self.base_peer6_err + 1, self.statistics.get_err_counter(self.peer6_error) + ) # send a valid handsake init for which we expect a response p = peer_1.mk_handshake(self.pg1, True) @@ -725,25 +759,31 @@ class TestWg(VppTestCase): # route a packet into the wg interface # this is dropped because the peer is still not initiated - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst="1::3:2") / - UDP(sport=555, dport=556) / - Raw()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst="1::3:2") + / UDP(sport=555, dport=556) + / Raw() + ) self.send_and_assert_no_replies(self.pg0, [p]) - self.assertEqual(self.base_kp6_err + 2, - self.statistics.get_err_counter(self.kp6_error)) + self.assertEqual( + self.base_kp6_err + 2, self.statistics.get_err_counter(self.kp6_error) + ) # send a data packet from the peer through the tunnel # this completes the handshake - p = (IPv6(src="1::3:1", dst=self.pg0.remote_ip6, hlim=20) / - UDP(sport=222, dport=223) / - Raw()) + p = ( + IPv6(src="1::3:1", dst=self.pg0.remote_ip6, hlim=20) + / UDP(sport=222, dport=223) + / Raw() + ) d = peer_1.encrypt_transport(p) - p = (peer_1.mk_tunnel_header(self.pg1, True) / - (Wireguard(message_type=4, reserved_zero=0) / - WireguardTransport(receiver_index=peer_1.sender, - counter=0, - encrypted_encapsulated_packet=d))) + p = peer_1.mk_tunnel_header(self.pg1, True) / ( + Wireguard(message_type=4, reserved_zero=0) + / WireguardTransport( + receiver_index=peer_1.sender, counter=0, encrypted_encapsulated_packet=d + ) + ) rxs = self.send_and_expect(self.pg1, [p], self.pg0) for rx in rxs: @@ -751,10 +791,12 @@ class TestWg(VppTestCase): self.assertEqual(rx[IPv6].hlim, 19) # send a packets that are routed into the tunnel - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst="1::3:2") / - UDP(sport=555, dport=556) / - Raw(b'\x00' * 80)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst="1::3:2") + / UDP(sport=555, dport=556) + / Raw(b"\x00" * 80) + ) rxs = self.send_and_expect(self.pg0, p * 255, self.pg1) @@ -763,19 +805,28 @@ class TestWg(VppTestCase): # chech the oringial packet is present self.assertEqual(rx[IPv6].dst, p[IPv6].dst) - self.assertEqual(rx[IPv6].hlim, p[IPv6].hlim-1) + self.assertEqual(rx[IPv6].hlim, p[IPv6].hlim - 1) # send packets into the tunnel, expect to receive them on # the other side - p = [(peer_1.mk_tunnel_header(self.pg1, True) / - Wireguard(message_type=4, reserved_zero=0) / - WireguardTransport( - receiver_index=peer_1.sender, - counter=ii+1, - encrypted_encapsulated_packet=peer_1.encrypt_transport( - (IPv6(src="1::3:1", dst=self.pg0.remote_ip6, hlim=20) / - UDP(sport=222, dport=223) / - Raw())))) for ii in range(255)] + p = [ + ( + peer_1.mk_tunnel_header(self.pg1, True) + / Wireguard(message_type=4, reserved_zero=0) + / WireguardTransport( + receiver_index=peer_1.sender, + counter=ii + 1, + encrypted_encapsulated_packet=peer_1.encrypt_transport( + ( + IPv6(src="1::3:1", dst=self.pg0.remote_ip6, hlim=20) + / UDP(sport=222, dport=223) + / Raw() + ) + ), + ) + ) + for ii in range(255) + ] rxs = self.send_and_expect(self.pg1, p, self.pg0) @@ -788,54 +839,55 @@ class TestWg(VppTestCase): wg0.remove_vpp_config() def test_wg_peer_v6o4(self): - """ Test v6o4""" + """Test v6o4""" port = 12353 # Create interfaces - wg0 = VppWgInterface(self, - self.pg1.local_ip4, - port).add_vpp_config() + wg0 = VppWgInterface(self, self.pg1.local_ip4, port).add_vpp_config() wg0.admin_up() wg0.config_ip6() - peer_1 = VppWgPeer(self, - wg0, - self.pg1.remote_ip4, - port+1, - ["1::3:0/112"]).add_vpp_config(True) + peer_1 = VppWgPeer( + self, wg0, self.pg1.remote_ip4, port + 1, ["1::3:0/112"] + ).add_vpp_config(True) self.assertEqual(len(self.vapi.wireguard_peers_dump()), 1) - r1 = VppIpRoute(self, "1::3:0", 112, - [VppRoutePath("1::3:1", - wg0.sw_if_index)]).add_vpp_config() + r1 = VppIpRoute( + self, "1::3:0", 112, [VppRoutePath("1::3:1", wg0.sw_if_index)] + ).add_vpp_config() # route a packet into the wg interface # use the allowed-ip prefix # this is dropped because the peer is not initiated - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst="1::3:2") / - UDP(sport=555, dport=556) / - Raw()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst="1::3:2") + / UDP(sport=555, dport=556) + / Raw() + ) self.send_and_assert_no_replies(self.pg0, [p]) - self.assertEqual(self.base_kp6_err + 1, - self.statistics.get_err_counter(self.kp6_error)) + self.assertEqual( + self.base_kp6_err + 1, self.statistics.get_err_counter(self.kp6_error) + ) # send a handsake from the peer with an invalid MAC p = peer_1.mk_handshake(self.pg1) - p[WireguardInitiation].mac1 = b'foobar' + p[WireguardInitiation].mac1 = b"foobar" self.send_and_assert_no_replies(self.pg1, [p]) - self.assertEqual(self.base_mac4_err + 1, - self.statistics.get_err_counter(self.mac4_error)) + self.assertEqual( + self.base_mac4_err + 1, self.statistics.get_err_counter(self.mac4_error) + ) # send a handsake from the peer but signed by the wrong key. - p = peer_1.mk_handshake(self.pg1, - False, - X25519PrivateKey.generate().public_key()) + p = peer_1.mk_handshake( + self.pg1, False, X25519PrivateKey.generate().public_key() + ) self.send_and_assert_no_replies(self.pg1, [p]) - self.assertEqual(self.base_peer4_err + 1, - self.statistics.get_err_counter(self.peer4_error)) + self.assertEqual( + self.base_peer4_err + 1, self.statistics.get_err_counter(self.peer4_error) + ) # send a valid handsake init for which we expect a response p = peer_1.mk_handshake(self.pg1) @@ -846,25 +898,31 @@ class TestWg(VppTestCase): # route a packet into the wg interface # this is dropped because the peer is still not initiated - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst="1::3:2") / - UDP(sport=555, dport=556) / - Raw()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst="1::3:2") + / UDP(sport=555, dport=556) + / Raw() + ) self.send_and_assert_no_replies(self.pg0, [p]) - self.assertEqual(self.base_kp6_err + 2, - self.statistics.get_err_counter(self.kp6_error)) + self.assertEqual( + self.base_kp6_err + 2, self.statistics.get_err_counter(self.kp6_error) + ) # send a data packet from the peer through the tunnel # this completes the handshake - p = (IPv6(src="1::3:1", dst=self.pg0.remote_ip6, hlim=20) / - UDP(sport=222, dport=223) / - Raw()) + p = ( + IPv6(src="1::3:1", dst=self.pg0.remote_ip6, hlim=20) + / UDP(sport=222, dport=223) + / Raw() + ) d = peer_1.encrypt_transport(p) - p = (peer_1.mk_tunnel_header(self.pg1) / - (Wireguard(message_type=4, reserved_zero=0) / - WireguardTransport(receiver_index=peer_1.sender, - counter=0, - encrypted_encapsulated_packet=d))) + p = peer_1.mk_tunnel_header(self.pg1) / ( + Wireguard(message_type=4, reserved_zero=0) + / WireguardTransport( + receiver_index=peer_1.sender, counter=0, encrypted_encapsulated_packet=d + ) + ) rxs = self.send_and_expect(self.pg1, [p], self.pg0) for rx in rxs: @@ -872,10 +930,12 @@ class TestWg(VppTestCase): self.assertEqual(rx[IPv6].hlim, 19) # send a packets that are routed into the tunnel - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IPv6(src=self.pg0.remote_ip6, dst="1::3:2") / - UDP(sport=555, dport=556) / - Raw(b'\x00' * 80)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IPv6(src=self.pg0.remote_ip6, dst="1::3:2") + / UDP(sport=555, dport=556) + / Raw(b"\x00" * 80) + ) rxs = self.send_and_expect(self.pg0, p * 255, self.pg1) @@ -884,19 +944,28 @@ class TestWg(VppTestCase): # chech the oringial packet is present self.assertEqual(rx[IPv6].dst, p[IPv6].dst) - self.assertEqual(rx[IPv6].hlim, p[IPv6].hlim-1) + self.assertEqual(rx[IPv6].hlim, p[IPv6].hlim - 1) # send packets into the tunnel, expect to receive them on # the other side - p = [(peer_1.mk_tunnel_header(self.pg1) / - Wireguard(message_type=4, reserved_zero=0) / - WireguardTransport( - receiver_index=peer_1.sender, - counter=ii+1, - encrypted_encapsulated_packet=peer_1.encrypt_transport( - (IPv6(src="1::3:1", dst=self.pg0.remote_ip6, hlim=20) / - UDP(sport=222, dport=223) / - Raw())))) for ii in range(255)] + p = [ + ( + peer_1.mk_tunnel_header(self.pg1) + / Wireguard(message_type=4, reserved_zero=0) + / WireguardTransport( + receiver_index=peer_1.sender, + counter=ii + 1, + encrypted_encapsulated_packet=peer_1.encrypt_transport( + ( + IPv6(src="1::3:1", dst=self.pg0.remote_ip6, hlim=20) + / UDP(sport=222, dport=223) + / Raw() + ) + ), + ) + ) + for ii in range(255) + ] rxs = self.send_and_expect(self.pg1, p, self.pg0) @@ -909,53 +978,54 @@ class TestWg(VppTestCase): wg0.remove_vpp_config() def test_wg_peer_v4o6(self): - """ Test v4o6""" + """Test v4o6""" port = 12363 # Create interfaces - wg0 = VppWgInterface(self, - self.pg1.local_ip6, - port).add_vpp_config() + wg0 = VppWgInterface(self, self.pg1.local_ip6, port).add_vpp_config() wg0.admin_up() wg0.config_ip4() - peer_1 = VppWgPeer(self, - wg0, - self.pg1.remote_ip6, - port+1, - ["10.11.3.0/24"]).add_vpp_config() + peer_1 = VppWgPeer( + self, wg0, self.pg1.remote_ip6, port + 1, ["10.11.3.0/24"] + ).add_vpp_config() self.assertEqual(len(self.vapi.wireguard_peers_dump()), 1) - r1 = VppIpRoute(self, "10.11.3.0", 24, - [VppRoutePath("10.11.3.1", - wg0.sw_if_index)]).add_vpp_config() + r1 = VppIpRoute( + self, "10.11.3.0", 24, [VppRoutePath("10.11.3.1", wg0.sw_if_index)] + ).add_vpp_config() # route a packet into the wg interface # use the allowed-ip prefix # this is dropped because the peer is not initiated - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst="10.11.3.2") / - UDP(sport=555, dport=556) / - Raw()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst="10.11.3.2") + / UDP(sport=555, dport=556) + / Raw() + ) self.send_and_assert_no_replies(self.pg0, [p]) - self.assertEqual(self.base_kp4_err + 1, - self.statistics.get_err_counter(self.kp4_error)) + self.assertEqual( + self.base_kp4_err + 1, self.statistics.get_err_counter(self.kp4_error) + ) # send a handsake from the peer with an invalid MAC p = peer_1.mk_handshake(self.pg1, True) - p[WireguardInitiation].mac1 = b'foobar' + p[WireguardInitiation].mac1 = b"foobar" self.send_and_assert_no_replies(self.pg1, [p]) - self.assertEqual(self.base_mac6_err + 1, - self.statistics.get_err_counter(self.mac6_error)) + self.assertEqual( + self.base_mac6_err + 1, self.statistics.get_err_counter(self.mac6_error) + ) # send a handsake from the peer but signed by the wrong key. - p = peer_1.mk_handshake(self.pg1, - True, - X25519PrivateKey.generate().public_key()) + p = peer_1.mk_handshake( + self.pg1, True, X25519PrivateKey.generate().public_key() + ) self.send_and_assert_no_replies(self.pg1, [p]) - self.assertEqual(self.base_peer6_err + 1, - self.statistics.get_err_counter(self.peer6_error)) + self.assertEqual( + self.base_peer6_err + 1, self.statistics.get_err_counter(self.peer6_error) + ) # send a valid handsake init for which we expect a response p = peer_1.mk_handshake(self.pg1, True) @@ -966,25 +1036,31 @@ class TestWg(VppTestCase): # route a packet into the wg interface # this is dropped because the peer is still not initiated - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst="10.11.3.2") / - UDP(sport=555, dport=556) / - Raw()) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst="10.11.3.2") + / UDP(sport=555, dport=556) + / Raw() + ) self.send_and_assert_no_replies(self.pg0, [p]) - self.assertEqual(self.base_kp4_err + 2, - self.statistics.get_err_counter(self.kp4_error)) + self.assertEqual( + self.base_kp4_err + 2, self.statistics.get_err_counter(self.kp4_error) + ) # send a data packet from the peer through the tunnel # this completes the handshake - p = (IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20) / - UDP(sport=222, dport=223) / - Raw()) + p = ( + IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20) + / UDP(sport=222, dport=223) + / Raw() + ) d = peer_1.encrypt_transport(p) - p = (peer_1.mk_tunnel_header(self.pg1, True) / - (Wireguard(message_type=4, reserved_zero=0) / - WireguardTransport(receiver_index=peer_1.sender, - counter=0, - encrypted_encapsulated_packet=d))) + p = peer_1.mk_tunnel_header(self.pg1, True) / ( + Wireguard(message_type=4, reserved_zero=0) + / WireguardTransport( + receiver_index=peer_1.sender, counter=0, encrypted_encapsulated_packet=d + ) + ) rxs = self.send_and_expect(self.pg1, [p], self.pg0) for rx in rxs: @@ -992,10 +1068,12 @@ class TestWg(VppTestCase): self.assertEqual(rx[IP].ttl, 19) # send a packets that are routed into the tunnel - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst="10.11.3.2") / - UDP(sport=555, dport=556) / - Raw(b'\x00' * 80)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst="10.11.3.2") + / UDP(sport=555, dport=556) + / Raw(b"\x00" * 80) + ) rxs = self.send_and_expect(self.pg0, p * 255, self.pg1) @@ -1004,19 +1082,28 @@ class TestWg(VppTestCase): # chech the oringial packet is present self.assertEqual(rx[IP].dst, p[IP].dst) - self.assertEqual(rx[IP].ttl, p[IP].ttl-1) + self.assertEqual(rx[IP].ttl, p[IP].ttl - 1) # send packets into the tunnel, expect to receive them on # the other side - p = [(peer_1.mk_tunnel_header(self.pg1, True) / - Wireguard(message_type=4, reserved_zero=0) / - WireguardTransport( - receiver_index=peer_1.sender, - counter=ii+1, - encrypted_encapsulated_packet=peer_1.encrypt_transport( - (IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20) / - UDP(sport=222, dport=223) / - Raw())))) for ii in range(255)] + p = [ + ( + peer_1.mk_tunnel_header(self.pg1, True) + / Wireguard(message_type=4, reserved_zero=0) + / WireguardTransport( + receiver_index=peer_1.sender, + counter=ii + 1, + encrypted_encapsulated_packet=peer_1.encrypt_transport( + ( + IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20) + / UDP(sport=222, dport=223) + / Raw() + ) + ), + ) + ) + for ii in range(255) + ] rxs = self.send_and_expect(self.pg1, p, self.pg0) @@ -1029,16 +1116,12 @@ class TestWg(VppTestCase): wg0.remove_vpp_config() def test_wg_multi_peer(self): - """ multiple peer setup """ + """multiple peer setup""" port = 12373 # Create interfaces - wg0 = VppWgInterface(self, - self.pg1.local_ip4, - port).add_vpp_config() - wg1 = VppWgInterface(self, - self.pg2.local_ip4, - port+1).add_vpp_config() + wg0 = VppWgInterface(self, self.pg1.local_ip4, port).add_vpp_config() + wg1 = VppWgInterface(self, self.pg2.local_ip4, port + 1).add_vpp_config() wg0.admin_up() wg1.admin_up() @@ -1060,25 +1143,43 @@ class TestWg(VppTestCase): routes_1 = [] routes_2 = [] for i in range(NUM_PEERS): - peers_1.append(VppWgPeer(self, - wg0, - self.pg1.remote_hosts[i].ip4, - port+1+i, - ["10.0.%d.4/32" % i]).add_vpp_config()) - routes_1.append(VppIpRoute(self, "10.0.%d.4" % i, 32, - [VppRoutePath(self.pg1.remote_hosts[i].ip4, - wg0.sw_if_index)]).add_vpp_config()) - - peers_2.append(VppWgPeer(self, - wg1, - self.pg2.remote_hosts[i].ip4, - port+100+i, - ["10.100.%d.4/32" % i]).add_vpp_config()) - routes_2.append(VppIpRoute(self, "10.100.%d.4" % i, 32, - [VppRoutePath(self.pg2.remote_hosts[i].ip4, - wg1.sw_if_index)]).add_vpp_config()) - - self.assertEqual(len(self.vapi.wireguard_peers_dump()), NUM_PEERS*2) + peers_1.append( + VppWgPeer( + self, + wg0, + self.pg1.remote_hosts[i].ip4, + port + 1 + i, + ["10.0.%d.4/32" % i], + ).add_vpp_config() + ) + routes_1.append( + VppIpRoute( + self, + "10.0.%d.4" % i, + 32, + [VppRoutePath(self.pg1.remote_hosts[i].ip4, wg0.sw_if_index)], + ).add_vpp_config() + ) + + peers_2.append( + VppWgPeer( + self, + wg1, + self.pg2.remote_hosts[i].ip4, + port + 100 + i, + ["10.100.%d.4/32" % i], + ).add_vpp_config() + ) + routes_2.append( + VppIpRoute( + self, + "10.100.%d.4" % i, + 32, + [VppRoutePath(self.pg2.remote_hosts[i].ip4, wg1.sw_if_index)], + ).add_vpp_config() + ) + + self.assertEqual(len(self.vapi.wireguard_peers_dump()), NUM_PEERS * 2) self.logger.info(self.vapi.cli("show wireguard peer")) self.logger.info(self.vapi.cli("show wireguard interface")) @@ -1104,7 +1205,7 @@ class TestWg(VppTestCase): wg1.remove_vpp_config() def test_wg_multi_interface(self): - """ Multi-tunnel on the same port """ + """Multi-tunnel on the same port""" port = 12500 # Create many wireguard interfaces @@ -1120,21 +1221,28 @@ class TestWg(VppTestCase): wg_ifs = [] for i in range(NUM_IFS): # Use the same port for each interface - wg0 = VppWgInterface(self, - self.pg1.local_ip4, - port).add_vpp_config() + wg0 = VppWgInterface(self, self.pg1.local_ip4, port).add_vpp_config() wg0.admin_up() wg0.config_ip4() wg_ifs.append(wg0) - peers.append(VppWgPeer(self, - wg0, - self.pg1.remote_hosts[i].ip4, - port+1+i, - ["10.0.%d.0/24" % i]).add_vpp_config()) - - routes.append(VppIpRoute(self, "10.0.%d.0" % i, 24, - [VppRoutePath("10.0.%d.4" % i, - wg0.sw_if_index)]).add_vpp_config()) + peers.append( + VppWgPeer( + self, + wg0, + self.pg1.remote_hosts[i].ip4, + port + 1 + i, + ["10.0.%d.0/24" % i], + ).add_vpp_config() + ) + + routes.append( + VppIpRoute( + self, + "10.0.%d.0" % i, + 24, + [VppRoutePath("10.0.%d.4" % i, wg0.sw_if_index)], + ).add_vpp_config() + ) self.assertEqual(len(self.vapi.wireguard_peers_dump()), NUM_IFS) @@ -1146,16 +1254,20 @@ class TestWg(VppTestCase): # send a data packet from the peer through the tunnel # this completes the handshake - p = (IP(src="10.0.%d.4" % i, - dst=self.pg0.remote_hosts[i].ip4, ttl=20) / - UDP(sport=222, dport=223) / - Raw()) + p = ( + IP(src="10.0.%d.4" % i, dst=self.pg0.remote_hosts[i].ip4, ttl=20) + / UDP(sport=222, dport=223) + / Raw() + ) d = peers[i].encrypt_transport(p) - p = (peers[i].mk_tunnel_header(self.pg1) / - (Wireguard(message_type=4, reserved_zero=0) / - WireguardTransport(receiver_index=peers[i].sender, - counter=0, - encrypted_encapsulated_packet=d))) + p = peers[i].mk_tunnel_header(self.pg1) / ( + Wireguard(message_type=4, reserved_zero=0) + / WireguardTransport( + receiver_index=peers[i].sender, + counter=0, + encrypted_encapsulated_packet=d, + ) + ) rxs = self.send_and_expect(self.pg1, [p], self.pg0) for rx in rxs: self.assertEqual(rx[IP].dst, self.pg0.remote_hosts[i].ip4) @@ -1163,10 +1275,12 @@ class TestWg(VppTestCase): # send a packets that are routed into the tunnel for i in range(NUM_IFS): - p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_hosts[i].ip4, dst="10.0.%d.4" % i) / - UDP(sport=555, dport=556) / - Raw(b'\x00' * 80)) + p = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_hosts[i].ip4, dst="10.0.%d.4" % i) + / UDP(sport=555, dport=556) + / Raw(b"\x00" * 80) + ) rxs = self.send_and_expect(self.pg0, p * 64, self.pg1) @@ -1175,20 +1289,32 @@ class TestWg(VppTestCase): # check the oringial packet is present self.assertEqual(rx[IP].dst, p[IP].dst) - self.assertEqual(rx[IP].ttl, p[IP].ttl-1) + self.assertEqual(rx[IP].ttl, p[IP].ttl - 1) # send packets into the tunnel for i in range(NUM_IFS): - p = [(peers[i].mk_tunnel_header(self.pg1) / - Wireguard(message_type=4, reserved_zero=0) / - WireguardTransport( - receiver_index=peers[i].sender, - counter=ii+1, - encrypted_encapsulated_packet=peers[i].encrypt_transport( - (IP(src="10.0.%d.4" % i, - dst=self.pg0.remote_hosts[i].ip4, ttl=20) / - UDP(sport=222, dport=223) / - Raw())))) for ii in range(64)] + p = [ + ( + peers[i].mk_tunnel_header(self.pg1) + / Wireguard(message_type=4, reserved_zero=0) + / WireguardTransport( + receiver_index=peers[i].sender, + counter=ii + 1, + encrypted_encapsulated_packet=peers[i].encrypt_transport( + ( + IP( + src="10.0.%d.4" % i, + dst=self.pg0.remote_hosts[i].ip4, + ttl=20, + ) + / UDP(sport=222, dport=223) + / Raw() + ) + ), + ) + ) + for ii in range(64) + ] rxs = self.send_and_expect(self.pg1, p, self.pg0) @@ -1204,22 +1330,16 @@ class TestWg(VppTestCase): i.remove_vpp_config() def test_wg_event(self): - """ Test events """ + """Test events""" port = 12600 - ESTABLISHED_FLAG = VppEnum.\ - vl_api_wireguard_peer_flags_t.\ - WIREGUARD_PEER_ESTABLISHED - DEAD_FLAG = VppEnum.\ - vl_api_wireguard_peer_flags_t.\ - WIREGUARD_PEER_STATUS_DEAD + ESTABLISHED_FLAG = ( + VppEnum.vl_api_wireguard_peer_flags_t.WIREGUARD_PEER_ESTABLISHED + ) + DEAD_FLAG = VppEnum.vl_api_wireguard_peer_flags_t.WIREGUARD_PEER_STATUS_DEAD # Create interfaces - wg0 = VppWgInterface(self, - self.pg1.local_ip4, - port).add_vpp_config() - wg1 = VppWgInterface(self, - self.pg2.local_ip4, - port+1).add_vpp_config() + wg0 = VppWgInterface(self, self.pg1.local_ip4, port).add_vpp_config() + wg1 = VppWgInterface(self, self.pg2.local_ip4, port + 1).add_vpp_config() wg0.admin_up() wg1.admin_up() @@ -1241,25 +1361,43 @@ class TestWg(VppTestCase): routes_0 = [] routes_1 = [] for i in range(NUM_PEERS): - peers_0.append(VppWgPeer(self, - wg0, - self.pg1.remote_hosts[i].ip4, - port+1+i, - ["10.0.%d.4/32" % i]).add_vpp_config()) - routes_0.append(VppIpRoute(self, "10.0.%d.4" % i, 32, - [VppRoutePath(self.pg1.remote_hosts[i].ip4, - wg0.sw_if_index)]).add_vpp_config()) - - peers_1.append(VppWgPeer(self, - wg1, - self.pg2.remote_hosts[i].ip4, - port+100+i, - ["10.100.%d.4/32" % i]).add_vpp_config()) - routes_1.append(VppIpRoute(self, "10.100.%d.4" % i, 32, - [VppRoutePath(self.pg2.remote_hosts[i].ip4, - wg1.sw_if_index)]).add_vpp_config()) - - self.assertEqual(len(self.vapi.wireguard_peers_dump()), NUM_PEERS*2) + peers_0.append( + VppWgPeer( + self, + wg0, + self.pg1.remote_hosts[i].ip4, + port + 1 + i, + ["10.0.%d.4/32" % i], + ).add_vpp_config() + ) + routes_0.append( + VppIpRoute( + self, + "10.0.%d.4" % i, + 32, + [VppRoutePath(self.pg1.remote_hosts[i].ip4, wg0.sw_if_index)], + ).add_vpp_config() + ) + + peers_1.append( + VppWgPeer( + self, + wg1, + self.pg2.remote_hosts[i].ip4, + port + 100 + i, + ["10.100.%d.4/32" % i], + ).add_vpp_config() + ) + routes_1.append( + VppIpRoute( + self, + "10.100.%d.4" % i, + 32, + [VppRoutePath(self.pg2.remote_hosts[i].ip4, wg1.sw_if_index)], + ).add_vpp_config() + ) + + self.assertEqual(len(self.vapi.wireguard_peers_dump()), NUM_PEERS * 2) # Want events from the first perr of wg0 # and from all wg1 peers @@ -1271,16 +1409,14 @@ class TestWg(VppTestCase): p = peers_0[i].mk_handshake(self.pg1) rx = self.send_and_expect(self.pg1, [p], self.pg1) peers_0[i].consume_response(rx[0]) - if (i == 0): + if i == 0: peers_0[0].wait_event(ESTABLISHED_FLAG) p = peers_1[i].mk_handshake(self.pg2) rx = self.send_and_expect(self.pg2, [p], self.pg2) peers_1[i].consume_response(rx[0]) - wg1.wait_events( - ESTABLISHED_FLAG, - [peers_1[0].index, peers_1[1].index]) + wg1.wait_events(ESTABLISHED_FLAG, [peers_1[0].index, peers_1[1].index]) # remove routes for r in routes_0: @@ -1292,7 +1428,7 @@ class TestWg(VppTestCase): for i in range(NUM_PEERS): self.assertTrue(peers_0[i].query_vpp_config()) peers_0[i].remove_vpp_config() - if (i == 0): + if i == 0: peers_0[i].wait_event(0) peers_0[i].wait_event(DEAD_FLAG) for p in peers_1: @@ -1306,32 +1442,28 @@ class TestWg(VppTestCase): class WireguardHandoffTests(TestWg): - """ Wireguard Tests in multi worker setup """ + """Wireguard Tests in multi worker setup""" + vpp_worker_count = 2 def test_wg_peer_init(self): - """ Handoff """ + """Handoff""" port = 12383 # Create interfaces - wg0 = VppWgInterface(self, - self.pg1.local_ip4, - port).add_vpp_config() + wg0 = VppWgInterface(self, self.pg1.local_ip4, port).add_vpp_config() wg0.admin_up() wg0.config_ip4() - peer_1 = VppWgPeer(self, - wg0, - self.pg1.remote_ip4, - port+1, - ["10.11.2.0/24", - "10.11.3.0/24"]).add_vpp_config() + peer_1 = VppWgPeer( + self, wg0, self.pg1.remote_ip4, port + 1, ["10.11.2.0/24", "10.11.3.0/24"] + ).add_vpp_config() self.assertEqual(len(self.vapi.wireguard_peers_dump()), 1) - r1 = VppIpRoute(self, "10.11.3.0", 24, - [VppRoutePath("10.11.3.1", - wg0.sw_if_index)]).add_vpp_config() + r1 = VppIpRoute( + self, "10.11.3.0", 24, [VppRoutePath("10.11.3.1", wg0.sw_if_index)] + ).add_vpp_config() # send a valid handsake init for which we expect a response p = peer_1.mk_handshake(self.pg1) @@ -1342,17 +1474,19 @@ class WireguardHandoffTests(TestWg): # send a data packet from the peer through the tunnel # this completes the handshake and pins the peer to worker 0 - p = (IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20) / - UDP(sport=222, dport=223) / - Raw()) + p = ( + IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20) + / UDP(sport=222, dport=223) + / Raw() + ) d = peer_1.encrypt_transport(p) - p = (peer_1.mk_tunnel_header(self.pg1) / - (Wireguard(message_type=4, reserved_zero=0) / - WireguardTransport(receiver_index=peer_1.sender, - counter=0, - encrypted_encapsulated_packet=d))) - rxs = self.send_and_expect(self.pg1, [p], self.pg0, - worker=0) + p = peer_1.mk_tunnel_header(self.pg1) / ( + Wireguard(message_type=4, reserved_zero=0) + / WireguardTransport( + receiver_index=peer_1.sender, counter=0, encrypted_encapsulated_packet=d + ) + ) + rxs = self.send_and_expect(self.pg1, [p], self.pg0, worker=0) for rx in rxs: self.assertEqual(rx[IP].dst, self.pg0.remote_ip4) @@ -1360,23 +1494,34 @@ class WireguardHandoffTests(TestWg): # send a packets that are routed into the tunnel # and pins the peer tp worker 1 - pe = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / - IP(src=self.pg0.remote_ip4, dst="10.11.3.2") / - UDP(sport=555, dport=556) / - Raw(b'\x00' * 80)) + pe = ( + Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) + / IP(src=self.pg0.remote_ip4, dst="10.11.3.2") + / UDP(sport=555, dport=556) + / Raw(b"\x00" * 80) + ) rxs = self.send_and_expect(self.pg0, pe * 255, self.pg1, worker=1) peer_1.validate_encapped(rxs, pe) # send packets into the tunnel, from the other worker - p = [(peer_1.mk_tunnel_header(self.pg1) / - Wireguard(message_type=4, reserved_zero=0) / - WireguardTransport( + p = [ + ( + peer_1.mk_tunnel_header(self.pg1) + / Wireguard(message_type=4, reserved_zero=0) + / WireguardTransport( receiver_index=peer_1.sender, - counter=ii+1, + counter=ii + 1, encrypted_encapsulated_packet=peer_1.encrypt_transport( - (IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20) / - UDP(sport=222, dport=223) / - Raw())))) for ii in range(255)] + ( + IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20) + / UDP(sport=222, dport=223) + / Raw() + ) + ), + ) + ) + for ii in range(255) + ] rxs = self.send_and_expect(self.pg1, p, self.pg0, worker=1) @@ -1396,4 +1541,4 @@ class WireguardHandoffTests(TestWg): @unittest.skip("test disabled") def test_wg_multi_interface(self): - """ Multi-tunnel on the same port """ + """Multi-tunnel on the same port""" diff --git a/test/util.py b/test/util.py index 2c24571c350..249bd864259 100644 --- a/test/util.py +++ b/test/util.py @@ -11,8 +11,12 @@ from collections import UserDict import scapy.compat from scapy.layers.l2 import Ether from scapy.layers.inet import IP -from scapy.layers.inet6 import IPv6, IPv6ExtHdrFragment, IPv6ExtHdrRouting,\ - IPv6ExtHdrHopByHop +from scapy.layers.inet6 import ( + IPv6, + IPv6ExtHdrFragment, + IPv6ExtHdrRouting, + IPv6ExtHdrHopByHop, +) from scapy.packet import Raw from scapy.utils import hexdump from scapy.utils6 import in6_mactoifaceid @@ -21,7 +25,7 @@ from io import BytesIO from vpp_papi import mac_pton # Set up an empty logger for the testcase that can be overridden as necessary -null_logger = logging.getLogger('VppTestCase.util') +null_logger = logging.getLogger("VppTestCase.util") null_logger.addHandler(logging.NullHandler()) @@ -30,14 +34,16 @@ def pr(packet): def ppp(headline, packet): - """ Return string containing headline and output of scapy packet.show() """ - return '%s\n%s\n\n%s\n' % (headline, - hexdump(packet, dump=True), - packet.show(dump=True)) + """Return string containing headline and output of scapy packet.show()""" + return "%s\n%s\n\n%s\n" % ( + headline, + hexdump(packet, dump=True), + packet.show(dump=True), + ) def ppc(headline, capture, limit=10): - """ Return string containing ppp() printout for a capture. + """Return string containing ppp() printout for a capture. :param headline: printed as first line of output :param capture: packets to print @@ -48,14 +54,17 @@ def ppc(headline, capture, limit=10): tail = "" if limit < len(capture): tail = "\nPrint limit reached, %s out of %s packets printed" % ( - limit, len(capture)) - body = "".join([ppp("Packet #%s:" % count, p) - for count, p in zip(range(0, limit), capture)]) + limit, + len(capture), + ) + body = "".join( + [ppp("Packet #%s:" % count, p) for count, p in zip(range(0, limit), capture)] + ) return "%s\n%s%s" % (headline, body, tail) def ip4_range(ip4, s, e): - tmp = ip4.rsplit('.', 1)[0] + tmp = ip4.rsplit(".", 1)[0] return ("%s.%d" % (tmp, i) for i in range(s, e)) @@ -65,14 +74,18 @@ def mcast_ip_to_mac(ip): raise ValueError("Must be multicast address.") ip_as_int = int(ip) if ip.version == 4: - mcast_mac = "01:00:5e:%02x:%02x:%02x" % ((ip_as_int >> 16) & 0x7f, - (ip_as_int >> 8) & 0xff, - ip_as_int & 0xff) + mcast_mac = "01:00:5e:%02x:%02x:%02x" % ( + (ip_as_int >> 16) & 0x7F, + (ip_as_int >> 8) & 0xFF, + ip_as_int & 0xFF, + ) else: - mcast_mac = "33:33:%02x:%02x:%02x:%02x" % ((ip_as_int >> 24) & 0xff, - (ip_as_int >> 16) & 0xff, - (ip_as_int >> 8) & 0xff, - ip_as_int & 0xff) + mcast_mac = "33:33:%02x:%02x:%02x:%02x" % ( + (ip_as_int >> 24) & 0xFF, + (ip_as_int >> 16) & 0xFF, + (ip_as_int >> 8) & 0xFF, + ip_as_int & 0xFF, + ) return mcast_mac @@ -84,8 +97,7 @@ def mk_ll_addr(mac): def ip6_normalize(ip6): - return socket.inet_ntop(socket.AF_INET6, - socket.inet_pton(socket.AF_INET6, ip6)) + return socket.inet_ntop(socket.AF_INET6, socket.inet_pton(socket.AF_INET6, ip6)) def get_core_path(tempdir): @@ -107,13 +119,14 @@ def check_core_path(logger, core_path): if corefmt.startswith("|"): logger.error( "WARNING: redirecting the core dump through a" - " filter may result in truncated dumps.") + " filter may result in truncated dumps." + ) logger.error( " You may want to check the filter settings" " or uninstall it and edit the" - " /proc/sys/kernel/core_pattern accordingly.") - logger.error( - " current core pattern is: %s" % corefmt) + " /proc/sys/kernel/core_pattern accordingly." + ) + logger.error(" current core pattern is: %s" % corefmt) class NumericConstant: @@ -136,55 +149,57 @@ class NumericConstant: class Host: - """ Generic test host "connected" to VPPs interface. """ + """Generic test host "connected" to VPPs interface.""" @property def mac(self): - """ MAC address """ + """MAC address""" return self._mac @property def bin_mac(self): - """ MAC address """ + """MAC address""" return mac_pton(self._mac) @property def ip4(self): - """ IPv4 address - string """ + """IPv4 address - string""" return self._ip4 @property def ip4n(self): - """ IPv4 address of remote host - raw, suitable as API parameter.""" + """IPv4 address of remote host - raw, suitable as API parameter.""" return socket.inet_pton(socket.AF_INET, self._ip4) @property def ip6(self): - """ IPv6 address - string """ + """IPv6 address - string""" return self._ip6 @property def ip6n(self): - """ IPv6 address of remote host - raw, suitable as API parameter.""" + """IPv6 address of remote host - raw, suitable as API parameter.""" return socket.inet_pton(socket.AF_INET6, self._ip6) @property def ip6_ll(self): - """ IPv6 link-local address - string """ + """IPv6 link-local address - string""" return self._ip6_ll @property def ip6n_ll(self): - """ IPv6 link-local address of remote host - + """IPv6 link-local address of remote host - raw, suitable as API parameter.""" return socket.inet_pton(socket.AF_INET6, self._ip6_ll) def __eq__(self, other): if isinstance(other, Host): - return (self.mac == other.mac and - self.ip4 == other.ip4 and - self.ip6 == other.ip6 and - self.ip6_ll == other.ip6_ll) + return ( + self.mac == other.mac + and self.ip4 == other.ip4 + and self.ip6 == other.ip6 + and self.ip6_ll == other.ip6_ll + ) else: return False @@ -192,10 +207,12 @@ class Host: return not self.__eq__(other) def __repr__(self): - return "Host { mac:%s ip4:%s ip6:%s ip6_ll:%s }" % (self.mac, - self.ip4, - self.ip6, - self.ip6_ll) + return "Host { mac:%s ip4:%s ip6:%s ip6_ll:%s }" % ( + self.mac, + self.ip4, + self.ip6, + self.ip6_ll, + ) def __hash__(self): return hash(self.__repr__()) @@ -207,8 +224,8 @@ class Host: self._ip6_ll = ip6_ll -class L4_Conn(): - """ L4 'connection' tied to two VPP interfaces """ +class L4_Conn: + """L4 'connection' tied to two VPP interfaces""" def __init__(self, testcase, if1, if2, af, l4proto, port1, port2): self.testcase = testcase @@ -228,22 +245,25 @@ class L4_Conn(): s1 = 1 - side src_if = self.ifs[s0] dst_if = self.ifs[s1] - layer_3 = [IP(src=src_if.remote_ip4, dst=dst_if.remote_ip4), - IPv6(src=src_if.remote_ip6, dst=dst_if.remote_ip6)] - merged_l4args = {'sport': self.ports[s0], 'dport': self.ports[s1]} + layer_3 = [ + IP(src=src_if.remote_ip4, dst=dst_if.remote_ip4), + IPv6(src=src_if.remote_ip6, dst=dst_if.remote_ip6), + ] + merged_l4args = {"sport": self.ports[s0], "dport": self.ports[s1]} merged_l4args.update(l4args) - p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) / - layer_3[is_ip6] / - self.l4proto(**merged_l4args) / - Raw(payload)) + p = ( + Ether(dst=src_if.local_mac, src=src_if.remote_mac) + / layer_3[is_ip6] + / self.l4proto(**merged_l4args) + / Raw(payload) + ) return p def send(self, side, flags=None, payload=""): l4args = {} if flags is not None: - l4args['flags'] = flags - self.ifs[side].add_stream(self.pkt(side, - l4args=l4args, payload=payload)) + l4args["flags"] = flags + self.ifs[side].add_stream(self.pkt(side, l4args=l4args, payload=payload)) self.ifs[1 - side].enable_capture() self.testcase.pg_start() @@ -285,8 +305,8 @@ def fragment_rfc791(packet, fragsize, logger=null_logger): pre_ip_len = len(packet) - len(packet[IP]) ip_header_len = packet[IP].ihl * 4 hex_packet = scapy.compat.raw(packet) - hex_headers = hex_packet[:(pre_ip_len + ip_header_len)] - hex_payload = hex_packet[(pre_ip_len + ip_header_len):] + hex_headers = hex_packet[: (pre_ip_len + ip_header_len)] + hex_payload = hex_packet[(pre_ip_len + ip_header_len) :] pkts = [] ihl = packet[IP].ihl @@ -294,14 +314,14 @@ def fragment_rfc791(packet, fragsize, logger=null_logger): nfb = int((fragsize - pre_ip_len - ihl * 4) / 8) fo = packet[IP].frag - p = packet.__class__(hex_headers + hex_payload[:nfb * 8]) + p = packet.__class__(hex_headers + hex_payload[: nfb * 8]) p[IP].flags = "MF" p[IP].frag = fo p[IP].len = ihl * 4 + nfb * 8 del p[IP].chksum pkts.append(p) - p = packet.__class__(hex_headers + hex_payload[nfb * 8:]) + p = packet.__class__(hex_headers + hex_payload[nfb * 8 :]) p[IP].len = otl - nfb * 8 p[IP].frag = fo + nfb del p[IP].chksum @@ -345,15 +365,19 @@ def fragment_rfc8200(packet, identification, fragsize, logger=null_logger): routing_hdr = counter elif l.__class__ is IPv6ExtHdrHopByHop: hop_by_hop_hdr = counter - elif seen_ipv6 and not upper_layer and \ - not l.__class__.__name__.startswith('IPv6ExtHdr'): + elif ( + seen_ipv6 + and not upper_layer + and not l.__class__.__name__.startswith("IPv6ExtHdr") + ): upper_layer = counter counter = counter + 1 l = packet.getlayer(counter) logger.debug( - "Layers seen: IPv6(#%s), Routing(#%s), HopByHop(#%s), upper(#%s)" % - (ipv6_nr, routing_hdr, hop_by_hop_hdr, upper_layer)) + "Layers seen: IPv6(#%s), Routing(#%s), HopByHop(#%s), upper(#%s)" + % (ipv6_nr, routing_hdr, hop_by_hop_hdr, upper_layer) + ) if upper_layer is None: raise Exception("Upper layer header not found in IPv6 packet") @@ -379,18 +403,27 @@ def fragment_rfc8200(packet, identification, fragsize, logger=null_logger): logger.debug(ppp("Fragment header:", fragment_ext_hdr)) len_ext_and_upper_layer_payload = len(ext_and_upper_layer.payload) - if not len_ext_and_upper_layer_payload and \ - hasattr(ext_and_upper_layer, "data"): + if not len_ext_and_upper_layer_payload and hasattr(ext_and_upper_layer, "data"): len_ext_and_upper_layer_payload = len(ext_and_upper_layer.data) - if len(per_fragment_headers) + len(fragment_ext_hdr) +\ - len(ext_and_upper_layer) - len_ext_and_upper_layer_payload\ - > fragsize: - raise Exception("Cannot fragment this packet - MTU too small " - "(%s, %s, %s, %s, %s)" % ( - len(per_fragment_headers), len(fragment_ext_hdr), - len(ext_and_upper_layer), - len_ext_and_upper_layer_payload, fragsize)) + if ( + len(per_fragment_headers) + + len(fragment_ext_hdr) + + len(ext_and_upper_layer) + - len_ext_and_upper_layer_payload + > fragsize + ): + raise Exception( + "Cannot fragment this packet - MTU too small " + "(%s, %s, %s, %s, %s)" + % ( + len(per_fragment_headers), + len(fragment_ext_hdr), + len(ext_and_upper_layer), + len_ext_and_upper_layer_payload, + fragsize, + ) + ) orig_nh = packet[IPv6].nh p = per_fragment_headers @@ -399,7 +432,7 @@ def fragment_rfc8200(packet, identification, fragsize, logger=null_logger): p = p / fragment_ext_hdr del p[IPv6ExtHdrFragment].nh first_payload_len_nfb = int((fragsize - len(p)) / 8) - p = p / Raw(hex_payload[:first_payload_len_nfb * 8]) + p = p / Raw(hex_payload[: first_payload_len_nfb * 8]) del p[IPv6].plen p[IPv6ExtHdrFragment].nh = orig_nh p[IPv6ExtHdrFragment].id = identification @@ -417,7 +450,7 @@ def fragment_rfc8200(packet, identification, fragsize, logger=null_logger): p = p / fragment_ext_hdr del p[IPv6ExtHdrFragment].nh l_nfb = int((fragsize - len(p)) / 8) - p = p / Raw(hex_payload[offset:offset + l_nfb * 8]) + p = p / Raw(hex_payload[offset : offset + l_nfb * 8]) p[IPv6ExtHdrFragment].nh = orig_nh p[IPv6ExtHdrFragment].id = identification p[IPv6ExtHdrFragment].offset = int(offset / 8) @@ -437,11 +470,11 @@ def reassemble4_core(listoffragments, return_ip): first = listoffragments[0] buffer.seek(20) for pkt in listoffragments: - buffer.seek(pkt[IP].frag*8) + buffer.seek(pkt[IP].frag * 8) buffer.write(bytes(pkt[IP].payload)) first.len = len(buffer.getvalue()) + 20 first.flags = 0 - del(first.chksum) + del first.chksum if return_ip: header = bytes(first[IP])[:20] return first[IP].__class__(header + buffer.getvalue()) @@ -472,8 +505,7 @@ def recursive_dict_merge(dict_base, dict_update): for key in dict_update: if key in dict_base: if type(dict_update[key]) is dict: - dict_base[key] = recursive_dict_merge(dict_base[key], - dict_update[key]) + dict_base[key] = recursive_dict_merge(dict_base[key], dict_update[key]) else: dict_base[key] = dict_update[key] else: diff --git a/test/vpp_acl.py b/test/vpp_acl.py index 2d2f7ca257b..958d6973f26 100644 --- a/test/vpp_acl.py +++ b/test/vpp_acl.py @@ -7,7 +7,6 @@ from vpp_papi_provider import UnexpectedApiReturnValueError class VppAclPlugin(VppObject): - def __init__(self, test, enable_intf_counters=False): self._test = test self.enable_intf_counters = enable_intf_counters @@ -30,11 +29,11 @@ class VppAclPlugin(VppObject): pass def object_id(self): - return ("acl-plugin-%d" % (self._sw_if_index)) + return "acl-plugin-%d" % (self._sw_if_index) -class AclRule(): - """ ACL Rule """ +class AclRule: + """ACL Rule""" # port ranges PORTS_ALL = -1 @@ -70,10 +69,18 @@ class AclRule(): icmp6_code_from_2 = 8 icmp6_code_to_2 = 42 - def __init__(self, is_permit, src_prefix=IPv4Network('0.0.0.0/0'), - dst_prefix=IPv4Network('0.0.0.0/0'), - proto=0, ports=PORTS_ALL, sport_from=None, sport_to=None, - dport_from=None, dport_to=None): + def __init__( + self, + is_permit, + src_prefix=IPv4Network("0.0.0.0/0"), + dst_prefix=IPv4Network("0.0.0.0/0"), + proto=0, + ports=PORTS_ALL, + sport_from=None, + sport_to=None, + dport_from=None, + dport_to=None, + ): self.is_permit = is_permit self.src_prefix = src_prefix self.dst_prefix = dst_prefix @@ -92,9 +99,17 @@ class AclRule(): self.dport_to = dport_to def __copy__(self): - new_rule = AclRule(self.is_permit, self.src_prefix, self.dst_prefix, - self._proto, self._ports, self.sport_from, - self.sport_to, self.dport_from, self.dport_to) + new_rule = AclRule( + self.is_permit, + self.src_prefix, + self.dst_prefix, + self._proto, + self._ports, + self.sport_from, + self.sport_to, + self.dport_from, + self.dport_to, + ) return new_rule def update_ports(self): @@ -172,17 +187,20 @@ class AclRule(): self.update_ports() def encode(self): - return {'is_permit': self.is_permit, 'proto': self.proto, - 'srcport_or_icmptype_first': self.sport_from, - 'srcport_or_icmptype_last': self.sport_to, - 'src_prefix': self.src_prefix, - 'dstport_or_icmpcode_first': self.dport_from, - 'dstport_or_icmpcode_last': self.dport_to, - 'dst_prefix': self.dst_prefix} + return { + "is_permit": self.is_permit, + "proto": self.proto, + "srcport_or_icmptype_first": self.sport_from, + "srcport_or_icmptype_last": self.sport_to, + "src_prefix": self.src_prefix, + "dstport_or_icmpcode_first": self.dport_from, + "dstport_or_icmpcode_last": self.dport_to, + "dst_prefix": self.dst_prefix, + } class VppAcl(VppObject): - """ VPP ACL """ + """VPP ACL""" def __init__(self, test, rules, acl_index=INVALID_INDEX, tag=None): self._test = test @@ -211,8 +229,11 @@ class VppAcl(VppObject): def add_vpp_config(self, expect_error=False): try: reply = self._test.vapi.acl_add_replace( - acl_index=self._acl_index, tag=self.tag, count=self.count, - r=self.encode_rules()) + acl_index=self._acl_index, + tag=self.tag, + count=self.count, + r=self.encode_rules(), + ) self._acl_index = reply.acl_index self._test.registry.register(self, self._test.logger) if expect_error: @@ -247,11 +268,11 @@ class VppAcl(VppObject): return False def object_id(self): - return ("acl-%s-%d" % (self.tag, self._acl_index)) + return "acl-%s-%d" % (self.tag, self._acl_index) class VppEtypeWhitelist(VppObject): - """ VPP Etype Whitelist """ + """VPP Etype Whitelist""" def __init__(self, test, sw_if_index, whitelist, n_input=0): self._test = test @@ -269,26 +290,31 @@ class VppEtypeWhitelist(VppObject): def add_vpp_config(self): self._test.vapi.acl_interface_set_etype_whitelist( - sw_if_index=self._sw_if_index, count=self.count, - n_input=self.n_input, whitelist=self.whitelist) + sw_if_index=self._sw_if_index, + count=self.count, + n_input=self.n_input, + whitelist=self.whitelist, + ) self._test.registry.register(self, self._test.logger) return self def remove_vpp_config(self): self._test.vapi.acl_interface_set_etype_whitelist( - sw_if_index=self._sw_if_index, count=0, n_input=0, whitelist=[]) + sw_if_index=self._sw_if_index, count=0, n_input=0, whitelist=[] + ) def query_vpp_config(self): self._test.vapi.acl_interface_etype_whitelist_dump( - sw_if_index=self._sw_if_index) + sw_if_index=self._sw_if_index + ) return False def object_id(self): - return ("acl-etype_wl-%d" % (self._sw_if_index)) + return "acl-etype_wl-%d" % (self._sw_if_index) class VppAclInterface(VppObject): - """ VPP ACL Interface """ + """VPP ACL Interface""" def __init__(self, test, sw_if_index, acls, n_input=0): self._test = test @@ -313,8 +339,11 @@ class VppAclInterface(VppObject): def add_vpp_config(self, expect_error=False): try: reply = self._test.vapi.acl_interface_set_acl_list( - sw_if_index=self._sw_if_index, n_input=self.n_input, - count=self.count, acls=self.encode_acls()) + sw_if_index=self._sw_if_index, + n_input=self.n_input, + count=self.count, + acls=self.encode_acls(), + ) self._test.registry.register(self, self._test.logger) if expect_error: self._test.fail("Unexpected api reply") @@ -327,7 +356,8 @@ class VppAclInterface(VppObject): def remove_vpp_config(self, expect_error=False): try: reply = self._test.vapi.acl_interface_set_acl_list( - sw_if_index=self._sw_if_index, n_input=0, count=0, acls=[]) + sw_if_index=self._sw_if_index, n_input=0, count=0, acls=[] + ) if expect_error: self._test.fail("Unexpected api reply") except UnexpectedApiReturnValueError: @@ -335,35 +365,38 @@ class VppAclInterface(VppObject): self._test.fail("Unexpected api reply") def query_vpp_config(self): - dump = self._test.vapi.acl_interface_list_dump( - sw_if_index=self._sw_if_index) + dump = self._test.vapi.acl_interface_list_dump(sw_if_index=self._sw_if_index) for acl_list in dump: if acl_list.count > 0: return True return False def object_id(self): - return ("acl-if-list-%d" % (self._sw_if_index)) + return "acl-if-list-%d" % (self._sw_if_index) -class MacipRule(): - """ Mac Ip rule """ +class MacipRule: + """Mac Ip rule""" - def __init__(self, is_permit, src_mac=0, src_mac_mask=0, - src_prefix=IPv4Network('0.0.0.0/0')): + def __init__( + self, is_permit, src_mac=0, src_mac_mask=0, src_prefix=IPv4Network("0.0.0.0/0") + ): self.is_permit = is_permit self.src_mac = src_mac self.src_mac_mask = src_mac_mask self.src_prefix = src_prefix def encode(self): - return {'is_permit': self.is_permit, 'src_mac': self.src_mac, - 'src_mac_mask': self.src_mac_mask, - 'src_prefix': self.src_prefix} + return { + "is_permit": self.is_permit, + "src_mac": self.src_mac, + "src_mac_mask": self.src_mac_mask, + "src_prefix": self.src_prefix, + } class VppMacipAcl(VppObject): - """ Vpp Mac Ip ACL """ + """Vpp Mac Ip ACL""" def __init__(self, test, rules, acl_index=INVALID_INDEX, tag=None): self._test = test @@ -392,8 +425,11 @@ class VppMacipAcl(VppObject): def add_vpp_config(self, expect_error=False): try: reply = self._test.vapi.macip_acl_add_replace( - acl_index=self._acl_index, tag=self.tag, count=self.count, - r=self.encode_rules()) + acl_index=self._acl_index, + tag=self.tag, + count=self.count, + r=self.encode_rules(), + ) self._acl_index = reply.acl_index self._test.registry.register(self, self._test.logger) if expect_error: @@ -428,11 +464,11 @@ class VppMacipAcl(VppObject): return False def object_id(self): - return ("macip-acl-%s-%d" % (self.tag, self._acl_index)) + return "macip-acl-%s-%d" % (self.tag, self._acl_index) class VppMacipAclInterface(VppObject): - """ VPP Mac Ip ACL Interface """ + """VPP Mac Ip ACL Interface""" def __init__(self, test, sw_if_index, acls): self._test = test @@ -450,19 +486,20 @@ class VppMacipAclInterface(VppObject): def add_vpp_config(self): for acl in self.acls: self._test.vapi.macip_acl_interface_add_del( - is_add=True, sw_if_index=self._sw_if_index, - acl_index=acl.acl_index) + is_add=True, sw_if_index=self._sw_if_index, acl_index=acl.acl_index + ) self._test.registry.register(self, self._test.logger) def remove_vpp_config(self): for acl in self.acls: self._test.vapi.macip_acl_interface_add_del( - is_add=False, sw_if_index=self._sw_if_index, - acl_index=acl.acl_index) + is_add=False, sw_if_index=self._sw_if_index, acl_index=acl.acl_index + ) def dump(self): return self._test.vapi.macip_acl_interface_list_dump( - sw_if_index=self._sw_if_index) + sw_if_index=self._sw_if_index + ) def query_vpp_config(self): dump = self.dump() @@ -473,4 +510,4 @@ class VppMacipAclInterface(VppObject): return False def object_id(self): - return ("macip-acl-if-list-%d" % (self._sw_if_index)) + return "macip-acl-if-list-%d" % (self._sw_if_index) diff --git a/test/vpp_bier.py b/test/vpp_bier.py index 6e087a8ee0b..9fdaf1faa1c 100644 --- a/test/vpp_bier.py +++ b/test/vpp_bier.py @@ -18,7 +18,7 @@ class BIER_HDR_PAYLOAD: BIER_HDR_PROTO_OAM = 8 -class VppBierTableID(): +class VppBierTableID: def __init__(self, sub_domain_id, set_id, hdr_len_id): self.set_id = set_id self.sub_domain_id = sub_domain_id @@ -28,9 +28,11 @@ class VppBierTableID(): def find_bier_table(test, bti): tables = test.vapi.bier_table_dump() for t in tables: - if bti.set_id == t.bt_tbl_id.bt_set \ - and bti.sub_domain_id == t.bt_tbl_id.bt_sub_domain \ - and bti.hdr_len_id == t.bt_tbl_id.bt_hdr_len_id: + if ( + bti.set_id == t.bt_tbl_id.bt_set + and bti.sub_domain_id == t.bt_tbl_id.bt_sub_domain + and bti.hdr_len_id == t.bt_tbl_id.bt_hdr_len_id + ): return True return False @@ -38,10 +40,12 @@ def find_bier_table(test, bti): def find_bier_route(test, bti, bp): routes = test.vapi.bier_route_dump(bti) for r in routes: - if bti.set_id == r.br_route.br_tbl_id.bt_set \ - and bti.sub_domain_id == r.br_route.br_tbl_id.bt_sub_domain \ - and bti.hdr_len_id == r.br_route.br_tbl_id.bt_hdr_len_id \ - and bp == r.br_route.br_bp: + if ( + bti.set_id == r.br_route.br_tbl_id.bt_set + and bti.sub_domain_id == r.br_route.br_tbl_id.bt_sub_domain + and bti.hdr_len_id == r.br_route.br_tbl_id.bt_hdr_len_id + and bp == r.br_route.br_bp + ): return True return False @@ -57,8 +61,7 @@ def find_bier_disp_table(test, bdti): def find_bier_disp_entry(test, bdti, bp): entries = test.vapi.bier_disp_entry_dump(bdti) for e in entries: - if bp == e.bde_bp \ - and bdti == e.bde_tbl_id: + if bp == e.bde_bp and bdti == e.bde_tbl_id: return True return False @@ -66,10 +69,12 @@ def find_bier_disp_entry(test, bdti, bp): def find_bier_imp(test, bti, bp): imps = test.vapi.bier_imp_dump() for i in imps: - if bti.set_id == i.bi_tbl_id.bt_set \ - and bti.sub_domain_id == i.bi_tbl_id.bt_sub_domain \ - and bti.hdr_len_id == i.bi_tbl_id.bt_hdr_len_id \ - and bp == i.bi_src: + if ( + bti.set_id == i.bi_tbl_id.bt_set + and bti.sub_domain_id == i.bi_tbl_id.bt_sub_domain + and bti.hdr_len_id == i.bi_tbl_id.bt_hdr_len_id + and bp == i.bi_src + ): return True return False @@ -85,22 +90,18 @@ class VppBierTable(VppObject): self.mpls_label = mpls_label def add_vpp_config(self): - self._test.vapi.bier_table_add_del( - self.id, - self.mpls_label, - is_add=1) + self._test.vapi.bier_table_add_del(self.id, self.mpls_label, is_add=1) self._test.registry.register(self, self._test.logger) def remove_vpp_config(self): - self._test.vapi.bier_table_add_del( - self.id, - self.mpls_label, - is_add=0) + self._test.vapi.bier_table_add_del(self.id, self.mpls_label, is_add=0) def object_id(self): - return "bier-table;[%d:%d:%d]" % (self.id.set_id, - self.id.sub_domain_id, - self.id.hdr_len_id) + return "bier-table;[%d:%d:%d]" % ( + self.id.set_id, + self.id.sub_domain_id, + self.id.hdr_len_id, + ) def query_vpp_config(self): return find_bier_table(self._test, self.id) @@ -122,18 +123,14 @@ class VppBierRoute(VppObject): def add_vpp_config(self): self._test.vapi.bier_route_add_del( - self.tbl_id, - self.bp, - self.encoded_paths, - is_add=1) + self.tbl_id, self.bp, self.encoded_paths, is_add=1 + ) self._test.registry.register(self, self._test.logger) def remove_vpp_config(self): self._test.vapi.bier_route_add_del( - self.tbl_id, - self.bp, - self.encoded_paths, - is_add=0) + self.tbl_id, self.bp, self.encoded_paths, is_add=0 + ) def update_paths(self, paths): self.paths = paths @@ -141,46 +138,37 @@ class VppBierRoute(VppObject): for path in self.paths: self.encoded_paths.append(path.encode()) self._test.vapi.bier_route_add_del( - self.tbl_id, - self.bp, - self.encoded_paths, - is_replace=1) + self.tbl_id, self.bp, self.encoded_paths, is_replace=1 + ) def add_path(self, path): self.encoded_paths.append(path.encode()) self._test.vapi.bier_route_add_del( - self.tbl_id, - self.bp, - [path.encode()], - is_add=1, - is_replace=0) + self.tbl_id, self.bp, [path.encode()], is_add=1, is_replace=0 + ) self.paths.append(path) self._test.registry.register(self, self._test.logger) def remove_path(self, path): self.encoded_paths.remove(path.encode()) self._test.vapi.bier_route_add_del( - self.tbl_id, - self.bp, - [path.encode()], - is_add=0, - is_replace=0) + self.tbl_id, self.bp, [path.encode()], is_add=0, is_replace=0 + ) self.paths.remove(path) def remove_all_paths(self): self._test.vapi.bier_route_add_del( - self.tbl_id, - self.bp, - [], - is_add=0, - is_replace=1) + self.tbl_id, self.bp, [], is_add=0, is_replace=1 + ) self.paths = [] def object_id(self): - return "bier-route;[%d:%d:%d:%d]" % (self.tbl_id.set_id, - self.tbl_id.sub_domain_id, - self.tbl_id.hdr_len_id, - self.bp) + return "bier-route;[%d:%d:%d:%d]" % ( + self.tbl_id.set_id, + self.tbl_id.sub_domain_id, + self.tbl_id.hdr_len_id, + self.bp, + ) def query_vpp_config(self): return find_bier_route(self._test, self.tbl_id, self.bp) @@ -198,22 +186,20 @@ class VppBierImp(VppObject): self.src = src def add_vpp_config(self): - res = self._test.vapi.bier_imp_add( - self.tbl_id, - self.src, - self.ibytes) + res = self._test.vapi.bier_imp_add(self.tbl_id, self.src, self.ibytes) self.bi_index = res.bi_index self._test.registry.register(self, self._test.logger) def remove_vpp_config(self): - self._test.vapi.bier_imp_del( - self.bi_index) + self._test.vapi.bier_imp_del(self.bi_index) def object_id(self): - return "bier-imp;[%d:%d:%d:%d]" % (self.tbl_id.set_id, - self.tbl_id.sub_domain_id, - self.tbl_id.hdr_len_id, - self.src) + return "bier-imp;[%d:%d:%d:%d]" % ( + self.tbl_id.set_id, + self.tbl_id.sub_domain_id, + self.tbl_id.hdr_len_id, + self.src, + ) def query_vpp_config(self): return find_bier_imp(self._test, self.tbl_id, self.src) @@ -229,15 +215,11 @@ class VppBierDispTable(VppObject): self.id = id def add_vpp_config(self): - self._test.vapi.bier_disp_table_add_del( - self.id, - is_add=1) + self._test.vapi.bier_disp_table_add_del(self.id, is_add=1) self._test.registry.register(self, self._test.logger) def remove_vpp_config(self): - self._test.vapi.bier_disp_table_add_del( - self.id, - is_add=0) + self._test.vapi.bier_disp_table_add_del(self.id, is_add=0) def object_id(self): return "bier-disp-table;[%d]" % (self.id) @@ -251,8 +233,9 @@ class VppBierDispEntry(VppObject): BIER Disposition Entry """ - def __init__(self, test, tbl_id, bp, payload_proto, nh_proto, - nh, nh_tbl, rpf_id=~0): + def __init__( + self, test, tbl_id, bp, payload_proto, nh_proto, nh, nh_tbl, rpf_id=~0 + ): self._test = test self.tbl_id = tbl_id self.nh_tbl = nh_tbl @@ -271,7 +254,8 @@ class VppBierDispEntry(VppObject): self.nh, self.nh_tbl, self.rpf_id, - is_add=1) + is_add=1, + ) self._test.registry.register(self, self._test.logger) def remove_vpp_config(self): @@ -283,11 +267,11 @@ class VppBierDispEntry(VppObject): self.nh, self.nh_tbl, self.rpf_id, - is_add=0) + is_add=0, + ) def object_id(self): - return "bier-disp-entry;[%d:%d]" % (self.tbl_id, - self.bp) + return "bier-disp-entry;[%d:%d]" % (self.tbl_id, self.bp) def query_vpp_config(self): return find_bier_disp_entry(self._test, self.tbl_id, self.bp) diff --git a/test/vpp_bond_interface.py b/test/vpp_bond_interface.py index 60c1ac1557b..636315cfce2 100644 --- a/test/vpp_bond_interface.py +++ b/test/vpp_bond_interface.py @@ -5,10 +5,19 @@ from vpp_interface import VppInterface class VppBondInterface(VppInterface): """VPP bond interface.""" - def __init__(self, test, mode, lb=0, numa_only=0, enable_gso=0, - use_custom_mac=0, mac_address='', id=0xFFFFFFFF): - - """ Create VPP Bond interface """ + def __init__( + self, + test, + mode, + lb=0, + numa_only=0, + enable_gso=0, + use_custom_mac=0, + mac_address="", + id=0xFFFFFFFF, + ): + + """Create VPP Bond interface""" super(VppBondInterface, self).__init__(test) self.mode = mode self.lb = lb @@ -19,29 +28,28 @@ class VppBondInterface(VppInterface): self.id = id def add_vpp_config(self): - r = self.test.vapi.bond_create2(self.mode, - self.lb, - self.numa_only, - self.enable_gso, - self.use_custom_mac, - self.mac_address, - self.id) + r = self.test.vapi.bond_create2( + self.mode, + self.lb, + self.numa_only, + self.enable_gso, + self.use_custom_mac, + self.mac_address, + self.id, + ) self.set_sw_if_index(r.sw_if_index) def remove_vpp_config(self): self.test.vapi.bond_delete(self.sw_if_index) - def add_member_vpp_bond_interface(self, - sw_if_index, - is_passive=0, - is_long_timeout=0): - self.test.vapi.bond_add_member(sw_if_index, - self.sw_if_index, - is_passive, - is_long_timeout) - - def detach_vpp_bond_interface(self, - sw_if_index): + def add_member_vpp_bond_interface( + self, sw_if_index, is_passive=0, is_long_timeout=0 + ): + self.test.vapi.bond_add_member( + sw_if_index, self.sw_if_index, is_passive, is_long_timeout + ) + + def detach_vpp_bond_interface(self, sw_if_index): self.test.vapi.bond_detach_member(sw_if_index) def is_interface_config_in_dump(self, dump): diff --git a/test/vpp_bvi_interface.py b/test/vpp_bvi_interface.py index 7039f29ca8d..9ab80e91c14 100644 --- a/test/vpp_bvi_interface.py +++ b/test/vpp_bvi_interface.py @@ -6,13 +6,12 @@ class VppBviInterface(VppInterface, VppObject): """VPP bvi interface.""" def __init__(self, test): - """ Create VPP BVI interface """ + """Create VPP BVI interface""" super(VppBviInterface, self).__init__(test) self.add_vpp_config() def add_vpp_config(self): - r = self.test.vapi.bvi_create(user_instance=0xffffffff, - mac="00:00:00:00:00:00") + r = self.test.vapi.bvi_create(user_instance=0xFFFFFFFF, mac="00:00:00:00:00:00") self.set_sw_if_index(r.sw_if_index) def remove_vpp_config(self): diff --git a/test/vpp_devices.py b/test/vpp_devices.py index 9e272cafe32..cff08e84435 100644 --- a/test/vpp_devices.py +++ b/test/vpp_devices.py @@ -2,27 +2,26 @@ from vpp_interface import VppInterface class VppTAPInterface(VppInterface): - @property def tap_id(self): """TAP id""" return self._tap_id - def __init__(self, test, tap_id=0xffffffff, mac_addr=None): + def __init__(self, test, tap_id=0xFFFFFFFF, mac_addr=None): self._test = test self._tap_id = tap_id self._mac_addr = mac_addr def get_vpp_dump(self): - dump = self._test.vapi.sw_interface_tap_v2_dump( - sw_if_index=self.sw_if_index) + dump = self._test.vapi.sw_interface_tap_v2_dump(sw_if_index=self.sw_if_index) return dump def add_vpp_config(self): reply = self._test.vapi.tap_create_v2( id=self._tap_id, use_random_mac=bool(self._mac_addr), - mac_address=self._mac_addr) + mac_address=self._mac_addr, + ) self.set_sw_if_index(reply.sw_if_index) self._test.registry.register(self, self.test.logger) diff --git a/test/vpp_dhcp.py b/test/vpp_dhcp.py index f8265a26252..eb07df2ecd7 100644 --- a/test/vpp_dhcp.py +++ b/test/vpp_dhcp.py @@ -2,7 +2,6 @@ from vpp_object import VppObject class VppDHCPProxy(VppObject): - def __init__( self, test, @@ -17,14 +16,9 @@ class VppDHCPProxy(VppObject): self._dhcp_server = dhcp_server self._dhcp_src_address = dhcp_src_address - def set_proxy( - self, - dhcp_server, - dhcp_src_address, - rx_vrf_id=0, - server_vrf_id=0): + def set_proxy(self, dhcp_server, dhcp_src_address, rx_vrf_id=0, server_vrf_id=0): if self.query_vpp_config(): - raise Exception('Vpp config present') + raise Exception("Vpp config present") self._rx_vrf_id = rx_vrf_id self._server_vrf_id = server_vrf_id self._dhcp_server = dhcp_server @@ -36,7 +30,8 @@ class VppDHCPProxy(VppObject): rx_vrf_id=self._rx_vrf_id, server_vrf_id=self._server_vrf_id, dhcp_server=self._dhcp_server, - dhcp_src_address=self._dhcp_src_address) + dhcp_src_address=self._dhcp_src_address, + ) self._test.registry.register(self, self._test.logger) def remove_vpp_config(self): @@ -45,7 +40,8 @@ class VppDHCPProxy(VppObject): server_vrf_id=self._server_vrf_id, dhcp_server=self._dhcp_server, dhcp_src_address=self._dhcp_src_address, - is_add=0) + is_add=0, + ) def get_vpp_dump(self): dump = self._test.vapi.dhcp_proxy_dump() @@ -62,17 +58,17 @@ class VppDHCPProxy(VppObject): class VppDHCPClient(VppObject): - def __init__( - self, - test, - sw_if_index, - hostname, - id=None, - want_dhcp_event=False, - set_broadcast_flag=True, - dscp=None, - pid=None): + self, + test, + sw_if_index, + hostname, + id=None, + want_dhcp_event=False, + set_broadcast_flag=True, + dscp=None, + pid=None, + ): self._test = test self._sw_if_index = sw_if_index self._hostname = hostname @@ -83,16 +79,17 @@ class VppDHCPClient(VppObject): self._pid = pid def set_client( - self, - sw_if_index, - hostname, - id=None, - want_dhcp_event=False, - set_broadcast_flag=True, - dscp=None, - pid=None): + self, + sw_if_index, + hostname, + id=None, + want_dhcp_event=False, + set_broadcast_flag=True, + dscp=None, + pid=None, + ): if self.query_vpp_config(): - raise Exception('Vpp config present') + raise Exception("Vpp config present") self._sw_if_index = sw_if_index self._hostname = hostname self._id = id @@ -102,19 +99,21 @@ class VppDHCPClient(VppObject): self._pid = pid def add_vpp_config(self): - id = self._id.encode('ascii') if self._id else None - client = {'sw_if_index': self._sw_if_index, 'hostname': self._hostname, - 'id': id, - 'want_dhcp_event': self._want_dhcp_event, - 'set_broadcast_flag': self._set_broadcast_flag, - 'dscp': self._dscp, 'pid': self._pid} + id = self._id.encode("ascii") if self._id else None + client = { + "sw_if_index": self._sw_if_index, + "hostname": self._hostname, + "id": id, + "want_dhcp_event": self._want_dhcp_event, + "set_broadcast_flag": self._set_broadcast_flag, + "dscp": self._dscp, + "pid": self._pid, + } self._test.vapi.dhcp_client_config(is_add=1, client=client) self._test.registry.register(self, self._test.logger) def remove_vpp_config(self): - client = client = { - 'sw_if_index': self._sw_if_index, - 'hostname': self._hostname} + client = client = {"sw_if_index": self._sw_if_index, "hostname": self._hostname} self._test.vapi.dhcp_client_config(client=client, is_add=0) def get_vpp_dump(self): diff --git a/test/vpp_gre_interface.py b/test/vpp_gre_interface.py index 770292e80b8..9b02488349b 100644 --- a/test/vpp_gre_interface.py +++ b/test/vpp_gre_interface.py @@ -1,4 +1,3 @@ - from vpp_interface import VppInterface import socket from vpp_papi import VppEnum @@ -9,10 +8,18 @@ class VppGreInterface(VppInterface): VPP GRE interface """ - def __init__(self, test, src_ip, dst_ip, outer_table_id=0, - type=None, mode=None, flags=0, - session=0): - """ Create VPP GRE interface """ + def __init__( + self, + test, + src_ip, + dst_ip, + outer_table_id=0, + type=None, + mode=None, + flags=0, + session=0, + ): + """Create VPP GRE interface""" super(VppGreInterface, self).__init__(test) self.t_src = src_ip self.t_dst = dst_ip @@ -21,25 +28,25 @@ class VppGreInterface(VppInterface): self.t_flags = flags self.t_type = type if not self.t_type: - self.t_type = (VppEnum.vl_api_gre_tunnel_type_t. - GRE_API_TUNNEL_TYPE_L3) + self.t_type = VppEnum.vl_api_gre_tunnel_type_t.GRE_API_TUNNEL_TYPE_L3 self.t_mode = mode if not self.t_mode: - self.t_mode = (VppEnum.vl_api_tunnel_mode_t. - TUNNEL_API_MODE_P2P) + self.t_mode = VppEnum.vl_api_tunnel_mode_t.TUNNEL_API_MODE_P2P def add_vpp_config(self): r = self.test.vapi.gre_tunnel_add_del( is_add=1, tunnel={ - 'src': self.t_src, - 'dst': self.t_dst, - 'outer_table_id': self.t_outer_table, - 'instance': 0xffffffff, - 'type': self.t_type, - 'mode': self.t_mode, - 'flags': self.t_flags, - 'session_id': self.t_session}) + "src": self.t_src, + "dst": self.t_dst, + "outer_table_id": self.t_outer_table, + "instance": 0xFFFFFFFF, + "type": self.t_type, + "mode": self.t_mode, + "flags": self.t_flags, + "session_id": self.t_session, + }, + ) self.set_sw_if_index(r.sw_if_index) self.generate_remote_hosts() self.test.registry.register(self, self.test.logger) @@ -50,21 +57,22 @@ class VppGreInterface(VppInterface): self.test.vapi.gre_tunnel_add_del( is_add=0, tunnel={ - 'src': self.t_src, - 'dst': self.t_dst, - 'outer_table_id': self.t_outer_table, - 'instance': 0xffffffff, - 'type': self.t_type, - 'mode': self.t_mode, - 'flags': self.t_flags, - 'session_id': self.t_session}) + "src": self.t_src, + "dst": self.t_dst, + "outer_table_id": self.t_outer_table, + "instance": 0xFFFFFFFF, + "type": self.t_type, + "mode": self.t_mode, + "flags": self.t_flags, + "session_id": self.t_session, + }, + ) def object_id(self): return "gre-%d" % self.sw_if_index def query_vpp_config(self): - return (self.test.vapi.gre_tunnel_dump( - sw_if_index=self._sw_if_index)) + return self.test.vapi.gre_tunnel_dump(sw_if_index=self._sw_if_index) @property def remote_ip(self): diff --git a/test/vpp_igmp.py b/test/vpp_igmp.py index 8f78a9b909a..da2beb0605d 100644 --- a/test/vpp_igmp.py +++ b/test/vpp_igmp.py @@ -1,4 +1,3 @@ - from vpp_object import VppObject import socket @@ -15,22 +14,28 @@ class IGMP_FILTER: def find_igmp_state(states, itf, gaddr, saddr): for s in states: - if s.sw_if_index == itf.sw_if_index and \ - str(s.gaddr) == gaddr and str(s.saddr) == saddr: + if ( + s.sw_if_index == itf.sw_if_index + and str(s.gaddr) == gaddr + and str(s.saddr) == saddr + ): return True return False def wait_for_igmp_event(test, timeout, itf, gaddr, saddr, ff): ev = test.vapi.wait_for_event(timeout, "igmp_event") - if ev.sw_if_index == itf.sw_if_index and \ - str(ev.gaddr) == gaddr and str(ev.saddr) == saddr and \ - ev.filter == ff: + if ( + ev.sw_if_index == itf.sw_if_index + and str(ev.gaddr) == gaddr + and str(ev.saddr) == saddr + and ev.filter == ff + ): return True return False -class IgmpSG(): +class IgmpSG: def __init__(self, gaddr, saddrs): self.gaddr = gaddr self.gaddr_p = socket.inet_pton(socket.AF_INET, gaddr) @@ -43,7 +48,7 @@ class IgmpSG(): self.saddrs_encoded.append(ss) -class IgmpRecord(): +class IgmpRecord: def __init__(self, sg, type): self.sg = sg self.type = type @@ -58,15 +63,11 @@ class VppHostState(VppObject): def add_vpp_config(self): self._test.vapi.igmp_listen( - self.filter, self.sw_if_index, - self.sg.saddrs_encoded, self.sg.gaddr_p) + self.filter, self.sw_if_index, self.sg.saddrs_encoded, self.sg.gaddr_p + ) def remove_vpp_config(self): - self._test.vapi.igmp_listen( - self.filter, - self.sw_if_index, - [], - self.sg.gaddr_p) + self._test.vapi.igmp_listen(self.filter, self.sw_if_index, [], self.sg.gaddr_p) def object_id(self): return "%s:%d" % (self.sg, self.sw_if_index) diff --git a/test/vpp_ikev2.py b/test/vpp_ikev2.py index de2081268ee..b9a6d8c2f7d 100644 --- a/test/vpp_ikev2.py +++ b/test/vpp_ikev2.py @@ -4,24 +4,24 @@ from vpp_papi import VppEnum class AuthMethod: - v = {'rsa-sig': 1, - 'shared-key': 2} + v = {"rsa-sig": 1, "shared-key": 2} @staticmethod - def value(key): return AuthMethod.v[key] + def value(key): + return AuthMethod.v[key] class IDType: - v = {'ip4-addr': 1, - 'fqdn': 2, - 'ip6-addr': 5} + v = {"ip4-addr": 1, "fqdn": 2, "ip6-addr": 5} @staticmethod - def value(key): return IDType.v[key] + def value(key): + return IDType.v[key] class Profile(VppObject): - """ IKEv2 profile """ + """IKEv2 profile""" + def __init__(self, test, profile_name): self.test = test self.vapi = test.vapi @@ -38,49 +38,49 @@ class Profile(VppObject): elif isinstance(method, str): m = AuthMethod.value(method) else: - raise Exception('unsupported type {}'.format(method)) - self.auth = {'auth_method': m, - 'data': data, - 'is_hex': is_hex} + raise Exception("unsupported type {}".format(method)) + self.auth = {"auth_method": m, "data": data, "is_hex": is_hex} def add_local_id(self, id_type, data): if isinstance(id_type, str): t = IDType.value(id_type) - self.local_id = {'id_type': t, - 'data': data, - 'is_local': True} + self.local_id = {"id_type": t, "data": data, "is_local": True} def add_remote_id(self, id_type, data): if isinstance(id_type, str): t = IDType.value(id_type) - self.remote_id = {'id_type': t, - 'data': data, - 'is_local': False} + self.remote_id = {"id_type": t, "data": data, "is_local": False} - def add_local_ts(self, start_addr, end_addr, start_port=0, end_port=0xffff, - proto=0, is_ip4=True): + def add_local_ts( + self, start_addr, end_addr, start_port=0, end_port=0xFFFF, proto=0, is_ip4=True + ): self.ts_is_ip4 = is_ip4 - self.local_ts = {'is_local': True, - 'protocol_id': proto, - 'start_port': start_port, - 'end_port': end_port, - 'start_addr': start_addr, - 'end_addr': end_addr} - - def add_remote_ts(self, start_addr, end_addr, start_port=0, - end_port=0xffff, proto=0): + self.local_ts = { + "is_local": True, + "protocol_id": proto, + "start_port": start_port, + "end_port": end_port, + "start_addr": start_addr, + "end_addr": end_addr, + } + + def add_remote_ts( + self, start_addr, end_addr, start_port=0, end_port=0xFFFF, proto=0 + ): try: IPv4Address(start_addr) is_ip4 = True except AddressValueError: is_ip4 = False self.ts_is_ip4 = is_ip4 - self.remote_ts = {'is_local': False, - 'protocol_id': proto, - 'start_port': start_port, - 'end_port': end_port, - 'start_addr': start_addr, - 'end_addr': end_addr} + self.remote_ts = { + "is_local": False, + "protocol_id": proto, + "start_port": start_port, + "end_port": end_port, + "start_addr": start_addr, + "end_addr": end_addr, + } def add_responder_hostname(self, hn): self.responder_hostname = hn @@ -101,72 +101,78 @@ class Profile(VppObject): self.lifetime_data = data def set_ipsec_over_udp_port(self, port): - self.ipsec_udp_port = {'is_set': 1, - 'port': port} + self.ipsec_udp_port = {"is_set": 1, "port": port} def set_tunnel_interface(self, sw_if_index): self.tun_itf = sw_if_index def object_id(self): - return 'ikev2-profile-%s' % self.profile_name + return "ikev2-profile-%s" % self.profile_name def remove_vpp_config(self): self.vapi.ikev2_profile_add_del(name=self.profile_name, is_add=False) def add_vpp_config(self): self.vapi.ikev2_profile_add_del(name=self.profile_name, is_add=True) - if hasattr(self, 'auth'): - self.vapi.ikev2_profile_set_auth(name=self.profile_name, - data_len=len(self.auth['data']), - **self.auth) - if hasattr(self, 'local_id'): - self.vapi.ikev2_profile_set_id(name=self.profile_name, - data_len=len(self.local_id - ['data']), - **self.local_id) - if hasattr(self, 'remote_id'): - self.vapi.ikev2_profile_set_id(name=self.profile_name, - data_len=len(self.remote_id - ['data']), - **self.remote_id) - if hasattr(self, 'local_ts'): - self.vapi.ikev2_profile_set_ts(name=self.profile_name, - ts=self.local_ts) - - if hasattr(self, 'remote_ts'): - self.vapi.ikev2_profile_set_ts(name=self.profile_name, - ts=self.remote_ts) - - if hasattr(self, 'responder'): - self.vapi.ikev2_set_responder(name=self.profile_name, - responder=self.responder) - - if hasattr(self, 'responder_hostname'): + if hasattr(self, "auth"): + self.vapi.ikev2_profile_set_auth( + name=self.profile_name, data_len=len(self.auth["data"]), **self.auth + ) + if hasattr(self, "local_id"): + self.vapi.ikev2_profile_set_id( + name=self.profile_name, + data_len=len(self.local_id["data"]), + **self.local_id, + ) + if hasattr(self, "remote_id"): + self.vapi.ikev2_profile_set_id( + name=self.profile_name, + data_len=len(self.remote_id["data"]), + **self.remote_id, + ) + if hasattr(self, "local_ts"): + self.vapi.ikev2_profile_set_ts(name=self.profile_name, ts=self.local_ts) + + if hasattr(self, "remote_ts"): + self.vapi.ikev2_profile_set_ts(name=self.profile_name, ts=self.remote_ts) + + if hasattr(self, "responder"): + self.vapi.ikev2_set_responder( + name=self.profile_name, responder=self.responder + ) + + if hasattr(self, "responder_hostname"): print(self.responder_hostname) - self.vapi.ikev2_set_responder_hostname(name=self.profile_name, - **self.responder_hostname) + self.vapi.ikev2_set_responder_hostname( + name=self.profile_name, **self.responder_hostname + ) - if hasattr(self, 'ike_transforms'): - self.vapi.ikev2_set_ike_transforms(name=self.profile_name, - tr=self.ike_transforms) + if hasattr(self, "ike_transforms"): + self.vapi.ikev2_set_ike_transforms( + name=self.profile_name, tr=self.ike_transforms + ) - if hasattr(self, 'esp_transforms'): - self.vapi.ikev2_set_esp_transforms(name=self.profile_name, - tr=self.esp_transforms) + if hasattr(self, "esp_transforms"): + self.vapi.ikev2_set_esp_transforms( + name=self.profile_name, tr=self.esp_transforms + ) if self.udp_encap: self.vapi.ikev2_profile_set_udp_encap(name=self.profile_name) - if hasattr(self, 'lifetime_data'): - self.vapi.ikev2_set_sa_lifetime(name=self.profile_name, - **self.lifetime_data) - - if hasattr(self, 'ipsec_udp_port'): - self.vapi.ikev2_profile_set_ipsec_udp_port(name=self.profile_name, - **self.ipsec_udp_port) - if hasattr(self, 'tun_itf'): - self.vapi.ikev2_set_tunnel_interface(name=self.profile_name, - sw_if_index=self.tun_itf) + if hasattr(self, "lifetime_data"): + self.vapi.ikev2_set_sa_lifetime( + name=self.profile_name, **self.lifetime_data + ) + + if hasattr(self, "ipsec_udp_port"): + self.vapi.ikev2_profile_set_ipsec_udp_port( + name=self.profile_name, **self.ipsec_udp_port + ) + if hasattr(self, "tun_itf"): + self.vapi.ikev2_set_tunnel_interface( + name=self.profile_name, sw_if_index=self.tun_itf + ) if not self.natt: self.vapi.ikev2_profile_disable_natt(name=self.profile_name) diff --git a/test/vpp_interface.py b/test/vpp_interface.py index b7c830b06fd..cee6ea4f080 100644 --- a/test/vpp_interface.py +++ b/test/vpp_interface.py @@ -49,7 +49,7 @@ class VppInterface(metaclass=abc.ABCMeta): @property def local_ip4_prefix_len(self): - """Local IPv4 prefix length """ + """Local IPv4 prefix length""" return self._local_ip4_len @local_ip4_prefix_len.setter @@ -58,8 +58,8 @@ class VppInterface(metaclass=abc.ABCMeta): @property def local_ip4_prefix(self): - """Local IPv4 prefix """ - return ("%s/%d" % (self._local_ip4, self._local_ip4_len)) + """Local IPv4 prefix""" + return "%s/%d" % (self._local_ip4, self._local_ip4_len) @property def remote_ip4(self): @@ -77,7 +77,7 @@ class VppInterface(metaclass=abc.ABCMeta): @property def local_ip6_prefix_len(self): - """Local IPv6 prefix length """ + """Local IPv6 prefix length""" return self._local_ip6_len @local_ip6_prefix_len.setter @@ -86,8 +86,8 @@ class VppInterface(metaclass=abc.ABCMeta): @property def local_ip6_prefix(self): - """Local IPv4 prefix """ - return ("%s/%d" % (self._local_ip6, self._local_ip6_len)) + """Local IPv4 prefix""" + return "%s/%d" % (self._local_ip6, self._local_ip6_len) @property def remote_ip6(self): @@ -100,7 +100,9 @@ class VppInterface(metaclass=abc.ABCMeta): if not self._local_ip6_ll: self._local_ip6_ll = str( self.test.vapi.sw_interface_ip6_get_link_local_address( - self.sw_if_index).ip) + self.sw_if_index + ).ip + ) return self._local_ip6_ll @property @@ -173,8 +175,7 @@ class VppInterface(metaclass=abc.ABCMeta): self._hosts_by_mac = {} self._hosts_by_ip4 = {} self._hosts_by_ip6 = {} - for i in range( - 2, count + 2): # 0: network address, 1: local vpp address + for i in range(2, count + 2): # 0: network address, 1: local vpp address mac = "02:%02x:00:00:ff:%02x" % (self.sw_if_index, i) ip4 = "172.16.%u.%u" % (self.sw_if_index, i) ip6 = "fd01:%x::%x" % (self.sw_if_index, i) @@ -196,14 +197,12 @@ class VppInterface(metaclass=abc.ABCMeta): def set_mac(self, mac): self._local_mac = str(mac) - self.test.vapi.sw_interface_set_mac_address( - self.sw_if_index, mac.packed) + self.test.vapi.sw_interface_set_mac_address(self.sw_if_index, mac.packed) return self def set_sw_if_index(self, sw_if_index): if sw_if_index > 255: - raise RuntimeError("Don't support sw_if_index values " - "greater than 255.") + raise RuntimeError("Don't support sw_if_index values greater than 255.") self._sw_if_index = sw_if_index self.generate_remote_hosts() @@ -220,10 +219,14 @@ class VppInterface(metaclass=abc.ABCMeta): self.has_ip6_config = False self.ip6_table_id = 0 - self._local_addr = {socket.AF_INET: self.local_ip4, - socket.AF_INET6: self.local_ip6} - self._remote_addr = {socket.AF_INET: self.remote_ip4, - socket.AF_INET6: self.remote_ip6} + self._local_addr = { + socket.AF_INET: self.local_ip4, + socket.AF_INET6: self.local_ip6, + } + self._remote_addr = { + socket.AF_INET: self.remote_ip4, + socket.AF_INET6: self.remote_ip6, + } r = self.test.vapi.sw_interface_dump(sw_if_index=self.sw_if_index) for intf in r: @@ -235,15 +238,16 @@ class VppInterface(metaclass=abc.ABCMeta): else: raise Exception( "Could not find interface with sw_if_index %d " - "in interface dump %s" % - (self.sw_if_index, moves.reprlib.repr(r))) + "in interface dump %s" % (self.sw_if_index, moves.reprlib.repr(r)) + ) self._remote_ip6_ll = mk_ll_addr(self.remote_mac) self._local_ip6_ll = None def config_ip4(self): """Configure IPv4 address on the VPP interface.""" self.test.vapi.sw_interface_add_del_address( - sw_if_index=self.sw_if_index, prefix=self.local_ip4_prefix) + sw_if_index=self.sw_if_index, prefix=self.local_ip4_prefix + ) self.has_ip4_config = True return self @@ -252,8 +256,8 @@ class VppInterface(metaclass=abc.ABCMeta): try: if self.has_ip4_config: self.test.vapi.sw_interface_add_del_address( - sw_if_index=self.sw_if_index, - prefix=self.local_ip4_prefix, is_add=0) + sw_if_index=self.sw_if_index, prefix=self.local_ip4_prefix, is_add=0 + ) except AttributeError: self.has_ip4_config = False self.has_ip4_config = False @@ -265,15 +269,14 @@ class VppInterface(metaclass=abc.ABCMeta): :param vrf_id: The FIB table / VRF ID. (Default value = 0) """ for host in self._remote_hosts: - self.test.vapi.ip_neighbor_add_del(self.sw_if_index, - host.mac, - host.ip4) + self.test.vapi.ip_neighbor_add_del(self.sw_if_index, host.mac, host.ip4) return self def config_ip6(self): """Configure IPv6 address on the VPP interface.""" self.test.vapi.sw_interface_add_del_address( - sw_if_index=self.sw_if_index, prefix=self.local_ip6_prefix) + sw_if_index=self.sw_if_index, prefix=self.local_ip6_prefix + ) self.has_ip6_config = True return self @@ -282,8 +285,8 @@ class VppInterface(metaclass=abc.ABCMeta): try: if self.has_ip6_config: self.test.vapi.sw_interface_add_del_address( - sw_if_index=self.sw_if_index, - prefix=self.local_ip6_prefix, is_add=0) + sw_if_index=self.sw_if_index, prefix=self.local_ip6_prefix, is_add=0 + ) except AttributeError: self.has_ip6_config = False self.has_ip6_config = False @@ -295,9 +298,7 @@ class VppInterface(metaclass=abc.ABCMeta): :param vrf_id: The FIB table / VRF ID. (Default value = 0) """ for host in self._remote_hosts: - self.test.vapi.ip_neighbor_add_del(self.sw_if_index, - host.mac, - host.ip6) + self.test.vapi.ip_neighbor_add_del(self.sw_if_index, host.mac, host.ip6) def unconfig(self): """Unconfigure IPv6 and IPv4 address on the VPP interface.""" @@ -311,8 +312,7 @@ class VppInterface(metaclass=abc.ABCMeta): .. note:: Must be called before configuring IP4 addresses. """ self.ip4_table_id = table_id - self.test.vapi.sw_interface_set_table( - self.sw_if_index, 0, self.ip4_table_id) + self.test.vapi.sw_interface_set_table(self.sw_if_index, 0, self.ip4_table_id) return self def set_table_ip6(self, table_id): @@ -321,15 +321,14 @@ class VppInterface(metaclass=abc.ABCMeta): .. note:: Must be called before configuring IP6 addresses. """ self.ip6_table_id = table_id - self.test.vapi.sw_interface_set_table( - self.sw_if_index, 1, self.ip6_table_id) + self.test.vapi.sw_interface_set_table(self.sw_if_index, 1, self.ip6_table_id) return self def disable_ipv6_ra(self): """Configure IPv6 RA suppress on the VPP interface.""" self.test.vapi.sw_interface_ip6nd_ra_config( - sw_if_index=self.sw_if_index, - suppress=1) + sw_if_index=self.sw_if_index, suppress=1 + ) return self def ip6_ra_config(self, no=0, suppress=0, send_unicast=0): @@ -338,11 +337,13 @@ class VppInterface(metaclass=abc.ABCMeta): sw_if_index=self.sw_if_index, is_no=no, suppress=suppress, - send_unicast=send_unicast) + send_unicast=send_unicast, + ) return self - def ip6_ra_prefix(self, prefix, is_no=0, - off_link=0, no_autoconfig=0, use_default=0): + def ip6_ra_prefix( + self, prefix, is_no=0, off_link=0, no_autoconfig=0, use_default=0 + ): """Configure IPv6 RA suppress on the VPP interface. prefix can be a string in the format of '<address>/<length_in_bits>' @@ -352,21 +353,23 @@ class VppInterface(metaclass=abc.ABCMeta): sw_if_index=self.sw_if_index, prefix=prefix, use_default=use_default, - off_link=off_link, no_autoconfig=no_autoconfig, - is_no=is_no) + off_link=off_link, + no_autoconfig=no_autoconfig, + is_no=is_no, + ) return self def admin_up(self): """Put interface ADMIN-UP.""" self.test.vapi.sw_interface_set_flags( self.sw_if_index, - flags=VppEnum.vl_api_if_status_flags_t.IF_STATUS_API_FLAG_ADMIN_UP) + flags=VppEnum.vl_api_if_status_flags_t.IF_STATUS_API_FLAG_ADMIN_UP, + ) return self def admin_down(self): """Put interface ADMIN-down.""" - self.test.vapi.sw_interface_set_flags(self.sw_if_index, - flags=0) + self.test.vapi.sw_interface_set_flags(self.sw_if_index, flags=0) return self def link_up(self): @@ -379,14 +382,12 @@ class VppInterface(metaclass=abc.ABCMeta): def ip6_enable(self): """IPv6 Enable interface""" - self.test.vapi.sw_interface_ip6_enable_disable(self.sw_if_index, - enable=1) + self.test.vapi.sw_interface_ip6_enable_disable(self.sw_if_index, enable=1) return self def ip6_disable(self): """Put interface ADMIN-DOWN.""" - self.test.vapi.sw_interface_ip6_enable_disable(self.sw_if_index, - enable=0) + self.test.vapi.sw_interface_ip6_enable_disable(self.sw_if_index, enable=0) return self def add_sub_if(self, sub_if): @@ -394,7 +395,7 @@ class VppInterface(metaclass=abc.ABCMeta): :param sub_if: sub-interface """ - if not hasattr(self, 'sub_if'): + if not hasattr(self, "sub_if"): self.sub_if = sub_if else: if isinstance(self.sub_if, list): @@ -415,30 +416,30 @@ class VppInterface(metaclass=abc.ABCMeta): def is_ip4_entry_in_fib_dump(self, dump): for i in dump: - n = IPv4Network(text_type("%s/%d" % (self.local_ip4, - self.local_ip4_prefix_len))) - if i.route.prefix == n and \ - i.route.table_id == self.ip4_table_id: + n = IPv4Network( + text_type("%s/%d" % (self.local_ip4, self.local_ip4_prefix_len)) + ) + if i.route.prefix == n and i.route.table_id == self.ip4_table_id: return True return False def set_unnumbered(self, ip_sw_if_index): - """ Set the interface to unnumbered via ip_sw_if_index """ - self.test.vapi.sw_interface_set_unnumbered(ip_sw_if_index, - self.sw_if_index) + """Set the interface to unnumbered via ip_sw_if_index""" + self.test.vapi.sw_interface_set_unnumbered(ip_sw_if_index, self.sw_if_index) return self def unset_unnumbered(self, ip_sw_if_index): - """ Unset the interface to unnumbered via ip_sw_if_index """ - self.test.vapi.sw_interface_set_unnumbered(ip_sw_if_index, - self.sw_if_index, is_add=0) + """Unset the interface to unnumbered via ip_sw_if_index""" + self.test.vapi.sw_interface_set_unnumbered( + ip_sw_if_index, self.sw_if_index, is_add=0 + ) return self def set_proxy_arp(self, enable=1): - """ Set the interface to enable/disable Proxy ARP """ + """Set the interface to enable/disable Proxy ARP""" self.test.vapi.proxy_arp_intfc_enable_disable( - sw_if_index=self.sw_if_index, - enable=enable) + sw_if_index=self.sw_if_index, enable=enable + ) return self def query_vpp_config(self): @@ -447,8 +448,10 @@ class VppInterface(metaclass=abc.ABCMeta): def get_interface_config_from_dump(self, dump): for i in dump: - if i.interface_name.rstrip(' \t\r\n\0') == self.name and \ - i.sw_if_index == self.sw_if_index: + if ( + i.interface_name.rstrip(" \t\r\n\0") == self.name + and i.sw_if_index == self.sw_if_index + ): return i else: return None @@ -456,34 +459,25 @@ class VppInterface(metaclass=abc.ABCMeta): def is_interface_config_in_dump(self, dump): return self.get_interface_config_from_dump(dump) is not None - def assert_interface_state(self, admin_up_down, link_up_down, - expect_event=False): + def assert_interface_state(self, admin_up_down, link_up_down, expect_event=False): if expect_event: - event = self.test.vapi.wait_for_event(timeout=1, - name='sw_interface_event') - self.test.assert_equal(event.sw_if_index, self.sw_if_index, - "sw_if_index") - self.test.assert_equal((event.flags & 1), admin_up_down, - "admin state") - self.test.assert_equal((event.flags & 2), link_up_down, - "link state") + event = self.test.vapi.wait_for_event(timeout=1, name="sw_interface_event") + self.test.assert_equal(event.sw_if_index, self.sw_if_index, "sw_if_index") + self.test.assert_equal((event.flags & 1), admin_up_down, "admin state") + self.test.assert_equal((event.flags & 2), link_up_down, "link state") dump = self.test.vapi.sw_interface_dump() if_state = self.get_interface_config_from_dump(dump) - self.test.assert_equal((if_state.flags & 1), admin_up_down, - "admin state") - self.test.assert_equal((if_state.flags & 2), link_up_down, - "link state") + self.test.assert_equal((if_state.flags & 1), admin_up_down, "admin state") + self.test.assert_equal((if_state.flags & 2), link_up_down, "link state") def __str__(self): return self.name def get_rx_stats(self): - return (self.test.statistics["/if/rx"] - [:, self.sw_if_index].sum_packets()) + return self.test.statistics["/if/rx"][:, self.sw_if_index].sum_packets() def get_tx_stats(self): - return (self.test.statistics["/if/tx"] - [:, self.sw_if_index].sum_packets()) + return self.test.statistics["/if/tx"][:, self.sw_if_index].sum_packets() def set_l3_mtu(self, mtu): self.test.vapi.sw_interface_set_mtu(self.sw_if_index, [mtu, 0, 0, 0]) diff --git a/test/vpp_ip.py b/test/vpp_ip.py index 48b6b9d2da6..24e7c19652a 100644 --- a/test/vpp_ip.py +++ b/test/vpp_ip.py @@ -8,6 +8,7 @@ from ipaddress import ip_address from socket import AF_INET, AF_INET6 from vpp_papi import VppEnum from vpp_object import VppObject + try: text_type = unicode except NameError: @@ -25,7 +26,7 @@ class DpoProto: DPO_PROTO_NSH = 5 -INVALID_INDEX = 0xffffffff +INVALID_INDEX = 0xFFFFFFFF def get_dpo_proto(addr): @@ -35,16 +36,16 @@ def get_dpo_proto(addr): return DpoProto.DPO_PROTO_IP4 -class VppIpAddressUnion(): +class VppIpAddressUnion: def __init__(self, addr): self.addr = addr self.ip_addr = ip_address(text_type(self.addr)) def encode(self): if self.version == 6: - return {'ip6': self.ip_addr} + return {"ip6": self.ip_addr} else: - return {'ip4': self.ip_addr} + return {"ip4": self.ip_addr} @property def version(self): @@ -72,9 +73,11 @@ class VppIpAddressUnion(): else: return self.ip_addr == other.ip6 else: - raise Exception("Comparing VppIpAddressUnions:%s" - " with incomparable type: %s", - self, other) + raise Exception( + "Comparing VppIpAddressUnions:%s with incomparable type: %s", + self, + other, + ) def __ne__(self, other): return not (self == other) @@ -83,26 +86,22 @@ class VppIpAddressUnion(): return str(self.ip_addr) -class VppIpMPrefix(): +class VppIpMPrefix: def __init__(self, saddr, gaddr, glen): self.saddr = saddr self.gaddr = gaddr self.glen = glen - if ip_address(self.saddr).version != \ - ip_address(self.gaddr).version: - raise ValueError('Source and group addresses must be of the ' - 'same address family.') + if ip_address(self.saddr).version != ip_address(self.gaddr).version: + raise ValueError( + "Source and group addresses must be of the same address family." + ) def encode(self): return { - 'af': ip_address(self.gaddr).vapi_af, - 'grp_address': { - ip_address(self.gaddr).vapi_af_name: self.gaddr - }, - 'src_address': { - ip_address(self.saddr).vapi_af_name: self.saddr - }, - 'grp_address_length': self.glen, + "af": ip_address(self.gaddr).vapi_af, + "grp_address": {ip_address(self.gaddr).vapi_af_name: self.gaddr}, + "src_address": {ip_address(self.saddr).vapi_af_name: self.saddr}, + "grp_address_length": self.glen, } @property @@ -118,21 +117,29 @@ class VppIpMPrefix(): def __eq__(self, other): if isinstance(other, self.__class__): - return (self.glen == other.glen and - self.saddr == other.gaddr and - self.saddr == other.saddr) - elif (hasattr(other, "grp_address_length") and - hasattr(other, "grp_address") and - hasattr(other, "src_address")): + return ( + self.glen == other.glen + and self.saddr == other.gaddr + and self.saddr == other.saddr + ) + elif ( + hasattr(other, "grp_address_length") + and hasattr(other, "grp_address") + and hasattr(other, "src_address") + ): # vl_api_mprefix_t if 4 == self.version: - return (self.glen == other.grp_address_length and - self.gaddr == str(other.grp_address.ip4) and - self.saddr == str(other.src_address.ip4)) + return ( + self.glen == other.grp_address_length + and self.gaddr == str(other.grp_address.ip4) + and self.saddr == str(other.src_address.ip4) + ) else: - return (self.glen == other.grp_address_length and - self.gaddr == str(other.grp_address.ip6) and - self.saddr == str(other.src_address.ip6)) + return ( + self.glen == other.grp_address_length + and self.gaddr == str(other.grp_address.ip6) + and self.saddr == str(other.src_address.ip6) + ) return NotImplemented @@ -143,12 +150,14 @@ class VppIpPuntPolicer(VppObject): self._is_ip6 = is_ip6 def add_vpp_config(self): - self._test.vapi.ip_punt_police(policer_index=self._policer_index, - is_ip6=self._is_ip6, is_add=True) + self._test.vapi.ip_punt_police( + policer_index=self._policer_index, is_ip6=self._is_ip6, is_add=True + ) def remove_vpp_config(self): - self._test.vapi.ip_punt_police(policer_index=self._policer_index, - is_ip6=self._is_ip6, is_add=False) + self._test.vapi.ip_punt_police( + policer_index=self._policer_index, is_ip6=self._is_ip6, is_add=False + ) def query_vpp_config(self): NotImplemented @@ -162,8 +171,11 @@ class VppIpPuntRedirect(VppObject): self._nh_addr = ip_address(nh_addr) def encode(self): - return {"rx_sw_if_index": self._rx_index, - "tx_sw_if_index": self._tx_index, "nh": self._nh_addr} + return { + "rx_sw_if_index": self._rx_index, + "tx_sw_if_index": self._tx_index, + "nh": self._nh_addr, + } def add_vpp_config(self): self._test.vapi.ip_punt_redirect(punt=self.encode(), is_add=True) @@ -176,7 +188,8 @@ class VppIpPuntRedirect(VppObject): def get_vpp_config(self): is_ipv6 = True if self._nh_addr.version == 6 else False return self._test.vapi.ip_punt_redirect_dump( - sw_if_index=self._rx_index, is_ipv6=is_ipv6) + sw_if_index=self._rx_index, is_ipv6=is_ipv6 + ) def query_vpp_config(self): if self.get_vpp_config(): @@ -192,39 +205,38 @@ class VppIpPathMtu(VppObject): self.table_id = table_id def add_vpp_config(self): - self._test.vapi.ip_path_mtu_update(pmtu={'nh': self.nh, - 'table_id': self.table_id, - 'path_mtu': self.pmtu}) + self._test.vapi.ip_path_mtu_update( + pmtu={"nh": self.nh, "table_id": self.table_id, "path_mtu": self.pmtu} + ) self._test.registry.register(self, self._test.logger) return self def modify(self, pmtu): self.pmtu = pmtu - self._test.vapi.ip_path_mtu_update(pmtu={'nh': self.nh, - 'table_id': self.table_id, - 'path_mtu': self.pmtu}) + self._test.vapi.ip_path_mtu_update( + pmtu={"nh": self.nh, "table_id": self.table_id, "path_mtu": self.pmtu} + ) return self def remove_vpp_config(self): - self._test.vapi.ip_path_mtu_update(pmtu={'nh': self.nh, - 'table_id': self.table_id, - 'path_mtu': 0}) + self._test.vapi.ip_path_mtu_update( + pmtu={"nh": self.nh, "table_id": self.table_id, "path_mtu": 0} + ) def query_vpp_config(self): - ds = list(self._test.vapi.vpp.details_iter( - self._test.vapi.ip_path_mtu_get)) + ds = list(self._test.vapi.vpp.details_iter(self._test.vapi.ip_path_mtu_get)) for d in ds: - if self.nh == str(d.pmtu.nh) \ - and self.table_id == d.pmtu.table_id \ - and self.pmtu == d.pmtu.path_mtu: + if ( + self.nh == str(d.pmtu.nh) + and self.table_id == d.pmtu.table_id + and self.pmtu == d.pmtu.path_mtu + ): return True return False def object_id(self): - return ("ip-path-mtu-%d-%s-%d" % (self.table_id, - self.nh, - self.pmtu)) + return "ip-path-mtu-%d-%s-%d" % (self.table_id, self.nh, self.pmtu) def __str__(self): return self.object_id() diff --git a/test/vpp_ip_route.py b/test/vpp_ip_route.py index f5e5a8801e4..06a963cfd88 100644 --- a/test/vpp_ip_route.py +++ b/test/vpp_ip_route.py @@ -5,13 +5,12 @@ """ from vpp_object import VppObject -from vpp_ip import DpoProto, INVALID_INDEX, VppIpAddressUnion, \ - VppIpMPrefix +from vpp_ip import DpoProto, INVALID_INDEX, VppIpAddressUnion, VppIpMPrefix from ipaddress import ip_network, ip_address, IPv4Network, IPv6Network from vpp_papi_exceptions import UnexpectedApiReturnValueError # from vnet/vnet/mpls/mpls_types.h -MPLS_IETF_MAX_LABEL = 0xfffff +MPLS_IETF_MAX_LABEL = 0xFFFFF MPLS_LABEL_INVALID = MPLS_IETF_MAX_LABEL + 1 try: @@ -85,8 +84,7 @@ def find_route(test, addr, len, table_id=0, sw_if_index=None): routes = test.vapi.ip_route_dump(table_id, True) for e in routes: - if table_id == e.route.table_id \ - and str(e.route.prefix) == str(prefix): + if table_id == e.route.table_id and str(e.route.prefix) == str(prefix): if not sw_if_index: return True else: @@ -95,15 +93,14 @@ def find_route(test, addr, len, table_id=0, sw_if_index=None): if e.route.n_paths != 1: return False else: - return (e.route.paths[0].sw_if_index == sw_if_index) + return e.route.paths[0].sw_if_index == sw_if_index return False def find_route_in_dump(dump, route, table): for r in dump: - if table.table_id == r.route.table_id \ - and route.prefix == r.route.prefix: + if table.table_id == r.route.table_id and route.prefix == r.route.prefix: if len(route.paths) == r.route.n_paths: return True return False @@ -111,17 +108,13 @@ def find_route_in_dump(dump, route, table): def find_mroute_in_dump(dump, route, table): for r in dump: - if table.table_id == r.route.table_id \ - and route.prefix == r.route.prefix: + if table.table_id == r.route.table_id and route.prefix == r.route.prefix: return True return False -def find_mroute(test, grp_addr, src_addr, grp_addr_len, - table_id=0): - ip_mprefix = VppIpMPrefix(text_type(src_addr), - text_type(grp_addr), - grp_addr_len) +def find_mroute(test, grp_addr, src_addr, grp_addr_len, table_id=0): + ip_mprefix = VppIpMPrefix(text_type(src_addr), text_type(grp_addr), grp_addr_len) if 4 == ip_mprefix.version: routes = test.vapi.ip_mroute_dump(table_id, False) @@ -137,16 +130,18 @@ def find_mroute(test, grp_addr, src_addr, grp_addr_len, def find_mpls_route(test, table_id, label, eos_bit, paths=None): dump = test.vapi.mpls_route_dump(table_id) for e in dump: - if label == e.mr_route.mr_label \ - and eos_bit == e.mr_route.mr_eos \ - and table_id == e.mr_route.mr_table_id: + if ( + label == e.mr_route.mr_label + and eos_bit == e.mr_route.mr_eos + and table_id == e.mr_route.mr_table_id + ): if not paths: return True else: - if (len(paths) != len(e.mr_route.mr_paths)): + if len(paths) != len(e.mr_route.mr_paths): return False for i in range(len(paths)): - if (paths[i] != e.mr_route.mr_paths[i]): + if paths[i] != e.mr_route.mr_paths[i]: return False return True return False @@ -156,54 +151,49 @@ def fib_interface_ip_prefix(test, addr, len, sw_if_index): # can't use python net here since we need the host bits in the prefix prefix = "%s/%d" % (addr, len) addrs = test.vapi.ip_address_dump( - sw_if_index, - is_ipv6=(6 == ip_address(addr).version)) + sw_if_index, is_ipv6=(6 == ip_address(addr).version) + ) for a in addrs: - if a.sw_if_index == sw_if_index and \ - str(a.prefix) == prefix: + if a.sw_if_index == sw_if_index and str(a.prefix) == prefix: return True return False class VppIpTable(VppObject): - - def __init__(self, - test, - table_id, - is_ip6=0, - register=True): + def __init__(self, test, table_id, is_ip6=0, register=True): self._test = test self.table_id = table_id self.is_ip6 = is_ip6 self.register = register def add_vpp_config(self): - self._test.vapi.ip_table_add_del(is_add=1, - table={'is_ip6': self.is_ip6, - 'table_id': self.table_id}) + self._test.vapi.ip_table_add_del( + is_add=1, table={"is_ip6": self.is_ip6, "table_id": self.table_id} + ) if self.register: self._test.registry.register(self, self._test.logger) return self def remove_vpp_config(self): - self._test.vapi.ip_table_add_del(is_add=0, - table={'is_ip6': self.is_ip6, - 'table_id': self.table_id}) + self._test.vapi.ip_table_add_del( + is_add=0, table={"is_ip6": self.is_ip6, "table_id": self.table_id} + ) def replace_begin(self): self._test.vapi.ip_table_replace_begin( - table={'is_ip6': self.is_ip6, - 'table_id': self.table_id}) + table={"is_ip6": self.is_ip6, "table_id": self.table_id} + ) def replace_end(self): self._test.vapi.ip_table_replace_end( - table={'is_ip6': self.is_ip6, - 'table_id': self.table_id}) + table={"is_ip6": self.is_ip6, "table_id": self.table_id} + ) def flush(self): - self._test.vapi.ip_table_flush(table={'is_ip6': self.is_ip6, - 'table_id': self.table_id}) + self._test.vapi.ip_table_flush( + table={"is_ip6": self.is_ip6, "table_id": self.table_id} + ) def dump(self): return self._test.vapi.ip_route_dump(self.table_id, self.is_ip6) @@ -216,19 +206,15 @@ class VppIpTable(VppObject): # the default table always exists return False # find the default route - return find_route(self._test, - "::" if self.is_ip6 else "0.0.0.0", - 0, - self.table_id) + return find_route( + self._test, "::" if self.is_ip6 else "0.0.0.0", 0, self.table_id + ) def object_id(self): - return ("table-%s-%d" % - ("v6" if self.is_ip6 == 1 else "v4", - self.table_id)) + return "table-%s-%d" % ("v6" if self.is_ip6 == 1 else "v4", self.table_id) class VppIpInterfaceAddress(VppObject): - def __init__(self, test, intf, addr, len, bind=None): self._test = test self.intf = intf @@ -242,55 +228,57 @@ class VppIpInterfaceAddress(VppObject): def add_vpp_config(self): self._test.vapi.sw_interface_add_del_address( - sw_if_index=self.intf.sw_if_index, prefix=self.prefix, - is_add=1) + sw_if_index=self.intf.sw_if_index, prefix=self.prefix, is_add=1 + ) self._test.registry.register(self, self._test.logger) return self def remove_vpp_config(self): self._test.vapi.sw_interface_add_del_address( - sw_if_index=self.intf.sw_if_index, prefix=self.prefix, - is_add=0) + sw_if_index=self.intf.sw_if_index, prefix=self.prefix, is_add=0 + ) def query_vpp_config(self): # search for the IP address mapping and the two expected # FIB entries v = ip_address(self.addr).version - if ((v == 4 and self.len < 31) or (v == 6 and self.len < 127)): - return (fib_interface_ip_prefix(self._test, - self.addr, - self.len, - self.intf.sw_if_index) & - find_route(self._test, - self.addr, - self.len, - table_id=self.table_id, - sw_if_index=self.intf.sw_if_index) & - find_route(self._test, - self.addr, - self.host_len, - table_id=self.table_id, - sw_if_index=self.intf.sw_if_index)) + if (v == 4 and self.len < 31) or (v == 6 and self.len < 127): + return ( + fib_interface_ip_prefix( + self._test, self.addr, self.len, self.intf.sw_if_index + ) + & find_route( + self._test, + self.addr, + self.len, + table_id=self.table_id, + sw_if_index=self.intf.sw_if_index, + ) + & find_route( + self._test, + self.addr, + self.host_len, + table_id=self.table_id, + sw_if_index=self.intf.sw_if_index, + ) + ) else: - return (fib_interface_ip_prefix(self._test, - self.addr, - self.len, - self.intf.sw_if_index) & - find_route(self._test, - self.addr, - self.host_len, - table_id=self.table_id, - sw_if_index=self.intf.sw_if_index)) + return fib_interface_ip_prefix( + self._test, self.addr, self.len, self.intf.sw_if_index + ) & find_route( + self._test, + self.addr, + self.host_len, + table_id=self.table_id, + sw_if_index=self.intf.sw_if_index, + ) def object_id(self): - return "interface-ip-%s-%d-%s" % (self.intf, - self.table_id, - self.prefix) + return "interface-ip-%s-%d-%s" % (self.intf, self.table_id, self.prefix) class VppIp6LinkLocalAddress(VppObject): - def __init__(self, test, intf, addr): self._test = test self.intf = intf @@ -298,7 +286,8 @@ class VppIp6LinkLocalAddress(VppObject): def add_vpp_config(self): self._test.vapi.sw_interface_ip6_set_link_local_address( - sw_if_index=self.intf.sw_if_index, ip=self.addr) + sw_if_index=self.intf.sw_if_index, ip=self.addr + ) self._test.registry.register(self, self._test.logger) return self @@ -315,7 +304,6 @@ class VppIp6LinkLocalAddress(VppObject): class VppIpInterfaceBind(VppObject): - def __init__(self, test, intf, table): self._test = test self.intf = intf @@ -341,9 +329,12 @@ class VppIpInterfaceBind(VppObject): if 0 == self.table.table_id: return False try: - return self._test.vapi.sw_interface_get_table( - self.intf.sw_if_index, - self.table.is_ip6).vrf_id == self.table.table_id + return ( + self._test.vapi.sw_interface_get_table( + self.intf.sw_if_index, self.table.is_ip6 + ).vrf_id + == self.table.table_id + ) except UnexpectedApiReturnValueError as e: if e.retval == -2: # INVALID_SW_IF_INDEX return False @@ -362,22 +353,28 @@ class VppMplsLabel: def encode(self): is_uniform = 0 if self.mode is MplsLspMode.PIPE else 1 - return {'label': self.value, - 'ttl': self.ttl, - 'exp': self.exp, - 'is_uniform': is_uniform} + return { + "label": self.value, + "ttl": self.ttl, + "exp": self.exp, + "is_uniform": is_uniform, + } def __eq__(self, other): if isinstance(other, self.__class__): - return (self.value == other.value and - self.ttl == other.ttl and - self.exp == other.exp and - self.mode == other.mode) - elif hasattr(other, 'label'): - return (self.value == other.label and - self.ttl == other.ttl and - self.exp == other.exp and - (self.mode == MplsLspMode.UNIFORM) == other.is_uniform) + return ( + self.value == other.value + and self.ttl == other.ttl + and self.exp == other.exp + and self.mode == other.mode + ) + elif hasattr(other, "label"): + return ( + self.value == other.label + and self.ttl == other.ttl + and self.exp == other.exp + and (self.mode == MplsLspMode.UNIFORM) == other.is_uniform + ) else: return False @@ -386,20 +383,18 @@ class VppMplsLabel: class VppFibPathNextHop: - def __init__(self, addr, - via_label=MPLS_LABEL_INVALID, - next_hop_id=INVALID_INDEX): + def __init__(self, addr, via_label=MPLS_LABEL_INVALID, next_hop_id=INVALID_INDEX): self.addr = VppIpAddressUnion(addr) self.via_label = via_label self.obj_id = next_hop_id def encode(self): if self.via_label is not MPLS_LABEL_INVALID: - return {'via_label': self.via_label} + return {"via_label": self.via_label} if self.obj_id is not INVALID_INDEX: - return {'obj_id': self.obj_id} + return {"obj_id": self.obj_id} else: - return {'address': self.addr.encode()} + return {"address": self.addr.encode()} def proto(self): if self.via_label is MPLS_LABEL_INVALID: @@ -411,25 +406,27 @@ class VppFibPathNextHop: if not isinstance(other, self.__class__): # try the other instance's __eq__. return NotImplemented - return (self.addr == other.addr and - self.via_label == other.via_label and - self.obj_id == other.obj_id) + return ( + self.addr == other.addr + and self.via_label == other.via_label + and self.obj_id == other.obj_id + ) class VppRoutePath: - def __init__( - self, - nh_addr, - nh_sw_if_index, - nh_table_id=0, - labels=[], - nh_via_label=MPLS_LABEL_INVALID, - rpf_id=0, - next_hop_id=INVALID_INDEX, - proto=None, - flags=FibPathFlags.FIB_PATH_FLAG_NONE, - type=FibPathType.FIB_PATH_TYPE_NORMAL): + self, + nh_addr, + nh_sw_if_index, + nh_table_id=0, + labels=[], + nh_via_label=MPLS_LABEL_INVALID, + rpf_id=0, + next_hop_id=INVALID_INDEX, + proto=None, + flags=FibPathFlags.FIB_PATH_FLAG_NONE, + type=FibPathType.FIB_PATH_TYPE_NORMAL, + ): self.nh_itf = nh_sw_if_index self.nh_table_id = nh_table_id self.nh_labels = labels @@ -451,36 +448,37 @@ class VppRoutePath: if type(l) == VppMplsLabel: lstack.append(l.encode()) else: - lstack.append({'label': l, - 'ttl': 255}) - while (len(lstack) < 16): + lstack.append({"label": l, "ttl": 255}) + while len(lstack) < 16: lstack.append({}) return lstack def encode(self): - return {'weight': 1, - 'preference': 0, - 'table_id': self.nh_table_id, - 'nh': self.nh.encode(), - 'next_hop_id': self.next_hop_id, - 'sw_if_index': self.nh_itf, - 'rpf_id': self.rpf_id, - 'proto': self.proto, - 'type': self.type, - 'flags': self.flags, - 'n_labels': len(self.nh_labels), - 'label_stack': self.encode_labels()} + return { + "weight": 1, + "preference": 0, + "table_id": self.nh_table_id, + "nh": self.nh.encode(), + "next_hop_id": self.next_hop_id, + "sw_if_index": self.nh_itf, + "rpf_id": self.rpf_id, + "proto": self.proto, + "type": self.type, + "flags": self.flags, + "n_labels": len(self.nh_labels), + "label_stack": self.encode_labels(), + } def __eq__(self, other): if isinstance(other, self.__class__): return self.nh == other.nh - elif hasattr(other, 'sw_if_index'): + elif hasattr(other, "sw_if_index"): # vl_api_fib_path_t - if (len(self.nh_labels) != other.n_labels): + if len(self.nh_labels) != other.n_labels: return False for i in range(len(self.nh_labels)): - if (self.nh_labels[i] != other.label_stack[i]): + if self.nh_labels[i] != other.label_stack[i]: return False return self.nh_itf == other.sw_if_index else: @@ -491,26 +489,28 @@ class VppRoutePath: class VppMRoutePath(VppRoutePath): - - def __init__(self, nh_sw_if_index, flags, - nh=None, - proto=FibPathProto.FIB_PATH_NH_PROTO_IP4, - type=FibPathType.FIB_PATH_TYPE_NORMAL, - bier_imp=INVALID_INDEX): + def __init__( + self, + nh_sw_if_index, + flags, + nh=None, + proto=FibPathProto.FIB_PATH_NH_PROTO_IP4, + type=FibPathType.FIB_PATH_TYPE_NORMAL, + bier_imp=INVALID_INDEX, + ): if not nh: - nh = "::" if proto is FibPathProto.FIB_PATH_NH_PROTO_IP6 \ - else "0.0.0.0" - super(VppMRoutePath, self).__init__(nh, - nh_sw_if_index, - proto=proto, - type=type, - next_hop_id=bier_imp) + nh = "::" if proto is FibPathProto.FIB_PATH_NH_PROTO_IP6 else "0.0.0.0" + super(VppMRoutePath, self).__init__( + nh, nh_sw_if_index, proto=proto, type=type, next_hop_id=bier_imp + ) self.nh_i_flags = flags self.bier_imp = bier_imp def encode(self): - return {'path': super(VppMRoutePath, self).encode(), - 'itf_flags': self.nh_i_flags} + return { + "path": super(VppMRoutePath, self).encode(), + "itf_flags": self.nh_i_flags, + } class VppIpRoute(VppObject): @@ -518,8 +518,9 @@ class VppIpRoute(VppObject): IP Route """ - def __init__(self, test, dest_addr, - dest_addr_len, paths, table_id=0, register=True): + def __init__( + self, test, dest_addr, dest_addr_len, paths, table_id=0, register=True + ): self._test = test self.paths = paths self.table_id = table_id @@ -533,8 +534,7 @@ class VppIpRoute(VppObject): self.encoded_paths.append(path.encode()) def __eq__(self, other): - if self.table_id == other.table_id and \ - self.prefix == other.prefix: + if self.table_id == other.table_id and self.prefix == other.prefix: return True return False @@ -545,24 +545,28 @@ class VppIpRoute(VppObject): self.encoded_paths.append(path.encode()) self.modified = True - self._test.vapi.ip_route_add_del(route={'table_id': self.table_id, - 'prefix': self.prefix, - 'n_paths': len( - self.encoded_paths), - 'paths': self.encoded_paths, - }, - is_add=1, - is_multipath=0) + self._test.vapi.ip_route_add_del( + route={ + "table_id": self.table_id, + "prefix": self.prefix, + "n_paths": len(self.encoded_paths), + "paths": self.encoded_paths, + }, + is_add=1, + is_multipath=0, + ) def add_vpp_config(self): r = self._test.vapi.ip_route_add_del( - route={'table_id': self.table_id, - 'prefix': self.prefix, - 'n_paths': len(self.encoded_paths), - 'paths': self.encoded_paths, - }, + route={ + "table_id": self.table_id, + "prefix": self.prefix, + "n_paths": len(self.encoded_paths), + "paths": self.encoded_paths, + }, is_add=1, - is_multipath=0) + is_multipath=0, + ) self.stats_index = r.stats_index if self.register: self._test.registry.register(self, self._test.logger) @@ -575,32 +579,36 @@ class VppIpRoute(VppObject): # passing no paths and multipath=0 if self.modified: self._test.vapi.ip_route_add_del( - route={'table_id': self.table_id, - 'prefix': self.prefix, - 'n_paths': len( - self.encoded_paths), - 'paths': self.encoded_paths}, + route={ + "table_id": self.table_id, + "prefix": self.prefix, + "n_paths": len(self.encoded_paths), + "paths": self.encoded_paths, + }, is_add=0, - is_multipath=1) + is_multipath=1, + ) else: self._test.vapi.ip_route_add_del( - route={'table_id': self.table_id, - 'prefix': self.prefix, - 'n_paths': 0}, + route={"table_id": self.table_id, "prefix": self.prefix, "n_paths": 0}, is_add=0, - is_multipath=0) + is_multipath=0, + ) def query_vpp_config(self): - return find_route(self._test, - self.prefix.network_address, - self.prefix.prefixlen, - self.table_id) + return find_route( + self._test, + self.prefix.network_address, + self.prefix.prefixlen, + self.table_id, + ) def object_id(self): - return ("%s:table-%d-%s" % ( - 'ip6-route' if self.prefix.version == 6 else 'ip-route', - self.table_id, - self.prefix)) + return "%s:table-%d-%s" % ( + "ip6-route" if self.prefix.version == 6 else "ip-route", + self.table_id, + self.prefix, + ) def get_stats_to(self): c = self._test.statistics.get_counter("/net/route/to") @@ -616,9 +624,9 @@ class VppIpRouteV2(VppObject): IP Route V2 """ - def __init__(self, test, dest_addr, - dest_addr_len, paths, table_id=0, - register=True, src=0): + def __init__( + self, test, dest_addr, dest_addr_len, paths, table_id=0, register=True, src=0 + ): self._test = test self.paths = paths self.table_id = table_id @@ -633,8 +641,7 @@ class VppIpRouteV2(VppObject): self.encoded_paths.append(path.encode()) def __eq__(self, other): - if self.table_id == other.table_id and \ - self.prefix == other.prefix: + if self.table_id == other.table_id and self.prefix == other.prefix: return True return False @@ -645,26 +652,30 @@ class VppIpRouteV2(VppObject): self.encoded_paths.append(path.encode()) self.modified = True - self._test.vapi.ip_route_add_del_v2(route={'table_id': self.table_id, - 'prefix': self.prefix, - 'src': self.src, - 'n_paths': len( - self.encoded_paths), - 'paths': self.encoded_paths, - }, - is_add=1, - is_multipath=0) + self._test.vapi.ip_route_add_del_v2( + route={ + "table_id": self.table_id, + "prefix": self.prefix, + "src": self.src, + "n_paths": len(self.encoded_paths), + "paths": self.encoded_paths, + }, + is_add=1, + is_multipath=0, + ) def add_vpp_config(self): r = self._test.vapi.ip_route_add_del_v2( - route={'table_id': self.table_id, - 'prefix': self.prefix, - 'n_paths': len(self.encoded_paths), - 'paths': self.encoded_paths, - 'src': self.src, - }, + route={ + "table_id": self.table_id, + "prefix": self.prefix, + "n_paths": len(self.encoded_paths), + "paths": self.encoded_paths, + "src": self.src, + }, is_add=1, - is_multipath=0) + is_multipath=0, + ) self.stats_index = r.stats_index if self.register: self._test.registry.register(self, self._test.logger) @@ -677,34 +688,42 @@ class VppIpRouteV2(VppObject): # passing no paths and multipath=0 if self.modified: self._test.vapi.ip_route_add_del_v2( - route={'table_id': self.table_id, - 'prefix': self.prefix, - 'src': self.src, - 'n_paths': len( - self.encoded_paths), - 'paths': self.encoded_paths}, + route={ + "table_id": self.table_id, + "prefix": self.prefix, + "src": self.src, + "n_paths": len(self.encoded_paths), + "paths": self.encoded_paths, + }, is_add=0, - is_multipath=1) + is_multipath=1, + ) else: self._test.vapi.ip_route_add_del_v2( - route={'table_id': self.table_id, - 'prefix': self.prefix, - 'src': self.src, - 'n_paths': 0}, + route={ + "table_id": self.table_id, + "prefix": self.prefix, + "src": self.src, + "n_paths": 0, + }, is_add=0, - is_multipath=0) + is_multipath=0, + ) def query_vpp_config(self): - return find_route(self._test, - self.prefix.network_address, - self.prefix.prefixlen, - self.table_id) + return find_route( + self._test, + self.prefix.network_address, + self.prefix.prefixlen, + self.table_id, + ) def object_id(self): - return ("%s:table-%d-%s" % ( - 'ip6-route' if self.prefix.version == 6 else 'ip-route', - self.table_id, - self.prefix)) + return "%s:table-%d-%s" % ( + "ip6-route" if self.prefix.version == 6 else "ip-route", + self.table_id, + self.prefix, + ) def get_stats_to(self): c = self._test.statistics.get_counter("/net/route/to") @@ -720,9 +739,17 @@ class VppIpMRoute(VppObject): IP Multicast Route """ - def __init__(self, test, src_addr, grp_addr, - grp_addr_len, e_flags, paths, table_id=0, - rpf_id=0): + def __init__( + self, + test, + src_addr, + grp_addr, + grp_addr_len, + e_flags, + paths, + table_id=0, + rpf_id=0, + ): self._test = test self.paths = paths self.table_id = table_id @@ -736,38 +763,37 @@ class VppIpMRoute(VppObject): def encode(self, paths=None): _paths = self.encoded_paths if paths is None else paths - return {'table_id': self.table_id, - 'entry_flags': self.e_flags, - 'rpf_id': self.rpf_id, - 'prefix': self.prefix.encode(), - 'n_paths': len(_paths), - 'paths': _paths, - } + return { + "table_id": self.table_id, + "entry_flags": self.e_flags, + "rpf_id": self.rpf_id, + "prefix": self.prefix.encode(), + "n_paths": len(_paths), + "paths": _paths, + } def add_vpp_config(self): - r = self._test.vapi.ip_mroute_add_del(route=self.encode(), - is_multipath=1, - is_add=1) + r = self._test.vapi.ip_mroute_add_del( + route=self.encode(), is_multipath=1, is_add=1 + ) self.stats_index = r.stats_index self._test.registry.register(self, self._test.logger) return self def remove_vpp_config(self): - self._test.vapi.ip_mroute_add_del(route=self.encode(), - is_multipath=1, - is_add=0) + self._test.vapi.ip_mroute_add_del(route=self.encode(), is_multipath=1, is_add=0) def update_entry_flags(self, flags): self.e_flags = flags - self._test.vapi.ip_mroute_add_del(route=self.encode(paths=[]), - is_multipath=1, - is_add=1) + self._test.vapi.ip_mroute_add_del( + route=self.encode(paths=[]), is_multipath=1, is_add=1 + ) def update_rpf_id(self, rpf_id): self.rpf_id = rpf_id - self._test.vapi.ip_mroute_add_del(route=self.encode(paths=[]), - is_multipath=1, - is_add=1) + self._test.vapi.ip_mroute_add_del( + route=self.encode(paths=[]), is_multipath=1, is_add=1 + ) def update_path_flags(self, itf, flags): for p in range(len(self.paths)): @@ -777,23 +803,25 @@ class VppIpMRoute(VppObject): break self._test.vapi.ip_mroute_add_del( - route=self.encode( - paths=[self.encoded_paths[p]]), - is_add=1, - is_multipath=0) + route=self.encode(paths=[self.encoded_paths[p]]), is_add=1, is_multipath=0 + ) def query_vpp_config(self): - return find_mroute(self._test, - self.prefix.gaddr, - self.prefix.saddr, - self.prefix.length, - self.table_id) + return find_mroute( + self._test, + self.prefix.gaddr, + self.prefix.saddr, + self.prefix.length, + self.table_id, + ) def object_id(self): - return ("%d:(%s,%s/%d)" % (self.table_id, - self.prefix.saddr, - self.prefix.gaddr, - self.prefix.length)) + return "%d:(%s,%s/%d)" % ( + self.table_id, + self.prefix.saddr, + self.prefix.gaddr, + self.prefix.length, + ) def get_stats(self): c = self._test.statistics.get_counter("/net/mroute") @@ -818,8 +846,16 @@ class VppMplsIpBind(VppObject): MPLS to IP Binding """ - def __init__(self, test, local_label, dest_addr, dest_addr_len, - table_id=0, ip_table_id=0, is_ip6=0): + def __init__( + self, + test, + local_label, + dest_addr, + dest_addr_len, + table_id=0, + ip_table_id=0, + is_ip6=0, + ): self._test = test self.dest_addr_len = dest_addr_len self.dest_addr = dest_addr @@ -830,54 +866,54 @@ class VppMplsIpBind(VppObject): self.prefix = mk_network(dest_addr, dest_addr_len) def add_vpp_config(self): - self._test.vapi.mpls_ip_bind_unbind(self.local_label, - self.prefix, - table_id=self.table_id, - ip_table_id=self.ip_table_id) + self._test.vapi.mpls_ip_bind_unbind( + self.local_label, + self.prefix, + table_id=self.table_id, + ip_table_id=self.ip_table_id, + ) self._test.registry.register(self, self._test.logger) def remove_vpp_config(self): - self._test.vapi.mpls_ip_bind_unbind(self.local_label, - self.prefix, - table_id=self.table_id, - ip_table_id=self.ip_table_id, - is_bind=0) + self._test.vapi.mpls_ip_bind_unbind( + self.local_label, + self.prefix, + table_id=self.table_id, + ip_table_id=self.ip_table_id, + is_bind=0, + ) def query_vpp_config(self): dump = self._test.vapi.mpls_route_dump(self.table_id) for e in dump: - if self.local_label == e.mr_route.mr_label \ - and self.table_id == e.mr_route.mr_table_id: + if ( + self.local_label == e.mr_route.mr_label + and self.table_id == e.mr_route.mr_table_id + ): return True return False def object_id(self): - return ("%d:%s binds %d:%s/%d" - % (self.table_id, - self.local_label, - self.ip_table_id, - self.dest_addr, - self.dest_addr_len)) + return "%d:%s binds %d:%s/%d" % ( + self.table_id, + self.local_label, + self.ip_table_id, + self.dest_addr, + self.dest_addr_len, + ) class VppMplsTable(VppObject): - - def __init__(self, - test, - table_id): + def __init__(self, test, table_id): self._test = test self.table_id = table_id def add_vpp_config(self): - self._test.vapi.mpls_table_add_del( - self.table_id, - is_add=1) + self._test.vapi.mpls_table_add_del(self.table_id, is_add=1) self._test.registry.register(self, self._test.logger) def remove_vpp_config(self): - self._test.vapi.mpls_table_add_del( - self.table_id, - is_add=0) + self._test.vapi.mpls_table_add_del(self.table_id, is_add=0) def query_vpp_config(self): dump = self._test.vapi.mpls_table_dump() @@ -887,7 +923,7 @@ class VppMplsTable(VppObject): return False def object_id(self): - return ("table-mpls-%d" % (self.table_id)) + return "table-mpls-%d" % (self.table_id) class VppMplsRoute(VppObject): @@ -895,9 +931,16 @@ class VppMplsRoute(VppObject): MPLS Route/LSP """ - def __init__(self, test, local_label, eos_bit, paths, table_id=0, - is_multicast=0, - eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP4): + def __init__( + self, + test, + local_label, + eos_bit, + paths, + table_id=0, + is_multicast=0, + eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP4, + ): self._test = test self.paths = paths self.local_label = local_label @@ -911,12 +954,16 @@ class VppMplsRoute(VppObject): for path in self.paths: paths.append(path.encode()) - r = self._test.vapi.mpls_route_add_del(self.table_id, - self.local_label, - self.eos_bit, - self.eos_proto, - self.is_multicast, - paths, 1, 0) + r = self._test.vapi.mpls_route_add_del( + self.table_id, + self.local_label, + self.eos_bit, + self.eos_proto, + self.is_multicast, + paths, + 1, + 0, + ) self.stats_index = r.stats_index self._test.registry.register(self, self._test.logger) @@ -925,22 +972,28 @@ class VppMplsRoute(VppObject): for path in self.paths: paths.append(path.encode()) - self._test.vapi.mpls_route_add_del(self.table_id, - self.local_label, - self.eos_bit, - self.eos_proto, - self.is_multicast, - paths, 0, 0) + self._test.vapi.mpls_route_add_del( + self.table_id, + self.local_label, + self.eos_bit, + self.eos_proto, + self.is_multicast, + paths, + 0, + 0, + ) def query_vpp_config(self): - return find_mpls_route(self._test, self.table_id, - self.local_label, self.eos_bit) + return find_mpls_route( + self._test, self.table_id, self.local_label, self.eos_bit + ) def object_id(self): - return ("mpls-route-%d:%s/%d" - % (self.table_id, - self.local_label, - 20 + self.eos_bit)) + return "mpls-route-%d:%s/%d" % ( + self.table_id, + self.local_label, + 20 + self.eos_bit, + ) def get_stats_to(self): c = self._test.statistics.get_counter("/net/route/to") diff --git a/test/vpp_ipip_tun_interface.py b/test/vpp_ipip_tun_interface.py index 6517458d3d6..259767653bd 100644 --- a/test/vpp_ipip_tun_interface.py +++ b/test/vpp_ipip_tun_interface.py @@ -8,9 +8,9 @@ class VppIpIpTunInterface(VppTunnelInterface): VPP IP-IP Tunnel interface """ - def __init__(self, test, parent_if, src, dst, - table_id=0, dscp=0x0, - flags=0, mode=None): + def __init__( + self, test, parent_if, src, dst, table_id=0, dscp=0x0, flags=0, mode=None + ): super(VppIpIpTunInterface, self).__init__(test, parent_if) self.src = src self.dst = dst @@ -19,23 +19,22 @@ class VppIpIpTunInterface(VppTunnelInterface): self.flags = flags self.mode = mode if not self.mode: - self.mode = (VppEnum.vl_api_tunnel_mode_t. - TUNNEL_API_MODE_P2P) + self.mode = VppEnum.vl_api_tunnel_mode_t.TUNNEL_API_MODE_P2P def add_vpp_config(self): r = self.test.vapi.ipip_add_tunnel( tunnel={ - 'src': self.src, - 'dst': self.dst, - 'table_id': self.table_id, - 'flags': self.flags, - 'dscp': self.dscp, - 'instance': 0xffffffff, - 'mode': self.mode, - }) + "src": self.src, + "dst": self.dst, + "table_id": self.table_id, + "flags": self.flags, + "dscp": self.dscp, + "instance": 0xFFFFFFFF, + "mode": self.mode, + } + ) self.set_sw_if_index(r.sw_if_index) - r = self.test.vapi.ipip_tunnel_dump( - sw_if_index=self.sw_if_index) + r = self.test.vapi.ipip_tunnel_dump(sw_if_index=self.sw_if_index) self.instance = r[0].tunnel.instance self.test.registry.register(self, self.test.logger) return self @@ -44,7 +43,7 @@ class VppIpIpTunInterface(VppTunnelInterface): self.test.vapi.ipip_del_tunnel(sw_if_index=self._sw_if_index) def query_vpp_config(self): - ts = self.test.vapi.ipip_tunnel_dump(sw_if_index=0xffffffff) + ts = self.test.vapi.ipip_tunnel_dump(sw_if_index=0xFFFFFFFF) for t in ts: if t.tunnel.sw_if_index == self._sw_if_index: return True diff --git a/test/vpp_ipsec.py b/test/vpp_ipsec.py index 76080e05c3a..1db7f853e72 100644 --- a/test/vpp_ipsec.py +++ b/test/vpp_ipsec.py @@ -10,7 +10,7 @@ except NameError: def mk_counter(): - return {'packets': 0, 'bytes': 0} + return {"packets": 0, "bytes": 0} class VppIpsecSpd(VppObject): @@ -52,14 +52,13 @@ class VppIpsecSpdItfBinding(VppObject): self.itf = itf def add_vpp_config(self): - self.test.vapi.ipsec_interface_add_del_spd(self.spd.id, - self.itf.sw_if_index) + self.test.vapi.ipsec_interface_add_del_spd(self.spd.id, self.itf.sw_if_index) self.test.registry.register(self, self.test.logger) def remove_vpp_config(self): - self.test.vapi.ipsec_interface_add_del_spd(self.spd.id, - self.itf.sw_if_index, - is_add=0) + self.test.vapi.ipsec_interface_add_del_spd( + self.spd.id, self.itf.sw_if_index, is_add=0 + ) def object_id(self): return "bind-%s-to-%s" % (self.spd.id, self.itf) @@ -77,17 +76,24 @@ class VppIpsecSpdEntry(VppObject): VPP SPD DB Entry """ - def __init__(self, test, spd, sa_id, - local_start, local_stop, - remote_start, remote_stop, - proto, - priority=100, - policy=None, - is_outbound=1, - remote_port_start=0, - remote_port_stop=65535, - local_port_start=0, - local_port_stop=65535): + def __init__( + self, + test, + spd, + sa_id, + local_start, + local_stop, + remote_start, + remote_stop, + proto, + priority=100, + policy=None, + is_outbound=1, + remote_port_start=0, + remote_port_stop=65535, + local_port_start=0, + local_port_stop=65535, + ): self.test = test self.spd = spd self.sa_id = sa_id @@ -99,11 +105,10 @@ class VppIpsecSpdEntry(VppObject): self.is_outbound = is_outbound self.priority = priority if not policy: - self.policy = (VppEnum.vl_api_ipsec_spd_action_t. - IPSEC_API_SPD_ACTION_BYPASS) + self.policy = VppEnum.vl_api_ipsec_spd_action_t.IPSEC_API_SPD_ACTION_BYPASS else: self.policy = policy - self.is_ipv6 = (0 if self.local_start.version == 4 else 1) + self.is_ipv6 = 0 if self.local_start.version == 4 else 1 self.local_port_start = local_port_start self.local_port_stop = local_port_stop self.remote_port_start = remote_port_start @@ -125,7 +130,8 @@ class VppIpsecSpdEntry(VppObject): local_port_start=self.local_port_start, local_port_stop=self.local_port_stop, remote_port_start=self.remote_port_start, - remote_port_stop=self.remote_port_stop) + remote_port_stop=self.remote_port_stop, + ) self.stat_index = rv.stat_index self.test.registry.register(self, self.test.logger) return self @@ -147,25 +153,30 @@ class VppIpsecSpdEntry(VppObject): local_port_stop=self.local_port_stop, remote_port_start=self.remote_port_start, remote_port_stop=self.remote_port_stop, - is_add=0) + is_add=0, + ) def object_id(self): - return "spd-entry-%d-%d-%d-%d-%d-%d" % (self.spd.id, - self.priority, - self.policy, - self.is_outbound, - self.is_ipv6, - self.remote_port_start) + return "spd-entry-%d-%d-%d-%d-%d-%d" % ( + self.spd.id, + self.priority, + self.policy, + self.is_outbound, + self.is_ipv6, + self.remote_port_start, + ) def query_vpp_config(self): ss = self.test.vapi.ipsec_spd_dump(self.spd.id) for s in ss: - if s.entry.sa_id == self.sa_id and \ - s.entry.is_outbound == self.is_outbound and \ - s.entry.priority == self.priority and \ - s.entry.policy == self.policy and \ - s.entry.remote_address_start == self.remote_start and \ - s.entry.remote_port_start == self.remote_port_start: + if ( + s.entry.sa_id == self.sa_id + and s.entry.is_outbound == self.is_outbound + and s.entry.priority == self.priority + and s.entry.policy == self.policy + and s.entry.remote_address_start == self.remote_start + and s.entry.remote_port_start == self.remote_port_start + ): return True return False @@ -174,11 +185,11 @@ class VppIpsecSpdEntry(VppObject): if worker is None: total = mk_counter() for t in c: - total['packets'] += t[self.stat_index]['packets'] + total["packets"] += t[self.stat_index]["packets"] return total else: # +1 to skip main thread - return c[worker+1][self.stat_index] + return c[worker + 1][self.stat_index] class VppIpsecSA(VppObject): @@ -188,14 +199,26 @@ class VppIpsecSA(VppObject): DEFAULT_UDP_PORT = 4500 - def __init__(self, test, id, spi, - integ_alg, integ_key, - crypto_alg, crypto_key, - proto, - tun_src=None, tun_dst=None, - flags=None, salt=0, tun_flags=None, - dscp=None, - udp_src=None, udp_dst=None, hop_limit=None): + def __init__( + self, + test, + id, + spi, + integ_alg, + integ_key, + crypto_alg, + crypto_key, + proto, + tun_src=None, + tun_dst=None, + flags=None, + salt=0, + tun_flags=None, + dscp=None, + udp_src=None, + udp_dst=None, + hop_limit=None, + ): e = VppEnum.vl_api_ipsec_sad_flags_t self.test = test self.id = id @@ -214,15 +237,16 @@ class VppIpsecSA(VppObject): self.flags = e.IPSEC_API_SAD_FLAG_NONE else: self.flags = flags - if (tun_src): + if tun_src: self.tun_src = ip_address(text_type(tun_src)) self.flags = self.flags | e.IPSEC_API_SAD_FLAG_IS_TUNNEL - if (tun_dst): + if tun_dst: self.tun_dst = ip_address(text_type(tun_dst)) self.udp_src = udp_src self.udp_dst = udp_dst - self.tun_flags = (VppEnum.vl_api_tunnel_encap_decap_flags_t. - TUNNEL_API_ENCAP_DECAP_FLAG_NONE) + self.tun_flags = ( + VppEnum.vl_api_tunnel_encap_decap_flags_t.TUNNEL_API_ENCAP_DECAP_FLAG_NONE + ) if tun_flags: self.tun_flags = tun_flags self.dscp = VppEnum.vl_api_ip_dscp_t.IP_API_DSCP_CS0 @@ -233,38 +257,39 @@ class VppIpsecSA(VppObject): self.hop_limit = hop_limit def tunnel_encode(self): - return {'src': (self.tun_src if self.tun_src else []), - 'dst': (self.tun_dst if self.tun_dst else []), - 'encap_decap_flags': self.tun_flags, - 'dscp': self.dscp, - 'hop_limit': self.hop_limit, - 'table_id': self.table_id - } + return { + "src": (self.tun_src if self.tun_src else []), + "dst": (self.tun_dst if self.tun_dst else []), + "encap_decap_flags": self.tun_flags, + "dscp": self.dscp, + "hop_limit": self.hop_limit, + "table_id": self.table_id, + } def add_vpp_config(self): entry = { - 'sad_id': self.id, - 'spi': self.spi, - 'integrity_algorithm': self.integ_alg, - 'integrity_key': { - 'length': len(self.integ_key), - 'data': self.integ_key, + "sad_id": self.id, + "spi": self.spi, + "integrity_algorithm": self.integ_alg, + "integrity_key": { + "length": len(self.integ_key), + "data": self.integ_key, }, - 'crypto_algorithm': self.crypto_alg, - 'crypto_key': { - 'data': self.crypto_key, - 'length': len(self.crypto_key), + "crypto_algorithm": self.crypto_alg, + "crypto_key": { + "data": self.crypto_key, + "length": len(self.crypto_key), }, - 'protocol': self.proto, - 'tunnel': self.tunnel_encode(), - 'flags': self.flags, - 'salt': self.salt + "protocol": self.proto, + "tunnel": self.tunnel_encode(), + "flags": self.flags, + "salt": self.salt, } # don't explicitly send the defaults, let papi fill them in if self.udp_src: - entry['udp_src_port'] = self.udp_src + entry["udp_src_port"] = self.udp_src if self.udp_dst: - entry['udp_dst_port'] = self.udp_dst + entry["udp_dst_port"] = self.udp_dst r = self.test.vapi.ipsec_sad_entry_add(entry=entry) self.stat_index = r.stat_index self.test.registry.register(self, self.test.logger) @@ -284,7 +309,7 @@ class VppIpsecSA(VppObject): if b.entry.sad_id == self.id: # if udp encap is configured then the ports should match # those configured or the default - if (self.flags & e.IPSEC_API_SAD_FLAG_UDP_ENCAP): + if self.flags & e.IPSEC_API_SAD_FLAG_UDP_ENCAP: if not b.entry.flags & e.IPSEC_API_SAD_FLAG_UDP_ENCAP: return False if self.udp_src: @@ -307,11 +332,11 @@ class VppIpsecSA(VppObject): if worker is None: total = mk_counter() for t in c: - total['packets'] += t[self.stat_index]['packets'] + total["packets"] += t[self.stat_index]["packets"] return total else: # +1 to skip main thread - return c[worker+1][self.stat_index] + return c[worker + 1][self.stat_index] def get_lost(self, worker=None): c = self.test.statistics.get_counter("/net/ipsec/sa/lost") @@ -322,7 +347,7 @@ class VppIpsecSA(VppObject): return total else: # +1 to skip main thread - return c[worker+1][self.stat_index] + return c[worker + 1][self.stat_index] class VppIpsecTunProtect(VppObject): @@ -348,11 +373,13 @@ class VppIpsecTunProtect(VppObject): self.sa_out = sa_out.id self.test.vapi.ipsec_tunnel_protect_update( tunnel={ - 'sw_if_index': self.itf._sw_if_index, - 'n_sa_in': len(self.sas_in), - 'sa_out': self.sa_out, - 'sa_in': self.sas_in, - 'nh': self.nh}) + "sw_if_index": self.itf._sw_if_index, + "n_sa_in": len(self.sas_in), + "sa_out": self.sa_out, + "sa_in": self.sas_in, + "nh": self.nh, + } + ) def object_id(self): return "ipsec-tun-protect-%s-%s" % (self.itf, self.nh) @@ -360,24 +387,24 @@ class VppIpsecTunProtect(VppObject): def add_vpp_config(self): self.test.vapi.ipsec_tunnel_protect_update( tunnel={ - 'sw_if_index': self.itf._sw_if_index, - 'n_sa_in': len(self.sas_in), - 'sa_out': self.sa_out, - 'sa_in': self.sas_in, - 'nh': self.nh}) + "sw_if_index": self.itf._sw_if_index, + "n_sa_in": len(self.sas_in), + "sa_out": self.sa_out, + "sa_in": self.sas_in, + "nh": self.nh, + } + ) self.test.registry.register(self, self.test.logger) def remove_vpp_config(self): self.test.vapi.ipsec_tunnel_protect_del( - sw_if_index=self.itf.sw_if_index, - nh=self.nh) + sw_if_index=self.itf.sw_if_index, nh=self.nh + ) def query_vpp_config(self): - bs = self.test.vapi.ipsec_tunnel_protect_dump( - sw_if_index=self.itf.sw_if_index) + bs = self.test.vapi.ipsec_tunnel_protect_dump(sw_if_index=self.itf.sw_if_index) for b in bs: - if b.tun.sw_if_index == self.itf.sw_if_index and \ - self.nh == str(b.tun.nh): + if b.tun.sw_if_index == self.itf.sw_if_index and self.nh == str(b.tun.nh): return True return False @@ -387,20 +414,21 @@ class VppIpsecInterface(VppInterface): VPP IPSec interface """ - def __init__(self, test, mode=None, instance=0xffffffff): + def __init__(self, test, mode=None, instance=0xFFFFFFFF): super(VppIpsecInterface, self).__init__(test) self.mode = mode if not self.mode: - self.mode = (VppEnum.vl_api_tunnel_mode_t. - TUNNEL_API_MODE_P2P) + self.mode = VppEnum.vl_api_tunnel_mode_t.TUNNEL_API_MODE_P2P self.instance = instance def add_vpp_config(self): - r = self.test.vapi.ipsec_itf_create(itf={ - 'user_instance': self.instance, - 'mode': self.mode, - }) + r = self.test.vapi.ipsec_itf_create( + itf={ + "user_instance": self.instance, + "mode": self.mode, + } + ) self.set_sw_if_index(r.sw_if_index) self.test.registry.register(self, self.test.logger) ts = self.test.vapi.ipsec_itf_dump(sw_if_index=self._sw_if_index) @@ -411,7 +439,7 @@ class VppIpsecInterface(VppInterface): self.test.vapi.ipsec_itf_delete(sw_if_index=self._sw_if_index) def query_vpp_config(self): - ts = self.test.vapi.ipsec_itf_dump(sw_if_index=0xffffffff) + ts = self.test.vapi.ipsec_itf_dump(sw_if_index=0xFFFFFFFF) for t in ts: if t.itf.sw_if_index == self._sw_if_index: return True diff --git a/test/vpp_l2.py b/test/vpp_l2.py index 7307d28ad13..872f42851b9 100644 --- a/test/vpp_l2.py +++ b/test/vpp_l2.py @@ -7,6 +7,7 @@ from vpp_object import VppObject from vpp_lo_interface import VppLoInterface from vpp_papi import MACAddress from vpp_sub_interface import L2_VTR_OP + try: text_type = unicode except NameError: @@ -47,8 +48,7 @@ def find_bridge_domain_arp_entry(test, bd_id, mac, ip): arps = test.vapi.bd_ip_mac_dump(bd_id) for arp in arps: # do IP addr comparison too once .api is fixed... - if mac == str(arp.entry.mac) and \ - ip == str(arp.entry.ip): + if mac == str(arp.entry.mac) and ip == str(arp.entry.ip): return True return False @@ -63,10 +63,17 @@ def find_l2_fib_entry(test, bd_id, mac, sw_if_index): class VppBridgeDomain(VppObject): - - def __init__(self, test, bd_id, - flood=1, uu_flood=1, forward=1, - learn=1, arp_term=1, arp_ufwd=0): + def __init__( + self, + test, + bd_id, + flood=1, + uu_flood=1, + forward=1, + learn=1, + arp_term=1, + arp_ufwd=0, + ): self._test = test self.bd_id = bd_id self.flood = flood @@ -77,14 +84,16 @@ class VppBridgeDomain(VppObject): self.arp_ufwd = arp_ufwd def add_vpp_config(self): - self._test.vapi.bridge_domain_add_del(bd_id=self.bd_id, - flood=self.flood, - uu_flood=self.uu_flood, - forward=self.forward, - learn=self.learn, - arp_term=self.arp_term, - arp_ufwd=self.arp_ufwd, - is_add=1) + self._test.vapi.bridge_domain_add_del( + bd_id=self.bd_id, + flood=self.flood, + uu_flood=self.uu_flood, + forward=self.forward, + learn=self.learn, + arp_term=self.arp_term, + arp_ufwd=self.arp_ufwd, + is_add=1, + ) self._test.registry.register(self, self._test.logger) return self @@ -99,9 +108,7 @@ class VppBridgeDomain(VppObject): class VppBridgeDomainPort(VppObject): - - def __init__(self, test, bd, itf, - port_type=L2_PORT_TYPE.NORMAL): + def __init__(self, test, bd, itf, port_type=L2_PORT_TYPE.NORMAL): self._test = test self.bd = bd self.itf = itf @@ -109,27 +116,30 @@ class VppBridgeDomainPort(VppObject): def add_vpp_config(self): self._test.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.itf.sw_if_index, bd_id=self.bd.bd_id, - port_type=self.port_type, enable=1) + rx_sw_if_index=self.itf.sw_if_index, + bd_id=self.bd.bd_id, + port_type=self.port_type, + enable=1, + ) self._test.registry.register(self, self._test.logger) return self def remove_vpp_config(self): self._test.vapi.sw_interface_set_l2_bridge( - rx_sw_if_index=self.itf.sw_if_index, bd_id=self.bd.bd_id, - port_type=self.port_type, enable=0) + rx_sw_if_index=self.itf.sw_if_index, + bd_id=self.bd.bd_id, + port_type=self.port_type, + enable=0, + ) def query_vpp_config(self): - return find_bridge_domain_port(self._test, - self.bd.bd_id, - self.itf.sw_if_index) + return find_bridge_domain_port(self._test, self.bd.bd_id, self.itf.sw_if_index) def object_id(self): return "BD-Port-%s-%s" % (self.bd, self.itf) class VppBridgeDomainArpEntry(VppObject): - def __init__(self, test, bd, mac, ip): self._test = test self.bd = bd @@ -137,35 +147,28 @@ class VppBridgeDomainArpEntry(VppObject): self.ip = ip def add_vpp_config(self): - self._test.vapi.bd_ip_mac_add_del(is_add=1, - entry={ - 'bd_id': self.bd.bd_id, - 'ip': self.ip, - 'mac': self.mac}) + self._test.vapi.bd_ip_mac_add_del( + is_add=1, entry={"bd_id": self.bd.bd_id, "ip": self.ip, "mac": self.mac} + ) self._test.registry.register(self, self._test.logger) return self def remove_vpp_config(self): - self._test.vapi.bd_ip_mac_add_del(is_add=0, - entry={ - 'bd_id': self.bd.bd_id, - 'ip': self.ip, - 'mac': self.mac}) + self._test.vapi.bd_ip_mac_add_del( + is_add=0, entry={"bd_id": self.bd.bd_id, "ip": self.ip, "mac": self.mac} + ) def query_vpp_config(self): - return find_bridge_domain_arp_entry(self._test, - self.bd.bd_id, - self.mac, - self.ip) + return find_bridge_domain_arp_entry( + self._test, self.bd.bd_id, self.mac, self.ip + ) def object_id(self): return "BD-Arp-Entry-%s-%s-%s" % (self.bd, self.mac, self.ip) class VppL2FibEntry(VppObject): - - def __init__(self, test, bd, mac, itf, - static_mac=0, filter_mac=0, bvi_mac=-1): + def __init__(self, test, bd, mac, itf, static_mac=0, filter_mac=0, bvi_mac=-1): self._test = test self.bd = bd self.mac = MACAddress(mac) @@ -185,29 +188,26 @@ class VppL2FibEntry(VppObject): is_add=1, static_mac=self.static_mac, filter_mac=self.filter_mac, - bvi_mac=self.bvi_mac) + bvi_mac=self.bvi_mac, + ) self._test.registry.register(self, self._test.logger) return self def remove_vpp_config(self): self._test.vapi.l2fib_add_del( - self.mac.packed, - self.bd.bd_id, - self.itf.sw_if_index, - is_add=0) + self.mac.packed, self.bd.bd_id, self.itf.sw_if_index, is_add=0 + ) def query_vpp_config(self): - return find_l2_fib_entry(self._test, - self.bd.bd_id, - self.mac.packed, - self.itf.sw_if_index) + return find_l2_fib_entry( + self._test, self.bd.bd_id, self.mac.packed, self.itf.sw_if_index + ) def object_id(self): return "L2-Fib-Entry-%s-%s-%s" % (self.bd, self.mac, self.itf) class VppL2Vtr(VppObject): - def __init__(self, test, itf, op): self._test = test self.itf = itf @@ -226,7 +226,7 @@ class VppL2Vtr(VppObject): d = self.itf.get_interface_config_from_dump(ds) if d is not None: - return (d.vtr_op == self.op) + return d.vtr_op == self.op return False def object_id(self): diff --git a/test/vpp_lb.py b/test/vpp_lb.py index d755cef70e5..56ae67b145f 100644 --- a/test/vpp_lb.py +++ b/test/vpp_lb.py @@ -16,7 +16,6 @@ import vpp_object class VppLbVip(vpp_object.VppObject): - def __init__(self, test, pfx, sfx, port, protocol): self._test = test self.pfx = pfx @@ -25,25 +24,21 @@ class VppLbVip(vpp_object.VppObject): self.protocol = protocol def add_vpp_config(self): - self._test_vapi.lb_add_del_vip(pfx=self.pfx, - sfx=self.pfx, - port=self.port, - protocol=self.protocol) + self._test_vapi.lb_add_del_vip( + pfx=self.pfx, sfx=self.pfx, port=self.port, protocol=self.protocol + ) self._test.registry.register(self, self._test.logger) def remove_vpp_config(self): - self._test.vapi.lb_add_del_vip(pfx=self.pfx, - sfx=self.pfx, - port=self.port, - protocol=self.protocol, - is_del=1) + self._test.vapi.lb_add_del_vip( + pfx=self.pfx, sfx=self.pfx, port=self.port, protocol=self.protocol, is_del=1 + ) def query_vpp_config(self): - details = self._test.vapi.lb_add_del_vip(fx=self.pfx, - sfx=self.pfx, - port=self.port, - protocol=self.protocol) + details = self._test.vapi.lb_add_del_vip( + fx=self.pfx, sfx=self.pfx, port=self.port, protocol=self.protocol + ) return True if self == details else False @@ -60,25 +55,28 @@ class VppLbAs(vpp_object.VppObject): self.is_flush = is_flush def add_vpp_config(self): - self._test_vapi.lb_add_del_as(pfx=self.pfx, - port=self.port, - protocol=self.protocol, - app_srv=self.app_srv, - is_flush=self.is_flush, - ) + self._test_vapi.lb_add_del_as( + pfx=self.pfx, + port=self.port, + protocol=self.protocol, + app_srv=self.app_srv, + is_flush=self.is_flush, + ) self._test.registry.register(self, self._test.logger) def remove_vpp_config(self): - self._test.vapi.lb_add_del_as(pfx=self.pfx, - port=self.port, - protocol=self.protocol, - app_srv=self.app_srv, - is_flush=self.is_flush, - is_del=1) + self._test.vapi.lb_add_del_as( + pfx=self.pfx, + port=self.port, + protocol=self.protocol, + app_srv=self.app_srv, + is_flush=self.is_flush, + is_del=1, + ) def query_vpp_config(self): - details = self._test.vapi.lb_as_dump(pfx=self.pfx, - port=self.port, - protocol=self.protocol) + details = self._test.vapi.lb_as_dump( + pfx=self.pfx, port=self.port, protocol=self.protocol + ) return True if self == details else False diff --git a/test/vpp_lo_interface.py b/test/vpp_lo_interface.py index 36f56bed8d7..9478689811d 100644 --- a/test/vpp_lo_interface.py +++ b/test/vpp_lo_interface.py @@ -6,7 +6,7 @@ class VppLoInterface(VppInterface, VppObject): """VPP loopback interface.""" def __init__(self, test): - """ Create VPP loopback interface """ + """Create VPP loopback interface""" super(VppLoInterface, self).__init__(test) self.add_vpp_config() diff --git a/test/vpp_memif.py b/test/vpp_memif.py index 226f8af72b5..6a97c2b9884 100644 --- a/test/vpp_memif.py +++ b/test/vpp_memif.py @@ -7,7 +7,7 @@ from vpp_papi import VppEnum def get_if_dump(dump, sw_if_index): for d in dump: - if (d.sw_if_index == sw_if_index): + if d.sw_if_index == sw_if_index: return d @@ -22,13 +22,11 @@ def remove_all_memif_vpp_config(_test): dump = _test.vapi.memif_socket_filename_dump() for d in dump: if d.socket_id != 0: - _test.vapi.memif_socket_filename_add_del( - 0, d.socket_id, d.socket_filename) + _test.vapi.memif_socket_filename_add_del(0, d.socket_id, d.socket_filename) class VppSocketFilename(VppObject): - def __init__(self, test, socket_id, socket_filename, - add_default_folder=False): + def __init__(self, test, socket_id, socket_filename, add_default_folder=False): self._test = test self.socket_id = socket_id self.socket_filename = socket_filename @@ -39,15 +37,16 @@ class VppSocketFilename(VppObject): def add_vpp_config(self): rv = self._test.vapi.memif_socket_filename_add_del( - 1, self.socket_id, self.socket_filename) + 1, self.socket_id, self.socket_filename + ) if self.add_default_folder: - self.socket_filename = "%s/%s" % (self._test.tempdir, - self.socket_filename) + self.socket_filename = "%s/%s" % (self._test.tempdir, self.socket_filename) return rv def remove_vpp_config(self): return self._test.vapi.memif_socket_filename_add_del( - 0, self.socket_id, self.socket_filename) + 0, self.socket_id, self.socket_filename + ) def query_vpp_config(self): return self._test.vapi.memif_socket_filename_dump() @@ -57,9 +56,20 @@ class VppSocketFilename(VppObject): class VppMemif(VppObject): - def __init__(self, test, role, mode, rx_queues=0, tx_queues=0, if_id=0, - socket_id=0, secret="", ring_size=0, buffer_size=0, - hw_addr=""): + def __init__( + self, + test, + role, + mode, + rx_queues=0, + tx_queues=0, + if_id=0, + socket_id=0, + secret="", + ring_size=0, + buffer_size=0, + hw_addr="", + ): self._test = test self.role = role self.mode = mode @@ -72,9 +82,9 @@ class VppMemif(VppObject): self.buffer_size = buffer_size self.hw_addr = hw_addr self.sw_if_index = None - self.ip_prefix = IPv4Network("192.168.%d.%d/24" % - (self.if_id + 1, self.role + 1), - strict=False) + self.ip_prefix = IPv4Network( + "192.168.%d.%d/24" % (self.if_id + 1, self.role + 1), strict=False + ) def add_vpp_config(self): rv = self._test.vapi.memif_create( @@ -87,7 +97,8 @@ class VppMemif(VppObject): secret=self.secret, ring_size=self.ring_size, buffer_size=self.buffer_size, - hw_addr=self.hw_addr) + hw_addr=self.hw_addr, + ) try: self.sw_if_index = rv.sw_if_index except AttributeError: @@ -99,12 +110,14 @@ class VppMemif(VppObject): def admin_up(self): if self.sw_if_index: return self._test.vapi.sw_interface_set_flags( - sw_if_index=self.sw_if_index, flags=1) + sw_if_index=self.sw_if_index, flags=1 + ) def admin_down(self): if self.sw_if_index: return self._test.vapi.sw_interface_set_flags( - sw_if_index=self.sw_if_index, flags=0) + sw_if_index=self.sw_if_index, flags=0 + ) def wait_for_link_up(self, timeout, step=1): if not self.sw_if_index: @@ -121,7 +134,8 @@ class VppMemif(VppObject): def config_ip4(self): return self._test.vapi.sw_interface_add_del_address( - sw_if_index=self.sw_if_index, prefix=self.ip_prefix) + sw_if_index=self.sw_if_index, prefix=self.ip_prefix + ) def remove_vpp_config(self): self._test.vapi.memif_delete(self.sw_if_index) diff --git a/test/vpp_mpls_tunnel_interface.py b/test/vpp_mpls_tunnel_interface.py index 598936136ad..6c8941a3f19 100644 --- a/test/vpp_mpls_tunnel_interface.py +++ b/test/vpp_mpls_tunnel_interface.py @@ -1,4 +1,3 @@ - from vpp_interface import VppInterface @@ -8,7 +7,7 @@ class VppMPLSTunnelInterface(VppInterface): """ def __init__(self, test, paths, is_multicast=0, is_l2=0): - """ Create MPLS Tunnel interface """ + """Create MPLS Tunnel interface""" super(VppMPLSTunnelInterface, self).__init__(test) self.t_paths = paths self.is_multicast = is_multicast @@ -19,28 +18,29 @@ class VppMPLSTunnelInterface(VppInterface): def add_vpp_config(self): reply = self.test.vapi.mpls_tunnel_add_del( - 0xffffffff, + 0xFFFFFFFF, self.encoded_paths, is_multicast=self.is_multicast, - l2_only=self.is_l2) + l2_only=self.is_l2, + ) self.set_sw_if_index(reply.sw_if_index) self.tunnel_index = reply.tunnel_index self._test.registry.register(self, self._test.logger) def remove_vpp_config(self): reply = self.test.vapi.mpls_tunnel_add_del( - self.sw_if_index, - self.encoded_paths, - is_add=0) + self.sw_if_index, self.encoded_paths, is_add=0 + ) def query_vpp_config(self): dump = self._test.vapi.mpls_tunnel_dump() for t in dump: - if self.sw_if_index == t.mt_tunnel.mt_sw_if_index and \ - self.tunnel_index == t.mt_tunnel.mt_tunnel_index: + if ( + self.sw_if_index == t.mt_tunnel.mt_sw_if_index + and self.tunnel_index == t.mt_tunnel.mt_tunnel_index + ): return True return False def object_id(self): - return ("mpls-tunnel%d-%d" % (self.tunnel_index, - self.sw_if_index)) + return "mpls-tunnel%d-%d" % (self.tunnel_index, self.sw_if_index) diff --git a/test/vpp_neighbor.py b/test/vpp_neighbor.py index 9ba87005c46..d7940266605 100644 --- a/test/vpp_neighbor.py +++ b/test/vpp_neighbor.py @@ -7,6 +7,7 @@ from ipaddress import ip_address from vpp_object import VppObject from vpp_papi import mac_pton, VppEnum + try: text_type = unicode except NameError: @@ -16,13 +17,14 @@ except NameError: def find_nbr(test, sw_if_index, nbr_addr, is_static=0, mac=None): ip_addr = ip_address(text_type(nbr_addr)) e = VppEnum.vl_api_ip_neighbor_flags_t - nbrs = test.vapi.ip_neighbor_dump(sw_if_index=sw_if_index, - af=ip_addr.vapi_af) + nbrs = test.vapi.ip_neighbor_dump(sw_if_index=sw_if_index, af=ip_addr.vapi_af) for n in nbrs: - if sw_if_index == n.neighbor.sw_if_index and \ - ip_addr == n.neighbor.ip_address and \ - is_static == (n.neighbor.flags & e.IP_API_NEIGHBOR_FLAG_STATIC): + if ( + sw_if_index == n.neighbor.sw_if_index + and ip_addr == n.neighbor.ip_address + and is_static == (n.neighbor.flags & e.IP_API_NEIGHBOR_FLAG_STATIC) + ): if mac: if mac == str(n.neighbor.mac_address): return True @@ -36,8 +38,15 @@ class VppNeighbor(VppObject): ARP Entry """ - def __init__(self, test, sw_if_index, mac_addr, nbr_addr, - is_static=False, is_no_fib_entry=False): + def __init__( + self, + test, + sw_if_index, + mac_addr, + nbr_addr, + is_static=False, + is_no_fib_entry=False, + ): self._test = test self.sw_if_index = sw_if_index self.mac_addr = mac_addr @@ -52,35 +61,26 @@ class VppNeighbor(VppObject): def add_vpp_config(self): r = self._test.vapi.ip_neighbor_add_del( - self.sw_if_index, - self.mac_addr, - self.nbr_addr, - is_add=1, - flags=self.flags) + self.sw_if_index, self.mac_addr, self.nbr_addr, is_add=1, flags=self.flags + ) self.stats_index = r.stats_index self._test.registry.register(self, self._test.logger) return self def remove_vpp_config(self): self._test.vapi.ip_neighbor_add_del( - self.sw_if_index, - self.mac_addr, - self.nbr_addr, - is_add=0, - flags=self.flags) + self.sw_if_index, self.mac_addr, self.nbr_addr, is_add=0, flags=self.flags + ) def is_static(self): e = VppEnum.vl_api_ip_neighbor_flags_t - return (self.flags & e.IP_API_NEIGHBOR_FLAG_STATIC) + return self.flags & e.IP_API_NEIGHBOR_FLAG_STATIC def query_vpp_config(self): - return find_nbr(self._test, - self.sw_if_index, - self.nbr_addr, - self.is_static()) + return find_nbr(self._test, self.sw_if_index, self.nbr_addr, self.is_static()) def object_id(self): - return ("%d:%s" % (self.sw_if_index, self.nbr_addr)) + return "%d:%s" % (self.sw_if_index, self.nbr_addr) def get_stats(self): c = self._test.statistics["/net/adjacency"] diff --git a/test/vpp_object.py b/test/vpp_object.py index 8dd2afac97c..d3652b1b62c 100644 --- a/test/vpp_object.py +++ b/test/vpp_object.py @@ -4,11 +4,11 @@ import abc class VppObject(metaclass=abc.ABCMeta): - """ Abstract vpp object """ + """Abstract vpp object""" @abc.abstractmethod def add_vpp_config(self) -> None: - """ Add the configuration for this object to vpp. """ + """Add the configuration for this object to vpp.""" pass @abc.abstractmethod @@ -20,18 +20,18 @@ class VppObject(metaclass=abc.ABCMeta): @abc.abstractmethod def remove_vpp_config(self) -> None: - """ Remove the configuration for this object from vpp. """ + """Remove the configuration for this object from vpp.""" pass def object_id(self) -> str: - """ Return a unique string representing this object. """ + """Return a unique string representing this object.""" return "Undefined. for <%s %s>" % (self.__class__.__name__, id(self)) def __str__(self) -> str: return self.object_id() def __repr__(self) -> str: - return '<%s>' % self.object_id() + return "<%s>" % self.object_id() def __hash__(self) -> int: return hash(self.object_id()) @@ -49,7 +49,8 @@ class VppObject(metaclass=abc.ABCMeta): class VppObjectRegistry: - """ Class which handles automatic configuration cleanup. """ + """Class which handles automatic configuration cleanup.""" + _shared_state = {} def __init__(self) -> None: @@ -60,7 +61,7 @@ class VppObjectRegistry: self._object_dict = dict() def register(self, obj: VppObject, logger) -> None: - """ Register an object in the registry. """ + """Register an object in the registry.""" if obj.object_id() not in self._object_dict: self._object_registry.append(obj) self._object_dict[obj.object_id()] = obj @@ -69,7 +70,7 @@ class VppObjectRegistry: logger.debug("REG: duplicate add, ignoring (%s)" % obj) def unregister_all(self, logger) -> None: - """ Remove all object registrations from registry. """ + """Remove all object registrations from registry.""" logger.debug("REG: removing all object registrations") self._object_registry = [] self._object_dict = dict() @@ -93,12 +94,14 @@ class VppObjectRegistry: failed.append(obj) else: logger.info( - "REG: Skipping removal for %s, configuration not present" % - obj) + "REG: Skipping removal for %s, configuration not present" % obj + ) self.unregister_all(logger) if failed: logger.error("REG: Couldn't remove configuration for object(s):") for obj in failed: logger.error(repr(obj)) - raise Exception("Couldn't remove configuration for object(s): %s" % - (", ".join(str(x) for x in failed))) + raise Exception( + "Couldn't remove configuration for object(s): %s" + % (", ".join(str(x) for x in failed)) + ) diff --git a/test/vpp_papi_exceptions.py b/test/vpp_papi_exceptions.py index 2f7da963f70..611e5a3845d 100644 --- a/test/vpp_papi_exceptions.py +++ b/test/vpp_papi_exceptions.py @@ -1,13 +1,13 @@ class CliFailedCommandError(Exception): - """ cli command failed.""" + """cli command failed.""" class CliSyntaxError(Exception): - """ cli command had a syntax error.""" + """cli command had a syntax error.""" class UnexpectedApiReturnValueError(Exception): - """ exception raised when the API return value is unexpected """ + """exception raised when the API return value is unexpected""" def __init__(self, retval, message): self.retval = retval diff --git a/test/vpp_papi_provider.py b/test/vpp_papi_provider.py index 9ff616c18e8..a4a3799f916 100644 --- a/test/vpp_papi_provider.py +++ b/test/vpp_papi_provider.py @@ -12,93 +12,215 @@ from six import moves, iteritems from config import config from vpp_papi import VPPApiClient from hook import Hook -from vpp_papi_exceptions import CliFailedCommandError, CliSyntaxError,\ - UnexpectedApiReturnValueError +from vpp_papi_exceptions import ( + CliFailedCommandError, + CliSyntaxError, + UnexpectedApiReturnValueError, +) # # Dictionary keyed on message name to override default values for # named parameters # defaultmapping = { - - 'acl_interface_add_del': {'is_add': 1, 'is_input': 1}, - 'bd_ip_mac_add_del': {'is_add': 1, }, - 'bfd_udp_add': {'is_authenticated': False, 'bfd_key_id': None, - 'conf_key_id': None}, - 'bfd_udp_auth_activate': {'bfd_key_id': None, 'conf_key_id': None, - 'is_delayed': False}, - 'bier_disp_entry_add_del': {'next_hop_rpf_id': -1, 'next_hop_is_ip4': 1, - 'is_add': 1, }, - 'bier_disp_table_add_del': {'is_add': 1, }, - 'bier_imp_add': {'is_add': 1, }, - 'bier_route_add_del': {'is_add': 1, }, - 'bier_table_add_del': {'is_add': 1, }, - 'bridge_domain_add_del': {'flood': 1, 'uu_flood': 1, 'forward': 1, - 'learn': 1, 'is_add': 1, }, - 'bvi_delete': {}, - 'geneve_add_del_tunnel': {'mcast_sw_if_index': 4294967295, 'is_add': 1, - 'decap_next_index': 4294967295, }, - 'input_acl_set_interface': {'ip4_table_index': 4294967295, - 'ip6_table_index': 4294967295, - 'l2_table_index': 4294967295, }, - 'ip6_add_del_address_using_prefix': {'is_add': 1, }, - 'ip6nd_send_router_solicitation': {'irt': 1, 'mrt': 120, }, - 'ip_add_del_route': {'next_hop_sw_if_index': 4294967295, - 'next_hop_weight': 1, 'next_hop_via_label': 1048576, - 'classify_table_index': 4294967295, 'is_add': 1, }, - 'ip_mroute_add_del': {'is_add': 1, }, - 'ip_neighbor_add_del': {'is_add': 1, }, - 'ipsec_interface_add_del_spd': {'is_add': 1, }, - 'ipsec_spd_add_del': {'is_add': 1, }, - 'ipsec_spd_dump': {'sa_id': 4294967295, }, - 'ipsec_spd_entry_add_del': {'local_port_stop': 65535, - 'remote_port_stop': 65535, 'priority': 100, - 'is_outbound': 1, - 'is_add': 1, }, - 'ipsec_tunnel_if_add_del': {'is_add': 1, 'anti_replay': 1, }, - 'l2_emulation': {'enable': 1, }, - 'l2fib_add_del': {'is_add': 1, }, - 'lisp_add_del_adjacency': {'is_add': 1, }, - 'lisp_add_del_local_eid': {'is_add': 1, }, - 'lisp_add_del_locator': {'priority': 1, 'weight': 1, 'is_add': 1, }, - 'lisp_add_del_locator_set': {'is_add': 1, }, - 'lisp_add_del_remote_mapping': {'is_add': 1, }, - 'macip_acl_interface_add_del': {'is_add': 1, }, - 'mpls_ip_bind_unbind': {'is_ip4': 1, 'is_bind': 1, }, - 'mpls_route_add_del': {'mr_next_hop_sw_if_index': 4294967295, - 'mr_next_hop_weight': 1, - 'mr_next_hop_via_label': 1048576, - 'mr_is_add': 1, - 'mr_classify_table_index': 4294967295, }, - 'mpls_table_add_del': {'is_add': 1, }, - 'mpls_tunnel_add_del': {'next_hop_sw_if_index': 4294967295, - 'next_hop_weight': 1, - 'next_hop_via_label': 1048576, - 'is_add': 1, }, - 'output_acl_set_interface': {'ip4_table_index': 4294967295, - 'ip6_table_index': 4294967295, - 'l2_table_index': 4294967295, }, - 'pppoe_add_del_session': {'is_add': 1, }, - 'policer_add_del': {'is_add': 1, 'conform_action': {'type': 1}, }, - 'set_ipfix_exporter': {'collector_port': 4739, }, - 'sr_policy_add': {'weight': 1, 'is_encap': 1, }, - 'sw_interface_add_del_address': {'is_add': 1, }, - 'sw_interface_ip6nd_ra_prefix': {'val_lifetime': 4294967295, - 'pref_lifetime': 4294967295, }, - 'sw_interface_set_ip_directed_broadcast': {'enable': 1, }, - 'sw_interface_set_l2_bridge': {'enable': 1, }, - 'sw_interface_set_mpls_enable': {'enable': 1, }, - 'sw_interface_set_mtu': {'mtu': [0, 0, 0, 0], }, - 'sw_interface_set_unnumbered': {'is_add': 1, }, - 'sw_interface_span_enable_disable': {'state': 1, }, - 'vxlan_add_del_tunnel': {'mcast_sw_if_index': 4294967295, 'is_add': 1, - 'decap_next_index': 4294967295, - 'instance': 4294967295, }, - 'want_bfd_events': {'enable_disable': 1, }, - 'want_igmp_events': {'enable': 1, }, - 'want_interface_events': {'enable_disable': 1, }, - 'want_l2_macs_events': {'enable_disable': 1, 'pid': os.getpid(), }, - 'want_l2_macs_events2': {'enable_disable': 1, 'pid': os.getpid(), }, + "acl_interface_add_del": {"is_add": 1, "is_input": 1}, + "bd_ip_mac_add_del": { + "is_add": 1, + }, + "bfd_udp_add": {"is_authenticated": False, "bfd_key_id": None, "conf_key_id": None}, + "bfd_udp_auth_activate": { + "bfd_key_id": None, + "conf_key_id": None, + "is_delayed": False, + }, + "bier_disp_entry_add_del": { + "next_hop_rpf_id": -1, + "next_hop_is_ip4": 1, + "is_add": 1, + }, + "bier_disp_table_add_del": { + "is_add": 1, + }, + "bier_imp_add": { + "is_add": 1, + }, + "bier_route_add_del": { + "is_add": 1, + }, + "bier_table_add_del": { + "is_add": 1, + }, + "bridge_domain_add_del": { + "flood": 1, + "uu_flood": 1, + "forward": 1, + "learn": 1, + "is_add": 1, + }, + "bvi_delete": {}, + "geneve_add_del_tunnel": { + "mcast_sw_if_index": 4294967295, + "is_add": 1, + "decap_next_index": 4294967295, + }, + "input_acl_set_interface": { + "ip4_table_index": 4294967295, + "ip6_table_index": 4294967295, + "l2_table_index": 4294967295, + }, + "ip6_add_del_address_using_prefix": { + "is_add": 1, + }, + "ip6nd_send_router_solicitation": { + "irt": 1, + "mrt": 120, + }, + "ip_add_del_route": { + "next_hop_sw_if_index": 4294967295, + "next_hop_weight": 1, + "next_hop_via_label": 1048576, + "classify_table_index": 4294967295, + "is_add": 1, + }, + "ip_mroute_add_del": { + "is_add": 1, + }, + "ip_neighbor_add_del": { + "is_add": 1, + }, + "ipsec_interface_add_del_spd": { + "is_add": 1, + }, + "ipsec_spd_add_del": { + "is_add": 1, + }, + "ipsec_spd_dump": { + "sa_id": 4294967295, + }, + "ipsec_spd_entry_add_del": { + "local_port_stop": 65535, + "remote_port_stop": 65535, + "priority": 100, + "is_outbound": 1, + "is_add": 1, + }, + "ipsec_tunnel_if_add_del": { + "is_add": 1, + "anti_replay": 1, + }, + "l2_emulation": { + "enable": 1, + }, + "l2fib_add_del": { + "is_add": 1, + }, + "lisp_add_del_adjacency": { + "is_add": 1, + }, + "lisp_add_del_local_eid": { + "is_add": 1, + }, + "lisp_add_del_locator": { + "priority": 1, + "weight": 1, + "is_add": 1, + }, + "lisp_add_del_locator_set": { + "is_add": 1, + }, + "lisp_add_del_remote_mapping": { + "is_add": 1, + }, + "macip_acl_interface_add_del": { + "is_add": 1, + }, + "mpls_ip_bind_unbind": { + "is_ip4": 1, + "is_bind": 1, + }, + "mpls_route_add_del": { + "mr_next_hop_sw_if_index": 4294967295, + "mr_next_hop_weight": 1, + "mr_next_hop_via_label": 1048576, + "mr_is_add": 1, + "mr_classify_table_index": 4294967295, + }, + "mpls_table_add_del": { + "is_add": 1, + }, + "mpls_tunnel_add_del": { + "next_hop_sw_if_index": 4294967295, + "next_hop_weight": 1, + "next_hop_via_label": 1048576, + "is_add": 1, + }, + "output_acl_set_interface": { + "ip4_table_index": 4294967295, + "ip6_table_index": 4294967295, + "l2_table_index": 4294967295, + }, + "pppoe_add_del_session": { + "is_add": 1, + }, + "policer_add_del": { + "is_add": 1, + "conform_action": {"type": 1}, + }, + "set_ipfix_exporter": { + "collector_port": 4739, + }, + "sr_policy_add": { + "weight": 1, + "is_encap": 1, + }, + "sw_interface_add_del_address": { + "is_add": 1, + }, + "sw_interface_ip6nd_ra_prefix": { + "val_lifetime": 4294967295, + "pref_lifetime": 4294967295, + }, + "sw_interface_set_ip_directed_broadcast": { + "enable": 1, + }, + "sw_interface_set_l2_bridge": { + "enable": 1, + }, + "sw_interface_set_mpls_enable": { + "enable": 1, + }, + "sw_interface_set_mtu": { + "mtu": [0, 0, 0, 0], + }, + "sw_interface_set_unnumbered": { + "is_add": 1, + }, + "sw_interface_span_enable_disable": { + "state": 1, + }, + "vxlan_add_del_tunnel": { + "mcast_sw_if_index": 4294967295, + "is_add": 1, + "decap_next_index": 4294967295, + "instance": 4294967295, + }, + "want_bfd_events": { + "enable_disable": 1, + }, + "want_igmp_events": { + "enable": 1, + }, + "want_interface_events": { + "enable_disable": 1, + }, + "want_l2_macs_events": { + "enable_disable": 1, + "pid": os.getpid(), + }, + "want_l2_macs_events2": { + "enable_disable": 1, + "pid": os.getpid(), + }, } @@ -125,35 +247,37 @@ class VppPapiProvider(object): # calling the constructor. VPPApiClient.apidir = config.vpp_install_dir - self.vpp = VPPApiClient(logger=test_class.logger, - read_timeout=read_timeout, - use_socket=True, - server_address=test_class.get_api_sock_path()) + self.vpp = VPPApiClient( + logger=test_class.logger, + read_timeout=read_timeout, + use_socket=True, + server_address=test_class.get_api_sock_path(), + ) self._events = queue.Queue() def __enter__(self): return self def assert_negative_api_retval(self): - """ Expect API failure - used with with, e.g.:: + """Expect API failure - used with with, e.g.:: - with self.vapi.assert_negative_api_retval(): - self.vapi.<api call expected to fail> + with self.vapi.assert_negative_api_retval(): + self.vapi.<api call expected to fail> - .. + .. """ self._expect_stack.append(self._expect_api_retval) self._expect_api_retval = self._negative return self def assert_zero_api_retval(self): - """ Expect API success - used with with, e.g.:: + """Expect API success - used with with, e.g.:: - with self.vapi.assert_negative_api_retval(): - self.vapi.<api call expected to succeed> + with self.vapi.assert_negative_api_retval(): + self.vapi.<api call expected to succeed> - :note: this is useful only inside another with block - as success is the default expected value + :note: this is useful only inside another with block + as success is the default expected value """ self._expect_stack.append(self._expect_api_retval) self._expect_api_retval = self._zero @@ -171,7 +295,7 @@ class VppPapiProvider(object): self.hook = hook def collect_events(self): - """ Collect all events from the internal queue and clear the queue. """ + """Collect all events from the internal queue and clear the queue.""" result = [] while True: try: @@ -182,26 +306,25 @@ class VppPapiProvider(object): return result def wait_for_event(self, timeout, name=None): - """ Wait for and return next event. """ + """Wait for and return next event.""" if name: - self.test_class.logger.debug("Expecting event '%s' within %ss", - name, timeout) + self.test_class.logger.debug( + "Expecting event '%s' within %ss", name, timeout + ) else: - self.test_class.logger.debug("Expecting event within %ss", - timeout) + self.test_class.logger.debug("Expecting event within %ss", timeout) try: e = self._events.get(timeout=timeout) except queue.Empty: raise Exception("Event did not occur within timeout") msgname = type(e).__name__ if name and msgname != name: - raise Exception("Unexpected event received: %s, expected: %s" - % msgname) + raise Exception("Unexpected event received: %s, expected: %s" % msgname) self.test_class.logger.debug("Returning event %s:%s" % (name, e)) return e def __call__(self, name, event): - """ Enqueue event in the internal event queue. """ + """Enqueue event in the internal event queue.""" self.test_class.logger.debug("New event: %s: %s" % (name, event)) self._events.put(event) @@ -255,7 +378,7 @@ class VppPapiProvider(object): self.vpp.disconnect() def api(self, api_fn, api_args, expected_retval=0): - """ Call API function and check it's return value. + """Call API function and check it's return value. Call the appropriate hooks before and after the API call :param api_fn: API function to call @@ -267,32 +390,44 @@ class VppPapiProvider(object): self.hook.before_api(api_fn.__name__, api_args) reply = api_fn(**api_args) if self._expect_api_retval == self._negative: - if hasattr(reply, 'retval') and reply.retval >= 0: - msg = "%s(%s) passed unexpectedly: expected negative " \ - "return value instead of %d in %s" % \ - (api_fn.__name__, as_fn_signature(api_args), - reply.retval, - moves.reprlib.repr(reply)) + if hasattr(reply, "retval") and reply.retval >= 0: + msg = ( + "%s(%s) passed unexpectedly: expected negative " + "return value instead of %d in %s" + % ( + api_fn.__name__, + as_fn_signature(api_args), + reply.retval, + moves.reprlib.repr(reply), + ) + ) self.test_class.logger.info(msg) raise UnexpectedApiReturnValueError(reply.retval, msg) elif self._expect_api_retval == self._zero: - if hasattr(reply, 'retval') and reply.retval != expected_retval: - msg = "%s(%s) failed, expected %d return value instead " \ - "of %d in %s" % (api_fn.__name__, - as_fn_signature(api_args), - expected_retval, reply.retval, - repr(reply)) + if hasattr(reply, "retval") and reply.retval != expected_retval: + msg = ( + "%s(%s) failed, expected %d return value instead " + "of %d in %s" + % ( + api_fn.__name__, + as_fn_signature(api_args), + expected_retval, + reply.retval, + repr(reply), + ) + ) self.test_class.logger.info(msg) raise UnexpectedApiReturnValueError(reply.retval, msg) else: - raise Exception("Internal error, unexpected value for " - "self._expect_api_retval %s" % - self._expect_api_retval) + raise Exception( + "Internal error, unexpected value for " + "self._expect_api_retval %s" % self._expect_api_retval + ) self.hook.after_api(api_fn.__name__, api_args) return reply def cli_return_response(self, cli): - """ Execute a CLI, calling the before/after hooks appropriately. + """Execute a CLI, calling the before/after hooks appropriately. Return the reply without examining it :param cli: CLI to execute @@ -300,13 +435,13 @@ class VppPapiProvider(object): """ self.hook.before_cli(cli) - cli += '\n' + cli += "\n" r = self.papi.cli_inband(cmd=cli) self.hook.after_cli(cli) return r def cli(self, cli): - """ Execute a CLI, calling the before/after hooks appropriately. + """Execute a CLI, calling the before/after hooks appropriately. :param cli: CLI to execute :returns: CLI output @@ -317,35 +452,43 @@ class VppPapiProvider(object): raise CliSyntaxError(r.reply) if r.retval != 0: raise CliFailedCommandError(r.reply) - if hasattr(r, 'reply'): + if hasattr(r, "reply"): return r.reply def ppcli(self, cli): - """ Helper method to print CLI command in case of info logging level. + """Helper method to print CLI command in case of info logging level. :param cli: CLI to execute :returns: CLI output """ return cli + "\n" + self.cli(cli) - def ip6nd_send_router_solicitation(self, sw_if_index, irt=1, mrt=120, - mrc=0, mrd=0): - return self.api(self.papi.ip6nd_send_router_solicitation, - {'irt': irt, - 'mrt': mrt, - 'mrc': mrc, - 'mrd': mrd, - 'sw_if_index': sw_if_index}) + def ip6nd_send_router_solicitation(self, sw_if_index, irt=1, mrt=120, mrc=0, mrd=0): + return self.api( + self.papi.ip6nd_send_router_solicitation, + { + "irt": irt, + "mrt": mrt, + "mrc": mrc, + "mrd": mrd, + "sw_if_index": sw_if_index, + }, + ) def want_interface_events(self, enable_disable=1): - return self.api(self.papi.want_interface_events, - {'enable_disable': enable_disable, - 'pid': os.getpid(), }) + return self.api( + self.papi.want_interface_events, + { + "enable_disable": enable_disable, + "pid": os.getpid(), + }, + ) def sw_interface_set_mac_address(self, sw_if_index, mac): - return self.api(self.papi.sw_interface_set_mac_address, - {'sw_if_index': sw_if_index, - 'mac_address': mac}) + return self.api( + self.papi.sw_interface_set_mac_address, + {"sw_if_index": sw_if_index, "mac_address": mac}, + ) def p2p_ethernet_add(self, sw_if_index, remote_mac, subif_id): """Create p2p ethernet subinterface @@ -356,9 +499,12 @@ class VppPapiProvider(object): """ return self.api( self.papi.p2p_ethernet_add, - {'parent_if_index': sw_if_index, - 'remote_mac': remote_mac, - 'subif_id': subif_id}) + { + "parent_if_index": sw_if_index, + "remote_mac": remote_mac, + "subif_id": subif_id, + }, + ) def p2p_ethernet_del(self, sw_if_index, remote_mac): """Delete p2p ethernet subinterface @@ -369,8 +515,8 @@ class VppPapiProvider(object): """ return self.api( self.papi.p2p_ethernet_del, - {'parent_if_index': sw_if_index, - 'remote_mac': remote_mac}) + {"parent_if_index": sw_if_index, "remote_mac": remote_mac}, + ) def create_vlan_subif(self, sw_if_index, vlan): """ @@ -379,42 +525,32 @@ class VppPapiProvider(object): :param sw_if_index: """ - return self.api(self.papi.create_vlan_subif, - {'sw_if_index': sw_if_index, - 'vlan_id': vlan}) + return self.api( + self.papi.create_vlan_subif, {"sw_if_index": sw_if_index, "vlan_id": vlan} + ) - def create_loopback(self, mac=''): + def create_loopback(self, mac=""): """ :param mac: (Optional) """ - return self.api(self.papi.create_loopback, - {'mac_address': mac}) + return self.api(self.papi.create_loopback, {"mac_address": mac}) def ip_route_dump(self, table_id, is_ip6=False): - return self.api(self.papi.ip_route_dump, - {'table': { - 'table_id': table_id, - 'is_ip6': is_ip6 - }}) + return self.api( + self.papi.ip_route_dump, {"table": {"table_id": table_id, "is_ip6": is_ip6}} + ) def ip_route_v2_dump(self, table_id, is_ip6=False, src=0): - return self.api(self.papi.ip_route_v2_dump, - { - 'src': src, - 'table': { - 'table_id': table_id, - 'is_ip6': is_ip6 - } - }) - - def ip_neighbor_add_del(self, - sw_if_index, - mac_address, - ip_address, - is_add=1, - flags=0): - """ Add neighbor MAC to IPv4 or IPv6 address. + return self.api( + self.papi.ip_route_v2_dump, + {"src": src, "table": {"table_id": table_id, "is_ip6": is_ip6}}, + ) + + def ip_neighbor_add_del( + self, sw_if_index, mac_address, ip_address, is_add=1, flags=0 + ): + """Add neighbor MAC to IPv4 or IPv6 address. :param sw_if_index: :param mac_address: @@ -425,23 +561,18 @@ class VppPapiProvider(object): return self.api( self.papi.ip_neighbor_add_del, { - 'is_add': is_add, - 'neighbor': { - 'sw_if_index': sw_if_index, - 'flags': flags, - 'mac_address': mac_address, - 'ip_address': ip_address - } - } + "is_add": is_add, + "neighbor": { + "sw_if_index": sw_if_index, + "flags": flags, + "mac_address": mac_address, + "ip_address": ip_address, + }, + }, ) - def udp_encap_add(self, - src_ip, - dst_ip, - src_port, - dst_port, - table_id=0): - """ Add a GRE tunnel + def udp_encap_add(self, src_ip, dst_ip, src_port, dst_port, table_id=0): + """Add a GRE tunnel :param src_ip: :param dst_ip: :param src_port: @@ -452,39 +583,34 @@ class VppPapiProvider(object): return self.api( self.papi.udp_encap_add, { - 'udp_encap': { - 'src_ip': src_ip, - 'dst_ip': dst_ip, - 'src_port': src_port, - 'dst_port': dst_port, - 'table_id': table_id + "udp_encap": { + "src_ip": src_ip, + "dst_ip": dst_ip, + "src_port": src_port, + "dst_port": dst_port, + "table_id": table_id, } - }) + }, + ) def udp_encap_del(self, id): - return self.api(self.papi.udp_encap_del, {'id': id}) + return self.api(self.papi.udp_encap_del, {"id": id}) def udp_encap_dump(self): return self.api(self.papi.udp_encap_dump, {}) def want_udp_encap_stats(self, enable=1): - return self.api(self.papi.want_udp_encap_stats, - {'enable': enable, - 'pid': os.getpid()}) + return self.api( + self.papi.want_udp_encap_stats, {"enable": enable, "pid": os.getpid()} + ) def mpls_route_dump(self, table_id): - return self.api(self.papi.mpls_route_dump, - {'table': { - 'mt_table_id': table_id - }}) + return self.api(self.papi.mpls_route_dump, {"table": {"mt_table_id": table_id}}) def mpls_table_dump(self): return self.api(self.papi.mpls_table_dump, {}) - def mpls_table_add_del( - self, - table_id, - is_add=1): + def mpls_table_add_del(self, table_id, is_add=1): """ :param table_id @@ -494,82 +620,74 @@ class VppPapiProvider(object): return self.api( self.papi.mpls_table_add_del, - {'mt_table': - { - 'mt_table_id': table_id, - }, - 'mt_is_add': is_add}) - - def mpls_route_add_del(self, - table_id, - label, - eos, - eos_proto, - is_multicast, - paths, - is_add, - is_multipath): - """ MPLS Route add/del """ + { + "mt_table": { + "mt_table_id": table_id, + }, + "mt_is_add": is_add, + }, + ) + + def mpls_route_add_del( + self, table_id, label, eos, eos_proto, is_multicast, paths, is_add, is_multipath + ): + """MPLS Route add/del""" return self.api( self.papi.mpls_route_add_del, - {'mr_route': - { - 'mr_table_id': table_id, - 'mr_label': label, - 'mr_eos': eos, - 'mr_eos_proto': eos_proto, - 'mr_is_multicast': is_multicast, - 'mr_n_paths': len(paths), - 'mr_paths': paths, - }, - 'mr_is_add': is_add, - 'mr_is_multipath': is_multipath}) - - def mpls_ip_bind_unbind( - self, - label, - prefix, - table_id=0, - ip_table_id=0, - is_bind=1): - """ - """ + { + "mr_route": { + "mr_table_id": table_id, + "mr_label": label, + "mr_eos": eos, + "mr_eos_proto": eos_proto, + "mr_is_multicast": is_multicast, + "mr_n_paths": len(paths), + "mr_paths": paths, + }, + "mr_is_add": is_add, + "mr_is_multipath": is_multipath, + }, + ) + + def mpls_ip_bind_unbind(self, label, prefix, table_id=0, ip_table_id=0, is_bind=1): + """ """ return self.api( self.papi.mpls_ip_bind_unbind, - {'mb_mpls_table_id': table_id, - 'mb_label': label, - 'mb_ip_table_id': ip_table_id, - 'mb_is_bind': is_bind, - 'mb_prefix': prefix}) + { + "mb_mpls_table_id": table_id, + "mb_label": label, + "mb_ip_table_id": ip_table_id, + "mb_is_bind": is_bind, + "mb_prefix": prefix, + }, + ) def mpls_tunnel_add_del( - self, - tun_sw_if_index, - paths, - is_add=1, - l2_only=0, - is_multicast=0): - """ - """ + self, tun_sw_if_index, paths, is_add=1, l2_only=0, is_multicast=0 + ): + """ """ return self.api( self.papi.mpls_tunnel_add_del, - {'mt_is_add': is_add, - 'mt_tunnel': - { - 'mt_sw_if_index': tun_sw_if_index, - 'mt_l2_only': l2_only, - 'mt_is_multicast': is_multicast, - 'mt_n_paths': len(paths), - 'mt_paths': paths, - }}) + { + "mt_is_add": is_add, + "mt_tunnel": { + "mt_sw_if_index": tun_sw_if_index, + "mt_l2_only": l2_only, + "mt_is_multicast": is_multicast, + "mt_n_paths": len(paths), + "mt_paths": paths, + }, + }, + ) def input_acl_set_interface( - self, - is_add, - sw_if_index, - ip4_table_index=0xFFFFFFFF, - ip6_table_index=0xFFFFFFFF, - l2_table_index=0xFFFFFFFF): + self, + is_add, + sw_if_index, + ip4_table_index=0xFFFFFFFF, + ip6_table_index=0xFFFFFFFF, + l2_table_index=0xFFFFFFFF, + ): """ :param is_add: :param sw_if_index: @@ -580,19 +698,23 @@ class VppPapiProvider(object): return self.api( self.papi.input_acl_set_interface, - {'sw_if_index': sw_if_index, - 'ip4_table_index': ip4_table_index, - 'ip6_table_index': ip6_table_index, - 'l2_table_index': l2_table_index, - 'is_add': is_add}) + { + "sw_if_index": sw_if_index, + "ip4_table_index": ip4_table_index, + "ip6_table_index": ip6_table_index, + "l2_table_index": l2_table_index, + "is_add": is_add, + }, + ) def output_acl_set_interface( - self, - is_add, - sw_if_index, - ip4_table_index=0xFFFFFFFF, - ip6_table_index=0xFFFFFFFF, - l2_table_index=0xFFFFFFFF): + self, + is_add, + sw_if_index, + ip4_table_index=0xFFFFFFFF, + ip6_table_index=0xFFFFFFFF, + l2_table_index=0xFFFFFFFF, + ): """ :param is_add: :param sw_if_index: @@ -603,50 +725,50 @@ class VppPapiProvider(object): return self.api( self.papi.output_acl_set_interface, - {'sw_if_index': sw_if_index, - 'ip4_table_index': ip4_table_index, - 'ip6_table_index': ip6_table_index, - 'l2_table_index': l2_table_index, - 'is_add': is_add}) + { + "sw_if_index": sw_if_index, + "ip4_table_index": ip4_table_index, + "ip6_table_index": ip6_table_index, + "l2_table_index": l2_table_index, + "is_add": is_add, + }, + ) def set_ipfix_exporter( - self, - collector_address, - src_address, - path_mtu, - template_interval, - vrf_id=0, - collector_port=4739, - udp_checksum=0): + self, + collector_address, + src_address, + path_mtu, + template_interval, + vrf_id=0, + collector_port=4739, + udp_checksum=0, + ): return self.api( self.papi.set_ipfix_exporter, { - 'collector_address': collector_address, - 'collector_port': collector_port, - 'src_address': src_address, - 'vrf_id': vrf_id, - 'path_mtu': path_mtu, - 'template_interval': template_interval, - 'udp_checksum': udp_checksum, - }) + "collector_address": collector_address, + "collector_port": collector_port, + "src_address": src_address, + "vrf_id": vrf_id, + "path_mtu": path_mtu, + "template_interval": template_interval, + "udp_checksum": udp_checksum, + }, + ) def mfib_signal_dump(self): return self.api(self.papi.mfib_signal_dump, {}) def ip_mroute_dump(self, table_id, is_ip6=False): - return self.api(self.papi.ip_mroute_dump, - {'table': { - 'table_id': table_id, - 'is_ip6': is_ip6 - }}) + return self.api( + self.papi.ip_mroute_dump, + {"table": {"table_id": table_id, "is_ip6": is_ip6}}, + ) def pppoe_add_del_session( - self, - client_ip, - client_mac, - session_id=0, - is_add=1, - decap_vrf_id=0): + self, client_ip, client_mac, session_id=0, is_add=1, decap_vrf_id=0 + ): """ :param is_add: (Default value = 1) @@ -657,139 +779,155 @@ class VppPapiProvider(object): :param decap_vrf_id: (Default value = 0) """ - return self.api(self.papi.pppoe_add_del_session, - {'is_add': is_add, - 'session_id': session_id, - 'client_ip': client_ip, - 'decap_vrf_id': decap_vrf_id, - 'client_mac': client_mac}) + return self.api( + self.papi.pppoe_add_del_session, + { + "is_add": is_add, + "session_id": session_id, + "client_ip": client_ip, + "decap_vrf_id": decap_vrf_id, + "client_mac": client_mac, + }, + ) def sr_mpls_policy_add(self, bsid, weight, type, segments): - return self.api(self.papi.sr_mpls_policy_add, - {'bsid': bsid, - 'weight': weight, - 'is_spray': type, - 'n_segments': len(segments), - 'segments': segments}) + return self.api( + self.papi.sr_mpls_policy_add, + { + "bsid": bsid, + "weight": weight, + "is_spray": type, + "n_segments": len(segments), + "segments": segments, + }, + ) def sr_mpls_policy_del(self, bsid): - return self.api(self.papi.sr_mpls_policy_del, - {'bsid': bsid}) + return self.api(self.papi.sr_mpls_policy_del, {"bsid": bsid}) - def bier_table_add_del(self, - bti, - mpls_label, - is_add=1): - """ BIER Table add/del """ + def bier_table_add_del(self, bti, mpls_label, is_add=1): + """BIER Table add/del""" return self.api( self.papi.bier_table_add_del, - {'bt_tbl_id': {"bt_set": bti.set_id, - "bt_sub_domain": bti.sub_domain_id, - "bt_hdr_len_id": bti.hdr_len_id}, - 'bt_label': mpls_label, - 'bt_is_add': is_add}) + { + "bt_tbl_id": { + "bt_set": bti.set_id, + "bt_sub_domain": bti.sub_domain_id, + "bt_hdr_len_id": bti.hdr_len_id, + }, + "bt_label": mpls_label, + "bt_is_add": is_add, + }, + ) def bier_table_dump(self): return self.api(self.papi.bier_table_dump, {}) - def bier_route_add_del(self, - bti, - bp, - paths, - is_add=1, - is_replace=0): - """ BIER Route add/del """ + def bier_route_add_del(self, bti, bp, paths, is_add=1, is_replace=0): + """BIER Route add/del""" return self.api( self.papi.bier_route_add_del, { - 'br_route': { - 'br_tbl_id': {"bt_set": bti.set_id, - "bt_sub_domain": bti.sub_domain_id, - "bt_hdr_len_id": bti.hdr_len_id}, - 'br_bp': bp, - 'br_n_paths': len(paths), - 'br_paths': paths, + "br_route": { + "br_tbl_id": { + "bt_set": bti.set_id, + "bt_sub_domain": bti.sub_domain_id, + "bt_hdr_len_id": bti.hdr_len_id, + }, + "br_bp": bp, + "br_n_paths": len(paths), + "br_paths": paths, }, - 'br_is_add': is_add, - 'br_is_replace': is_replace - }) + "br_is_add": is_add, + "br_is_replace": is_replace, + }, + ) def bier_route_dump(self, bti): return self.api( self.papi.bier_route_dump, - {'br_tbl_id': {"bt_set": bti.set_id, - "bt_sub_domain": bti.sub_domain_id, - "bt_hdr_len_id": bti.hdr_len_id}}) + { + "br_tbl_id": { + "bt_set": bti.set_id, + "bt_sub_domain": bti.sub_domain_id, + "bt_hdr_len_id": bti.hdr_len_id, + } + }, + ) - def bier_imp_add(self, - bti, - src, - ibytes, - is_add=1): - """ BIER Imposition Add """ + def bier_imp_add(self, bti, src, ibytes, is_add=1): + """BIER Imposition Add""" return self.api( self.papi.bier_imp_add, - {'bi_tbl_id': {"bt_set": bti.set_id, - "bt_sub_domain": bti.sub_domain_id, - "bt_hdr_len_id": bti.hdr_len_id}, - 'bi_src': src, - 'bi_n_bytes': len(ibytes), - 'bi_bytes': ibytes}) + { + "bi_tbl_id": { + "bt_set": bti.set_id, + "bt_sub_domain": bti.sub_domain_id, + "bt_hdr_len_id": bti.hdr_len_id, + }, + "bi_src": src, + "bi_n_bytes": len(ibytes), + "bi_bytes": ibytes, + }, + ) def bier_imp_del(self, bi_index): - """ BIER Imposition del """ - return self.api( - self.papi.bier_imp_del, - {'bi_index': bi_index}) + """BIER Imposition del""" + return self.api(self.papi.bier_imp_del, {"bi_index": bi_index}) def bier_imp_dump(self): return self.api(self.papi.bier_imp_dump, {}) - def bier_disp_table_add_del(self, - bdti, - is_add=1): - """ BIER Disposition Table add/del """ + def bier_disp_table_add_del(self, bdti, is_add=1): + """BIER Disposition Table add/del""" return self.api( self.papi.bier_disp_table_add_del, - {'bdt_tbl_id': bdti, - 'bdt_is_add': is_add}) + {"bdt_tbl_id": bdti, "bdt_is_add": is_add}, + ) def bier_disp_table_dump(self): return self.api(self.papi.bier_disp_table_dump, {}) - def bier_disp_entry_add_del(self, - bdti, - bp, - payload_proto, - next_hop_afi, - next_hop, - next_hop_tbl_id=0, - next_hop_rpf_id=~0, - next_hop_is_ip4=1, - is_add=1): - """ BIER Route add/del """ + def bier_disp_entry_add_del( + self, + bdti, + bp, + payload_proto, + next_hop_afi, + next_hop, + next_hop_tbl_id=0, + next_hop_rpf_id=~0, + next_hop_is_ip4=1, + is_add=1, + ): + """BIER Route add/del""" lstack = [] - while (len(lstack) < 16): + while len(lstack) < 16: lstack.append({}) return self.api( self.papi.bier_disp_entry_add_del, - {'bde_tbl_id': bdti, - 'bde_bp': bp, - 'bde_payload_proto': payload_proto, - 'bde_n_paths': 1, - 'bde_paths': [{'table_id': next_hop_tbl_id, - 'rpf_id': next_hop_rpf_id, - 'n_labels': 0, - 'label_stack': lstack}], - 'bde_is_add': is_add}) + { + "bde_tbl_id": bdti, + "bde_bp": bp, + "bde_payload_proto": payload_proto, + "bde_n_paths": 1, + "bde_paths": [ + { + "table_id": next_hop_tbl_id, + "rpf_id": next_hop_rpf_id, + "n_labels": 0, + "label_stack": lstack, + } + ], + "bde_is_add": is_add, + }, + ) def bier_disp_entry_dump(self, bdti): - return self.api( - self.papi.bier_disp_entry_dump, - {'bde_tbl_id': bdti}) + return self.api(self.papi.bier_disp_entry_dump, {"bde_tbl_id": bdti}) def ipsec_spd_add_del(self, spd_id, is_add=1): - """ SPD add/del - Wrapper to add or del ipsec SPD + """SPD add/del - Wrapper to add or del ipsec SPD Sample CLI : 'ipsec spd add 1' :param spd_id - SPD ID to be created in the vpp . mandatory @@ -798,8 +936,8 @@ class VppPapiProvider(object): :returns: reply from the API """ return self.api( - self.papi.ipsec_spd_add_del, { - 'spd_id': spd_id, 'is_add': is_add}) + self.papi.ipsec_spd_add_del, {"spd_id": spd_id, "is_add": is_add} + ) def ipsec_spds_dump(self): return self.api(self.papi.ipsec_spds_dump, {}) @@ -818,32 +956,39 @@ class VppPapiProvider(object): """ return self.api( self.papi.ipsec_interface_add_del_spd, - {'spd_id': spd_id, 'sw_if_index': sw_if_index, 'is_add': is_add}) + {"spd_id": spd_id, "sw_if_index": sw_if_index, "is_add": is_add}, + ) def ipsec_spd_interface_dump(self, spd_index=None): - return self.api(self.papi.ipsec_spd_interface_dump, - {'spd_index': spd_index if spd_index else 0, - 'spd_index_valid': 1 if spd_index else 0}) - - def ipsec_spd_entry_add_del(self, - spd_id, - sa_id, - local_address_start, - local_address_stop, - remote_address_start, - remote_address_stop, - local_port_start=0, - local_port_stop=65535, - remote_port_start=0, - remote_port_stop=65535, - protocol=0, - policy=0, - priority=100, - is_outbound=1, - is_add=1, - is_ipv6=0, - is_ip_any=0): - """ IPSEC policy SPD add/del - + return self.api( + self.papi.ipsec_spd_interface_dump, + { + "spd_index": spd_index if spd_index else 0, + "spd_index_valid": 1 if spd_index else 0, + }, + ) + + def ipsec_spd_entry_add_del( + self, + spd_id, + sa_id, + local_address_start, + local_address_stop, + remote_address_start, + remote_address_stop, + local_port_start=0, + local_port_stop=65535, + remote_port_start=0, + remote_port_stop=65535, + protocol=0, + policy=0, + priority=100, + is_outbound=1, + is_add=1, + is_ipv6=0, + is_ip_any=0, + ): + """IPSEC policy SPD add/del - Wrapper to configure ipsec SPD policy entries in VPP :param spd_id: SPD ID for the policy @@ -867,130 +1012,144 @@ class VppPapiProvider(object): return self.api( self.papi.ipsec_spd_entry_add_del, { - 'is_add': is_add, - 'entry': - { - 'spd_id': spd_id, - 'sa_id': sa_id, - 'local_address_start': local_address_start, - 'local_address_stop': local_address_stop, - 'remote_address_start': remote_address_start, - 'remote_address_stop': remote_address_stop, - 'local_port_start': local_port_start, - 'local_port_stop': local_port_stop, - 'remote_port_start': remote_port_start, - 'remote_port_stop': remote_port_stop, - 'protocol': protocol, - 'policy': policy, - 'priority': priority, - 'is_outbound': is_outbound, - } - }) - - def ipsec_spd_dump(self, spd_id, sa_id=0xffffffff): - return self.api(self.papi.ipsec_spd_dump, - {'spd_id': spd_id, - 'sa_id': sa_id}) + "is_add": is_add, + "entry": { + "spd_id": spd_id, + "sa_id": sa_id, + "local_address_start": local_address_start, + "local_address_stop": local_address_stop, + "remote_address_start": remote_address_start, + "remote_address_stop": remote_address_stop, + "local_port_start": local_port_start, + "local_port_stop": local_port_stop, + "remote_port_start": remote_port_start, + "remote_port_stop": remote_port_stop, + "protocol": protocol, + "policy": policy, + "priority": priority, + "is_outbound": is_outbound, + }, + }, + ) - def ipsec_tunnel_if_add_del(self, local_ip, remote_ip, local_spi, - remote_spi, crypto_alg, local_crypto_key, - remote_crypto_key, integ_alg, local_integ_key, - remote_integ_key, is_add=1, esn=0, salt=0, - anti_replay=1, renumber=0, - udp_encap=0, show_instance=0xffffffff): + def ipsec_spd_dump(self, spd_id, sa_id=0xFFFFFFFF): + return self.api(self.papi.ipsec_spd_dump, {"spd_id": spd_id, "sa_id": sa_id}) + + def ipsec_tunnel_if_add_del( + self, + local_ip, + remote_ip, + local_spi, + remote_spi, + crypto_alg, + local_crypto_key, + remote_crypto_key, + integ_alg, + local_integ_key, + remote_integ_key, + is_add=1, + esn=0, + salt=0, + anti_replay=1, + renumber=0, + udp_encap=0, + show_instance=0xFFFFFFFF, + ): return self.api( self.papi.ipsec_tunnel_if_add_del, { - 'local_ip': local_ip, - 'remote_ip': remote_ip, - 'local_spi': local_spi, - 'remote_spi': remote_spi, - 'crypto_alg': crypto_alg, - 'local_crypto_key_len': len(local_crypto_key), - 'local_crypto_key': local_crypto_key, - 'remote_crypto_key_len': len(remote_crypto_key), - 'remote_crypto_key': remote_crypto_key, - 'integ_alg': integ_alg, - 'local_integ_key_len': len(local_integ_key), - 'local_integ_key': local_integ_key, - 'remote_integ_key_len': len(remote_integ_key), - 'remote_integ_key': remote_integ_key, - 'is_add': is_add, - 'esn': esn, - 'anti_replay': anti_replay, - 'renumber': renumber, - 'show_instance': show_instance, - 'udp_encap': udp_encap, - 'salt': salt - }) + "local_ip": local_ip, + "remote_ip": remote_ip, + "local_spi": local_spi, + "remote_spi": remote_spi, + "crypto_alg": crypto_alg, + "local_crypto_key_len": len(local_crypto_key), + "local_crypto_key": local_crypto_key, + "remote_crypto_key_len": len(remote_crypto_key), + "remote_crypto_key": remote_crypto_key, + "integ_alg": integ_alg, + "local_integ_key_len": len(local_integ_key), + "local_integ_key": local_integ_key, + "remote_integ_key_len": len(remote_integ_key), + "remote_integ_key": remote_integ_key, + "is_add": is_add, + "esn": esn, + "anti_replay": anti_replay, + "renumber": renumber, + "show_instance": show_instance, + "udp_encap": udp_encap, + "salt": salt, + }, + ) def ipsec_select_backend(self, protocol, index): - return self.api(self.papi.ipsec_select_backend, - {'protocol': protocol, 'index': index}) + return self.api( + self.papi.ipsec_select_backend, {"protocol": protocol, "index": index} + ) def ipsec_backend_dump(self): return self.api(self.papi.ipsec_backend_dump, {}) - def punt_socket_register(self, reg, pathname, - header_version=1): - """ Register punt socket """ - return self.api(self.papi.punt_socket_register, - {'header_version': header_version, - 'punt': reg, - 'pathname': pathname}) + def punt_socket_register(self, reg, pathname, header_version=1): + """Register punt socket""" + return self.api( + self.papi.punt_socket_register, + {"header_version": header_version, "punt": reg, "pathname": pathname}, + ) def punt_socket_deregister(self, reg): - """ Unregister punt socket """ - return self.api(self.papi.punt_socket_deregister, - {'punt': reg}) + """Unregister punt socket""" + return self.api(self.papi.punt_socket_deregister, {"punt": reg}) def igmp_enable_disable(self, sw_if_index, enable, host): - """ Enable/disable IGMP on a given interface """ - return self.api(self.papi.igmp_enable_disable, - {'enable': enable, - 'mode': host, - 'sw_if_index': sw_if_index}) + """Enable/disable IGMP on a given interface""" + return self.api( + self.papi.igmp_enable_disable, + {"enable": enable, "mode": host, "sw_if_index": sw_if_index}, + ) def igmp_proxy_device_add_del(self, vrf_id, sw_if_index, add): - """ Add/del IGMP proxy device """ - return self.api(self.papi.igmp_proxy_device_add_del, - {'vrf_id': vrf_id, 'sw_if_index': sw_if_index, - 'add': add}) + """Add/del IGMP proxy device""" + return self.api( + self.papi.igmp_proxy_device_add_del, + {"vrf_id": vrf_id, "sw_if_index": sw_if_index, "add": add}, + ) def igmp_proxy_device_add_del_interface(self, vrf_id, sw_if_index, add): - """ Add/del interface to/from IGMP proxy device """ - return self.api(self.papi.igmp_proxy_device_add_del_interface, - {'vrf_id': vrf_id, 'sw_if_index': sw_if_index, - 'add': add}) + """Add/del interface to/from IGMP proxy device""" + return self.api( + self.papi.igmp_proxy_device_add_del_interface, + {"vrf_id": vrf_id, "sw_if_index": sw_if_index, "add": add}, + ) def igmp_listen(self, filter, sw_if_index, saddrs, gaddr): - """ Listen for new (S,G) on specified interface + """Listen for new (S,G) on specified interface :param enable: add/delas :param sw_if_index: interface sw index :param saddr: source ip4 addr :param gaddr: group ip4 addr """ - return self.api(self.papi.igmp_listen, - { - 'group': - { - 'filter': filter, - 'sw_if_index': sw_if_index, - 'n_srcs': len(saddrs), - 'saddrs': saddrs, - 'gaddr': gaddr - } - }) + return self.api( + self.papi.igmp_listen, + { + "group": { + "filter": filter, + "sw_if_index": sw_if_index, + "n_srcs": len(saddrs), + "saddrs": saddrs, + "gaddr": gaddr, + } + }, + ) def igmp_clear_interface(self, sw_if_index): - """ Remove all (S,G)s from specified interface - doesn't send IGMP report! + """Remove all (S,G)s from specified interface + doesn't send IGMP report! """ - return self.api( - self.papi.igmp_clear_interface, { - 'sw_if_index': sw_if_index}) + return self.api(self.papi.igmp_clear_interface, {"sw_if_index": sw_if_index}) def want_igmp_events(self, enable=1): - return self.api(self.papi.want_igmp_events, {'enable': enable, - 'pid': os.getpid()}) + return self.api( + self.papi.want_igmp_events, {"enable": enable, "pid": os.getpid()} + ) diff --git a/test/vpp_pg_interface.py b/test/vpp_pg_interface.py index 779eb0be6d9..2682774caab 100644 --- a/test/vpp_pg_interface.py +++ b/test/vpp_pg_interface.py @@ -13,20 +13,28 @@ from vpp_interface import VppInterface from vpp_papi import VppEnum from scapy.layers.l2 import Ether, ARP -from scapy.layers.inet6 import IPv6, ICMPv6ND_NS, ICMPv6ND_NA,\ - ICMPv6NDOptSrcLLAddr, ICMPv6NDOptDstLLAddr, ICMPv6ND_RA, RouterAlert, \ - IPv6ExtHdrHopByHop +from scapy.layers.inet6 import ( + IPv6, + ICMPv6ND_NS, + ICMPv6ND_NA, + ICMPv6NDOptSrcLLAddr, + ICMPv6NDOptDstLLAddr, + ICMPv6ND_RA, + RouterAlert, + IPv6ExtHdrHopByHop, +) from util import ppp, ppc, UnexpectedPacketError from scapy.utils6 import in6_getnsma, in6_getnsmac, in6_ismaddr class CaptureTimeoutError(Exception): - """ Exception raised if capture or packet doesn't appear within timeout """ + """Exception raised if capture or packet doesn't appear within timeout""" + pass def is_ipv6_misc(p): - """ Is packet one of uninteresting IPv6 broadcasts? """ + """Is packet one of uninteresting IPv6 broadcasts?""" if p.haslayer(ICMPv6ND_RA): if in6_ismaddr(p[IPv6].dst): return True @@ -72,10 +80,9 @@ class VppPGInterface(VppInterface): return self._out_path def get_in_path(self, worker): - """ pcap file path - injected packets""" + """pcap file path - injected packets""" if worker is not None: - return "%s/pg%u_wrk%u_in.pcap" % (self.test.tempdir, self.pg_index, - worker) + return "%s/pg%u_wrk%u_in.pcap" % (self.test.tempdir, self.pg_index, worker) return "%s/pg%u_in.pcap" % (self.test.tempdir, self.pg_index) @property @@ -92,7 +99,10 @@ class VppPGInterface(VppInterface): def get_input_cli(self, nb_replays=None, worker=None): """return CLI string to load the injected packets""" input_cli = "packet-generator new pcap %s source pg%u name %s" % ( - self.get_in_path(worker), self.pg_index, self.get_cap_name(worker)) + self.get_in_path(worker), + self.pg_index, + self.get_cap_name(worker), + ) if nb_replays is not None: return "%s limit %d" % (input_cli, nb_replays) if worker is not None: @@ -114,7 +124,7 @@ class VppPGInterface(VppInterface): return v def __init__(self, test, pg_index, gso, gso_size, mode): - """ Create VPP packet-generator interface """ + """Create VPP packet-generator interface""" super().__init__(test) r = test.vapi.pg_create_interface_v2(pg_index, gso, gso_size, mode) @@ -130,9 +140,10 @@ class VppPGInterface(VppInterface): self._out_file = "pg%u_out.pcap" % self.pg_index self._out_path = self.test.tempdir + "/" + self._out_file self._capture_cli = "packet-generator capture pg%u pcap %s" % ( - self.pg_index, self.out_path) - self._cap_name = "pcap%u-sw_if_index-%s" % ( - self.pg_index, self.sw_if_index) + self.pg_index, + self.out_path, + ) + self._cap_name = "pcap%u-sw_if_index-%s" % (self.pg_index, self.sw_if_index) def handle_old_pcap_file(self, path, counter): filename = os.path.basename(path) @@ -149,22 +160,22 @@ class VppPGInterface(VppInterface): try: if os.path.isfile(path): - name = "%s/history.[timestamp:%f].[%s-counter:%04d].%s" % \ - (self.test.tempdir, - time.time(), - self.name, - counter, - filename) + name = "%s/history.[timestamp:%f].[%s-counter:%04d].%s" % ( + self.test.tempdir, + time.time(), + self.name, + counter, + filename, + ) self.test.logger.debug("Renaming %s->%s" % (path, name)) os.rename(path, name) except OSError: - self.test.logger.debug("OSError: Could not rename %s %s" % - (path, filename)) + self.test.logger.debug("OSError: Could not rename %s %s" % (path, filename)) def enable_capture(self): - """ Enable capture on this packet-generator interface - of at most n packets. - If n < 0, this is no limit + """Enable capture on this packet-generator interface + of at most n packets. + If n < 0, this is no limit """ # disable the capture to flush the capture self.disable_capture() @@ -177,16 +188,14 @@ class VppPGInterface(VppInterface): self.test.vapi.cli("%s disable" % self.capture_cli) def coalesce_enable(self): - """ Enable packet coalesce on this packet-generator interface""" + """Enable packet coalesce on this packet-generator interface""" self._coalesce_enabled = 1 - self.test.vapi.pg_interface_enable_disable_coalesce(self.sw_if_index, - 1) + self.test.vapi.pg_interface_enable_disable_coalesce(self.sw_if_index, 1) def coalesce_disable(self): - """ Disable packet coalesce on this packet-generator interface""" + """Disable packet coalesce on this packet-generator interface""" self._coalesce_enabled = 0 - self.test.vapi.pg_interface_enable_disable_coalesce(self.sw_if_index, - 0) + self.test.vapi.pg_interface_enable_disable_coalesce(self.sw_if_index, 0) def add_stream(self, pkts, nb_replays=None, worker=None): """ @@ -201,31 +210,31 @@ class VppPGInterface(VppInterface): self.test.vapi.cli(self.get_input_cli(nb_replays, worker)) def generate_debug_aid(self, kind): - """ Create a hardlink to the out file with a counter and a file + """Create a hardlink to the out file with a counter and a file containing stack trace to ease debugging in case of multiple capture - files present. """ - self.test.logger.debug("Generating debug aid for %s on %s" % - (kind, self._name)) - link_path, stack_path = ["%s/debug_%s_%s_%s.%s" % - (self.test.tempdir, self._name, - self._out_assert_counter, kind, suffix) - for suffix in ["pcap", "stack"] - ] + files present.""" + self.test.logger.debug("Generating debug aid for %s on %s" % (kind, self._name)) + link_path, stack_path = [ + "%s/debug_%s_%s_%s.%s" + % (self.test.tempdir, self._name, self._out_assert_counter, kind, suffix) + for suffix in ["pcap", "stack"] + ] os.link(self.out_path, link_path) with open(stack_path, "w") as f: f.writelines(format_stack()) self._out_assert_counter += 1 def _get_capture(self, timeout, filter_out_fn=is_ipv6_misc): - """ Helper method to get capture and filter it """ + """Helper method to get capture and filter it""" try: if not self.wait_for_capture_file(timeout): return None output = rdpcap(self.out_path) self.test.logger.debug("Capture has %s packets" % len(output.res)) except: - self.test.logger.debug("Exception in scapy.rdpcap (%s): %s" % - (self.out_path, format_exc())) + self.test.logger.debug( + "Exception in scapy.rdpcap (%s): %s" % (self.out_path, format_exc()) + ) return None before = len(output.res) if filter_out_fn: @@ -233,13 +242,15 @@ class VppPGInterface(VppInterface): removed = before - len(output.res) if removed: self.test.logger.debug( - "Filtered out %s packets from capture (returning %s)" % - (removed, len(output.res))) + "Filtered out %s packets from capture (returning %s)" + % (removed, len(output.res)) + ) return output - def get_capture(self, expected_count=None, remark=None, timeout=1, - filter_out_fn=is_ipv6_misc): - """ Get captured packets + def get_capture( + self, expected_count=None, remark=None, timeout=1, filter_out_fn=is_ipv6_misc + ): + """Get captured packets :param expected_count: expected number of packets to capture, if None, then self.test.packet_count_for_dst_pg_idx is @@ -255,15 +266,16 @@ class VppPGInterface(VppInterface): name = self.name if remark is None else "%s (%s)" % (self.name, remark) based_on = "based on provided argument" if expected_count is None: - expected_count = \ - self.test.get_packet_count_for_if_idx(self.sw_if_index) + expected_count = self.test.get_packet_count_for_if_idx(self.sw_if_index) based_on = "based on stored packet_infos" if expected_count == 0: raise Exception( - "Internal error, expected packet count for %s is 0!" % - name) - self.test.logger.debug("Expecting to capture %s (%s) packets on %s" % ( - expected_count, based_on, name)) + "Internal error, expected packet count for %s is 0!" % name + ) + self.test.logger.debug( + "Expecting to capture %s (%s) packets on %s" + % (expected_count, based_on, name) + ) while remaining_time > 0: before = time.time() capture = self._get_capture(remaining_time, filter_out_fn) @@ -273,14 +285,14 @@ class VppPGInterface(VppInterface): # bingo, got the packets we expected return capture elif len(capture.res) > expected_count: - self.test.logger.error( - ppc("Unexpected packets captured:", capture)) + self.test.logger.error(ppc("Unexpected packets captured:", capture)) break else: - self.test.logger.debug("Partial capture containing %s " - "packets doesn't match expected " - "count %s (yet?)" % - (len(capture.res), expected_count)) + self.test.logger.debug( + "Partial capture containing %s " + "packets doesn't match expected " + "count %s (yet?)" % (len(capture.res), expected_count) + ) elif expected_count == 0: # bingo, got None as we expected - return empty capture return PacketList() @@ -290,26 +302,29 @@ class VppPGInterface(VppInterface): if len(capture) > 0 and 0 == expected_count: rem = f"\n{remark}" if remark else "" raise UnexpectedPacketError( - capture[0], - f"\n({len(capture)} packets captured in total){rem}") - raise Exception("Captured packets mismatch, captured %s packets, " - "expected %s packets on %s" % - (len(capture.res), expected_count, name)) + capture[0], f"\n({len(capture)} packets captured in total){rem}" + ) + raise Exception( + "Captured packets mismatch, captured %s packets, " + "expected %s packets on %s" % (len(capture.res), expected_count, name) + ) else: if 0 == expected_count: return raise Exception("No packets captured on %s" % name) - def assert_nothing_captured(self, timeout=1, remark=None, - filter_out_fn=is_ipv6_misc): - """ Assert that nothing unfiltered was captured on interface + def assert_nothing_captured( + self, timeout=1, remark=None, filter_out_fn=is_ipv6_misc + ): + """Assert that nothing unfiltered was captured on interface :param remark: remark printed into debug logs :param filter_out_fn: filter applied to each packet, packets for which the filter returns True are removed from capture """ - capture = self.get_capture(0, timeout=timeout, remark=remark, - filter_out_fn=filter_out_fn) + capture = self.get_capture( + 0, timeout=timeout, remark=remark, filter_out_fn=filter_out_fn + ) if not capture or len(capture.res) == 0: # junk filtered out, we're good return @@ -322,7 +337,7 @@ class VppPGInterface(VppInterface): # # also have a 5-minute timeout just in case things go terribly wrong... deadline = time.time() + 300 - while self.test.vapi.cli('show packet-generator').find("Yes") != -1: + while self.test.vapi.cli("show packet-generator").find("Yes") != -1: self._test.sleep(0.01) # yield if time.time() > deadline: self.test.logger.debug("Timeout waiting for pg to stop") @@ -339,19 +354,21 @@ class VppPGInterface(VppInterface): self.wait_for_pg_stop() deadline = time.time() + timeout if not os.path.isfile(self.out_path): - self.test.logger.debug("Waiting for capture file %s to appear, " - "timeout is %ss" % (self.out_path, timeout)) + self.test.logger.debug( + "Waiting for capture file %s to appear, " + "timeout is %ss" % (self.out_path, timeout) + ) else: - self.test.logger.debug("Capture file %s already exists" % - self.out_path) + self.test.logger.debug("Capture file %s already exists" % self.out_path) return True while time.time() < deadline: if os.path.isfile(self.out_path): break self._test.sleep(0) # yield if os.path.isfile(self.out_path): - self.test.logger.debug("Capture file appeared after %fs" % - (time.time() - (deadline - timeout))) + self.test.logger.debug( + "Capture file appeared after %fs" % (time.time() - (deadline - timeout)) + ) else: self.test.logger.debug("Timeout - capture file still nowhere") return False @@ -374,7 +391,8 @@ class VppPGInterface(VppInterface): if len(hdr) == packet_header_size: # parse the capture length - caplen sec, usec, caplen, wirelen = struct.unpack( - self._pcap_reader.endian + "IIII", hdr) + self._pcap_reader.endian + "IIII", hdr + ) self._pcap_reader.f.seek(0, 2) # seek to end of file end_pos = self._pcap_reader.f.tell() # get position at end if end_pos >= orig_pos + len(hdr) + caplen: @@ -394,19 +412,22 @@ class VppPGInterface(VppInterface): deadline = time.time() + timeout if self._pcap_reader is None: if not self.wait_for_capture_file(timeout): - raise CaptureTimeoutError("Capture file %s did not appear " - "within timeout" % self.out_path) + raise CaptureTimeoutError( + "Capture file %s did not appear within timeout" % self.out_path + ) while time.time() < deadline: try: self._pcap_reader = PcapReader(self.out_path) break except: self.test.logger.debug( - "Exception in scapy.PcapReader(%s): %s" % - (self.out_path, format_exc())) + "Exception in scapy.PcapReader(%s): %s" + % (self.out_path, format_exc()) + ) if not self._pcap_reader: - raise CaptureTimeoutError("Capture file %s did not appear within " - "timeout" % self.out_path) + raise CaptureTimeoutError( + "Capture file %s did not appear within timeout" % self.out_path + ) poll = False if timeout > 0: @@ -423,12 +444,14 @@ class VppPGInterface(VppInterface): if p is not None: if filter_out_fn is not None and filter_out_fn(p): self.test.logger.debug( - "Packet received after %ss was filtered out" % - (time.time() - (deadline - timeout))) + "Packet received after %ss was filtered out" + % (time.time() - (deadline - timeout)) + ) else: self.test.logger.debug( - "Packet received after %fs" % - (time.time() - (deadline - timeout))) + "Packet received after %fs" + % (time.time() - (deadline - timeout)) + ) return p self._test.sleep(0) # yield poll = False @@ -437,9 +460,12 @@ class VppPGInterface(VppInterface): def create_arp_req(self): """Create ARP request applicable for this interface""" - return (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.remote_mac) / - ARP(op=ARP.who_has, pdst=self.local_ip4, - psrc=self.remote_ip4, hwsrc=self.remote_mac)) + return Ether(dst="ff:ff:ff:ff:ff:ff", src=self.remote_mac) / ARP( + op=ARP.who_has, + pdst=self.local_ip4, + psrc=self.remote_ip4, + hwsrc=self.remote_mac, + ) def create_ndp_req(self, addr=None): """Create NDP - NS applicable for this interface""" @@ -448,10 +474,12 @@ class VppPGInterface(VppInterface): nsma = in6_getnsma(inet_pton(socket.AF_INET6, addr)) d = inet_ntop(socket.AF_INET6, nsma) - return (Ether(dst=in6_getnsmac(nsma)) / - IPv6(dst=d, src=self.remote_ip6) / - ICMPv6ND_NS(tgt=addr) / - ICMPv6NDOptSrcLLAddr(lladdr=self.remote_mac)) + return ( + Ether(dst=in6_getnsmac(nsma)) + / IPv6(dst=d, src=self.remote_ip6) + / ICMPv6ND_NS(tgt=addr) + / ICMPv6NDOptSrcLLAddr(lladdr=self.remote_mac) + ) def resolve_arp(self, pg_interface=None): """Resolve ARP using provided packet-generator interface @@ -462,8 +490,10 @@ class VppPGInterface(VppInterface): """ if pg_interface is None: pg_interface = self - self.test.logger.info("Sending ARP request for %s on port %s" % - (self.local_ip4, pg_interface.name)) + self.test.logger.info( + "Sending ARP request for %s on port %s" + % (self.local_ip4, pg_interface.name) + ) arp_req = self.create_arp_req() pg_interface.add_stream(arp_req) pg_interface.enable_capture() @@ -472,21 +502,21 @@ class VppPGInterface(VppInterface): try: captured_packet = pg_interface.wait_for_packet(1) except: - self.test.logger.info("No ARP received on port %s" % - pg_interface.name) + self.test.logger.info("No ARP received on port %s" % pg_interface.name) return arp_reply = captured_packet.copy() # keep original for exception try: if arp_reply[ARP].op == ARP.is_at: - self.test.logger.info("VPP %s MAC address is %s " % - (self.name, arp_reply[ARP].hwsrc)) + self.test.logger.info( + "VPP %s MAC address is %s " % (self.name, arp_reply[ARP].hwsrc) + ) self._local_mac = arp_reply[ARP].hwsrc else: - self.test.logger.info("No ARP received on port %s" % - pg_interface.name) + self.test.logger.info("No ARP received on port %s" % pg_interface.name) except: self.test.logger.error( - ppp("Unexpected response to ARP request:", captured_packet)) + ppp("Unexpected response to ARP request:", captured_packet) + ) raise def resolve_ndp(self, pg_interface=None, timeout=1, link_layer=False): @@ -502,8 +532,9 @@ class VppPGInterface(VppInterface): if pg_interface is None: pg_interface = self addr = self.local_ip6_ll if link_layer else self.local_ip6 - self.test.logger.info("Sending NDP request for %s on port %s" % - (addr, pg_interface.name)) + self.test.logger.info( + "Sending NDP request for %s on port %s" % (addr, pg_interface.name) + ) ndp_req = self.create_ndp_req(addr) pg_interface.add_stream(ndp_req) pg_interface.enable_capture() @@ -516,25 +547,26 @@ class VppPGInterface(VppInterface): while now < deadline: try: captured_packet = pg_interface.wait_for_packet( - deadline - now, filter_out_fn=None) + deadline - now, filter_out_fn=None + ) except: - self.test.logger.error( - "Timeout while waiting for NDP response") + self.test.logger.error("Timeout while waiting for NDP response") raise ndp_reply = captured_packet.copy() # keep original for exception try: ndp_na = ndp_reply[ICMPv6ND_NA] opt = ndp_na[ICMPv6NDOptDstLLAddr] - self.test.logger.info("VPP %s MAC address is %s " % - (self.name, opt.lladdr)) + self.test.logger.info( + "VPP %s MAC address is %s " % (self.name, opt.lladdr) + ) self._local_mac = opt.lladdr self.test.logger.debug(self.test.vapi.cli("show trace")) # we now have the MAC we've been after return except: self.test.logger.info( - ppp("Unexpected response to NDP request:", - captured_packet)) + ppp("Unexpected response to NDP request:", captured_packet) + ) now = time.time() self.test.logger.debug(self.test.vapi.cli("show trace")) diff --git a/test/vpp_policer.py b/test/vpp_policer.py index 0f3b073d6e3..b0097b370e5 100644 --- a/test/vpp_policer.py +++ b/test/vpp_policer.py @@ -8,25 +8,36 @@ class Dir(Enum): TX = 1 -class PolicerAction(): - """ sse2 qos action """ +class PolicerAction: + """sse2 qos action""" def __init__(self, type, dscp): self.type = type self.dscp = dscp def encode(self): - return {'type': self.type, 'dscp': self.dscp} + return {"type": self.type, "dscp": self.dscp} class VppPolicer(VppObject): - """ Policer """ - - def __init__(self, test, name, cir, eir, commited_burst, excess_burst, - rate_type=0, round_type=0, type=0, color_aware=False, - conform_action=PolicerAction(1, 0), - exceed_action=PolicerAction(0, 0), - violate_action=PolicerAction(0, 0)): + """Policer""" + + def __init__( + self, + test, + name, + cir, + eir, + commited_burst, + excess_burst, + rate_type=0, + round_type=0, + type=0, + color_aware=False, + conform_action=PolicerAction(1, 0), + exceed_action=PolicerAction(0, 0), + violate_action=PolicerAction(0, 0), + ): self._test = test self.name = name self.cir = cir @@ -48,13 +59,19 @@ class VppPolicer(VppObject): def add_vpp_config(self): r = self._test.vapi.policer_add_del( - name=self.name, cir=self.cir, - eir=self.eir, cb=self.commited_burst, eb=self.excess_burst, - rate_type=self.rate_type, round_type=self.round_type, - type=self.type, color_aware=self.color_aware, + name=self.name, + cir=self.cir, + eir=self.eir, + cb=self.commited_burst, + eb=self.excess_burst, + rate_type=self.rate_type, + round_type=self.round_type, + type=self.type, + color_aware=self.color_aware, conform_action=self.conform_action.encode(), exceed_action=self.exceed_action.encode(), - violate_action=self.violate_action.encode()) + violate_action=self.violate_action.encode(), + ) self._test.registry.register(self, self._test.logger) self._policer_index = r.policer_index return self @@ -64,27 +81,29 @@ class VppPolicer(VppObject): self._policer_index = INVALID_INDEX def bind_vpp_config(self, worker, bind): - self._test.vapi.policer_bind(name=self.name, worker_index=worker, - bind_enable=bind) + self._test.vapi.policer_bind( + name=self.name, worker_index=worker, bind_enable=bind + ) def apply_vpp_config(self, if_index, dir: Dir, apply): if dir == Dir.RX: self._test.vapi.policer_input( - name=self.name, sw_if_index=if_index, apply=apply) + name=self.name, sw_if_index=if_index, apply=apply + ) else: self._test.vapi.policer_output( - name=self.name, sw_if_index=if_index, apply=apply) + name=self.name, sw_if_index=if_index, apply=apply + ) def query_vpp_config(self): - dump = self._test.vapi.policer_dump( - match_name_valid=True, match_name=self.name) + dump = self._test.vapi.policer_dump(match_name_valid=True, match_name=self.name) for policer in dump: if policer.name == self.name: return True return False def object_id(self): - return ("policer-%s" % (self.name)) + return "policer-%s" % (self.name) def get_stats(self, worker=None): conform = self._test.statistics.get_counter("/net/policer/conform") @@ -95,14 +114,14 @@ class VppPolicer(VppObject): total = {} for name, c in counters.items(): - total[f'{name}_packets'] = 0 - total[f'{name}_bytes'] = 0 + total[f"{name}_packets"] = 0 + total[f"{name}_bytes"] = 0 for i in range(len(c)): t = c[i] if worker is not None and i != worker + 1: continue stat_index = self._policer_index - total[f'{name}_packets'] += t[stat_index]['packets'] - total[f'{name}_bytes'] += t[stat_index]['bytes'] + total[f"{name}_packets"] += t[stat_index]["packets"] + total[f"{name}_bytes"] += t[stat_index]["bytes"] return total diff --git a/test/vpp_pppoe_interface.py b/test/vpp_pppoe_interface.py index 505ac4c6425..0d5516eab60 100644 --- a/test/vpp_pppoe_interface.py +++ b/test/vpp_pppoe_interface.py @@ -1,4 +1,3 @@ - from vpp_interface import VppInterface import socket from vpp_papi import mac_pton @@ -9,9 +8,8 @@ class VppPppoeInterface(VppInterface): VPP Pppoe interface """ - def __init__(self, test, client_ip, client_mac, - session_id, decap_vrf_id=0): - """ Create VPP PPPoE4 interface """ + def __init__(self, test, client_ip, client_mac, session_id, decap_vrf_id=0): + """Create VPP PPPoE4 interface""" super(VppPppoeInterface, self).__init__(test) self.client_ip = client_ip self.client_mac = client_mac @@ -21,9 +19,11 @@ class VppPppoeInterface(VppInterface): def add_vpp_config(self): r = self.test.vapi.pppoe_add_del_session( - self.client_ip, self.client_mac, - session_id=self.session_id, - decap_vrf_id=self.decap_vrf_id) + self.client_ip, + self.client_mac, + session_id=self.session_id, + decap_vrf_id=self.decap_vrf_id, + ) self.set_sw_if_index(r.sw_if_index) self.vpp_sw_if_index = r.sw_if_index self.generate_remote_hosts() @@ -31,12 +31,12 @@ class VppPppoeInterface(VppInterface): def remove_vpp_config(self): self.unconfig() self.test.vapi.pppoe_add_del_session( - self.client_ip, self.client_mac, - session_id=self.session_id, - decap_vrf_id=self.decap_vrf_id, - is_add=0) + self.client_ip, + self.client_mac, + session_id=self.session_id, + decap_vrf_id=self.decap_vrf_id, + is_add=0, + ) def set_unnumbered(self, swif_iface): - self.test.vapi.sw_interface_set_unnumbered( - swif_iface, - self.vpp_sw_if_index) + self.test.vapi.sw_interface_set_unnumbered(swif_iface, self.vpp_sw_if_index) diff --git a/test/vpp_qos.py b/test/vpp_qos.py index a7fa9e748aa..a7374d1b1d8 100644 --- a/test/vpp_qos.py +++ b/test/vpp_qos.py @@ -8,7 +8,7 @@ from vpp_object import VppObject class VppQosRecord(VppObject): - """ QoS Record(ing) configuration """ + """QoS Record(ing) configuration""" def __init__(self, test, intf, source): self._test = test @@ -18,32 +18,34 @@ class VppQosRecord(VppObject): def add_vpp_config(self): self._test.vapi.qos_record_enable_disable( enable=1, - record={'sw_if_index': self.intf.sw_if_index, - 'input_source': self.source}) + record={"sw_if_index": self.intf.sw_if_index, "input_source": self.source}, + ) self._test.registry.register(self, self._test.logger) return self def remove_vpp_config(self): self._test.vapi.qos_record_enable_disable( enable=0, - record={'sw_if_index': self.intf.sw_if_index, - 'input_source': self.source}) + record={"sw_if_index": self.intf.sw_if_index, "input_source": self.source}, + ) def query_vpp_config(self): rs = self._test.vapi.qos_record_dump() for r in rs: - if self.intf.sw_if_index == r.record.sw_if_index and \ - self.source == r.record.input_source: + if ( + self.intf.sw_if_index == r.record.sw_if_index + and self.source == r.record.input_source + ): return True return False def object_id(self): - return ("qos-record-%s-%d" % (self.intf, self.source)) + return "qos-record-%s-%d" % (self.intf, self.source) class VppQosStore(VppObject): - """ QoS Store(ing) configuration """ + """QoS Store(ing) configuration""" def __init__(self, test, intf, source, value): self._test = test @@ -54,34 +56,39 @@ class VppQosStore(VppObject): def add_vpp_config(self): self._test.vapi.qos_store_enable_disable( enable=1, - store={'sw_if_index': self.intf.sw_if_index, - 'input_source': self.source, - 'value': self.value}) + store={ + "sw_if_index": self.intf.sw_if_index, + "input_source": self.source, + "value": self.value, + }, + ) self._test.registry.register(self, self._test.logger) return self def remove_vpp_config(self): self._test.vapi.qos_store_enable_disable( enable=0, - store={'sw_if_index': self.intf.sw_if_index, - 'input_source': self.source}) + store={"sw_if_index": self.intf.sw_if_index, "input_source": self.source}, + ) def query_vpp_config(self): rs = self._test.vapi.qos_store_dump() for r in rs: - if self.intf.sw_if_index == r.store.sw_if_index and \ - self.source == r.store.input_source and \ - self.value == r.store.value: + if ( + self.intf.sw_if_index == r.store.sw_if_index + and self.source == r.store.input_source + and self.value == r.store.value + ): return True return False def object_id(self): - return ("qos-store-%s-%d" % (self.intf, self.source)) + return "qos-store-%s-%d" % (self.intf, self.source) class VppQosEgressMap(VppObject): - """ QoS Egress Map(ping) configuration """ + """QoS Egress Map(ping) configuration""" def __init__(self, test, id, rows): self._test = test @@ -89,9 +96,7 @@ class VppQosEgressMap(VppObject): self.rows = rows def add_vpp_config(self): - self._test.vapi.qos_egress_map_update( - map={'id': self.id, - 'rows': self.rows}) + self._test.vapi.qos_egress_map_update(map={"id": self.id, "rows": self.rows}) self._test.registry.register(self, self._test.logger) return self @@ -107,11 +112,11 @@ class VppQosEgressMap(VppObject): return False def object_id(self): - return ("qos-map-%d" % (self.id)) + return "qos-map-%d" % (self.id) class VppQosMark(VppObject): - """ QoS Mark(ing) configuration """ + """QoS Mark(ing) configuration""" def __init__(self, test, intf, map, source): self._test = test @@ -122,27 +127,32 @@ class VppQosMark(VppObject): def add_vpp_config(self): self._test.vapi.qos_mark_enable_disable( enable=1, - mark={'sw_if_index': self.intf.sw_if_index, - 'map_id': self.map.id, - 'output_source': self.source}) + mark={ + "sw_if_index": self.intf.sw_if_index, + "map_id": self.map.id, + "output_source": self.source, + }, + ) self._test.registry.register(self, self._test.logger) return self def remove_vpp_config(self): self._test.vapi.qos_mark_enable_disable( enable=0, - mark={'sw_if_index': self.intf.sw_if_index, - 'output_source': self.source}) + mark={"sw_if_index": self.intf.sw_if_index, "output_source": self.source}, + ) def query_vpp_config(self): ms = self._test.vapi.qos_mark_dump() for m in ms: - if self.intf.sw_if_index == m.mark.sw_if_index and \ - self.source == m.mark.output_source and \ - self.map.id == m.mark.map_id: + if ( + self.intf.sw_if_index == m.mark.sw_if_index + and self.source == m.mark.output_source + and self.map.id == m.mark.map_id + ): return True return False def object_id(self): - return ("qos-mark-%s-%d" % (self.intf, self.source)) + return "qos-mark-%s-%d" % (self.intf, self.source) diff --git a/test/vpp_srv6.py b/test/vpp_srv6.py index d6efedc9f3e..d789105d7a7 100644 --- a/test/vpp_srv6.py +++ b/test/vpp_srv6.py @@ -8,12 +8,12 @@ from vpp_object import VppObject from socket import inet_pton, inet_ntop, AF_INET, AF_INET6 -class SRv6LocalSIDBehaviors(): +class SRv6LocalSIDBehaviors: # from src/vnet/srv6/sr.h SR_BEHAVIOR_END = 1 SR_BEHAVIOR_X = 2 SR_BEHAVIOR_T = 3 - SR_BEHAVIOR_D_FIRST = 4 # Unused. Separator in between regular and D + SR_BEHAVIOR_D_FIRST = 4 # Unused. Separator in between regular and D SR_BEHAVIOR_DX2 = 5 SR_BEHAVIOR_DX6 = 6 SR_BEHAVIOR_DX4 = 7 @@ -21,16 +21,16 @@ class SRv6LocalSIDBehaviors(): SR_BEHAVIOR_DT4 = 9 SR_BEHAVIOR_END_UN_PERF = 10 SR_BEHAVIOR_END_UN = 11 - SR_BEHAVIOR_LAST = 12 # Must always be the last one + SR_BEHAVIOR_LAST = 12 # Must always be the last one -class SRv6PolicyType(): +class SRv6PolicyType: # from src/vnet/srv6/sr.h SR_POLICY_TYPE_DEFAULT = 0 SR_POLICY_TYPE_SPRAY = 1 -class SRv6PolicySteeringTypes(): +class SRv6PolicySteeringTypes: # from src/vnet/srv6/sr.h SR_STEER_L2 = 2 SR_STEER_IPV4 = 4 @@ -42,8 +42,17 @@ class VppSRv6LocalSID(VppObject): SRv6 LocalSID """ - def __init__(self, test, localsid, behavior, nh_addr, - end_psp, sw_if_index, vlan_index, fib_table): + def __init__( + self, + test, + localsid, + behavior, + nh_addr, + end_psp, + sw_if_index, + vlan_index, + fib_table, + ): self._test = test self.localsid = localsid self.behavior = behavior @@ -63,7 +72,8 @@ class VppSRv6LocalSID(VppObject): end_psp=self.end_psp, sw_if_index=self.sw_if_index, vlan_index=self.vlan_index, - fib_table=self.fib_table) + fib_table=self.fib_table, + ) self._configured = True def remove_vpp_config(self): @@ -75,7 +85,8 @@ class VppSRv6LocalSID(VppObject): end_psp=self.end_psp, sw_if_index=self.sw_if_index, vlan_index=self.vlan_index, - fib_table=self.fib_table) + fib_table=self.fib_table, + ) self._configured = False def query_vpp_config(self): @@ -84,10 +95,7 @@ class VppSRv6LocalSID(VppObject): return self._configured def object_id(self): - return ("%d;%s,%d" - % (self.fib_table, - self.localsid, - self.behavior)) + return "%d;%s,%d" % (self.fib_table, self.localsid, self.behavior) class VppSRv6Policy(VppObject): @@ -95,9 +103,9 @@ class VppSRv6Policy(VppObject): SRv6 Policy """ - def __init__(self, test, bsid, - is_encap, sr_type, weight, fib_table, - segments, source): + def __init__( + self, test, bsid, is_encap, sr_type, weight, fib_table, segments, source + ): self._test = test self.bsid = bsid self.is_encap = is_encap @@ -113,17 +121,17 @@ class VppSRv6Policy(VppObject): def add_vpp_config(self): self._test.vapi.sr_policy_add( - bsid=self.bsid, - weight=self.weight, - is_encap=self.is_encap, - is_spray=self.sr_type, - fib_table=self.fib_table, - sids={'num_sids': self.n_segments, 'sids': self.segments}) + bsid=self.bsid, + weight=self.weight, + is_encap=self.is_encap, + is_spray=self.sr_type, + fib_table=self.fib_table, + sids={"num_sids": self.n_segments, "sids": self.segments}, + ) self._configured = True def remove_vpp_config(self): - self._test.vapi.sr_policy_del( - self.bsid) + self._test.vapi.sr_policy_del(self.bsid) self._configured = False def query_vpp_config(self): @@ -132,11 +140,12 @@ class VppSRv6Policy(VppObject): return self._configured def object_id(self): - return ("%d;%s-><%s>;%d" - % (self.sr_type, - self.bsid, - ','.join(self.segments), - self.is_encap)) + return "%d;%s-><%s>;%d" % ( + self.sr_type, + self.bsid, + ",".join(self.segments), + self.is_encap, + ) class VppSRv6Steering(VppObject): @@ -144,14 +153,17 @@ class VppSRv6Steering(VppObject): SRv6 Steering """ - def __init__(self, test, - bsid, - prefix, - mask_width, - traffic_type, - sr_policy_index, - table_id, - sw_if_index): + def __init__( + self, + test, + bsid, + prefix, + mask_width, + traffic_type, + sr_policy_index, + table_id, + sw_if_index, + ): self._test = test self.bsid = bsid self.prefix = prefix @@ -164,24 +176,26 @@ class VppSRv6Steering(VppObject): def add_vpp_config(self): self._test.vapi.sr_steering_add_del( - is_del=0, - bsid=self.bsid, - sr_policy_index=self.sr_policy_index, - table_id=self.table_id, - prefix={'address': self.prefix, 'len': self.mask_width}, - sw_if_index=self.sw_if_index, - traffic_type=self.traffic_type) + is_del=0, + bsid=self.bsid, + sr_policy_index=self.sr_policy_index, + table_id=self.table_id, + prefix={"address": self.prefix, "len": self.mask_width}, + sw_if_index=self.sw_if_index, + traffic_type=self.traffic_type, + ) self._configured = True def remove_vpp_config(self): self._test.vapi.sr_steering_add_del( - is_del=1, - bsid=self.bsid, - sr_policy_index=self.sr_policy_index, - table_id=self.table_id, - prefix={'address': self.prefix, 'len': self.mask_width}, - sw_if_index=self.sw_if_index, - traffic_type=self.traffic_type) + is_del=1, + bsid=self.bsid, + sr_policy_index=self.sr_policy_index, + table_id=self.table_id, + prefix={"address": self.prefix, "len": self.mask_width}, + sw_if_index=self.sw_if_index, + traffic_type=self.traffic_type, + ) self._configured = False def query_vpp_config(self): @@ -190,9 +204,10 @@ class VppSRv6Steering(VppObject): return self._configured def object_id(self): - return ("%d;%d;%s/%d->%s" - % (self.table_id, - self.traffic_type, - self.prefix, - self.mask_width, - self.bsid)) + return "%d;%d;%s/%d->%s" % ( + self.table_id, + self.traffic_type, + self.prefix, + self.mask_width, + self.bsid, + ) diff --git a/test/vpp_sub_interface.py b/test/vpp_sub_interface.py index 21560cb99d0..b896a6efbe3 100644 --- a/test/vpp_sub_interface.py +++ b/test/vpp_sub_interface.py @@ -18,7 +18,6 @@ class L2_VTR_OP: class VppSubInterface(VppPGInterface, metaclass=abc.ABCMeta): - @property def parent(self): """Parent interface for this sub-interface""" @@ -117,26 +116,33 @@ class VppSubInterface(VppPGInterface, metaclass=abc.ABCMeta): self._tag2 = 0 self._push1q = 0 - if (vtr == L2_VTR_OP.L2_PUSH_1 or - vtr == L2_VTR_OP.L2_TRANSLATE_1_1 or - vtr == L2_VTR_OP.L2_TRANSLATE_2_1): + if ( + vtr == L2_VTR_OP.L2_PUSH_1 + or vtr == L2_VTR_OP.L2_TRANSLATE_1_1 + or vtr == L2_VTR_OP.L2_TRANSLATE_2_1 + ): self._tag1 = tag self._push1q = push1q - if (vtr == L2_VTR_OP.L2_PUSH_2 or - vtr == L2_VTR_OP.L2_TRANSLATE_1_2 or - vtr == L2_VTR_OP.L2_TRANSLATE_2_2): + if ( + vtr == L2_VTR_OP.L2_PUSH_2 + or vtr == L2_VTR_OP.L2_TRANSLATE_1_2 + or vtr == L2_VTR_OP.L2_TRANSLATE_2_2 + ): self._tag1 = outer self._tag2 = inner self._push1q = push1q self.test.vapi.l2_interface_vlan_tag_rewrite( - sw_if_index=self.sw_if_index, vtr_op=vtr, push_dot1q=self._push1q, - tag1=self._tag1, tag2=self._tag2) + sw_if_index=self.sw_if_index, + vtr_op=vtr, + push_dot1q=self._push1q, + tag1=self._tag1, + tag2=self._tag2, + ) self._vtr = vtr class VppDot1QSubint(VppSubInterface): - @property def vlan(self): """VLAN tag""" @@ -168,7 +174,6 @@ class VppDot1QSubint(VppSubInterface): class VppDot1ADSubint(VppSubInterface): - @property def outer_vlan(self): """Outer VLAN tag""" @@ -181,13 +186,18 @@ class VppDot1ADSubint(VppSubInterface): def __init__(self, test, parent, sub_id, outer_vlan, inner_vlan): super(VppDot1ADSubint, self).__init__(test, parent, sub_id) - flags = (VppEnum.vl_api_sub_if_flags_t.SUB_IF_API_FLAG_DOT1AD | - VppEnum.vl_api_sub_if_flags_t.SUB_IF_API_FLAG_TWO_TAGS | - VppEnum.vl_api_sub_if_flags_t.SUB_IF_API_FLAG_EXACT_MATCH) - r = test.vapi.create_subif(sw_if_index=parent.sw_if_index, - sub_id=sub_id, outer_vlan_id=outer_vlan, - inner_vlan_id=inner_vlan, - sub_if_flags=flags) + flags = ( + VppEnum.vl_api_sub_if_flags_t.SUB_IF_API_FLAG_DOT1AD + | VppEnum.vl_api_sub_if_flags_t.SUB_IF_API_FLAG_TWO_TAGS + | VppEnum.vl_api_sub_if_flags_t.SUB_IF_API_FLAG_EXACT_MATCH + ) + r = test.vapi.create_subif( + sw_if_index=parent.sw_if_index, + sub_id=sub_id, + outer_vlan_id=outer_vlan, + inner_vlan_id=inner_vlan, + sub_if_flags=flags, + ) self.set_sw_if_index(r.sw_if_index) self._outer_vlan = outer_vlan self._inner_vlan = inner_vlan @@ -204,16 +214,13 @@ class VppDot1ADSubint(VppSubInterface): return self.add_dot1ad_layer(packet, self.outer_vlan, self.inner_vlan) def remove_dot1_layer(self, packet): - return self.remove_dot1ad_layer(packet, self.outer_vlan, - self.inner_vlan) + return self.remove_dot1ad_layer(packet, self.outer_vlan, self.inner_vlan) class VppP2PSubint(VppSubInterface): - def __init__(self, test, parent, sub_id, remote_mac): super(VppP2PSubint, self).__init__(test, parent, sub_id) - r = test.vapi.p2p_ethernet_add(parent.sw_if_index, - remote_mac, sub_id) + r = test.vapi.p2p_ethernet_add(parent.sw_if_index, remote_mac, sub_id) self.set_sw_if_index(r.sw_if_index) self.parent_sw_if_index = parent.sw_if_index self.p2p_remote_mac = remote_mac diff --git a/test/vpp_teib.py b/test/vpp_teib.py index ee2d89fe080..14688181582 100644 --- a/test/vpp_teib.py +++ b/test/vpp_teib.py @@ -9,14 +9,12 @@ from vpp_object import VppObject def find_teib(test, ne): ns = test.vapi.teib_dump() for n in ns: - if ne.peer == str(n.entry.peer) \ - and ne.itf._sw_if_index == n.entry.sw_if_index: + if ne.peer == str(n.entry.peer) and ne.itf._sw_if_index == n.entry.sw_if_index: return True return False class VppTeib(VppObject): - def __init__(self, test, itf, peer, nh, table_id=0): self._test = test self.table_id = table_id @@ -28,11 +26,12 @@ class VppTeib(VppObject): r = self._test.vapi.teib_entry_add_del( is_add=1, entry={ - 'nh_table_id': self.table_id, - 'sw_if_index': self.itf.sw_if_index, - 'peer': self.peer, - 'nh': self.nh, - }) + "nh_table_id": self.table_id, + "sw_if_index": self.itf.sw_if_index, + "peer": self.peer, + "nh": self.nh, + }, + ) self._test.registry.register(self, self._test.logger) return self @@ -40,13 +39,14 @@ class VppTeib(VppObject): r = self._test.vapi.teib_entry_add_del( is_add=0, entry={ - 'nh_table_id': self.table_id, - 'sw_if_index': self.itf.sw_if_index, - 'peer': self.peer, - }) + "nh_table_id": self.table_id, + "sw_if_index": self.itf.sw_if_index, + "peer": self.peer, + }, + ) def query_vpp_config(self): return find_teib(self._test, self) def object_id(self): - return ("teib-%s-%s" % (self.itf, self.peer)) + return "teib-%s-%s" % (self.itf, self.peer) diff --git a/test/vpp_tunnel_interface.py b/test/vpp_tunnel_interface.py index 6a336eb72d9..d70328eb239 100644 --- a/test/vpp_tunnel_interface.py +++ b/test/vpp_tunnel_interface.py @@ -4,7 +4,7 @@ from vpp_interface import VppInterface class VppTunnelInterface(VppInterface, metaclass=abc.ABCMeta): - """ VPP tunnel interface abstraction """ + """VPP tunnel interface abstraction""" def __init__(self, test, parent_if): super(VppTunnelInterface, self).__init__(test) @@ -24,7 +24,9 @@ class VppTunnelInterface(VppInterface, metaclass=abc.ABCMeta): def add_stream(self, pkts): return self.parent_if.add_stream(pkts) - def get_capture(self, expected_count=None, remark=None, timeout=1, - filter_out_fn=is_ipv6_misc): - return self.parent_if.get_capture(expected_count, remark, timeout, - filter_out_fn) + def get_capture( + self, expected_count=None, remark=None, timeout=1, filter_out_fn=is_ipv6_misc + ): + return self.parent_if.get_capture( + expected_count, remark, timeout, filter_out_fn + ) diff --git a/test/vpp_udp_decap.py b/test/vpp_udp_decap.py index 2bd03ce75c0..3231826f31b 100644 --- a/test/vpp_udp_decap.py +++ b/test/vpp_udp_decap.py @@ -8,19 +8,10 @@ from socket import inet_pton, inet_ntop, AF_INET, AF_INET6 class VppUdpDecap(VppObject): - - def __init__(self, - test, - is_ip4, - dst_port, - next_proto): + def __init__(self, test, is_ip4, dst_port, next_proto): self._test = test self.active = False - self.udp_decap = { - 'is_ip4': is_ip4, - 'port': dst_port, - 'next_proto': next_proto - } + self.udp_decap = {"is_ip4": is_ip4, "port": dst_port, "next_proto": next_proto} def add_vpp_config(self): self._test.vapi.udp_decap_add_del(True, self.udp_decap) diff --git a/test/vpp_udp_encap.py b/test/vpp_udp_encap.py index aad87bd5912..b89e9411e6a 100644 --- a/test/vpp_udp_encap.py +++ b/test/vpp_udp_encap.py @@ -10,25 +10,20 @@ from socket import inet_pton, inet_ntop, AF_INET, AF_INET6 def find_udp_encap(test, ue): encaps = test.vapi.udp_encap_dump() for e in encaps: - if ue.id == e.udp_encap.id \ - and ue.src_ip == str(e.udp_encap.src_ip) \ - and ue.dst_ip == str(e.udp_encap.dst_ip) \ - and e.udp_encap.dst_port == ue.dst_port \ - and e.udp_encap.src_port == ue.src_port: + if ( + ue.id == e.udp_encap.id + and ue.src_ip == str(e.udp_encap.src_ip) + and ue.dst_ip == str(e.udp_encap.dst_ip) + and e.udp_encap.dst_port == ue.dst_port + and e.udp_encap.src_port == ue.src_port + ): return True return False class VppUdpEncap(VppObject): - - def __init__(self, - test, - src_ip, - dst_ip, - src_port, - dst_port, - table_id=0): + def __init__(self, test, src_ip, dst_ip, src_port, dst_port, table_id=0): self._test = test self.table_id = table_id self.src_ip_s = src_ip @@ -40,11 +35,8 @@ class VppUdpEncap(VppObject): def add_vpp_config(self): r = self._test.vapi.udp_encap_add( - self.src_ip, - self.dst_ip, - self.src_port, - self.dst_port, - self.table_id) + self.src_ip, self.dst_ip, self.src_port, self.dst_port, self.table_id + ) self.id = r.id self._test.registry.register(self, self._test.logger) @@ -55,7 +47,7 @@ class VppUdpEncap(VppObject): return find_udp_encap(self._test, self) def object_id(self): - return ("udp-encap-%d" % self.id) + return "udp-encap-%d" % self.id def get_stats(self): c = self._test.statistics.get_counter("/net/udp-encap") diff --git a/test/vpp_vhost_interface.py b/test/vpp_vhost_interface.py index 8fa2d7172f1..a20504ba1ce 100644 --- a/test/vpp_vhost_interface.py +++ b/test/vpp_vhost_interface.py @@ -4,13 +4,24 @@ from vpp_interface import VppInterface class VppVhostInterface(VppInterface): """VPP vhost interface.""" - def __init__(self, test, sock_filename, is_server=0, renumber=0, - disable_mrg_rxbuf=0, disable_indirect_desc=0, enable_gso=0, - enable_packed_ring=0, enable_event_idx=0, - custom_dev_instance=0xFFFFFFFF, use_custom_mac=0, - mac_address='', tag=''): + def __init__( + self, + test, + sock_filename, + is_server=0, + renumber=0, + disable_mrg_rxbuf=0, + disable_indirect_desc=0, + enable_gso=0, + enable_packed_ring=0, + enable_event_idx=0, + custom_dev_instance=0xFFFFFFFF, + use_custom_mac=0, + mac_address="", + tag="", + ): - """ Create VPP Vhost interface """ + """Create VPP Vhost interface""" super(VppVhostInterface, self).__init__(test) self.is_server = is_server self.sock_filename = sock_filename @@ -26,18 +37,20 @@ class VppVhostInterface(VppInterface): self.tag = tag def add_vpp_config(self): - r = self.test.vapi.create_vhost_user_if_v2(self.is_server, - self.sock_filename, - self.renumber, - self.disable_mrg_rxbuf, - self.disable_indirect_desc, - self.enable_gso, - self.enable_packed_ring, - self.enable_event_idx, - self.custom_dev_instance, - self.use_custom_mac, - self.mac_address, - self.tag) + r = self.test.vapi.create_vhost_user_if_v2( + self.is_server, + self.sock_filename, + self.renumber, + self.disable_mrg_rxbuf, + self.disable_indirect_desc, + self.enable_gso, + self.enable_packed_ring, + self.enable_event_idx, + self.custom_dev_instance, + self.use_custom_mac, + self.mac_address, + self.tag, + ) self.set_sw_if_index(r.sw_if_index) def remove_vpp_config(self): diff --git a/test/vpp_vxlan_gpe_tunnel.py b/test/vpp_vxlan_gpe_tunnel.py index cff5e456aee..2826c29c6b3 100644 --- a/test/vpp_vxlan_gpe_tunnel.py +++ b/test/vpp_vxlan_gpe_tunnel.py @@ -2,7 +2,7 @@ from vpp_interface import VppInterface from vpp_papi import VppEnum -INDEX_INVALID = 0xffffffff +INDEX_INVALID = 0xFFFFFFFF DEFAULT_PORT = 4790 UNDEFINED_PORT = 0 @@ -19,11 +19,13 @@ def find_vxlan_gpe_tunnel(test, src, dst, s_port, d_port, vni): dst_port = d_port for t in ts: - if src == str(t.local) and \ - dst == str(t.remote) and \ - src_port == t.local_port and \ - dst_port == t.remote_port and \ - t.vni == vni: + if ( + src == str(t.local) + and dst == str(t.remote) + and src_port == t.local_port + and dst_port == t.remote_port + and t.vni == vni + ): return t.sw_if_index return INDEX_INVALID @@ -33,12 +35,20 @@ class VppVxlanGpeTunnel(VppInterface): VPP VXLAN GPE interface """ - def __init__(self, test, src_addr, dst_addr, vni, - src_port=UNDEFINED_PORT, dst_port=UNDEFINED_PORT, - mcast_sw_if_index=INDEX_INVALID, - encap_vrf_id=None, - decap_vrf_id=None, protocol=3): - """ Create VXLAN GPE Tunnel interface """ + def __init__( + self, + test, + src_addr, + dst_addr, + vni, + src_port=UNDEFINED_PORT, + dst_port=UNDEFINED_PORT, + mcast_sw_if_index=INDEX_INVALID, + encap_vrf_id=None, + decap_vrf_id=None, + protocol=3, + ): + """Create VXLAN GPE Tunnel interface""" super(VppVxlanGpeTunnel, self).__init__(test) self.src = src_addr self.dst = dst_addr @@ -52,32 +62,38 @@ class VppVxlanGpeTunnel(VppInterface): def add_vpp_config(self): reply = self.test.vapi.vxlan_gpe_add_del_tunnel_v2( - is_add=1, local=self.src, remote=self.dst, vni=self.vni, - local_port=self.src_port, remote_port=self.dst_port, + is_add=1, + local=self.src, + remote=self.dst, + vni=self.vni, + local_port=self.src_port, + remote_port=self.dst_port, mcast_sw_if_index=self.mcast_sw_if_index, encap_vrf_id=self.encap_vrf_id, decap_vrf_id=self.decap_vrf_id, - protocol=self.protocol) + protocol=self.protocol, + ) self.set_sw_if_index(reply.sw_if_index) self._test.registry.register(self, self._test.logger) def remove_vpp_config(self): self.test.vapi.vxlan_gpe_add_del_tunnel_v2( - is_add=0, local=self.src, remote=self.dst, vni=self.vni, - local_port=self.src_port, remote_port=self.dst_port, + is_add=0, + local=self.src, + remote=self.dst, + vni=self.vni, + local_port=self.src_port, + remote_port=self.dst_port, mcast_sw_if_index=self.mcast_sw_if_index, encap_vrf_id=self.encap_vrf_id, decap_vrf_id=self.decap_vrf_id, - protocol=self.protocol) + protocol=self.protocol, + ) def query_vpp_config(self): - return (INDEX_INVALID != find_vxlan_gpe_tunnel(self._test, - self.src, - self.dst, - self.src_port, - self.dst_port, - self.vni)) + return INDEX_INVALID != find_vxlan_gpe_tunnel( + self._test, self.src, self.dst, self.src_port, self.dst_port, self.vni + ) def object_id(self): - return "vxlan-%d-%d-%s-%s" % (self.sw_if_index, self.vni, - self.src, self.dst) + return "vxlan-%d-%d-%s-%s" % (self.sw_if_index, self.vni, self.src, self.dst) diff --git a/test/vpp_vxlan_tunnel.py b/test/vpp_vxlan_tunnel.py index d7e087da6f8..8c993b09196 100644 --- a/test/vpp_vxlan_tunnel.py +++ b/test/vpp_vxlan_tunnel.py @@ -2,7 +2,7 @@ from vpp_interface import VppInterface from vpp_papi import VppEnum -INDEX_INVALID = 0xffffffff +INDEX_INVALID = 0xFFFFFFFF DEFAULT_PORT = 4789 UNDEFINED_PORT = 0 @@ -19,11 +19,13 @@ def find_vxlan_tunnel(test, src, dst, s_port, d_port, vni): dst_port = d_port for t in ts: - if src == str(t.src_address) and \ - dst == str(t.dst_address) and \ - src_port == t.src_port and \ - dst_port == t.dst_port and \ - t.vni == vni: + if ( + src == str(t.src_address) + and dst == str(t.dst_address) + and src_port == t.src_port + and dst_port == t.dst_port + and t.vni == vni + ): return t.sw_if_index return INDEX_INVALID @@ -33,13 +35,22 @@ class VppVxlanTunnel(VppInterface): VPP VXLAN interface """ - def __init__(self, test, src, dst, vni, - src_port=UNDEFINED_PORT, dst_port=UNDEFINED_PORT, - mcast_itf=None, - mcast_sw_if_index=INDEX_INVALID, - decap_next_index=INDEX_INVALID, - encap_vrf_id=None, instance=0xffffffff, is_l3=False): - """ Create VXLAN Tunnel interface """ + def __init__( + self, + test, + src, + dst, + vni, + src_port=UNDEFINED_PORT, + dst_port=UNDEFINED_PORT, + mcast_itf=None, + mcast_sw_if_index=INDEX_INVALID, + decap_next_index=INDEX_INVALID, + encap_vrf_id=None, + instance=0xFFFFFFFF, + is_l3=False, + ): + """Create VXLAN Tunnel interface""" super(VppVxlanTunnel, self).__init__(test) self.src = src self.dst = dst @@ -53,35 +64,44 @@ class VppVxlanTunnel(VppInterface): self.instance = instance self.is_l3 = is_l3 - if (self.mcast_itf): + if self.mcast_itf: self.mcast_sw_if_index = self.mcast_itf.sw_if_index def add_vpp_config(self): reply = self.test.vapi.vxlan_add_del_tunnel_v3( - is_add=1, src_address=self.src, dst_address=self.dst, vni=self.vni, - src_port=self.src_port, dst_port=self.dst_port, + is_add=1, + src_address=self.src, + dst_address=self.dst, + vni=self.vni, + src_port=self.src_port, + dst_port=self.dst_port, mcast_sw_if_index=self.mcast_sw_if_index, - encap_vrf_id=self.encap_vrf_id, is_l3=self.is_l3, - instance=self.instance, decap_next_index=self.decap_next_index) + encap_vrf_id=self.encap_vrf_id, + is_l3=self.is_l3, + instance=self.instance, + decap_next_index=self.decap_next_index, + ) self.set_sw_if_index(reply.sw_if_index) self._test.registry.register(self, self._test.logger) def remove_vpp_config(self): self.test.vapi.vxlan_add_del_tunnel_v2( - is_add=0, src_address=self.src, dst_address=self.dst, vni=self.vni, - src_port=self.src_port, dst_port=self.dst_port, + is_add=0, + src_address=self.src, + dst_address=self.dst, + vni=self.vni, + src_port=self.src_port, + dst_port=self.dst_port, mcast_sw_if_index=self.mcast_sw_if_index, - encap_vrf_id=self.encap_vrf_id, instance=self.instance, - decap_next_index=self.decap_next_index) + encap_vrf_id=self.encap_vrf_id, + instance=self.instance, + decap_next_index=self.decap_next_index, + ) def query_vpp_config(self): - return (INDEX_INVALID != find_vxlan_tunnel(self._test, - self.src, - self.dst, - self.src_port, - self.dst_port, - self.vni)) + return INDEX_INVALID != find_vxlan_tunnel( + self._test, self.src, self.dst, self.src_port, self.dst_port, self.vni + ) def object_id(self): - return "vxlan-%d-%d-%s-%s" % (self.sw_if_index, self.vni, - self.src, self.dst) + return "vxlan-%d-%d-%s-%s" % (self.sw_if_index, self.vni, self.src, self.dst) diff --git a/test/vrf.py b/test/vrf.py index b3daceed2c1..2db18c4824b 100644 --- a/test/vrf.py +++ b/test/vrf.py @@ -4,7 +4,8 @@ from util import NumericConstant class VRFState(NumericConstant): - """ VRF State """ + """VRF State""" + not_configured = 0 configured = 1 reset = 2 |