def print_metric(interface: str, label: str, value: int, color_c: str): if label == "Packet_Loss:": value = str(value) + "%" if color_c == "red": interfaces[interface].problem = True print(tcolor(f" {label} "), end="") print(tcolor(f"{value}", color=color_c))
class Test_Bool_is_type: @pytest.mark.parametrize( ["value", "strict_level", "expected"], list( itertools.product([True, False], [StrictLevel.MIN, StrictLevel.MAX], [True])) + list( itertools.product([0, 1, "True", "False", "true", "false"], [StrictLevel.MIN], [True])) + list( itertools.product([0, 1, 0.1, "True", "False", "true", "false"], [StrictLevel.MAX], [False])), ) def test_normal(self, value, strict_level, expected): type_checker = class_under_test(value, strict_level) assert type_checker.is_type() == expected assert type_checker.typecode == Typecode.BOOL @pytest.mark.parametrize( ["value", "strip_ansi_escape", "expected"], [[tcolor("True", "red"), False, False], [tcolor("True", "red"), True, True]], ) def test_normal_ansi(self, value, strip_ansi_escape, expected): type_checker = class_under_test(value, StrictLevel.MIN, strip_ansi_escape=strip_ansi_escape) assert type_checker.is_type() == expected assert type_checker.typecode == Typecode.BOOL
def test_smoke(self): string = "test" for color in AnsiFGColor: assert tcolor(string, color=color) != string for color in AnsiBGColor: assert tcolor(string, bg_color=color) != string
class Test_DateTime_is_type: @pytest.mark.parametrize( ["value", "strict_level", "expected"], list( itertools.product( [ datetime(2017, 3, 22, 10, 0, tzinfo=tzoffset(None, 32400)), date(2017, 3, 22) ], [StrictLevel.MIN, StrictLevel.MIN + 1, StrictLevel.MAX], [True], )) + list( itertools.product( [ None, "invalid time string", 9223372036854775807, "100-0004", "テスト".encode(), ], [StrictLevel.MIN, StrictLevel.MIN + 1, StrictLevel.MAX], [False], )) + list( itertools.product( [ "2017-03-22T10:00:00+0900", 1485685623, "1485685623", "1524930937.003555" ], [StrictLevel.MIN], [True], )) + list( itertools.product( ["2017-03-22T10:00:00+0900", 1485685623, "1485685623"], [StrictLevel.MAX], [False], )), ) def test_normal(self, value, strict_level, expected): type_object = class_under_test(value, strict_level) assert type_object.is_type() == expected assert type_object.typecode == Typecode.DATETIME @pytest.mark.parametrize( ["value", "strip_ansi_escape", "expected"], [ [tcolor("2017-03-22T10:00:00", "red"), False, False], [tcolor("2017-03-22T10:00:00", "red"), True, True], ], ) def test_normal_ansi(self, value, strip_ansi_escape, expected): type_checker = class_under_test(value, StrictLevel.MIN, strip_ansi_escape=strip_ansi_escape) assert type_checker.is_type() == expected assert type_checker.typecode == Typecode.DATETIME
def logging_success(self, source: Union[str, Path], table_name: str, is_create_table: bool) -> None: table_schema = self.__schema_extractor.fetch_table_schema( table_name.strip()) self.__result_counter.inc_success(is_create_table) self.__logger.info( "convert '{source:s}' to '{table_info:s}' table".format( source=tcolor(source, color="cyan"), table_info=tcolor( table_schema.dumps(output_format="text", verbosity_level=self.__verbosity_level), color="light_green", ), ))
def check_rx_and_tx_incrementing_errors(server: str, interface: str): """Updates Interface Class with amount of RX and TX errors for an interface""" global animate_timer if __name__ == "__main__": print( tcolor("Gathering Incrementing RX and TX Errors...", color="white"), end="\r", ) cmd = "sudo ip -s link show " + interface.lower( ) + r' | grep "RX\|TX" -A 1' result = send_command_to_server(cmd, server) parsed_data = result.split() if len(parsed_data) > 25: interfaces[interface].before_rx_errors = parsed_data[9] interfaces[interface].before_tx_errors = parsed_data[22] time.sleep(30) cmd = "sudo ip -s link show " + interface.lower( ) + r' | grep "RX\|TX" -A 1' result = send_command_to_server(cmd, server) parsed_data = result.split() if len(parsed_data) > 25: interfaces[interface].after_rx_errors = parsed_data[9] interfaces[interface].after_tx_errors = parsed_data[22] animate_timer += 1
def print_truecolor(c: Color) -> None: end = " " print(tcolor(c.color_code, bg_color=c), end=end) print(tcolor(c.color_code, color=c), end=end) print(tcolor(c.color_code, color=c, styles=["bold"]), end=end) print(tcolor(c.color_code, color=c, styles=["dim"]), end=end) print(tcolor(c.color_code, color=c, styles=["italic"]), end=end) print(tcolor(c.color_code, color=c, styles=["underline"]), end=end) print(tcolor(c.color_code, color=c, styles=["invert"]), end=end) print(tcolor(c.color_code, color=c, styles=["strike"]), end=end) print()
def normal_mode(server: str, mode: str): problem_ints = [] interface_list = [] netbox_collect_interfaces(server) if mode == "Entire_Server": for key in interfaces: interface_list.append(key) else: interface_list = return_interfaces(server, mode) if not interface_list: print("You must make an interface selection") sys.exit(1) loop_threaded_functions(server, interface_list, is_interface_up, " Validating Interfaces are UP") loop_threaded_functions(server, interface_list, check_light_levels, " Gathering Light Levels") loop_threaded_functions(server, interface_list, check_packet_loss, " Gathering Packet Loss") loop_threaded_functions( server, interface_list, check_incrementing_crc_errors, " Gathering Incrementing CRC Errors", ) loop_threaded_functions( server, interface_list, check_rx_and_tx_incrementing_errors, " Gathering Incrementing RX and TX Errors", ) print("\n Report Printout:") for interface in interface_list: print_report(interface) if interfaces[interface].problem is True: problem_ints.append(str(interfaces[interface].name)) print("\n") if problem_ints: print(tcolor(" The following interfaces have issues: ", color="white"), end="") print(tcolor(str([x for x in problem_ints]), color="red")) else: print(tcolor(" There were no issues found", color="green"))
def animate(count: int, msg: str): global animate_timer msg += "........................" while animate_timer < count: print("{:<44}".format(msg[:44]) + "[", end="") print(tcolor("Loading " + "\b |", color="yellow"), end="") print("]", end="\r") time.sleep(0.1) print("{:<44}".format(msg[:44]) + "[", end="") print(tcolor("Loading " + "\b /", color="yellow"), end="") print("]", end="\r") time.sleep(0.1) print("{:<44}".format(msg[:44]) + "[", end="") print(tcolor("Loading " + "\b -", color="yellow"), end="") print("]", end="\r") time.sleep(0.1) print("{:<44}".format(msg[:44]) + "[", end="") print(tcolor("Loading " + "\b \\", color="yellow"), end="") print("]", end="\r") time.sleep(0.1)
def main() -> int: string = " " step = 8 line = "" for i in range(0, 255, step): line += tcolor(string, bg_color=Color((255, i, 0))) for i in range(0, 255, step): line += tcolor(string, bg_color=Color((255 - i, 255, 0))) for i in range(0, 255, step): line += tcolor(string, bg_color=Color((0, 255, i))) for i in range(0, 255, step): line += tcolor(string, bg_color=Color((0, 255 - i, 255))) for r in range(16): print(line) return 0
def test_normal_ansi_color(self, capsys): writer = table_writer_class() writer.table_name = "ANCI escape sequence" writer.headers = ["colored_i", "colored_f", "colored_s", "wo_anci"] writer.value_matrix = [ [ tcolor("111", color="red"), tcolor("1.1", color="green"), tcolor("abc", color="blue"), "abc", ], [ tcolor("0", color="red"), tcolor("0.12", color="green"), tcolor("abcdef", color="blue"), "abcdef", ], ] writer.write_table() expected = dedent("""\ # ANCI escape sequence |colored_i|colored_f|colored_s|wo_anci| |--------:|--------:|---------|-------| | 111| 1.1|abc |abc | | 0| 0.12|abcdef |abcdef | """) out, err = capsys.readouterr() print_test_result(expected=expected, actual=out, error=err) assert regexp_ansi_escape.search(out) assert regexp_ansi_escape.sub("", out) == expected
def main() -> int: step = 32 print( "bg_color {color} {bold} {dim} {italic} {underline} {invert} {strike}" .format( color="color", bold=tcolor("bold", styles=["bold"]), dim=tcolor("dim", styles=["dim"]), italic=tcolor("italic", styles=["italic"]), underline=tcolor("underline", styles=["underline"]), invert=tcolor("invert", styles=["invert"]), strike=tcolor("strike", styles=["strike"]), )) for i in range(0, 255, step): print_truecolor(Color((255, i, 0))) for i in range(0, 255, step): print_truecolor(Color((255 - i, 255, 0))) for i in range(0, 255, step): print_truecolor(Color((0, 255, i))) for i in range(0, 255, step): print_truecolor(Color((0, 255 - i, 255))) return 0
class Test_IpAddress_is_type: @pytest.mark.parametrize( ["value", "strict_level", "expected"], [[tcolor("127.0.0.1", "red"), StrictLevel.MIN, True]] + list( itertools.product( ["", " ", sys.maxsize, str(sys.maxsize), inf, nan, None], [StrictLevel.MIN, StrictLevel.MAX], [False], )) + list( itertools.product( [ip_address("127.0.0.1"), ip_address("::1")], [StrictLevel.MIN, StrictLevel.MAX], [True], )) + list( itertools.product(["127.0.0.1", "::1", "800::800"], [StrictLevel.MIN], [True])) + list( itertools.product(["127.0.0.1", "::1", "800::800"], [StrictLevel.MAX], [False])), ) def test_normal(self, value, strict_level, expected): type_checker = IpAddress(value, strict_level=strict_level) assert type_checker.is_type() == expected assert type_checker.typecode == Typecode.IP_ADDRESS @pytest.mark.parametrize( ["value", "strip_ansi_escape", "expected"], [[tcolor("127.0.0.1", "red"), False, False], [tcolor("127.0.0.1", "red"), True, True]], ) def test_normal_ansi(self, value, strip_ansi_escape, expected): type_checker = class_under_test(value, StrictLevel.MIN, strip_ansi_escape=strip_ansi_escape) assert type_checker.is_type() == expected assert type_checker.typecode == Typecode.IP_ADDRESS
def apply_terminal_style(self, value: str, style: Style) -> str: if not self._writer.enable_ansi_escape: return value ansi_styles = [] if style.decoration_line in (DecorationLine.STRIKE, DecorationLine.LINE_THROUGH): ansi_styles.append("strike") if style.decoration_line == DecorationLine.UNDERLINE: ansi_styles.append("underline") if style.font_weight == FontWeight.BOLD: ansi_styles.append("bold") if self._writer.colorize_terminal: return tcolor(value, color=style.color, bg_color=style.bg_color, styles=ansi_styles) return tcolor(value, styles=ansi_styles)
def print_report(interface: str, mode=""): """Takes the Interface Class and calculates if there is a problem with the interface""" if mode == "Diagnostic": top_border(interface, interfaces[interface].provider) print(f" Light_Level: {interfaces[interface].light_level} dBm") print(tcolor(" -----------------------", color="white")) return RX_Errors = int(interfaces[interface].after_rx_errors) - int( interfaces[interface].before_rx_errors) TX_Errors = int(interfaces[interface].after_tx_errors) - int( interfaces[interface].before_tx_errors) CRC_Errors = int(interfaces[interface].after_crc_errors) - int( interfaces[interface].before_crc_errors) Light_Level = interfaces[interface].light_level Packet_Loss = interfaces[interface].packet_loss top_border(interface, interfaces[interface].provider) print_metric(interface, "RX_Errors:", RX_Errors, validate_metric(float(RX_Errors), 0.0, 1.0)) print_metric(interface, "TX Errors:", TX_Errors, validate_metric(float(TX_Errors), 0.0, 1.0)) print_metric( interface, "CRC_Errors:", CRC_Errors, validate_metric(float(CRC_Errors), 0.0, 1.0), ) if interfaces[interface].speed == "100G": print_light_level_array(interface, Light_Level) else: print_metric( interface, "Light_Level:", Light_Level, validate_metric(float(Light_Level), -9.0, -11.0, "light"), ) print_metric(interface, "Packet_Loss:", Packet_Loss, validate_metric(Packet_Loss, 0.4, 0.1)) print(tcolor(" -----------------------", color="white"), end="")
def as_markdown(self) -> str: h1_color = "cyan" h2_color = "light cyan" lines = [ tcolor("# {}".format(self.__make_subject()), color=h1_color), tcolor("## Date and time", color=h2_color), str(self.dtr), "", ] if self.facilities: lines.extend([ tcolor("## Facilities", color=h2_color), ", ".join([facility.name for facility in self.facilities]), "", ]) if self.attendees: lines.extend([ tcolor("## Attendees ({} users)".format(len(self.attendees)), color=h2_color), self.__make_attendees_block(), "", ]) if self.notes: lines.extend([tcolor("## Notes", color=h2_color), self.notes]) lines.extend([ "", "---", "- Registrant: {} {}".format(self.creator.name, self.created_at), "- Updater: {} {}".format(self.updater.name, self.updated_at), ]) return "\n".join(lines)
def main() -> int: template = "{:26} {:26} {:26}" print( template.format( tcolor("color", color="white"), tcolor("bg_color", color="white"), tcolor("invert", color="white"), )) print("━" * 50) for fg_color, bg_color in zip(AnsiFGColor, AnsiBGColor): print( template.format( tcolor(fg_color.name, color=fg_color), tcolor(bg_color.name, bg_color=bg_color), tcolor(fg_color.name, color=fg_color, styles=["invert"]), )) return 0
#!/usr/bin/env python3 from tcolorpy import tcolor print( tcolor("tcolopy example", color="#ee1177", styles=["bold", "italic", "underline"]))
s = g.get_server(args.server) exit_if_none(s, f"Could not find server {args.server}") p = g.get_pop(s.pop_id) ifaces = g.list_interfaces_by_field(field="pop_bpf_id", value=str(s.pop_bpf_id)) print("\nTesting midgress reachability for:\n") print(f"pop {p.name} {p.graph_id}") print(f"svr {s.name} {s.guid} {s.pop_id} {s.pop_bpf_id}") for iface in ifaces: if not iface.type == InterfaceType.TRANSIT: continue print(tcolor(f"\n{iface.name}:", color="blue")) if iface.v4_midgress_cidr.address: host = ping( iface.v4_midgress_cidr.address, count=10, interval=0.2, privileged=False ) msg = f" {host.packets_received} of {host.packets_sent} pkts ({host.min_rtt}/{host.avg_rtt}/{host.max_rtt})" color = "green" if host.is_alive else "red" print(f" {iface.v4_midgress_cidr.address:36}{tcolor(msg, color=color)}") if iface.v6_midgress_cidr.address: host = ping( iface.v6_midgress_cidr.address, count=10, interval=0.2, privileged=False ) msg = f" {host.packets_received} of {host.packets_sent} pkts ({host.min_rtt}/{host.avg_rtt}/{host.max_rtt})" color = "green" if host.is_alive else "red" print(f" {iface.v6_midgress_cidr.address:36}{tcolor(msg, color=color)}")
def top_border(interface: str, provider: str): print(f"\n {interface}: ", end="") print(tcolor(f"({provider[:10]})", color="white"), end="") print(tcolor("\n -----------------------", color="white"))
class Test_Integer_is_type: @pytest.mark.parametrize( ["value", "strict_level", "expected"], [ [str(sys.maxsize), StrictLevel.MIN, True], [str(sys.maxsize), StrictLevel.MIN + 1, True], [str(sys.maxsize), StrictLevel.MAX, False], ["45e76582", StrictLevel.MIN, True], ["45e76582", StrictLevel.MIN + 1, False], ["45e76582", StrictLevel.MAX, False], ["4.5e-4", StrictLevel.MIN, True], ["4.5e-4", StrictLevel.MIN + 1, False], ["4.5e-4", StrictLevel.MAX, False], [" 1 ", StrictLevel.MIN + 1, True], [True, StrictLevel.MIN + 1, False], [False, StrictLevel.MAX, False], ] + list( itertools.product( [ 0, sys.maxsize, -sys.maxsize, Decimal("1"), int(Decimal("45e765")) ], [StrictLevel.MIN, StrictLevel.MIN + 1], [True], )) + list( itertools.product( [ 0.5, 0.999, Decimal("1.1"), 1e-05, -1e-05, "0.5", ".999", "1e-05", "-1e-05", True, False, ], [StrictLevel.MIN], [True], )) + list( itertools.product( [ None, nan, inf, "", "0xff", "test", "1a1", "11a", "a11", "テスト".encode() ], [StrictLevel.MIN, StrictLevel.MAX], [False], )), ) def test_normal(self, value, strict_level, expected): type_checker = class_under_test(value, strict_level) assert type_checker.is_type() == expected assert type_checker.typecode == Typecode.INTEGER @pytest.mark.parametrize( ["value", "strip_ansi_escape", "expected"], [[tcolor("1", "red"), False, False], [tcolor("1", "red"), True, True]], ) def test_normal_ansi(self, value, strip_ansi_escape, expected): type_checker = class_under_test(value, StrictLevel.MIN, strip_ansi_escape=strip_ansi_escape) assert type_checker.is_type() == expected assert type_checker.typecode == Typecode.INTEGER
def test_normal_bg_color(self, string, styles, expected): assert tcolor("test", styles=styles) == expected
def write_completion_message(self) -> None: logger = self._logger logger.debug("----- {:s} completed -----".format(PROGRAM_NAME)) log_list = [ "source={}".format( tcolor( str( self._con.fetch_value( select="COUNT(DISTINCT({}))".format("source_id"), table_name=SourceInfo.get_table_name(), ) ), color="light_white", ) ) ] if self.get_success_count() > 0: log_list.append( tcolor("success=", color="green") + tcolor(str(self.get_success_count()), color="light_green"), ) if self._result_counter.fail_count > 0: log_list.append( tcolor("fail=", color="red") + tcolor(str(self._result_counter.fail_count), color="light_red"), ) if self._result_counter.skip_count > 0: log_list.append( tcolor("skip=", color="yellow") + tcolor(str(self._result_counter.skip_count), color="light_yellow"), ) if self._result_counter.created_table_count > 0: log_list.append( tcolor("created-table=", color="white") + tcolor(str(self._result_counter.skip_count), color="light_white"), ) logger.info("converted results: {}".format(", ".join(log_list))) database_path_msg = "database path: {:s}".format( tcolor(Path(self._con.database_path).relpath(), color="light_white"), ) if self.get_success_count() > 0: output_format, verbosity_level = self.__get_dump_param() logger.info(database_path_msg) try: logger.debug( "----- database schema -----\n{}".format( indent( self._con.schema_extractor.dumps( output_format=output_format, verbosity_level=verbosity_level ), " ", ) ) ) except: # noqa # avoid crashes caused by logging pass else: logger.debug(database_path_msg)
def test_normal(self, string, color, expected): assert tcolor(string, color=color) == expected
def test_exception(self, value, expected): with pytest.raises(expected): tcolor("test", color=value) == expected
def test_normal_fg_bg_color(self, string, color, bg_color, expected): assert tcolor(string, color=color, bg_color=bg_color) == expected
def print_complete(msg: str): msg += "....................." print(tcolor("{:<44}".format(msg[:44]) + "[", color="white"), end="") print(tcolor("Completed", color="green"), end="") print(tcolor("]", color="white"))
class Test_RealNumber_is_type: @pytest.mark.parametrize( ["value", "strict_level", "expected"], list( itertools.product( [ 0, 0.0, 0.0, sys.maxsize, -sys.maxsize, str(sys.maxsize), str(-sys.maxsize), "0.1", "-0.1", "1e-05", "4.5e-4", "45e76", int(Decimal("45e765")), ], [StrictLevel.MIN], [True], )) + list( itertools.product( [0, 0.0, 0.0, sys.maxsize, -sys.maxsize, "4.5e444"], [StrictLevel.MIN + 1], [False])) + list( itertools.product(["1.1", "4.5e-4"], [StrictLevel.MIN + 1], [True])) + list( itertools.product( [ 0, 0.0, Decimal("1"), sys.maxsize, -sys.maxsize, "1.0", str(sys.maxsize), str(-sys.maxsize), "0.1", "-0.1", "1e-05", ], [StrictLevel.MAX], [False], )) + list( itertools.product( [True, inf, nan, "", "0xf", "テスト".encode()], [StrictLevel.MIN, StrictLevel.MIN + 1, StrictLevel.MAX], [False], )) + list( itertools.product( [0.1, -0.1, 0.5, Decimal("1.1")], [StrictLevel.MIN, StrictLevel.MIN + 1, StrictLevel.MAX], [True], )), ) def test_normal(self, value, strict_level, expected): type_checker = class_under_test(value, strict_level) assert type_checker.is_type() == expected assert type_checker.typecode == Typecode.REAL_NUMBER @pytest.mark.parametrize( ["value", "strip_ansi_escape", "expected"], [[tcolor("1.1", "red"), False, False], [tcolor("1.1", "red"), True, True]], ) def test_normal_ansi(self, value, strip_ansi_escape, expected): type_checker = class_under_test(value, StrictLevel.MIN, strip_ansi_escape=strip_ansi_escape) assert type_checker.is_type() == expected assert type_checker.typecode == Typecode.REAL_NUMBER