Best Python code snippet using localstack_python
compile.py
Source:compile.py
...24 return ["Failed to stop container.", error]25 rmCont, error = subprocess.Popen(["docker", "container", "rm", containerID, ], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()26 if len(error) != 0:27 return ["Failed to remove container.", error]28def run_container(containerID, filename, input_file):29 #RUNS AND COMPILES FILE IN CONTAINER30 #copy user code and input files to container31 subprocess.run([ "docker", "cp", filename, containerID + ":" + "/testing"])32 subprocess.run(["docker", "cp", input_file, containerID + ":" + "/input"])33 #run the container34 runCont = subprocess.Popen(["docker", "container", "start", "-a", containerID, ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)35 #get outputs or errors36 output, error = runCont.communicate()37 exitstatus = subprocess.Popen(["docker", "inspect", containerID, "--format='{{.State.ExitCode}}'"], stdout=subprocess.PIPE)38 exitcode = exitstatus.communicate()[0]39 #Returns to the user that the container was timed out or that output was too long. Both security measures to prevent malicious code from crashing the server.40 if exitcode.decode().strip() == "'124'":41 output = "Time limit exceeded".encode()42 if len(output) > 2000:43 output = "Output exceeds size limit".encode()44 45 46 if len(error) != 0:47 return['error', error]48 else:49 return['worked', output]50def add_language_extension(filename, language):51 language_mapping = {'java':'.java', 'python':'.py', 'c':'.c'}52 if language in language_mapping:53 return filename + language_mapping[language]54 else:55 raise Exception('language not supported')56def test(candidate, testname, username, language, input=None):57 #if there is no container assigned, set up new one58 containerID = getattr(candidate, "containerID")59 if len(containerID) == 0:60 containerID = create_container()61 if len(containerID) != 0:62 Candidate.objects.filter(user=candidate.user).update(containerID=containerID)63 else:64 return ["Error creating container.", 0,0]65 else:66 containerID = getattr(candidate, "containerID")67 filename = os.path.join(USER_DIR, username, testname, add_language_extension('main', language))68 testfolder = os.path.join(TEST_DIR, testname)69 70 test_cases = os.listdir(os.path.join(testfolder, 'input'))71 outputs = []72 73 if input==None:74 testingInput = 'noncustom'75 else:76 testingInput = input77 #Results for run78 passes = 079 fails = 080 result = 081 if testingInput == 'noncustom':82 for i, test_case in enumerate(test_cases):83 out_str = "Test Case " + str(i+1) + ":\n"84 testingInput = os.path.join(testfolder, 'input', test_case.strip())85 output = run_container(containerID, filename, testingInput)86 87 if output[0] == 'error':88 out_str+=output[1].decode('ascii')89 else:90 with open(os.path.join(testfolder, 'output', test_case.strip()), 'r') as f:91 data = f.read()92 #test case result93 result = data.strip() == output[1].strip().decode("ASCII")94 out_str += str(result) +"\n"95 out_str += output[1].strip().decode("ASCII") + "\n"96 outputs.append(out_str + "\n")97 98 if result != 0:99 passes += 1100 else:101 fails +=1102 return outputs, passes, fails103 else:104 output = run_container(containerID, filename, testingInput)105 #add error handling106 return ["Custom testing", output[1]]107""" 108Function to test the code run on the code review page109Takes in the name of the test, username of code being tested, testing language and input for use if custom input is selected110Returns test output, test passes and fails111If custom input is selected returns just the output112"""113def reviewtest(testname, candusername, language,username , input=None):114 containerID = create_container()115 filename = os.path.join(USER_DIR, candusername, testname,username, 'temp', add_language_extension('main', language))116 117 testfolder = os.path.join(TEST_DIR, testname)118 passes = 0119 fails = 0120 result = 0121 122 test_cases = os.listdir(os.path.join(testfolder, 'input'))123 outputs = []124 if input==None:125 testingInput = 'noncustom'126 else:127 testingInput = input128 if testingInput == 'noncustom':129 for i, test_case in enumerate(test_cases):130 out_str = "Test Case " + str(i+1) + ":\n"131 output = run_container(containerID, filename, os.path.join(testfolder, 'input', test_case.strip()))132 if output[0] == 'error':133 out_str+=output[1].decode('ascii')134 135 else:136 with open(os.path.join(testfolder, 'output', test_case.strip()), 'r') as f:137 data = f.read()138 result = data.strip() == output[1].strip().decode("ASCII")139 out_str += str(data.strip() == output[1].strip().decode("ASCII")) +"\n"140 out_str += output[1].strip().decode("ASCII") + "\n"141 142 outputs.append(out_str + "\n")143 if result != 0:144 passes += 1145 else:146 fails +=1147 return outputs, passes, fails148 else:149 output = run_container(containerID, filename, testingInput)150 #add error handling151 return ["Custom testing", output[1]]152 153 remove_container(containerID)...
ui_run.py
Source:ui_run.py
1# -*- coding: utf-8 -*-2# Form implementation generated from reading ui file 'ui/run.ui'3#4# Created by: PyQt5 UI code generator 5.12.35#6# WARNING! All changes made in this file will be lost!7from PyQt5 import QtCore, QtGui, QtWidgets8from breezy.plugins.qbrz.lib.i18n import gettext9class Ui_RunDialog(object):10 def setupUi(self, RunDialog):11 RunDialog.setObjectName("RunDialog")12 RunDialog.resize(473, 367)13 self.main_v_layout = QtWidgets.QVBoxLayout(RunDialog)14 self.main_v_layout.setObjectName("main_v_layout")15 self.splitter = QtWidgets.QSplitter(RunDialog)16 self.splitter.setOrientation(QtCore.Qt.Vertical)17 self.splitter.setOpaqueResize(False)18 self.splitter.setChildrenCollapsible(False)19 self.splitter.setObjectName("splitter")20 self.run_container = QtWidgets.QGroupBox(self.splitter)21 self.run_container.setObjectName("run_container")22 self.run_container_layout = QtWidgets.QVBoxLayout(self.run_container)23 self.run_container_layout.setObjectName("run_container_layout")24 self.wd_layout = QtWidgets.QHBoxLayout()25 self.wd_layout.setObjectName("wd_layout")26 self.wd_label = QtWidgets.QLabel(self.run_container)27 self.wd_label.setObjectName("wd_label")28 self.wd_layout.addWidget(self.wd_label)29 self.wd_edit = QtWidgets.QLineEdit(self.run_container)30 self.wd_edit.setObjectName("wd_edit")31 self.wd_layout.addWidget(self.wd_edit)32 self.browse_button = QtWidgets.QPushButton(self.run_container)33 self.browse_button.setObjectName("browse_button")34 self.wd_layout.addWidget(self.browse_button)35 self.run_container_layout.addLayout(self.wd_layout)36 self.cmd_layout = QtWidgets.QGridLayout()37 self.cmd_layout.setObjectName("cmd_layout")38 self.cat_label = QtWidgets.QLabel(self.run_container)39 self.cat_label.setObjectName("cat_label")40 self.cmd_layout.addWidget(self.cat_label, 0, 0, 1, 1)41 self.cat_combobox = QtWidgets.QComboBox(self.run_container)42 self.cat_combobox.setMinimumSize(QtCore.QSize(170, 0))43 self.cat_combobox.setObjectName("cat_combobox")44 self.cmd_layout.addWidget(self.cat_combobox, 0, 1, 1, 1)45 self.cmd_label = QtWidgets.QLabel(self.run_container)46 self.cmd_label.setObjectName("cmd_label")47 self.cmd_layout.addWidget(self.cmd_label, 1, 0, 1, 1)48 self.cmd_combobox = QtWidgets.QComboBox(self.run_container)49 self.cmd_combobox.setMinimumSize(QtCore.QSize(170, 0))50 self.cmd_combobox.setEditable(True)51 self.cmd_combobox.setObjectName("cmd_combobox")52 self.cmd_layout.addWidget(self.cmd_combobox, 1, 1, 1, 1)53 self.hidden_checkbox = QtWidgets.QCheckBox(self.run_container)54 self.hidden_checkbox.setObjectName("hidden_checkbox")55 self.cmd_layout.addWidget(self.hidden_checkbox, 1, 2, 1, 1)56 self.run_container_layout.addLayout(self.cmd_layout)57 self.opt_arg_label = QtWidgets.QLabel(self.run_container)58 self.opt_arg_label.setLineWidth(0)59 self.opt_arg_label.setObjectName("opt_arg_label")60 self.run_container_layout.addWidget(self.opt_arg_label)61 self.opt_arg_edit = QtWidgets.QLineEdit(self.run_container)62 self.opt_arg_edit.setObjectName("opt_arg_edit")63 self.run_container_layout.addWidget(self.opt_arg_edit)64 self.opt_arg_btn_layout = QtWidgets.QHBoxLayout()65 self.opt_arg_btn_layout.setObjectName("opt_arg_btn_layout")66 self.directory_button = QtWidgets.QPushButton(self.run_container)67 self.directory_button.setObjectName("directory_button")68 self.opt_arg_btn_layout.addWidget(self.directory_button)69 self.filenames_button = QtWidgets.QPushButton(self.run_container)70 self.filenames_button.setObjectName("filenames_button")71 self.opt_arg_btn_layout.addWidget(self.filenames_button)72 spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)73 self.opt_arg_btn_layout.addItem(spacerItem)74 self.run_container_layout.addLayout(self.opt_arg_btn_layout)75 self.help_browser = QtWidgets.QTextBrowser(self.run_container)76 self.help_browser.setObjectName("help_browser")77 self.run_container_layout.addWidget(self.help_browser)78 self.subprocess_container = QtWidgets.QWidget(self.splitter)79 self.subprocess_container.setObjectName("subprocess_container")80 self.subprocess_container_layout = QtWidgets.QVBoxLayout(self.subprocess_container)81 self.subprocess_container_layout.setContentsMargins(0, 0, 0, 0)82 self.subprocess_container_layout.setObjectName("subprocess_container_layout")83 self.main_v_layout.addWidget(self.splitter)84 self.wd_label.setBuddy(self.wd_edit)85 self.cat_label.setBuddy(self.cmd_combobox)86 self.cmd_label.setBuddy(self.cmd_combobox)87 self.opt_arg_label.setBuddy(self.opt_arg_edit)88 self.retranslateUi(RunDialog)89 RunDialog.disableUi['bool'].connect(self.run_container.setDisabled)90 QtCore.QMetaObject.connectSlotsByName(RunDialog)91 RunDialog.setTabOrder(self.wd_edit, self.browse_button)92 RunDialog.setTabOrder(self.browse_button, self.hidden_checkbox)93 RunDialog.setTabOrder(self.hidden_checkbox, self.cmd_combobox)94 RunDialog.setTabOrder(self.cmd_combobox, self.opt_arg_edit)95 RunDialog.setTabOrder(self.opt_arg_edit, self.directory_button)96 RunDialog.setTabOrder(self.directory_button, self.filenames_button)97 RunDialog.setTabOrder(self.filenames_button, self.help_browser)98 def retranslateUi(self, RunDialog):99 _translate = QtCore.QCoreApplication.translate100 RunDialog.setWindowTitle(_translate("RunDialog", "Run bzr command"))101 self.run_container.setTitle(_translate("RunDialog", "Options"))102 self.wd_label.setText(_translate("RunDialog", "&Working directory:"))103 self.browse_button.setText(_translate("RunDialog", "&Browse..."))104 self.cat_label.setText(_translate("RunDialog", "C&ategory:"))105 self.cmd_label.setText(_translate("RunDialog", "&Command:"))106 self.hidden_checkbox.setText(_translate("RunDialog", "&Show hidden commands"))107 self.opt_arg_label.setText(_translate("RunDialog", "&Options and arguments for command:"))108 self.directory_button.setText(_translate("RunDialog", "Insert &directory..."))...
test_containers.py
Source:test_containers.py
...9 sys.exit(1)10if not IMAGE_DIR.exists():11 print(f"Expected image directory at {IMAGE_DIR}", file=sys.stderr)12 sys.exit(1)13def run_container(14 new_hostname: str,15 image_dir: Path,16 num_proc: int,17 program_path: Path,18 program_args: List[str],19 valgrind: bool = False20) -> subprocess.CompletedProcess:21 default_args = [str(CONTAINER_EXE), new_hostname, str(image_dir), str(num_proc), str(program_path)] \22 + program_args23 args = ["valgrind"] + default_args if valgrind else default_args24 return subprocess.run(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,25 universal_newlines=True, timeout=60)26def test_hostname():27 res = run_container(new_hostname="testHostName", image_dir=IMAGE_DIR,28 num_proc=5, program_path=Path("/bin/hostname"), program_args=[])29 assert res.returncode == 030 assert res.stderr == ""31 assert res.stdout.strip() == "testHostName"32def test_program_args():33 res = run_container(new_hostname="testHostName", image_dir=IMAGE_DIR,34 num_proc=5, program_path=Path("/bin/bash"), program_args=[ "--help"])35 assert res.returncode == 036 assert res.stderr == ""37 assert "GNU bash, version" in res.stdout38def test_max_processes():39 res = run_container(new_hostname="testHostName", image_dir=IMAGE_DIR,40 num_proc=2, program_path=Path("/bin/bash"), program_args=["-c", "sleep 3 | sleep 3"])41 assert res.returncode == 042 assert "No child processes" in res.stderr43def test_proc_mounted():44 res = run_container(new_hostname="testHostName", image_dir=IMAGE_DIR,45 num_proc=10, program_path=Path("/bin/findmnt"),46 program_args=[])47 assert res.returncode == 048 assert res.stderr == ""49 assert "/proc" in res.stdout50def test_proc_unmounted():51 res = run_container(new_hostname="testHostName", image_dir=IMAGE_DIR,52 num_proc=10, program_path=Path("/bin/bash"),53 program_args=[])54 res2 = subprocess.run(["findmnt | grep /image/proc"], stdin=subprocess.PIPE,55 stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, timeout=60, shell=True)56 assert res.returncode == 057 assert res.stderr == ""58 assert res2.stdout == ""59def test_valgrind_happy_flow():60 res = run_container(new_hostname="testHostName", image_dir=IMAGE_DIR,61 num_proc=10, program_path=Path("/bin/sleep"),62 program_args=["3"], valgrind=True)63 assert res.returncode == 0...
get_run_container.py
Source:get_run_container.py
1# coding=utf82# Autor : Dennis zhang3# Time : 2018/6/25 10:044# File : get_run_container.py5# Software PyCharm6from api.open_api import bash7def get_container_list(src_str):8 ret_dict={}9 container_list=[]10 for o in src_str:11 dict_value_list=[]12 exce_order = "ansible %s -m shell -a \"docker ps\"\13 |egrep -v \"SUCCESS\"|egrep -v \"CONTAINER ID\"|grep -v '|'|awk -F \" \" \'{print $2}\'"%o14 print(exce_order)15 str_run_container = bash(exce_order)16 run_container = str_run_container.replace('\n',' ',len(str_run_container)).split(' ')17 if len(run_container) > 1:18 container_list=container_list+run_container[:len(run_container)-1]19 dict_value_list=dict_value_list+run_container[:len(run_container)-1]20 ret_dict.update(dict({o:dict_value_list}))21 return container_list,ret_dict22def list_trans_dict(src):23 ret_dict={}24 for key, values in src.items():25 for o in values:26 midd=o.split(':')27 print("-----list_trans_dict----midd----",midd)28 ret_dict.update(dict({midd[0]:[midd[1], key]}))29 return ret_dict30def compare_dict(src_dict,dest_dict):31 ret_src_dict={}32 ret_dest_dict={}33 ret_list = []34 for o in src_dict.keys():35 mid_values = list(src_dict[o])36 if o not in dest_dict.keys():37 ret_values = str(o)+":"+str(mid_values[0])38 ret_src_dict.update({ret_values:mid_values[1]})39 else:40 mid_dest_values = list(dest_dict[o])41 if mid_values[0] != mid_dest_values[0]:42 ret_dest_values = str(o)+":"+mid_dest_values[0]43 ret_src_values = str(o)+":"+str(mid_values[0])44 dest_dict_ret = {ret_dest_values:mid_dest_values[1]}45 src_dict_ret = {ret_src_values:mid_values[1]}46 mid_ret_list = []47 mid_ret_list.append(dest_dict_ret)48 mid_ret_list.append(src_dict_ret)49 ret_list.append(mid_ret_list)50 print("------ret_src_dict---------",ret_src_dict)51 print("--------ret_list-------",ret_list)...
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!!