Best Python code snippet using avocado_python
code_generator_test.py
Source:code_generator_test.py  
...31    def test_cons_param(self):32        """Test that constructor parameters can be correctly used."""33        p = ('class X { X(String x) {' + self._wrap_print('x') +34             '} static void main(String[] args) {X inst = new X("pass");}}')35        self._check_output(p, 'X', 'pass')3637    def test_method_param(self):38        """Test that method parameters can be correctly used."""39        p = ('class X { void meth(String x){' + self._wrap_print('x') +40             '} static void main(String[] args) {' +41             'X inst = new X();inst.meth("pass");}}')42        self._check_output(p, 'X', 'pass')4344    def test_super_cons_implicitly_invoked(self):45        """Test that the super constructor is implicitly invoked."""46        self._check_output_file('test_super_cons_implicitly_invoked.jml',47                                'pass')4849    def test_super_cons_explicitly_invoked(self):50        """Test that the super classes constructor can be explicitly51        invoked correctly.52        """53        self._check_output_file('test_super_cons_explicitly_invoked.jml',54                                'pass')5556    def test_method_call(self):57        """Test a simple method call to a method in the current class."""58        p = ('class X { void meth() { int x = meth2();' +59             self._wrap_print('x') + '} byte meth2() {return 5;} ' +60             'static void main(String[] args){X inst = new X();inst.meth();}}')61        self._check_output(p, 'X', '5')6263    def test_method_return_array(self):64        """Test a method in the same class correctly returns an array."""65        p = ('class X { void meth() { byte[][] x = meth2();' +66             'int y = x[0][0];' + self._wrap_print('y') +67             '} byte[][] meth2() { byte[][] arr = new byte[5][5];'68             'arr[0][0] = 5; return arr;} static void main(String[] args) {' +69             'X inst = new X();inst.meth();}}')70        self._check_output(p, 'X', '5')7172    def test_method_call_external(self):73        """Test that a external method call is correctly compiled."""74        self._check_output_file('test_method_call_external.jml','10.1')7576    def test_method_call_static(self):77        """Test a static external method call."""78        self._check_output_file('test_method_call_static.jml', '10.0')7980    def test_private_method_call(self):81        """Test an invocation of a private method in the current class.82        """83        p = ('class X { private void meth() {' + self._wrap_print('10') +84             '} static void main(String[] args) {' +85             'X inst = new X();inst.meth();}}')86        self._check_output(p, 'X', '10')8788    def test_lib_method_call(self):89        """Test a call to a library class."""90        p = ('class X{static void main(String[] args) ' +91             '{Integer i = new Integer(5);' +92             self._wrap_print('i.intValue()') + '}}')93        self._check_output(p, 'X', '5')9495    def test_lib_method_call_params(self):96        """Test a call to a library class with parameters."""97        p = ('class X {static void main(String[] args)' +98             '{String s = new String("pass");' +99             self._wrap_print('s.endsWith("s")') + '}}')100        self._check_output(p, 'X', 'true')101102    def test_lib_method_in_super_call(self):103        """Test a method call to a library object where the method is defined104        in its super class.105        """106        p = ('class X{static void main(String[] args){' +107             self._wrap_print('Double.isNaN(1.1)') + '}}')108        self._check_output(p, 'X', 'false')109110    def test_method_call_explicitly_super(self):111        """Test that the method in the super class is called, even when there112        is one with the same name in the current class.113        """114        p = ('class X {  X() {' +115             self._wrap_print('super.equals(new Object())') +116             '}static void main(String[] args){X x = new X();} ' +117             'boolean equals(Object x) {return true;}}')118        self._check_output(p, 'X', 'false')119120    def test_lib_method_call_static(self):121        """Test a static method call. """122        p = ('class X {static void main(String[] args)' +123             '{GregorianCalendar x = new GregorianCalendar();' +124             self._wrap_print('x.isLenient()') + '}}')125        self._check_output(p, 'X', 'true')126127    def test_field_access(self):128        """Test a simple field accessing in the same class."""129        p = ('class X { int f; void meth() { f = 5;' +130             self._wrap_print('f') + '} static void main(' +131             'String[] args) { X inst = new X();inst.meth();}}')132        self._check_output(p, 'X', '5')133134    def test_field_inc(self):135        """Test incrementing a field in the current class."""136        p = ('class X { int f; void meth() {f = 5;f++;' +137             self._wrap_print('f') + '} static void main(' +138             'String[] args) {X inst = new X();inst.meth();}}')139        self._check_output(p, 'X', '6')140141    def test_field_array(self):142        """Test a field of array type correctly compiles."""143        p = ('class X { int[] f; void meth() { f = new int[1];' +144             'f[0] = 5;' + self._wrap_print('f[0]') + '} ' +145             'static void main(String[] args) ' +146             '{ X inst = new X();inst.meth();}}')147        self._check_output(p, 'X', '5')148149    def test_field_ref_external(self):150        """Test access to an external field."""151        self._check_output_file('test_field_ref_external.jml', 'pass')152153    def test_field_ref_static(self):154        """Test a reference to a static final field."""155        self._check_output_file('test_field_ref_static.jml', '10.5')156157    def test_field_ref_super(self):158        """Test a reference to a field in the super class."""159        self._check_output_file('test_field_ref_super.jml', '10')160161    def test_field_ref_private(self):162        """Test a reference to a private field in the current class."""163        p = ('class X { private int x; X() {x = 10;' +164             self._wrap_print('x') + '} static void main ' +165             '(String[] args) { new X();}}')166        self._check_output(p, 'X', '10')167168    def test_lib_field_ref(self):169        """Test that a public field can be accessed that is in a library class.170        """171        p = ('class X {static void main(String[] args) { '+172             'int x = Short.MAX_VALUE;'+ self._wrap_print('x') + '}}')173        self._check_output(p, 'X', '32767')174175    def test_var_dcl(self):176        """Test variable declarations."""177        p = self._wrap_stmts('int x = 1;' + self._wrap_print('x'))178        self._check_output(p, 'X', '1')179180    def test_if(self):181        """Test a simple if statement."""182        p = self._wrap_stmts('int x = 2; if (x > 2) {' +183                             self._wrap_print('"fail"') +184                             '} else {' + self._wrap_print('"pass"') + '}')185        self._check_output(p, 'X', "pass")186187    def test_nested_if(self):188        """Test nested if statements."""189        p = self._wrap_stmts('String s = "hello"; int x = 2; if (x > = 3) {' +190                             self._wrap_print('"fail"') +191                             '} else if (s == "hi") {' +192                             self._wrap_print('"fail2"') +193                             '} else {' + self._wrap_print('"pass"') + '}')194        self._check_output(p, 'X', 'pass')195196    def  test_while(self):197        """Test a while statement that increments an int and prints out it's198        value.199        """200        p = self._wrap_stmts('int i = 1; while (i <= 10) {' +201                             self._wrap_print('i') + 'i = i + 1;}')202        # The new lines are needed because each new print statement has203        # a new line character after it204        nl = os.linesep205        self._check_output(p, 'X', '1' + nl + '2' + nl + '3' + nl +206                           '4' + nl + '5' + nl + '6' + nl + '7' + nl +207                           '8' + nl + '9' + nl + '10')208209    def  test_for(self):210        """Test a for loop which loops five times, each time printing out "s".211        """212        p = self._wrap_stmts('String s = "s"; for (int i = 0; i <5; i++) {' +213                             self._wrap_print('s') + '}')214        nl = os.linesep215        self._check_output(p, 'X', 's' + nl + 's' + nl + 's' + nl + 's' + nl +216                           's')217218    def test_or(self):219        """Test the boolean or operator by including it in an if statement220        where only one side is true.221        """222        p = self._wrap_stmts('int x = 1; if (x != 1 || x == 1) {' +223                             self._wrap_print('"pass"') + '}')224        self._check_output(p, 'X', 'pass')225226    def test_and(self):227        """Test the boolean and operator by including it in an if statement228        where both sides are true.229        """230        p = self._wrap_stmts('int x = 1; if (x != 1 && x == 1) {' +231                             self._wrap_print('"fail"') +232                             '} else {' + self._wrap_print('"pass"') + '}')233        self._check_output(p, 'X', 'pass')234235    # Equality and relational operators already tested in previous tests.236237    def test_add(self):238        """Test simple addition in a print statement."""239        p = self._wrap_stmts(self._wrap_print('1 + 1'))240        self._check_output(p, 'X', '2')241242    def test_concat(self):243        """Test concatination of two strings."""244        p = self._wrap_stmts(self._wrap_print('"fst" + "snd"'))245        self._check_output(p, 'X', 'fstsnd')246247    def test_sub(self):248        """Test simple subtraction in a print statement."""249        p = self._wrap_stmts(self._wrap_print('1 - 1'))250        self._check_output(p, 'X', '0')251252    def test_mul(self):253        """Test simple multiplication in a print statement."""254        p = self._wrap_stmts(self._wrap_print('2*2'))255        self._check_output(p, 'X', '4')256257    def test_div(self):258        """Test simple division in a print statement."""259        p = self._wrap_stmts(self._wrap_print('4/2'))260        self._check_output(p, 'X', '2')261262    def test_not(self):263        """Test that the not operator inverts the boolean expression: true."""264        p = self._wrap_stmts(self._wrap_print('!true'))265        self._check_output(p, 'X', 'false')266267    def test_neg(self):268        """Test that the negative operator makes the expression negative."""269        p = self._wrap_stmts(self._wrap_print('-(2+2)'))270        self._check_output(p, 'X', '-4')271272    def test_pos(self):273        """Test that the positive operator has no effect on the expression's274        sign.275        """276        p = self._wrap_stmts(self._wrap_print('+(-2)'))277        self._check_output(p, 'X', '-2')278279    def test_inc(self):280        """Test that the increment operator increments by 1."""281        p = self._wrap_stmts('int x = 1; x++;' + self._wrap_print('x'))282        self._check_output(p, 'X', '2')283284    def test_dec(self):285        """Test that the decrement operator decrements by 1."""286        p = self._wrap_stmts('int x = 1; --x;' + self._wrap_print('x'))287        self._check_output(p, 'X', '0')288289    def test_brackets(self):290        """Test precedence rules are followed when parentheses are used."""291        p = self._wrap_stmts(self._wrap_print('(1+1)/1'))292        self._check_output(p, 'X', '2')293294    def test_array(self):295        """Test a simple array creation and access."""296        p = self._wrap_stmts('String[] arr = new String[5];' +297                             'arr[0] = "Hello";' + self._wrap_print('arr[0]'))298        self._check_output(p, 'X', 'Hello')299300    def test_multi_array(self):301        """Test creation and access of a multi-dimensional array."""302        p = self._wrap_stmts('int[][][] a = new int[5][10][1];' +303                             'a[2][1][0] = 10;' +304                             self._wrap_print('a[2][1][0]'))305        self._check_output(p, 'X', '10')306307    def test_array_init_loop(self):308        """Test an array being initialised in a for loop and printed309        in a for loop.310        """311        p = self._wrap_stmts('long[] a = new long[5];' +312                             'for (int i = 0; i < 5; i++) { a[i] = i;}' +313                             'for (int j = 4; j >= 0; j--) {' +314                             self._wrap_print('a[j]') + '}')315        nl = os.linesep316        self._check_output(p, 'X', '4' + nl + '3' + nl + '2' + nl + '1' + nl +317                           '0')318319    def test_matrix(self):320        """Test a simple matrix creation and access."""321        p = self._wrap_stmts('matrix m = |1,1|;' +322                     'm|0,0| = 10.5;' +323                     self._wrap_print('m|0,0|'))324        self._check_output(p, 'X', '10.5')325326    def test_matrix_mult(self):327        """Test a matrix multiplication."""328        p = self._wrap_stmts('matrix a1 = |2, 2|;' +329                             'a1|0,0| = 1;' +330                             'a1|0,1| = 2;' +331                             'a1|1,0| = 3;' +332                             'a1|1,0| = 4;' +333                             'matrix a2 = |2, 1|;' +334                             'a2|0,0| = 1;' +335                             'a2|1,0| = 2;' +336                             'matrix a3;' +337                             'a3 = a1 * a2;' +338                             'PrintStream ps = System.out;' +339                             'for (int n = 0; n<a1.rowLength; n++) {' +340                             'for (int o=0; o<a2.colLength;o++) {' +341                             'ps.println(a3|n,o|); }}')342        self._check_output(p, 'X', '5.0' + os.linesep + '4.0')343344    def test_matrix_mult_dimension_error(self):345        """Test an exception is thrown when the inner dimensions do not agree.346        """347        p = self._wrap_stmts('matrix a1 = |2, 2|;' +348                             'a1|0,0| = 1;' +349                             'a1|0,1| = 2;' +350                             'a1|1,0| = 3;' +351                             'a1|1,0| = 4;' +352                             'matrix a2 = |1, 1|;' +353                             'a2|0,0| = 1;' +354                             'matrix a3;' +355                             'a3 = a1 * a2;')356        self._check_output(p, 'X', 'Exception in thread "main" ' +357                           'java.lang.ArithmeticException: ' +358                           'Inner matrix dimensions must match for ' +359                           'multiplication!' + os.linesep +360                           '\tat X.main(X.j)', check_error = True)361362    def test_matrix_add(self):363        """Test a matrix addition."""364        p = self._wrap_stmts('matrix a1 = |2, 2|;' +365                             'a1|0,0| = 1;' +366                             'a1|0,1| = 2;' +367                             'a1|1,0| = 3;' +368                             'a1|1,1| = 4;' +369                             'matrix a2 = |2, 2|;' +370                             'a2|0,0| = 1;' +371                             'a2|0,1| = 2;' +372                             'a2|1,0| = 3;' +373                             'a2|1,1| = 4;' +374                             'matrix a3;' +375                             'a3 = a1 + a2;' +376                             'PrintStream ps = System.out;' +377                             'for (int n = 0; n<a1.rowLength; n++) {' +378                             'for (int o=0; o<a2.colLength;o++) {' +379                             'ps.println(a3|n,o|); }}')380        nl = os.linesep381        self._check_output(p, 'X', '2.0' + nl + '4.0' + nl + '6.0' +382                   nl + '8.0')383384    def test_matrix_add_dimension_error(self):385        """Test an exception is thrown when the dimensions are not the same386        for two matrices when subtracted.387        """388        p = self._wrap_stmts('matrix a1 = |2, 2|;' +389                             'a1|0,0| = 1;' +390                             'a1|0,1| = 2;' +391                             'a1|1,0| = 3;' +392                             'a1|1,0| = 4;' +393                             'matrix a2 = |1, 1|;' +394                             'a2|0,0| = 1;' +395                             'matrix a3;' +396                             'a3 = a1 - a2;')397        self._check_output(p, 'X', 'Exception in thread "main" ' +398                           'java.lang.ArithmeticException: ' +399                           'Matrix dimensions must be equal for ' +400                           'addition/subtraction!' + os.linesep +401                           '\tat X.main(X.j)', check_error = True)402403    def test_command_line_args(self):404        """Test that command line arguments are correctly read."""405        p = ('class X { static void main(String[] args) {' +406             self._wrap_print('args[0]') + '}}')407        self._check_output(p, 'X', 'arg', args = ['arg'])408409    def _wrap_stmts(self, stmts):410        """Helper method used so lines of code can be tested411        without having to create a class and method for it to go in.412        """413        return ("""414                class X {415                    static void main(String[] args) {416                        """ +417                        stmts +418                        """419                    }420               }421               """)422423    def _wrap_print(self, stmt):424        return ("""425                PrintStream ps = System.out;426                ps.println(""" + stmt + """);427                """)428429    def _check_output(self, program, class_name, exptd_result, args = [],430                      check_error = False):431        """Checks the program was compiled correctly.432        Given a program to run the compiler on, this method checks the result433        printed when the JVM is run with the code generator's output.434        """435        output_dir = os.path.join(os.path.dirname(__file__), 'bin_test_files')436        # Remove any old asm and binary files437        self._cleanup(output_dir)438        # Run the compiler with the program439        self._code_gen.compile_(program, output_dir)440        # Run the JVM on the compiled file441        cmd = ['java', '-cp', output_dir, class_name] + args442        process = subprocess.Popen(cmd, stdout = subprocess.PIPE,443                                   stderr = subprocess.PIPE)444        output = ''445        if not check_error:446            output = process.communicate()[0]447        else:448            output = process.communicate()[1]449        output = output.rstrip(os.linesep)450451        #Check the printed results match the expected result452        self.assertEqual(output, exptd_result)453454    def _check_output_file(self, file_name, exptd_result):455        """Helper method to allow the code generator to be run on a456        particular file, and the output checked457        """458        path = os.path.join(self._file_dir, file_name)459        # Remove the .jml extension460        class_name = file_name[:-4]461        return self._check_output(path, class_name, exptd_result)462463    def _cleanup(self, dir_):464        """Removes all files in the directory."""465        for file_ in os.listdir(dir_):466            file_path = os.path.join(dir_, file_)467            try:468                os.remove(file_path)469            except OSError:470                # It was a Folder
...cros_config_host_unittest.py
Source:cros_config_host_unittest.py  
...39    if model:40      call_args.extend(['--model', model])41    call_args.extend(args)42    return call_args, kwargs43  def _check_output(self, *args, **kwargs):44    call_args, kwargs = self._call_args(*args, **kwargs)45    return subprocess.run(46        call_args, encoding='utf-8', check=True,47        stdout=subprocess.PIPE, **kwargs).stdout48  def testListModels(self):49    output = self._check_output('list-models')50    self.CheckManyLinesWithoutSpaces(output, lines=2)51  def testListModelsWithFilter(self):52    output = self._check_output('list-models', model='another')53    self.assertEqual('another\n', output)54  def testListModelsWithEnvFilter(self):55    os.environ['CROS_CONFIG_MODEL'] = 'another'56    output = self._check_output('list-models')57    del os.environ['CROS_CONFIG_MODEL']58    self.assertEqual('another\n', output)59  def testGetPropSingle(self):60    output = self._check_output('get', '/', 'wallpaper', model='another')61    self.assertEqual(output, 'default' + os.linesep)62  def testGetPropSingleWrongModel(self):63    output = self._check_output(64        'get', '/', 'wallpaper', model='dne', stderr=subprocess.PIPE)65    self.assertEqual(output, '')66  def testGetPropSingleWrongPath(self):67    with self.assertRaises(subprocess.CalledProcessError):68      self._check_output('get', '/dne', 'wallpaper', model='another',69                         stderr=subprocess.DEVNULL)70  def testGetPropSingleWrongProp(self):71    with self.assertRaises(subprocess.CalledProcessError):72      self._check_output(73          'get', '/', 'dne', model='another', stderr=subprocess.DEVNULL)74  def testGetFirmwareUris(self):75    output = self._check_output('get-firmware-uris')76    self.CheckManyLines(output)77  def testGetMosysPlatform(self):78    output = self._check_output('get-mosys-platform')79    self.assertEqual(output, 'Some\n')80  def testGetFingerprintFirmwareROVersionFound(self):81    output = self._check_output('get-fpmcu-firmware-ro-version', 'bloonchipper')82    self.assertEqual(output, 'VERSION1\n')83  def testGetFingerprintFirmwareROVersionNotSpecified(self):84    # If the ro-version is not specified, nothing is returned and the exit code85    # should be 0.86    output = self._check_output('get-fpmcu-firmware-ro-version', 'some_fpmcu')87    self.assertEqual(output, '')88  def testGetTouchFirmwareFiles(self):89    output = self._check_output('get-touch-firmware-files')90    self.CheckManyLines(output, 10)91  def testGetAudioFiles(self):92    output = self._check_output('get-audio-files')93    self.CheckManyLines(output, 10)94  def testGetFirmwareBuildTargets(self):95    output = self._check_output('get-firmware-build-targets', 'coreboot')96    self.CheckManyLines(output, 1)97  def testGetWallpaperFiles(self):98    output = self._check_output('get-wallpaper-files')99    self.CheckManyLines(output, 1)100  def testGetIntelWifiSarFiles(self):101    output = self._check_output('get-intel-wifi-sar-files')102    self.CheckManyLines(output, 1)103if __name__ == '__main__':...git.py
Source:git.py  
...8    path: Path9    def list_commits(self, from_ref: str) -> Tuple[str, ...]:10        def iter_commtis(commit_ids: List[str]) -> Iterator[str]:11            for commit_id in commit_ids:12                yield self._check_output(13                    ["git", "log", "-1", "--format=%B", commit_id]14                )15        commit_ids = self._check_output(16            ["git", "log", "--format=%H", f"{from_ref}..HEAD"]17        ).splitlines()18        return tuple(iter_commtis(commit_ids))19    def retrieve_last_commit(self) -> str:20        return self._check_output(["git", "log", "-1", "--format=%B"])21    def retrieve_last_tag(self) -> str:22        return self._check_output(["git", "describe", "--abbrev=0", "--tags"])23    def retrieve_last_tag_or_none(self) -> Optional[str]:24        with suppress(subprocess.CalledProcessError, ValueError):25            return self.retrieve_last_tag()26        return None27    def retrieve_tag_body(self, tag: str) -> str:28        return self._check_output(29            ["git", "tag", "-l", "--format=%(body)", tag]30        )31    def retrieve_tag_subject(self, tag: str) -> str:32        return self._check_output(33            ["git", "tag", "-l", "--format=%(subject)", tag]34        )35    def _check_output(self, args: List[str]) -> str:36        maybe_output = subprocess.check_output(args, cwd=self.path)37        if maybe_output is not None:38            return maybe_output.strip().decode("utf-8")...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!!
