How to use test_stop_event_quit method in locust

Best Python code snippet using locust

test_runners.py

Source:test_runners.py Github

copy

Full Screen

...189 self.assertEqual(0, test_stop_run[0])190 runner.stop()191 self.assertEqual(1, test_stop_run[0])192 193 def test_stop_event_quit(self):194 class MyUser(User):195 wait_time = constant(1)196 @task197 def my_task(self):198 pass199 test_stop_run = [0]200 environment = Environment(user_classes=[User])201 def on_test_stop(*args, **kwargs):202 test_stop_run[0] += 1203 environment.events.test_stop.add_listener(on_test_stop)204 runner = LocalRunner(environment)205 runner.start(user_count=3, hatch_rate=3, wait=False)206 self.assertEqual(0, test_stop_run[0])207 runner.quit()208 self.assertEqual(1, test_stop_run[0])209 def test_stop_event_stop_and_quit(self):210 class MyUser(User):211 wait_time = constant(1)212 @task213 def my_task(self):214 pass215 test_stop_run = [0]216 environment = Environment(user_classes=[MyUser])217 def on_test_stop(*args, **kwargs):218 test_stop_run[0] += 1219 environment.events.test_stop.add_listener(on_test_stop)220 runner = LocalRunner(environment)221 runner.start(user_count=3, hatch_rate=3, wait=False)222 self.assertEqual(0, test_stop_run[0])223 runner.stop()224 runner.quit()225 self.assertEqual(1, test_stop_run[0])226 def test_change_user_count_during_hatching(self):227 class MyUser(User):228 wait_time = constant(1)229 @task230 def my_task(self):231 pass232 233 environment = Environment(user_classes=[MyUser])234 runner = LocalRunner(environment)235 runner.start(user_count=10, hatch_rate=5, wait=False)236 sleep(0.6)237 runner.start(user_count=5, hatch_rate=5, wait=False)238 runner.hatching_greenlet.join()239 self.assertEqual(5, len(runner.user_greenlets))240 runner.quit()241 242 def test_reset_stats(self):243 class MyUser(User):244 wait_time = constant(0)245 @task246 class task_set(TaskSet):247 @task248 def my_task(self):249 self.user.environment.events.request_success.fire(250 request_type="GET",251 name="/test",252 response_time=666,253 response_length=1337,254 )255 sleep(2)256 257 environment = Environment(user_classes=[MyUser], reset_stats=True)258 runner = LocalRunner(environment)259 runner.start(user_count=6, hatch_rate=12, wait=False)260 sleep(0.25)261 self.assertGreaterEqual(runner.stats.get("/test", "GET").num_requests, 3)262 sleep(0.3)263 self.assertLessEqual(runner.stats.get("/test", "GET").num_requests, 1)264 runner.quit()265 266 def test_no_reset_stats(self):267 class MyUser(User):268 wait_time = constant(0)269 @task270 class task_set(TaskSet):271 @task272 def my_task(self):273 self.user.environment.events.request_success.fire(274 request_type="GET",275 name="/test",276 response_time=666,277 response_length=1337,278 ) 279 sleep(2)280 281 environment = Environment(reset_stats=False, user_classes=[MyUser])282 runner = LocalRunner(environment)283 runner.start(user_count=6, hatch_rate=12, wait=False)284 sleep(0.25)285 self.assertGreaterEqual(runner.stats.get("/test", "GET").num_requests, 3)286 sleep(0.3)287 self.assertEqual(6, runner.stats.get("/test", "GET").num_requests)288 runner.quit()289 def test_runner_reference_on_environment(self):290 env = Environment()291 runner = env.create_local_runner()292 self.assertEqual(env, runner.environment)293 self.assertEqual(runner, env.runner)294class TestMasterWorkerRunners(LocustTestCase):295 def test_distributed_integration_run(self):296 """297 Full integration test that starts both a MasterRunner and three WorkerRunner instances 298 and makes sure that their stats is sent to the Master.299 """300 class TestUser(User):301 wait_time = constant(0.1)302 @task303 def incr_stats(l):304 l.environment.events.request_success.fire(305 request_type="GET",306 name="/",307 response_time=1337,308 response_length=666,309 )310 with mock.patch("locust.runners.WORKER_REPORT_INTERVAL", new=0.3):311 # start a Master runner312 master_env = Environment(user_classes=[TestUser])313 master = master_env.create_master_runner("*", 0)314 sleep(0)315 # start 3 Worker runners316 workers = []317 for i in range(3):318 worker_env = Environment(user_classes=[TestUser])319 worker = worker_env.create_worker_runner("127.0.0.1", master.server.port)320 workers.append(worker)321 322 # give workers time to connect323 sleep(0.1)324 # issue start command that should trigger TestUsers to be spawned in the Workers325 master.start(6, hatch_rate=1000)326 sleep(0.1)327 # check that worker nodes have started locusts328 for worker in workers:329 self.assertEqual(2, worker.user_count)330 # give time for users to generate stats, and stats to be sent to master331 sleep(1)332 master.quit()333 # make sure users are killed334 for worker in workers:335 self.assertEqual(0, worker.user_count)336 337 # check that stats are present in master338 self.assertGreater(339 master_env.runner.stats.total.num_requests, 340 20, 341 "For some reason the master node's stats has not come in",342 )343class TestMasterRunner(LocustTestCase):344 def setUp(self):345 super(TestMasterRunner, self).setUp()346 self.environment = Environment(events=locust.events, catch_exceptions=False)347 348 def tearDown(self):349 super(TestMasterRunner, self).tearDown()350 351 def get_runner(self):352 return self.environment.create_master_runner("*", 5557)353 354 def test_worker_connect(self):355 with mock.patch("locust.rpc.rpc.Server", mocked_rpc()) as server:356 master = self.get_runner()357 server.mocked_send(Message("client_ready", None, "zeh_fake_client1"))358 self.assertEqual(1, len(master.clients))359 self.assertTrue("zeh_fake_client1" in master.clients, "Could not find fake client in master instance's clients dict")360 server.mocked_send(Message("client_ready", None, "zeh_fake_client2"))361 server.mocked_send(Message("client_ready", None, "zeh_fake_client3"))362 server.mocked_send(Message("client_ready", None, "zeh_fake_client4"))363 self.assertEqual(4, len(master.clients))364 365 server.mocked_send(Message("quit", None, "zeh_fake_client3"))366 self.assertEqual(3, len(master.clients))367 368 def test_worker_stats_report_median(self):369 with mock.patch("locust.rpc.rpc.Server", mocked_rpc()) as server:370 master = self.get_runner()371 server.mocked_send(Message("client_ready", None, "fake_client"))372 373 master.stats.get("/", "GET").log(100, 23455)374 master.stats.get("/", "GET").log(800, 23455)375 master.stats.get("/", "GET").log(700, 23455)376 377 data = {"user_count":1}378 self.environment.events.report_to_master.fire(client_id="fake_client", data=data)379 master.stats.clear_all()380 381 server.mocked_send(Message("stats", data, "fake_client"))382 s = master.stats.get("/", "GET")383 self.assertEqual(700, s.median_response_time)384 def test_worker_stats_report_with_none_response_times(self):385 with mock.patch("locust.rpc.rpc.Server", mocked_rpc()) as server:386 master = self.get_runner()387 server.mocked_send(Message("client_ready", None, "fake_client"))388 389 master.stats.get("/mixed", "GET").log(0, 23455)390 master.stats.get("/mixed", "GET").log(800, 23455)391 master.stats.get("/mixed", "GET").log(700, 23455)392 master.stats.get("/mixed", "GET").log(None, 23455)393 master.stats.get("/mixed", "GET").log(None, 23455)394 master.stats.get("/mixed", "GET").log(None, 23455)395 master.stats.get("/mixed", "GET").log(None, 23455)396 master.stats.get("/onlyNone", "GET").log(None, 23455)397 398 data = {"user_count":1}399 self.environment.events.report_to_master.fire(client_id="fake_client", data=data)400 master.stats.clear_all()401 402 server.mocked_send(Message("stats", data, "fake_client"))403 s1 = master.stats.get("/mixed", "GET")404 self.assertEqual(700, s1.median_response_time)405 self.assertEqual(500, s1.avg_response_time) 406 s2 = master.stats.get("/onlyNone", "GET")407 self.assertEqual(0, s2.median_response_time)408 self.assertEqual(0, s2.avg_response_time)409 def test_master_marks_downed_workers_as_missing(self):410 with mock.patch("locust.rpc.rpc.Server", mocked_rpc()) as server:411 master = self.get_runner()412 server.mocked_send(Message("client_ready", None, "fake_client"))413 sleep(6)414 # print(master.clients['fake_client'].__dict__)415 assert master.clients['fake_client'].state == STATE_MISSING416 def test_last_worker_quitting_stops_test(self):417 with mock.patch("locust.rpc.rpc.Server", mocked_rpc()) as server:418 master = self.get_runner()419 server.mocked_send(Message("client_ready", None, "fake_client1"))420 server.mocked_send(Message("client_ready", None, "fake_client2"))421 master.start(1, 2)422 server.mocked_send(Message("hatching", None, "fake_client1"))423 server.mocked_send(Message("hatching", None, "fake_client2"))424 server.mocked_send(Message("quit", None, "fake_client1"))425 sleep(0)426 self.assertEqual(1, len(master.clients.all))427 self.assertNotEqual(STATE_STOPPED, master.state, "Not all workers quit but test stopped anyway.")428 server.mocked_send(Message("quit", None, "fake_client2"))429 sleep(0)430 self.assertEqual(0, len(master.clients.all))431 self.assertEqual(STATE_STOPPED, master.state, "All workers quit but test didn't stop.")432 @mock.patch("locust.runners.HEARTBEAT_INTERVAL", new=0.1)433 def test_last_worker_missing_stops_test(self):434 with mock.patch("locust.rpc.rpc.Server", mocked_rpc()) as server:435 master = self.get_runner()436 server.mocked_send(Message("client_ready", None, "fake_client1"))437 server.mocked_send(Message("client_ready", None, "fake_client2"))438 master.start(1, 2)439 server.mocked_send(Message("hatching", None, "fake_client1"))440 server.mocked_send(Message("hatching", None, "fake_client2"))441 sleep(0.3)442 server.mocked_send(Message("heartbeat", {'state': STATE_RUNNING, 'current_cpu_usage': 50}, "fake_client1"))443 sleep(0.3)444 self.assertEqual(1, len(master.clients.missing))445 self.assertNotEqual(STATE_STOPPED, master.state, "Not all workers went missing but test stopped anyway.")446 sleep(0.3)447 self.assertEqual(2, len(master.clients.missing))448 self.assertEqual(STATE_STOPPED, master.state, "All workers went missing but test didn't stop.")449 def test_master_total_stats(self):450 with mock.patch("locust.rpc.rpc.Server", mocked_rpc()) as server:451 master = self.get_runner()452 server.mocked_send(Message("client_ready", None, "fake_client"))453 stats = RequestStats()454 stats.log_request("GET", "/1", 100, 3546)455 stats.log_request("GET", "/1", 800, 56743)456 stats2 = RequestStats()457 stats2.log_request("GET", "/2", 700, 2201)458 server.mocked_send(Message("stats", {459 "stats":stats.serialize_stats(), 460 "stats_total": stats.total.serialize(),461 "errors":stats.serialize_errors(),462 "user_count": 1,463 }, "fake_client"))464 server.mocked_send(Message("stats", {465 "stats":stats2.serialize_stats(), 466 "stats_total": stats2.total.serialize(),467 "errors":stats2.serialize_errors(),468 "user_count": 2,469 }, "fake_client"))470 self.assertEqual(700, master.stats.total.median_response_time)471 def test_master_total_stats_with_none_response_times(self):472 with mock.patch("locust.rpc.rpc.Server", mocked_rpc()) as server:473 master = self.get_runner()474 server.mocked_send(Message("client_ready", None, "fake_client"))475 stats = RequestStats()476 stats.log_request("GET", "/1", 100, 3546)477 stats.log_request("GET", "/1", 800, 56743)478 stats.log_request("GET", "/1", None, 56743)479 stats2 = RequestStats()480 stats2.log_request("GET", "/2", 700, 2201)481 stats2.log_request("GET", "/2", None, 2201)482 stats3 = RequestStats()483 stats3.log_request("GET", "/3", None, 2201)484 server.mocked_send(Message("stats", {485 "stats":stats.serialize_stats(), 486 "stats_total": stats.total.serialize(),487 "errors":stats.serialize_errors(),488 "user_count": 1,489 }, "fake_client"))490 server.mocked_send(Message("stats", {491 "stats":stats2.serialize_stats(), 492 "stats_total": stats2.total.serialize(),493 "errors":stats2.serialize_errors(),494 "user_count": 2,495 }, "fake_client"))496 server.mocked_send(Message("stats", {497 "stats":stats3.serialize_stats(), 498 "stats_total": stats3.total.serialize(),499 "errors":stats3.serialize_errors(),500 "user_count": 2,501 }, "fake_client"))502 self.assertEqual(700, master.stats.total.median_response_time)503 504 def test_master_current_response_times(self):505 start_time = 1506 with mock.patch("time.time") as mocked_time:507 mocked_time.return_value = start_time508 with mock.patch("locust.rpc.rpc.Server", mocked_rpc()) as server:509 master = self.get_runner()510 self.environment.stats.reset_all()511 mocked_time.return_value += 1.0234512 server.mocked_send(Message("client_ready", None, "fake_client"))513 stats = RequestStats()514 stats.log_request("GET", "/1", 100, 3546)515 stats.log_request("GET", "/1", 800, 56743)516 server.mocked_send(Message("stats", {517 "stats":stats.serialize_stats(),518 "stats_total": stats.total.get_stripped_report(),519 "errors":stats.serialize_errors(),520 "user_count": 1,521 }, "fake_client"))522 mocked_time.return_value += 1523 stats2 = RequestStats()524 stats2.log_request("GET", "/2", 400, 2201)525 server.mocked_send(Message("stats", {526 "stats":stats2.serialize_stats(),527 "stats_total": stats2.total.get_stripped_report(),528 "errors":stats2.serialize_errors(),529 "user_count": 2,530 }, "fake_client"))531 mocked_time.return_value += 4532 self.assertEqual(400, master.stats.total.get_current_response_time_percentile(0.5))533 self.assertEqual(800, master.stats.total.get_current_response_time_percentile(0.95))534 535 # let 10 second pass, do some more requests, send it to the master and make536 # sure the current response time percentiles only accounts for these new requests537 mocked_time.return_value += 10.10023538 stats.log_request("GET", "/1", 20, 1)539 stats.log_request("GET", "/1", 30, 1)540 stats.log_request("GET", "/1", 3000, 1)541 server.mocked_send(Message("stats", {542 "stats":stats.serialize_stats(),543 "stats_total": stats.total.get_stripped_report(),544 "errors":stats.serialize_errors(),545 "user_count": 2,546 }, "fake_client"))547 self.assertEqual(30, master.stats.total.get_current_response_time_percentile(0.5))548 self.assertEqual(3000, master.stats.total.get_current_response_time_percentile(0.95))549 550 def test_rebalance_locust_users_on_worker_connect(self):551 with mock.patch("locust.rpc.rpc.Server", mocked_rpc()) as server:552 master = self.get_runner()553 server.mocked_send(Message("client_ready", None, "zeh_fake_client1"))554 self.assertEqual(1, len(master.clients))555 self.assertTrue("zeh_fake_client1" in master.clients, "Could not find fake client in master instance's clients dict")556 557 master.start(100, 20)558 self.assertEqual(1, len(server.outbox))559 client_id, msg = server.outbox.pop()560 self.assertEqual(100, msg.data["num_users"])561 self.assertEqual(20, msg.data["hatch_rate"])562 563 # let another worker connect564 server.mocked_send(Message("client_ready", None, "zeh_fake_client2"))565 self.assertEqual(2, len(master.clients))566 self.assertEqual(2, len(server.outbox))567 client_id, msg = server.outbox.pop()568 self.assertEqual(50, msg.data["num_users"])569 self.assertEqual(10, msg.data["hatch_rate"])570 client_id, msg = server.outbox.pop()571 self.assertEqual(50, msg.data["num_users"])572 self.assertEqual(10, msg.data["hatch_rate"])573 574 def test_sends_hatch_data_to_ready_running_hatching_workers(self):575 '''Sends hatch job to running, ready, or hatching workers'''576 with mock.patch("locust.rpc.rpc.Server", mocked_rpc()) as server:577 master = self.get_runner()578 master.clients[1] = WorkerNode(1)579 master.clients[2] = WorkerNode(2)580 master.clients[3] = WorkerNode(3)581 master.clients[1].state = STATE_INIT582 master.clients[2].state = STATE_HATCHING583 master.clients[3].state = STATE_RUNNING584 master.start(user_count=5, hatch_rate=5)585 self.assertEqual(3, len(server.outbox))586 587 def test_start_event(self):588 """589 Tests that test_start event is fired590 """591 with mock.patch("locust.rpc.rpc.Server", mocked_rpc()) as server:592 master = self.get_runner()593 594 run_count = [0]595 @self.environment.events.test_start.add_listener596 def on_test_start(*a, **kw):597 run_count[0] += 1 598 599 for i in range(5):600 server.mocked_send(Message("client_ready", None, "fake_client%i" % i))601 602 master.start(7, 7)603 self.assertEqual(5, len(server.outbox))604 self.assertEqual(1, run_count[0])605 606 # change number of users and check that test_start isn't fired again607 master.start(7, 7)608 self.assertEqual(1, run_count[0])609 # stop and start to make sure test_start is fired again610 master.stop()611 master.start(3, 3)612 self.assertEqual(2, run_count[0])613 master.quit()614 def test_stop_event(self):615 """616 Tests that test_stop event is fired617 """618 with mock.patch("locust.rpc.rpc.Server", mocked_rpc()) as server:619 master = self.get_runner()620 621 run_count = [0]622 @self.environment.events.test_stop.add_listener623 def on_test_stop(*a, **kw):624 run_count[0] += 1 625 626 for i in range(5):627 server.mocked_send(Message("client_ready", None, "fake_client%i" % i))628 629 master.start(7, 7)630 self.assertEqual(5, len(server.outbox))631 master.stop()632 self.assertEqual(1, run_count[0])633 run_count[0] = 0634 for i in range(5):635 server.mocked_send(Message("client_ready", None, "fake_client%i" % i))636 master.start(7, 7)637 master.stop()638 master.quit()639 self.assertEqual(1, run_count[0])640 def test_stop_event_quit(self):641 """642 Tests that test_stop event is fired when quit() is called directly643 """644 with mock.patch("locust.rpc.rpc.Server", mocked_rpc()) as server:645 master = self.get_runner()646 run_count = [0]647 @self.environment.events.test_stop.add_listener648 def on_test_stop(*a, **kw):649 run_count[0] += 1650 for i in range(5):651 server.mocked_send(Message("client_ready", None, "fake_client%i" % i))652 master.start(7, 7)653 self.assertEqual(5, len(server.outbox))654 master.quit()...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run locust automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful