Best Python code snippet using locust
runners.py
Source:runners.py  
...802    @property803    def worker_count(self):804        return len(self.clients.ready) + len(self.clients.spawning) + len(self.clients.running)805    @property806    def reported_user_classes_count(self) -> Dict[str, int]:807        reported_user_classes_count = defaultdict(lambda: 0)808        for client in self.clients.ready + self.clients.spawning + self.clients.running:809            for name, count in client.user_classes_count.items():810                reported_user_classes_count[name] += count811        return reported_user_classes_count812    def send_message(self, msg_type, data=None, client_id=None):813        """814        Sends a message to attached worker node(s)815        :param msg_type: The type of the message to send816        :param data: Optional data to send817        :param client_id: Optional id of the target worker node.818                            If None, will send to all attached workers819        """820        if client_id:...html.py
Source:html.py  
1from jinja2 import Environment, FileSystemLoader2import os3import pathlib4import datetime5from itertools import chain6from .stats import sort_stats7from .user.inspectuser import get_ratio8from html import escape9from json import dumps10from .runners import MasterRunner, STATE_STOPPED, STATE_STOPPING11def render_template(file, **kwargs):12    templates_path = os.path.join(pathlib.Path(__file__).parent.absolute(), "templates")13    env = Environment(loader=FileSystemLoader(templates_path), extensions=["jinja2.ext.do"])14    template = env.get_template(file)15    return template.render(**kwargs)16def get_html_report(environment, show_download_link=True):17    stats = environment.runner.stats18    start_ts = stats.start_time19    start_time = datetime.datetime.utcfromtimestamp(start_ts).strftime("%Y-%m-%d %H:%M:%S")20    end_ts = stats.last_request_timestamp21    if end_ts:22        end_time = datetime.datetime.utcfromtimestamp(end_ts).strftime("%Y-%m-%d %H:%M:%S")23    else:24        end_time = start_time25    host = None26    if environment.host:27        host = environment.host28    elif environment.runner.user_classes:29        all_hosts = {l.host for l in environment.runner.user_classes}30        if len(all_hosts) == 1:31            host = list(all_hosts)[0]32    requests_statistics = list(chain(sort_stats(stats.entries), [stats.total]))33    failures_statistics = sort_stats(stats.errors)34    exceptions_statistics = [35        {**exc, "nodes": ", ".join(exc["nodes"])} for exc in environment.runner.exceptions.values()36    ]37    history = stats.history38    static_js = []39    js_files = ["jquery-1.11.3.min.js", "echarts.common.min.js", "vintage.js", "chart.js", "tasks.js"]40    for js_file in js_files:41        path = os.path.join(os.path.dirname(__file__), "static", js_file)42        static_js.append("// " + js_file)43        with open(path, encoding="utf8") as f:44            static_js.append(f.read())45        static_js.extend(["", ""])46    static_css = []47    css_files = ["tables.css"]48    for css_file in css_files:49        path = os.path.join(os.path.dirname(__file__), "static", "css", css_file)50        static_css.append("/* " + css_file + " */")51        with open(path, encoding="utf8") as f:52            static_css.append(f.read())53        static_css.extend(["", ""])54    is_distributed = isinstance(environment.runner, MasterRunner)55    user_spawned = (56        environment.runner.reported_user_classes_count if is_distributed else environment.runner.user_classes_count57    )58    if environment.runner.state in [STATE_STOPPED, STATE_STOPPING]:59        user_spawned = environment.runner.final_user_classes_count60    task_data = {61        "per_class": get_ratio(environment.user_classes, user_spawned, False),62        "total": get_ratio(environment.user_classes, user_spawned, True),63    }64    res = render_template(65        "report.html",66        int=int,67        round=round,68        requests_statistics=requests_statistics,69        failures_statistics=failures_statistics,70        exceptions_statistics=exceptions_statistics,71        start_time=start_time,72        end_time=end_time,73        host=host,74        history=history,75        static_js="\n".join(static_js),76        static_css="\n".join(static_css),77        show_download_link=show_download_link,78        locustfile=environment.locustfile,79        tasks=escape(dumps(task_data)),80    )...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
