Best Python code snippet using molecule_python
test_ansible_runner.py
Source:test_ansible_runner.py
1# !/usr/bin/python32# coding: utf-83# ******************************************************************************4# Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.5# licensed under the Mulan PSL v2.6# You can use this software according to the terms and conditions of the Mulan PSL v2.7# You may obtain a copy of Mulan PSL v2 at:8# http://license.coscl.org.cn/MulanPSL29# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR10# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR11# PURPOSE.12# See the Mulan PSL v2 for more details.13# ******************************************************************************/14import uuid15import unittest16from unittest.mock import MagicMock17from datetime import timedelta18from zeus.deploy_manager.ansible_runner.ansible_runner import AnsibleRunner19from zeus.deploy_manager.ansible_runner.ansible_runner import ResultCallback20from ansible.executor.task_result import TaskResult21from ansible.inventory.host import Host22from ansible.executor.stats import AggregateStats23def get_mock_task_result(host_name, return_data):24 test_result = TaskResult(25 host=Host(host_name),26 task=get_mock_task(),27 return_data=return_data,28 )29 return test_result30def get_mock_task():31 mock_task = MagicMock()32 mock_task._role = None33 mock_task._parent = None34 mock_task.ignore_errors = False35 mock_task.ignore_unreachable = False36 mock_task._uuid = str(uuid.uuid4())37 mock_task.loop = None38 mock_task.copy.return_value = mock_task39 mock_task.get_name.return_value = "test_task"40 return mock_task41class TestAnsibleRunner(unittest.TestCase):42 def test_get_result(self):43 test_runner = AnsibleRunner(None, None)44 test_callback = ResultCallback()45 test_callback.host_ok["host1"] = {"task_name": "task_host1",46 "result": get_mock_task_result("host1",47 {"host1": "ok"})._result}48 test_callback.host_failed["host2"] = {"task_name": "task_host2",49 "result": get_mock_task_result("host2",50 {"host2": "failed"})._result}51 test_callback.host_skipped["host3"] = {"task_name": "task_host3",52 "result": get_mock_task_result("host3",53 {"host3": "skipped"})._result}54 test_callback.host_unreachable["host4"] = {"task_name": "task_host4",55 "result": get_mock_task_result("host4",56 {"host4": "unreachable"})._result}57 test_runner._callback = test_callback58 self.assertDictEqual(test_runner.get_result(),59 {'success': {'host1': {'task_name': 'task_host1',60 'result': {'host1': 'ok'}}},61 'failed': {'host2': {'task_name': 'task_host2',62 'result': {'host2': 'failed'}}},63 'unreachable': {'host4': {'task_name': 'task_host4',64 'result': {'host4': 'unreachable'}}},65 'skipped': {'host3': {'task_name': 'task_host3',66 'result': {'host3': 'skipped'}}}},67 msg="get result of all type")68 def test_no_failed(self):69 test_runner = AnsibleRunner("inventory", "password")70 test_runner._results_raw["failed"] = {}71 test_runner._results_raw["unreachable"] = {}72 self.assertTrue(test_runner.no_failed(), msg="No errors have occurred.")73 test_runner._results_raw["failed"] = {"host": "test"}74 test_runner._results_raw["unreachable"] = {}75 self.assertFalse(test_runner.no_failed(), msg="failed errors have occurred.")76 test_runner._results_raw["unreachable"] = {"host": "test"}77 test_runner._results_raw["failed"] = {}78 self.assertFalse(test_runner.no_failed(), msg="unreachable error has occurred.")79 test_runner._results_raw["unreachable"] = {"host": "test1"}80 test_runner._results_raw["failed"] = {"host": "test2"}81 self.assertFalse(test_runner.no_failed(),82 msg="unreachable and failed error has occurred.")83 def test_run(self):84 test_runner = AnsibleRunner("inventory", "password")85 self.assertIsNone(test_runner.run(None, None, None),86 msg="Host_list and module is invalid")87 def test_run_playbook(self):88 test_runner = AnsibleRunner("inventory", "password")89 with self.assertRaises(ValueError, msg="Invalid playbook file"):90 test_runner.run_playbook("test")91class TestResultCallback(unittest.TestCase):92 def test_v2_runner_on_ok(self):93 return_data_true = {"changed": "true", "cmd": "source /opt/zookeeper/bin/setId.sh",94 "delta": "0:00:00.002650",95 "end": "2021-08-19 11:46:21.142777", "rc": 0,96 "start": "2021-08-19 11:46:21.140127",97 "stderr": "", "stderr_lines": [], "stdout": "",98 "stdout_lines": []}99 test_result = get_mock_task_result("host1", return_data_true)100 result_callback = ResultCallback()101 result_callback.v2_runner_on_ok(test_result)102 self.assertDictEqual(result_callback.host_ok["host1"],103 {'result': return_data_true,104 'task_name': 'test_task'})105 def test_v2_runner_on_failed(self):106 return_data = {"changed": "false",107 "msg": "Failed to download metadata for repo 'Elasticsearch'",108 "rc": 1, "results": []}109 test_result = get_mock_task_result("host1", return_data)110 result_callback = ResultCallback()111 result_dict = {'result': return_data,112 'task_name': 'test_task'}113 result_callback.v2_runner_on_failed(test_result)114 self.assertDictEqual(result_callback.host_failed["host1"], result_dict)115 def test_v2_runner_on_unreachable(self):116 return_data = {'ansible_delegated_vars': {'ansible_host': 'host2'}}117 test_result = get_mock_task_result("host1", return_data)118 result_callback = ResultCallback()119 result_dict = {'result': return_data,120 'task_name': 'test_task'}121 result_callback.v2_runner_on_unreachable(test_result)122 self.assertDictEqual(result_callback.host_unreachable["host1"],123 result_dict)124 def test_v2_runner_on_skipped(self):125 return_data = {'ansible_delegated_vars': {'ansible_host': 'host2'}}126 test_result = get_mock_task_result("host1", return_data)127 result_callback = ResultCallback()128 result_callback.v2_runner_on_skipped(test_result)129 result_dict = {'result': return_data,130 'task_name': 'test_task'}131 result_callback.v2_runner_on_skipped(test_result)132 self.assertDictEqual(result_callback.host_skipped["host1"],133 result_dict)134 def test_v2_playbook_on_stats(self):135 test_stat = AggregateStats()136 result_callback = ResultCallback()137 result_callback.v2_playbook_on_stats(test_stat)138 def test_days_hours_minutes_seconds(self):139 test_time = timedelta(days=64, seconds=29156, microseconds=10)140 self.assertTupleEqual(ResultCallback._days_hours_minutes_seconds(test_time),141 (64, 8, 5, 28856),142 msg="day hour minutes second calculate succeed")143if __name__ == "__main__":...
bag_tasks.py
Source:bag_tasks.py
...15 def terminate(self):16 self.task.terminate()17 def set_status(self, status, success):18 self.status_update_signal.emit(status, success)19 def result_callback(self, result, success):20 self.set_status(result, success)21 def progress_callback(self, current, maximum):22 if self.task.canceled:23 return False24 self.progress_update_signal.emit(current, maximum)25 return True26class BagCreateOrUpdateTask(BagTask):27 def __init__(self, parent=None):28 super(BagCreateOrUpdateTask, self).__init__(parent)29 self.update = False30 def result_callback(self, result, success):31 status = "Bag %s completed successfully." % ("update" if self.update else "creation") if success else \32 "Bag %s error: %s" % ("update" if self.update else "creation", result)33 self.set_status(status, success)34 def createOrUpdate(self, bag_path, update, config_file):35 self.update = update36 self.task = Task(bdb.make_bag,37 [bag_path, ['md5', 'sha256'], update, True, False, None, None, None, config_file],38 self.result_callback)39 self.start()40class BagRevertTask(BagTask):41 def __init__(self, parent=None):42 super(BagRevertTask, self).__init__(parent)43 def result_callback(self, result, success):44 status = "Bag reverted successfully." if success else "Bag reversion failed: %s" % result45 self.set_status(status, success)46 def revert(self, bag_path):47 self.task = Task(bdb.revert_bag,48 [bag_path],49 self.result_callback)50 self.start()51class BagValidateTask(BagTask):52 def __init__(self, parent=None):53 super(BagValidateTask, self).__init__(parent)54 def result_callback(self, result, success):55 status = "Bag validation complete." if success else "Bag validation error: %s" % result56 self.set_status(status, success)57 def validate(self, bag_path, fast, config_file):58 self.task = Task(bdb.validate_bag,59 [bag_path, fast, self.progress_callback, config_file],60 self.result_callback)61 self.start()62class BagFetchTask(BagTask):63 def __init__(self, parent=None):64 super(BagFetchTask, self).__init__(parent)65 def result_callback(self, result, success):66 status = ("Bag fetch complete: All file references resolved successfully." if result else67 "Bag fetch incomplete: Some file references were not resolved.") if success else \68 "Bag fetch error: %s" % result69 self.set_status(status, success)70 def fetch(self, bag_path, fetch_all, keychain_file, config_file):71 self.task = Task(bdb.resolve_fetch,72 [bag_path, fetch_all, self.progress_callback, keychain_file, config_file],73 self.result_callback)74 self.start()75class BagArchiveTask(BagTask):76 def __init__(self, parent=None):77 super(BagArchiveTask, self).__init__(parent)78 def result_callback(self, result, success):79 status = "Bag archive complete." if success else "Bag archive error: %s" % result80 self.set_status(status, success)81 def archive(self, bag_path, archiver):82 self.task = Task(bdb.archive_bag,83 [bag_path, archiver],84 self.result_callback)85 self.start()86class BagExtractTask(BagTask):87 def __init__(self, parent=None):88 super(BagExtractTask, self).__init__(parent)89 def result_callback(self, result, success):90 status = "File extraction complete." if success else "File extraction error: %s" % result91 self.set_status(status, success)92 def extract(self, bag_path, output_path=None):93 self.task = Task(bdb.extract_bag,94 [bag_path, output_path],95 self.result_callback)96 self.start()97class BagMaterializeTask(BagTask):98 def __init__(self, parent=None):99 super(BagMaterializeTask, self).__init__(parent)100 def result_callback(self, result, success):101 status = "Bag materialization complete." if success else "Bag materialization error: %s" % result102 self.set_status(status, success)103 def materialize(self, bag_path, output_path=None):104 self.task = Task(bdb.materialize,105 [bag_path, output_path, self.progress_callback, self.progress_callback],106 self.result_callback)...
pycurl_rpc.py
Source:pycurl_rpc.py
...52 self.success = success53 self.response_buffer.close()54 self.completed_event.set()55 if self.result_callback is not None:56 self.result_callback(success, self.url)57# Called from cURL thread58def _post_string_noreturn(url, postdata, result_callback=None):59 ctx = BufferTransferContext("POST", url, postdata, result_callback)60 ctx.start()61def post_string_noreturn(url, postdata, result_callback=None):62 ciel.runtime.pycurl_thread.do_from_curl_thread(lambda: _post_string_noreturn(url, postdata, result_callback))63# Called from cURL thread64def _post_string(url, postdata):65 ctx = BufferTransferContext("POST", url, postdata)66 ctx.start()67 return ctx68def post_string(url, postdata):69 ctx = ciel.runtime.pycurl_thread.do_from_curl_thread_sync(lambda: _post_string(url, postdata))70 return ctx.get_result()...
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!!