mirror of
https://github.com/GNS3/gns3-server.git
synced 2026-10-10 12:36:25 +03:00
refactor: use f-strings in remaining modules, scripts and tests
This commit is contained in:
parent
be943fcdf3
commit
3135c8b7e3
@ -77,14 +77,14 @@ class CrashReport:
|
|||||||
dsn=CrashReport.DSN, release=__version__, default_integrations=False, integrations=[sentry_logging]
|
dsn=CrashReport.DSN, release=__version__, default_integrations=False, integrations=[sentry_logging]
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log.error("Crash report could not be sent: {}".format(e))
|
log.error(f"Crash report could not be sent: {e}")
|
||||||
return
|
return
|
||||||
|
|
||||||
tags = {
|
tags = {
|
||||||
"os:name": platform.system(),
|
"os:name": platform.system(),
|
||||||
"os:release": platform.release(),
|
"os:release": platform.release(),
|
||||||
"os:win_32": " ".join(platform.win32_ver()),
|
"os:win_32": " ".join(platform.win32_ver()),
|
||||||
"os:mac": "{} {}".format(platform.mac_ver()[0], platform.mac_ver()[2]),
|
"os:mac": f"{platform.mac_ver()[0]} {platform.mac_ver()[2]}",
|
||||||
"os:linux": distro.name(pretty=True),
|
"os:linux": distro.name(pretty=True),
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -93,7 +93,7 @@ class CrashReport:
|
|||||||
scope.set_tag(key, value)
|
scope.set_tag(key, value)
|
||||||
|
|
||||||
extra_context = {
|
extra_context = {
|
||||||
"python:version": "{}.{}.{}".format(sys.version_info[0], sys.version_info[1], sys.version_info[2]),
|
"python:version": f"{sys.version_info[0]}.{sys.version_info[1]}.{sys.version_info[2]}",
|
||||||
"python:bit": struct.calcsize("P") * 8,
|
"python:bit": struct.calcsize("P") * 8,
|
||||||
"python:encoding": sys.getdefaultencoding(),
|
"python:encoding": sys.getdefaultencoding(),
|
||||||
"python:frozen": "{}".format(hasattr(sys, "frozen")),
|
"python:frozen": "{}".format(hasattr(sys, "frozen")),
|
||||||
|
|||||||
@ -59,10 +59,10 @@ class GUID(TypeDecorator):
|
|||||||
return str(value)
|
return str(value)
|
||||||
else:
|
else:
|
||||||
if not isinstance(value, uuid.UUID):
|
if not isinstance(value, uuid.UUID):
|
||||||
return "{:032x}".format(uuid.UUID(value).int)
|
return f"{uuid.UUID(value).int:032x}"
|
||||||
else:
|
else:
|
||||||
# hexstring
|
# hexstring
|
||||||
return "{:032x}".format(value.int)
|
return f"{value.int:032x}"
|
||||||
|
|
||||||
def process_result_value(self, value, dialect):
|
def process_result_value(self, value, dialect):
|
||||||
if value is None:
|
if value is None:
|
||||||
|
|||||||
@ -260,9 +260,7 @@ class Server:
|
|||||||
raise SystemExit("Python 3.9 or higher is required")
|
raise SystemExit("Python 3.9 or higher is required")
|
||||||
|
|
||||||
log.info(
|
log.info(
|
||||||
"Running with Python {major}.{minor}.{micro} and has PID {pid}".format(
|
f"Running with Python {sys.version_info[0]}.{sys.version_info[1]}.{sys.version_info[2]} and has PID {os.getpid()}"
|
||||||
major=sys.version_info[0], minor=sys.version_info[1], micro=sys.version_info[2], pid=os.getpid()
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# check for the correct locale (UNIX/Linux only)
|
# check for the correct locale (UNIX/Linux only)
|
||||||
|
|||||||
@ -48,7 +48,7 @@ def int_to_macaddress(integer):
|
|||||||
"""
|
"""
|
||||||
Convert an integer to a mac address
|
Convert an integer to a mac address
|
||||||
"""
|
"""
|
||||||
return ":".join(textwrap.wrap("{:012x}".format(integer), width=2))
|
return ":".join(textwrap.wrap(f"{integer:012x}", width=2))
|
||||||
|
|
||||||
|
|
||||||
def parse_version(version):
|
def parse_version(version):
|
||||||
|
|||||||
@ -184,7 +184,7 @@ class ZipFile(zipfile.ZipFile):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
if not isinstance(comment, bytes):
|
if not isinstance(comment, bytes):
|
||||||
raise TypeError("comment: expected bytes, got {}".format(type(comment)))
|
raise TypeError(f"comment: expected bytes, got {type(comment)}")
|
||||||
# check for valid comment length
|
# check for valid comment length
|
||||||
if len(comment) >= zipfile.ZIP_MAX_COMMENT:
|
if len(comment) >= zipfile.ZIP_MAX_COMMENT:
|
||||||
if self.debug:
|
if self.debug:
|
||||||
|
|||||||
@ -70,7 +70,7 @@ async def list_images(image_type):
|
|||||||
for root, _, filenames in _os_walk(directory, recurse=recurse):
|
for root, _, filenames in _os_walk(directory, recurse=recurse):
|
||||||
for filename in filenames:
|
for filename in filenames:
|
||||||
if filename in files:
|
if filename in files:
|
||||||
log.debug("File {} has already been found, skipping...".format(filename))
|
log.debug(f"File {filename} has already been found, skipping...")
|
||||||
continue
|
continue
|
||||||
if filename.endswith(".md5sum") or filename.startswith("."):
|
if filename.endswith(".md5sum") or filename.startswith("."):
|
||||||
continue
|
continue
|
||||||
|
|||||||
@ -66,7 +66,7 @@ def _get_windows_interfaces_from_registry():
|
|||||||
if ip_address:
|
if ip_address:
|
||||||
# get the first IPv4 address only
|
# get the first IPv4 address only
|
||||||
ip_address = ip_address[0]
|
ip_address = ip_address[0]
|
||||||
npf_interface = "\\Device\\NPF_{guid}".format(guid=guid)
|
npf_interface = f"\\Device\\NPF_{guid}"
|
||||||
interfaces.append(
|
interfaces.append(
|
||||||
{
|
{
|
||||||
"id": npf_interface,
|
"id": npf_interface,
|
||||||
@ -116,7 +116,7 @@ def get_windows_interfaces():
|
|||||||
ip_address = network_config.IPAddress[0]
|
ip_address = network_config.IPAddress[0]
|
||||||
netmask = network_config.IPSubnet[0]
|
netmask = network_config.IPSubnet[0]
|
||||||
break
|
break
|
||||||
npf_interface = "\\Device\\NPF_{guid}".format(guid=adapter.GUID)
|
npf_interface = f"\\Device\\NPF_{adapter.GUID}"
|
||||||
interfaces.append(
|
interfaces.append(
|
||||||
{
|
{
|
||||||
"id": npf_interface,
|
"id": npf_interface,
|
||||||
|
|||||||
@ -39,7 +39,7 @@ class Welcome_dialog:
|
|||||||
if self.gns3_version() is None:
|
if self.gns3_version() is None:
|
||||||
self.display.set_background_title("GNS3")
|
self.display.set_background_title("GNS3")
|
||||||
else:
|
else:
|
||||||
self.display.set_background_title("GNS3 {}".format(self.gns3_version()))
|
self.display.set_background_title(f"GNS3 {self.gns3_version()}")
|
||||||
|
|
||||||
def get_ip(self):
|
def get_ip(self):
|
||||||
"""
|
"""
|
||||||
@ -228,42 +228,36 @@ class Welcome_dialog:
|
|||||||
if answer != self.display.OK:
|
if answer != self.display.OK:
|
||||||
return
|
return
|
||||||
if destination == self.get_ip():
|
if destination == self.get_ip():
|
||||||
self.display.msgbox("The destination cannot be the same as this VM IP address ({})".format(destination))
|
self.display.msgbox(f"The destination cannot be the same as this VM IP address ({destination})")
|
||||||
return
|
return
|
||||||
if option == "Send":
|
if option == "Send":
|
||||||
# first make sure they are no files belonging to root
|
# first make sure they are no files belonging to root
|
||||||
os.system("sudo chown -R gns3:gns3 /opt/gns3")
|
os.system("sudo chown -R gns3:gns3 /opt/gns3")
|
||||||
# then rsync the data
|
# then rsync the data
|
||||||
command = r"rsync -az --progress -e 'ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i /home/gns3/.ssh/gns3-vm-key' /opt/gns3 gns3@{}:/opt".format(
|
command = rf"rsync -az --progress -e 'ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i /home/gns3/.ssh/gns3-vm-key' /opt/gns3 gns3@{destination}:/opt"
|
||||||
destination
|
ret = os.system(f'bash -c "{command}"')
|
||||||
)
|
|
||||||
ret = os.system('bash -c "{}"'.format(command))
|
|
||||||
time.sleep(10)
|
time.sleep(10)
|
||||||
if ret != 0:
|
if ret != 0:
|
||||||
self.display.msgbox("Could not send data to the other GNS3 VM located at {}".format(destination))
|
self.display.msgbox(f"Could not send data to the other GNS3 VM located at {destination}")
|
||||||
else:
|
else:
|
||||||
self.display.msgbox(
|
self.display.msgbox(
|
||||||
"Images and projects have been successfully sent to the other GNS3 VM located at {}".format(
|
f"Images and projects have been successfully sent to the other GNS3 VM located at {destination}"
|
||||||
destination
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
elif option == "Setup":
|
elif option == "Setup":
|
||||||
script = """
|
script = f"""
|
||||||
if [ ! -f ~/.ssh/gns3-vm-key ]
|
if [ ! -f ~/.ssh/gns3-vm-key ]
|
||||||
then
|
then
|
||||||
ssh-keygen -f ~/.ssh/gns3-vm-key -N '' -C gns3@{}
|
ssh-keygen -f ~/.ssh/gns3-vm-key -N '' -C gns3@{self.get_ip()}
|
||||||
fi
|
fi
|
||||||
ssh-copy-id -i ~/.ssh/gns3-vm-key gns3@{}
|
ssh-copy-id -i ~/.ssh/gns3-vm-key gns3@{destination}
|
||||||
""".format(self.get_ip(), destination)
|
"""
|
||||||
ret = os.system('bash -c "{}"'.format(script))
|
ret = os.system(f'bash -c "{script}"')
|
||||||
time.sleep(10)
|
time.sleep(10)
|
||||||
if ret != 0:
|
if ret != 0:
|
||||||
self.display.msgbox("Error while setting up the migrate feature")
|
self.display.msgbox("Error while setting up the migrate feature")
|
||||||
else:
|
else:
|
||||||
self.display.msgbox(
|
self.display.msgbox(
|
||||||
"Configuration successful, you can now send data to the GNS3 VM located at {} without password".format(
|
f"Configuration successful, you can now send data to the GNS3 VM located at {destination} without password"
|
||||||
destination
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
|
|
||||||
def shrink_disk(self):
|
def shrink_disk(self):
|
||||||
@ -300,11 +294,7 @@ class Welcome_dialog:
|
|||||||
if version is None:
|
if version is None:
|
||||||
content += "GNS3 is not installed please install it with sudo pip3 install gns3-server. Or download a preinstalled VM.\n\n"
|
content += "GNS3 is not installed please install it with sudo pip3 install gns3-server. Or download a preinstalled VM.\n\n"
|
||||||
else:
|
else:
|
||||||
content = (
|
content = f"GNS3 version: {version}\nVM version: {self.gns3vm_version()}\nKVM support available: {self.kvm_support()}\n\n"
|
||||||
"GNS3 version: {gns3_version}\nVM version: {gns3vm_version}\nKVM support available: {kvm}\n\n".format(
|
|
||||||
gns3vm_version=self.gns3vm_version(), gns3_version=version, kvm=self.kvm_support()
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
ip = self.get_ip()
|
ip = self.get_ip()
|
||||||
|
|
||||||
@ -336,7 +326,7 @@ Images and projects are located in /opt/gns3
|
|||||||
try:
|
try:
|
||||||
response = urllib.request.urlopen("http://pypi.python.org/", timeout=5)
|
response = urllib.request.urlopen("http://pypi.python.org/", timeout=5)
|
||||||
except urllib.request.URLError as err:
|
except urllib.request.URLError as err:
|
||||||
self.display.infobox("Can't connect to Internet (pypi.python.org): {}".format(str(err)))
|
self.display.infobox(f"Can't connect to Internet (pypi.python.org): {err!s}")
|
||||||
time.sleep(15)
|
time.sleep(15)
|
||||||
return
|
return
|
||||||
self.display.infobox("Connection to Internet: OK")
|
self.display.infobox("Connection to Internet: OK")
|
||||||
@ -384,7 +374,7 @@ Images and projects are located in /opt/gns3
|
|||||||
|
|
||||||
major_version = self.gns3_major_version()
|
major_version = self.gns3_major_version()
|
||||||
if major_version == "2.2":
|
if major_version == "2.2":
|
||||||
os.system("nano ~/.config/GNS3/{}/gns3_server.conf".format(major_version))
|
os.system(f"nano ~/.config/GNS3/{major_version}/gns3_server.conf")
|
||||||
else:
|
else:
|
||||||
os.system("nano ~/.config/GNS3/gns3_server.conf")
|
os.system("nano ~/.config/GNS3/gns3_server.conf")
|
||||||
|
|
||||||
@ -474,7 +464,7 @@ Images and projects are located in /opt/gns3
|
|||||||
try:
|
try:
|
||||||
while True:
|
while True:
|
||||||
code, tag = self.display.menu(
|
code, tag = self.display.menu(
|
||||||
"GNS3 {}".format(self.gns3_version()),
|
f"GNS3 {self.gns3_version()}",
|
||||||
choices=[
|
choices=[
|
||||||
("Information", "Display VM information"),
|
("Information", "Display VM information"),
|
||||||
("Upgrade", "Upgrade GNS3"),
|
("Upgrade", "Upgrade GNS3"),
|
||||||
|
|||||||
@ -465,9 +465,7 @@ class TestNodeRoutes:
|
|||||||
|
|
||||||
compute.http_query.assert_called_with(
|
compute.http_query.assert_called_with(
|
||||||
"GET",
|
"GET",
|
||||||
"/projects/{project_id}/files/project-files/vpcs/{node_id}/hello".format(
|
f"/projects/{project.id}/files/project-files/vpcs/{node.id}/hello",
|
||||||
project_id=project.id, node_id=node.id
|
|
||||||
),
|
|
||||||
timeout=None,
|
timeout=None,
|
||||||
stream=True,
|
stream=True,
|
||||||
)
|
)
|
||||||
@ -491,16 +489,12 @@ class TestNodeRoutes:
|
|||||||
compute.http_query.assert_called_once()
|
compute.http_query.assert_called_once()
|
||||||
call_args = compute.http_query.call_args
|
call_args = compute.http_query.call_args
|
||||||
assert call_args[0][0] == "POST"
|
assert call_args[0][0] == "POST"
|
||||||
assert call_args[0][1] == "/projects/{project_id}/files/project-files/vpcs/{node_id}/hello".format(
|
assert call_args[0][1] == f"/projects/{project.id}/files/project-files/vpcs/{node.id}/hello"
|
||||||
project_id=project.id, node_id=node.id
|
|
||||||
)
|
|
||||||
assert call_args[1]["timeout"] is None
|
assert call_args[1]["timeout"] is None
|
||||||
# data should be an async generator from request.stream()
|
# data should be an async generator from request.stream()
|
||||||
assert hasattr(call_args[1]["data"], "__aiter__")
|
assert hasattr(call_args[1]["data"], "__aiter__")
|
||||||
|
|
||||||
response = await client.get(
|
response = await client.get(f"/projects/{project.id}/nodes/{node.id}/files/../hello")
|
||||||
"/projects/{project_id}/nodes/{node_id}/files/../hello".format(project_id=project.id, node_id=node.id)
|
|
||||||
)
|
|
||||||
assert response.status_code == status.HTTP_404_NOT_FOUND
|
assert response.status_code == status.HTTP_404_NOT_FOUND
|
||||||
|
|
||||||
# @pytest.mark.asyncio
|
# @pytest.mark.asyncio
|
||||||
|
|||||||
@ -244,10 +244,9 @@ class TestControllerProjectRoutes:
|
|||||||
)
|
)
|
||||||
assert response.status_code == status.HTTP_200_OK
|
assert response.status_code == status.HTTP_200_OK
|
||||||
assert response.headers["CONTENT-TYPE"] == "application/gns3project"
|
assert response.headers["CONTENT-TYPE"] == "application/gns3project"
|
||||||
assert response.headers[
|
assert (
|
||||||
"CONTENT-DISPOSITION"
|
response.headers["CONTENT-DISPOSITION"]
|
||||||
] == "attachment; filename=\"{name}.gns3project\"; filename*=UTF-8''{name}.gns3project".format(
|
== f"attachment; filename=\"{project.name}.gns3project\"; filename*=UTF-8''{project.name}.gns3project"
|
||||||
name=project.name
|
|
||||||
)
|
)
|
||||||
|
|
||||||
with open(str(tmpdir / "project.zip"), "wb+") as f:
|
with open(str(tmpdir / "project.zip"), "wb+") as f:
|
||||||
@ -283,10 +282,9 @@ class TestControllerProjectRoutes:
|
|||||||
)
|
)
|
||||||
assert response.status_code == status.HTTP_200_OK
|
assert response.status_code == status.HTTP_200_OK
|
||||||
assert response.headers["CONTENT-TYPE"] == "application/gns3project"
|
assert response.headers["CONTENT-TYPE"] == "application/gns3project"
|
||||||
assert response.headers[
|
assert (
|
||||||
"CONTENT-DISPOSITION"
|
response.headers["CONTENT-DISPOSITION"]
|
||||||
] == "attachment; filename=\"{name}.gns3project\"; filename*=UTF-8''{name}.gns3project".format(
|
== f"attachment; filename=\"{project.name}.gns3project\"; filename*=UTF-8''{project.name}.gns3project"
|
||||||
name=project.name
|
|
||||||
)
|
)
|
||||||
with open(str(tmpdir / "project.zip"), "wb+") as f:
|
with open(str(tmpdir / "project.zip"), "wb+") as f:
|
||||||
f.write(response.content)
|
f.write(response.content)
|
||||||
@ -343,10 +341,9 @@ class TestControllerProjectRoutes:
|
|||||||
|
|
||||||
if response.status_code == status.HTTP_200_OK:
|
if response.status_code == status.HTTP_200_OK:
|
||||||
assert response.headers["CONTENT-TYPE"] == "application/gns3project"
|
assert response.headers["CONTENT-TYPE"] == "application/gns3project"
|
||||||
assert response.headers[
|
assert (
|
||||||
"CONTENT-DISPOSITION"
|
response.headers["CONTENT-DISPOSITION"]
|
||||||
] == "attachment; filename=\"{name}.gns3project\"; filename*=UTF-8''{name}.gns3project".format(
|
== f"attachment; filename=\"{project.name}.gns3project\"; filename*=UTF-8''{project.name}.gns3project"
|
||||||
name=project.name
|
|
||||||
)
|
)
|
||||||
with open(str(tmpdir / "project.zip"), "wb+") as f:
|
with open(str(tmpdir / "project.zip"), "wb+") as f:
|
||||||
f.write(response.content)
|
f.write(response.content)
|
||||||
|
|||||||
@ -42,9 +42,7 @@ class TestVersionRoutes:
|
|||||||
params = {"version": "0.4.2"}
|
params = {"version": "0.4.2"}
|
||||||
response = await client.post(app.url_path_for("check_version"), json=params)
|
response = await client.post(app.url_path_for("check_version"), json=params)
|
||||||
assert response.status_code == status.HTTP_409_CONFLICT
|
assert response.status_code == status.HTTP_409_CONFLICT
|
||||||
assert response.json() == {
|
assert response.json() == {"message": f"Client version 0.4.2 is not the same as server version {__version__}"}
|
||||||
"message": "Client version 0.4.2 is not the same as server version {}".format(__version__)
|
|
||||||
}
|
|
||||||
|
|
||||||
async def test_version_invalid_input_schema(self, app: FastAPI, client: AsyncClient) -> None:
|
async def test_version_invalid_input_schema(self, app: FastAPI, client: AsyncClient) -> None:
|
||||||
|
|
||||||
|
|||||||
@ -46,15 +46,15 @@ def test_convert(directory, tmpdir):
|
|||||||
before_directory = os.path.join(topologies_directory, directory, "before")
|
before_directory = os.path.join(topologies_directory, directory, "before")
|
||||||
after_directory = os.path.join(topologies_directory, directory, "after")
|
after_directory = os.path.join(topologies_directory, directory, "after")
|
||||||
|
|
||||||
assert os.path.exists(before_directory), "No before directory found file for {}".format(directory)
|
assert os.path.exists(before_directory), f"No before directory found file for {directory}"
|
||||||
assert os.path.exists(after_directory), "No after directory found file for {}".format(directory)
|
assert os.path.exists(after_directory), f"No after directory found file for {directory}"
|
||||||
|
|
||||||
gns3_file = None
|
gns3_file = None
|
||||||
for file in os.listdir(before_directory):
|
for file in os.listdir(before_directory):
|
||||||
if file.endswith(".gns3"):
|
if file.endswith(".gns3"):
|
||||||
gns3_file = file
|
gns3_file = file
|
||||||
|
|
||||||
assert gns3_file, "No .gns3 found file for {}".format(before_directory)
|
assert gns3_file, f"No .gns3 found file for {before_directory}"
|
||||||
|
|
||||||
with open(os.path.join(before_directory, gns3_file)) as f:
|
with open(os.path.join(before_directory, gns3_file)) as f:
|
||||||
before_topology = json.load(f)
|
before_topology = json.load(f)
|
||||||
@ -76,19 +76,19 @@ def test_convert(directory, tmpdir):
|
|||||||
for file in files:
|
for file in files:
|
||||||
directory = os.path.relpath(root, after_directory)
|
directory = os.path.relpath(root, after_directory)
|
||||||
file_path = os.path.join(work_directory, directory, file)
|
file_path = os.path.join(work_directory, directory, file)
|
||||||
assert os.path.exists(file_path), "{} is missing".format(os.path.join(directory, file))
|
assert os.path.exists(file_path), f"{os.path.join(directory, file)} is missing"
|
||||||
|
|
||||||
# For gns3project we check if size are not too much differents
|
# For gns3project we check if size are not too much differents
|
||||||
if file_path.endswith(".gns3project"):
|
if file_path.endswith(".gns3project"):
|
||||||
size = os.stat(file_path).st_size
|
size = os.stat(file_path).st_size
|
||||||
other_size = os.stat(os.path.join(os.path.join(root, file))).st_size
|
other_size = os.stat(os.path.join(os.path.join(root, file))).st_size
|
||||||
assert size in range(other_size - 100, other_size + 100), "File {} is different".format(
|
assert size in range(other_size - 100, other_size + 100), (
|
||||||
os.path.join(directory, file)
|
f"File {os.path.join(directory, file)} is different"
|
||||||
)
|
)
|
||||||
# For non .gns3 file we check if the file are the same
|
# For non .gns3 file we check if the file are the same
|
||||||
elif not file_path.endswith(".gns3"):
|
elif not file_path.endswith(".gns3"):
|
||||||
assert os.stat(file_path).st_size == os.stat(os.path.join(os.path.join(root, file))).st_size, (
|
assert os.stat(file_path).st_size == os.stat(os.path.join(os.path.join(root, file))).st_size, (
|
||||||
"File {} is different".format(os.path.join(directory, file))
|
f"File {os.path.join(directory, file)} is different"
|
||||||
)
|
)
|
||||||
|
|
||||||
# Check if we don't have unexpected file in work directory
|
# Check if we don't have unexpected file in work directory
|
||||||
@ -98,7 +98,7 @@ def test_convert(directory, tmpdir):
|
|||||||
file_path = os.path.join(after_directory, directory, file)
|
file_path = os.path.join(after_directory, directory, file)
|
||||||
# .backup are created by the conversion process
|
# .backup are created by the conversion process
|
||||||
if ".backup" not in file_path:
|
if ".backup" not in file_path:
|
||||||
assert os.path.exists(file_path), "{} should not be here".format(os.path.join(directory, file))
|
assert os.path.exists(file_path), f"{os.path.join(directory, file)} should not be here"
|
||||||
|
|
||||||
with open(os.path.join(after_directory, gns3_file)) as f:
|
with open(os.path.join(after_directory, gns3_file)) as f:
|
||||||
after_topology = json.load(f)
|
after_topology = json.load(f)
|
||||||
@ -109,12 +109,12 @@ def compare_dict(path, source, reference):
|
|||||||
"""
|
"""
|
||||||
Compare two dictionary of a topology
|
Compare two dictionary of a topology
|
||||||
"""
|
"""
|
||||||
assert isinstance(source, dict), "Source is not a dict in {}".format(path)
|
assert isinstance(source, dict), f"Source is not a dict in {path}"
|
||||||
for key in source:
|
for key in source:
|
||||||
assert key in reference, "Unexpected {} in {} it should be {}".format(key, source, reference)
|
assert key in reference, f"Unexpected {key} in {source} it should be {reference}"
|
||||||
for key in sorted(reference.keys()):
|
for key in sorted(reference.keys()):
|
||||||
val = reference[key]
|
val = reference[key]
|
||||||
assert key in source, "{} is missing in {}".format(key, source)
|
assert key in source, f"{key} is missing in {source}"
|
||||||
if (
|
if (
|
||||||
isinstance(val, str)
|
isinstance(val, str)
|
||||||
or isinstance(val, float)
|
or isinstance(val, float)
|
||||||
@ -133,12 +133,12 @@ def compare_dict(path, source, reference):
|
|||||||
elif key == "version":
|
elif key == "version":
|
||||||
assert source[key] == __version__
|
assert source[key] == __version__
|
||||||
else:
|
else:
|
||||||
assert val == source[key], "Wrong value for {}: \n{}\nit should be\n{}".format(key, source[key], val)
|
assert val == source[key], f"Wrong value for {key}: \n{source[key]}\nit should be\n{val}"
|
||||||
elif isinstance(val, dict):
|
elif isinstance(val, dict):
|
||||||
compare_dict(path + key + "/", source[key], val)
|
compare_dict(path + key + "/", source[key], val)
|
||||||
elif isinstance(val, list):
|
elif isinstance(val, list):
|
||||||
assert len(val) == len(source[key]), "Not enough value in {} ({}/{}) it shoud be {} not {}".format(
|
assert len(val) == len(source[key]), (
|
||||||
key, len(val), len(source[key]), val, source[key]
|
f"Not enough value in {key} ({len(val)}/{len(source[key])}) it shoud be {val} not {source[key]}"
|
||||||
)
|
)
|
||||||
for idx, element in enumerate(source[key]):
|
for idx, element in enumerate(source[key]):
|
||||||
if isinstance(element, dict):
|
if isinstance(element, dict):
|
||||||
@ -146,4 +146,4 @@ def compare_dict(path, source, reference):
|
|||||||
else:
|
else:
|
||||||
assert element == val[idx]
|
assert element == val[idx]
|
||||||
else:
|
else:
|
||||||
assert False, "Value type for {} is not supported".format(key)
|
assert False, f"Value type for {key} is not supported"
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user