Best Python code snippet using locust
lab1.py
Source:lab1.py
...21def content_length(message):22 return pd.Series(message).str.len().sort_values(ascending=False)232425def avg_content_length(messages_length, rows):26 return messages_length.sum() / len(rows)272829def get_20_and_normalize(content):30 temp_content = content.head(20)31 temp_content.loc[:, 'count'] /= pd.Series(temp_content['count']).sum()32 return temp_content333435df = pd.read_csv(FILE_PATH, encoding="cp1251")36df = df.applymap(lambda s: s.lower() if isinstance(s, str) else s)37format_text(df)38ham = df[df.v1 == "ham"]39spam = df[df.v1 == "spam"]4041ham_count_words = ham['v2'].str.split().explode().value_counts()42spam_count_words = spam['v2'].str.split().explode().value_counts()4344ham_count_words = ham_count_words.to_frame().reset_index().rename(columns={'index': 'word', 'v2': 'count'})45spam_count_words = spam_count_words.to_frame().reset_index().rename(columns={'index': 'word', 'v2': 'count'})46ham_words_length = content_length(ham_count_words['word'])47spam_words_length = content_length(spam_count_words['word'])48ham_avg_words_length = avg_content_length(ham_words_length, ham_count_words)49spam_avg_words_length = avg_content_length(spam_words_length, spam_count_words)50ham_words_length = ham_words_length.to_frame().reset_index()51# ham_words_length.drop('index', inplace=True, axis=1)52ham_word_normalize = pd.Series(ham_words_length['word']).max()53ham_words_length.loc[:, 'word'] /= ham_word_normalize54# ham_words_length = ham_words_length.sort_values(by=['word']).reset_index()55ham_avg_words_length /= ham_word_normalize56spam_words_length = spam_words_length.to_frame().reset_index()57# spam_words_length.drop('index', inplace=True, axis=1)58spam_word_normalize = pd.Series(spam_words_length['word']).max()59spam_words_length.loc[:, 'word'] /= spam_word_normalize60spam_avg_words_length /= spam_word_normalize61# spam_words_length = spam_words_length.sort_values(by=['word']).reset_index()62ham_20_words = get_20_and_normalize(ham_count_words)63spam_20_words = get_20_and_normalize(spam_count_words)6465Path(OUTPUT_FOLDER).mkdir(parents=True, exist_ok=True)66ham_count_words.to_csv(OUTPUT_FOLDER + '/hamCounter.csv', index=False, sep='-')67spam_count_words.to_csv(OUTPUT_FOLDER + '/spamCounter.csv', index=False, sep='-')6869ham_message_length = content_length(ham['v2'])70spam_message_length = content_length(spam['v2'])71spam_avg_message_length = avg_content_length(spam_message_length, spam)72ham_avg_message_length = avg_content_length(ham_message_length, ham)73spam_message_length = spam_message_length.to_frame().reset_index()74# spam_message_length.drop('index', inplace=True, axis=1)75spam_message_normalize = pd.Series(spam_message_length['v2']).max()76spam_message_length.loc[:, 'v2'] /= spam_message_normalize77spam_avg_message_length /= spam_message_normalize78ham_message_length = ham_message_length.to_frame().reset_index()79# ham_message_length.drop('index', inplace=True, axis=1)80ham_message_normalize = pd.Series(ham_message_length['v2']).max()81ham_message_length.loc[:, 'v2'] /= ham_message_normalize82ham_avg_message_length /= ham_message_normalize8384fig1, (ax1, ax2) = plt.subplots(1, 2)85ax1.set_title("ham")86ax1.bar(ham_20_words['word'], ham_20_words['count'])
...
prometheus_exporter.py
Source:prometheus_exporter.py
1# coding: utf823import six4from itertools import chain56from flask import request, Response7from locust import Locust, TaskSet, task, web, runners, stats as locust_stats8from prometheus_client import Metric, REGISTRY, exposition910# This locustfile adds an external web endpoint to the locust master, and makes it serve as a prometheus exporter.11# Runs it as a normal locustfile, then points prometheus to it.12# locust -f prometheus_exporter.py --master1314# Lots of code taken from [mbolek's locust_exporter](https://github.com/mbolek/locust_exporter), thx mbolek!151617class LocustCollector(object):18 registry = REGISTRY1920 def collect(self):21 # locust_runner is not None, it indicates that test started.22 if runners.locust_runner:2324 stats = []2526 for s in chain(locust_stats.sort_stats(runners.locust_runner.request_stats),27 [runners.locust_runner.stats.total]):28 stats.append({29 "method": s.method,30 "name": s.name,31 "num_requests": s.num_requests,32 "num_failures": s.num_failures,33 "avg_response_time": s.avg_response_time,34 "min_response_time": s.min_response_time or 0,35 "max_response_time": s.max_response_time,36 "current_rps": s.current_rps,37 "median_response_time": s.median_response_time,38 "avg_content_length": s.avg_content_length,39 })4041 errors = [e.to_dict() for e in six.itervalues(runners.locust_runner.errors)]4243 metric = Metric('locust_user_count', 'Swarmed users', 'gauge')44 metric.add_sample('locust_user_count', value=runners.locust_runner.user_count, labels={})45 yield metric4647 metric = Metric('locust_errors', 'Locust requests errors', 'gauge')48 for err in errors:49 metric.add_sample('locust_errors', value=err['occurrences'],50 labels={'path': err['name'], 'method': err['method']})51 yield metric5253 is_distributed = isinstance(runners.locust_runner, runners.MasterLocustRunner)54 if is_distributed:55 metric = Metric('locust_slave_count', 'Locust number of slaves', 'gauge')56 metric.add_sample('locust_slave_count', value=len(runners.locust_runner.clients.values()), labels={})57 yield metric5859 metric = Metric('locust_fail_ratio', 'Locust failure ratio', 'gauge')60 metric.add_sample('locust_fail_ratio', value=runners.locust_runner.stats.total.fail_ratio, labels={})61 yield metric6263 metric = Metric('locust_state', 'State of the locust swarm', 'gauge')64 metric.add_sample('locust_state', value=1, labels={'state': runners.locust_runner.state})65 yield metric6667 stats_metrics = ['avg_content_length', 'avg_response_time', 'current_rps', 'max_response_time',68 'median_response_time', 'min_response_time', 'num_failures', 'num_requests']6970 for mtr in stats_metrics:71 mtype = 'gauge'72 if mtr in ['num_requests', 'num_failures']:73 mtype = 'counter'74 metric = Metric('locust_requests_' + mtr, 'Locust requests ' + mtr, mtype)75 for stat in stats:76 if 'Total' not in stat['name']:77 metric.add_sample('locust_requests_' + mtr, value=stat[mtr],78 labels={'path': stat['name'], 'method': stat['method']})79 yield metric808182@web.app.route("/export/prometheus")83def prometheus_exporter():84 registry = REGISTRY85 encoder, content_type = exposition.choose_encoder(request.headers.get('Accept'))86 if 'name[]' in request.args:87 registry = REGISTRY.restricted_registry(request.args.get('name[]'))88 body = encoder(registry)89 return Response(body, content_type=content_type)909192REGISTRY.register(LocustCollector())939495class DummyTaskSet(TaskSet):96 @task(20)97 def hello(self):98 pass99100101class Dummy(Locust):
...
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!!