Best Python code snippet using avocado_python
test_filter_test.py
Source:test_filter_test.py  
1#!/usr/bin/env vpython2# Copyright 2018 The Chromium Authors. All rights reserved.3# Use of this source code is governed by a BSD-style license that can be4# found in the LICENSE file.5import argparse6import sys7import tempfile8import unittest9from pylib.utils import test_filter10class ParseFilterFileTest(unittest.TestCase):11  def testParseFilterFile_commentsAndBlankLines(self):12    input_lines = [13      'positive1',14      '# comment',15      'positive2  # Another comment',16      ''17      'positive3'18    ]19    actual = test_filter.ParseFilterFile(input_lines)20    expected = ['positive1', 'positive2', 'positive3'], []21    self.assertEquals(expected, actual)22  def testParseFilterFile_onlyPositive(self):23    input_lines = [24      'positive1',25      'positive2'26    ]27    actual = test_filter.ParseFilterFile(input_lines)28    expected = ['positive1', 'positive2'], []29    self.assertEquals(expected, actual)30  def testParseFilterFile_onlyNegative(self):31    input_lines = [32      '-negative1',33      '-negative2'34    ]35    actual = test_filter.ParseFilterFile(input_lines)36    expected = [], ['negative1', 'negative2']37    self.assertEquals(expected, actual)38  def testParseFilterFile_positiveAndNegative(self):39    input_lines = [40      'positive1',41      'positive2',42      '-negative1',43      '-negative2'44    ]45    actual = test_filter.ParseFilterFile(input_lines)46    expected = ['positive1', 'positive2'], ['negative1', 'negative2']47    self.assertEquals(expected, actual)48class InitializeFilterFromArgsTest(unittest.TestCase):49  def testInitializeBasicFilter(self):50    parser = argparse.ArgumentParser()51    test_filter.AddFilterOptions(parser)52    args = parser.parse_args([53        '--test-filter',54        'FooTest.testFoo:BarTest.testBar'])55    expected = 'FooTest.testFoo:BarTest.testBar'56    actual = test_filter.InitializeFilterFromArgs(args)57    self.assertEquals(actual, expected)58  def testInitializeJavaStyleFilter(self):59    parser = argparse.ArgumentParser()60    test_filter.AddFilterOptions(parser)61    args = parser.parse_args([62        '--test-filter',63        'FooTest#testFoo:BarTest#testBar'])64    expected = 'FooTest.testFoo:BarTest.testBar'65    actual = test_filter.InitializeFilterFromArgs(args)66    self.assertEquals(actual, expected)67  def testInitializeBasicIsolatedScript(self):68    parser = argparse.ArgumentParser()69    test_filter.AddFilterOptions(parser)70    args = parser.parse_args([71        '--isolated-script-test-filter',72        'FooTest.testFoo::BarTest.testBar'])73    expected = 'FooTest.testFoo:BarTest.testBar'74    actual = test_filter.InitializeFilterFromArgs(args)75    self.assertEquals(actual, expected)76  def testFilterArgWithPositiveFilterInFilterFile(self):77    parser = argparse.ArgumentParser()78    test_filter.AddFilterOptions(parser)79    with tempfile.NamedTemporaryFile() as tmp_file:80      tmp_file.write('positive1\npositive2\n-negative2\n-negative3\n')81      tmp_file.seek(0)82      args = parser.parse_args([83          '--test-filter=-negative1',84          '--test-launcher-filter-file',85          tmp_file.name])86      expected = 'positive1:positive2-negative1:negative2:negative3'87      actual = test_filter.InitializeFilterFromArgs(args)88      self.assertEquals(actual, expected)89  def testFilterFileWithPositiveFilterInFilterArg(self):90    parser = argparse.ArgumentParser()91    test_filter.AddFilterOptions(parser)92    with tempfile.NamedTemporaryFile() as tmp_file:93      tmp_file.write('-negative2\n-negative3\n')94      tmp_file.seek(0)95      args = parser.parse_args([96          '--test-filter',97          'positive1:positive2-negative1',98          '--test-launcher-filter-file',99          tmp_file.name])100      expected = 'positive1:positive2-negative1:negative2:negative3'101      actual = test_filter.InitializeFilterFromArgs(args)102      self.assertEquals(actual, expected)103  def testPositiveFilterInBothFileAndArg(self):104    parser = argparse.ArgumentParser()105    test_filter.AddFilterOptions(parser)106    with tempfile.NamedTemporaryFile() as tmp_file:107      tmp_file.write('positive1\n')108      tmp_file.seek(0)109      args = parser.parse_args([110          '--test-filter',111          'positive2',112          '--test-launcher-filter-file',113          tmp_file.name])114      with self.assertRaises(test_filter.ConflictingPositiveFiltersException):115        test_filter.InitializeFilterFromArgs(args)116  def testFilterArgWithFilterFileAllNegative(self):117    parser = argparse.ArgumentParser()118    test_filter.AddFilterOptions(parser)119    with tempfile.NamedTemporaryFile() as tmp_file:120      tmp_file.write('-negative3\n-negative4\n')121      tmp_file.seek(0)122      args = parser.parse_args([123          '--test-filter=-negative1:negative2',124          '--test-launcher-filter-file',125          tmp_file.name])126      expected = '-negative1:negative2:negative3:negative4'127      actual = test_filter.InitializeFilterFromArgs(args)128      self.assertEquals(actual, expected)129class AppendPatternsToFilter(unittest.TestCase):130  def testAllEmpty(self):131    expected = ''132    actual = test_filter.AppendPatternsToFilter('', [], [])133    self.assertEquals(actual, expected)134  def testAppendOnlyPositiveToEmptyFilter(self):135    expected = 'positive'136    actual = test_filter.AppendPatternsToFilter('', ['positive'])137    self.assertEquals(actual, expected)138  def testAppendOnlyNegativeToEmptyFilter(self):139    expected = '-negative'140    actual = test_filter.AppendPatternsToFilter('',141                                                negative_patterns=['negative'])142    self.assertEquals(actual, expected)143  def testAppendToEmptyFilter(self):144    expected = 'positive-negative'145    actual = test_filter.AppendPatternsToFilter('', ['positive'], ['negative'])146    self.assertEquals(actual, expected)147  def testAppendToPositiveOnlyFilter(self):148    expected = 'positive1:positive2-negative'149    actual = test_filter.AppendPatternsToFilter('positive1', ['positive2'],150                                                ['negative'])151    self.assertEquals(actual, expected)152  def testAppendToNegativeOnlyFilter(self):153    expected = 'positive-negative1:negative2'154    actual = test_filter.AppendPatternsToFilter('-negative1', ['positive'],155                                                ['negative2'])156    self.assertEquals(actual, expected)157  def testAppendPositiveToFilter(self):158    expected = 'positive1:positive2-negative1'159    actual = test_filter.AppendPatternsToFilter('positive1-negative1',160                                                ['positive2'])161    self.assertEquals(actual, expected)162  def testAppendNegativeToFilter(self):163    expected = 'positive1-negative1:negative2'164    actual = test_filter.AppendPatternsToFilter('positive1-negative1',165                                                negative_patterns=['negative2'])166    self.assertEquals(actual, expected)167  def testAppendBothToFilter(self):168    expected = 'positive1:positive2-negative1:negative2'169    actual = test_filter.AppendPatternsToFilter('positive1-negative1',170                                                positive_patterns=['positive2'],171                                                negative_patterns=['negative2'])172    self.assertEquals(actual, expected)173  def testAppendMultipleToFilter(self):174    expected = 'positive1:positive2:positive3-negative1:negative2:negative3'175    actual = test_filter.AppendPatternsToFilter('positive1-negative1',176                                                ['positive2', 'positive3'],177                                                ['negative2', 'negative3'])178    self.assertEquals(actual, expected)179  def testRepeatedAppendToFilter(self):180    expected = 'positive1:positive2:positive3-negative1:negative2:negative3'181    filter_string = test_filter.AppendPatternsToFilter('positive1-negative1',182                                                       ['positive2'],183                                                       ['negative2'])184    actual = test_filter.AppendPatternsToFilter(filter_string, ['positive3'],185                                                ['negative3'])186    self.assertEquals(actual, expected)187  def testAppendHashSeparatedPatternsToFilter(self):188    expected = 'positive.test1:positive.test2-negative.test1:negative.test2'189    actual = test_filter.AppendPatternsToFilter('positive#test1-negative#test1',190                                                       ['positive#test2'],191                                                       ['negative#test2'])192    self.assertEquals(actual, expected)193class HasPositivePatterns(unittest.TestCase):194  def testEmpty(self):195    expected = False196    actual = test_filter.HasPositivePatterns('')197    self.assertEquals(actual, expected)198  def testHasOnlyPositive(self):199    expected = True200    actual = test_filter.HasPositivePatterns('positive')201    self.assertEquals(actual, expected)202  def testHasOnlyNegative(self):203    expected = False204    actual = test_filter.HasPositivePatterns('-negative')205    self.assertEquals(actual, expected)206  def testHasBoth(self):207    expected = True208    actual = test_filter.HasPositivePatterns('positive-negative')209    self.assertEquals(actual, expected)210if __name__ == '__main__':...test_match_filters.py
Source:test_match_filters.py  
1from panther_config import testing2from panther_utils import match_filters3class TestMatchFilters(testing.PantherPythonFilterTestCase):4    def test_deep_exists(self) -> None:5        test_filter = match_filters.deep_exists("a.b")6        self.assertFilterIsValid(test_filter)7        self.assertFilterMatches(test_filter, {"a": {"b": "targeted-value"}})8        self.assertFilterNotMatches(test_filter, {"a": {"c": "other-value"}})9    def test_deep_not_exists(self) -> None:10        test_filter = match_filters.deep_not_exists("a.b")11        self.assertFilterIsValid(test_filter)12        self.assertFilterNotMatches(test_filter, {"a": {"b": "targeted-value"}})13        self.assertFilterMatches(test_filter, {"a": {"c": "other-value"}})14    def test_deep_equal(self) -> None:15        test_filter = match_filters.deep_equal("a.b", "targeted-value")16        self.assertFilterIsValid(test_filter)17        self.assertFilterMatches(test_filter, {"a": {"b": "targeted-value"}})18        self.assertFilterNotMatches(test_filter, {"a": {"b": "other-value"}})19    def test_deep_not_equal(self) -> None:20        test_filter = match_filters.deep_not_equal("a.b", "targeted-value")21        self.assertFilterIsValid(test_filter)22        self.assertFilterNotMatches(test_filter, {"a": {"b": "targeted-value"}})23        self.assertFilterMatches(test_filter, {"a": {"b": "other-value"}})24    def test_deep_in(self) -> None:25        test_filter = match_filters.deep_in("a.b", ["targeted-value"])26        self.assertFilterIsValid(test_filter)27        self.assertFilterMatches(test_filter, {"a": {"b": "targeted-value"}})28        self.assertFilterNotMatches(test_filter, {"a": {"b": "other-value"}})29    def test_deep_not_in(self) -> None:30        test_filter = match_filters.deep_not_in("a.b", ["targeted-value"])31        self.assertFilterIsValid(test_filter)32        self.assertFilterNotMatches(test_filter, {"a": {"b": "targeted-value"}})33        self.assertFilterMatches(test_filter, {"a": {"b": "other-value"}})34    def test_deep_equal_pattern(self) -> None:35        test_filter = match_filters.deep_equal_pattern("a.b", r"target")36        self.assertFilterIsValid(test_filter)37        self.assertFilterMatches(test_filter, {"a": {"b": "targeted-value"}})38        self.assertFilterNotMatches(test_filter, {"a": {"b": "other-value"}})39    def test_deep_not_equal_pattern(self) -> None:40        test_filter = match_filters.deep_not_equal_pattern("a.b", r"target")41        self.assertFilterIsValid(test_filter)42        self.assertFilterNotMatches(test_filter, {"a": {"b": "targeted-value"}})43        self.assertFilterMatches(test_filter, {"a": {"b": "other-value"}})44    def test_deep_less_than(self) -> None:45        test_filter = match_filters.deep_less_than("a.b", 45)46        self.assertFilterIsValid(test_filter)47        self.assertFilterMatches(test_filter, {"a": {"b": 44}})48        self.assertFilterNotMatches(test_filter, {"a": {"b": 45}})49        self.assertFilterNotMatches(test_filter, {"a": {"b": 46}})50    def test_deep_less_than_or_equal(self) -> None:51        test_filter = match_filters.deep_less_than_or_equal("a.b", 45)52        self.assertFilterIsValid(test_filter)53        self.assertFilterMatches(test_filter, {"a": {"b": 44}})54        self.assertFilterMatches(test_filter, {"a": {"b": 45}})55        self.assertFilterNotMatches(test_filter, {"a": {"b": 46}})56    def test_deep_greater_than(self) -> None:57        test_filter = match_filters.deep_greater_than("a.b", 45)58        self.assertFilterIsValid(test_filter)59        self.assertFilterMatches(test_filter, {"a": {"b": 46}})60        self.assertFilterNotMatches(test_filter, {"a": {"b": 45}})61        self.assertFilterNotMatches(test_filter, {"a": {"b": 44}})62    def test_deep_greater_than_or_equal(self) -> None:63        test_filter = match_filters.deep_greater_than_or_equal("a.b", 45)64        self.assertFilterIsValid(test_filter)65        self.assertFilterMatches(test_filter, {"a": {"b": 46}})66        self.assertFilterMatches(test_filter, {"a": {"b": 45}})67        self.assertFilterNotMatches(test_filter, {"a": {"b": 44}})68    def test_deep_between(self) -> None:69        test_filter = match_filters.deep_between("a.b", val_min=45, val_max=50)70        self.assertFilterIsValid(test_filter)71        self.assertFilterNotMatches(test_filter, {"a": {"b": 44}})72        self.assertFilterMatches(test_filter, {"a": {"b": 45}})73        self.assertFilterMatches(test_filter, {"a": {"b": 46}})74        self.assertFilterMatches(test_filter, {"a": {"b": 49}})75        self.assertFilterMatches(test_filter, {"a": {"b": 50}})76        self.assertFilterNotMatches(test_filter, {"a": {"b": 51}})77        self.assertRaises(RuntimeError, lambda: match_filters.deep_between("x", 45, 45))78        self.assertRaises(RuntimeError, lambda: match_filters.deep_between("x", 45, 44))79    def test_deep_between_exclusive(self) -> None:80        test_filter = match_filters.deep_between_exclusive(81            "a.b", val_min=45, val_max=5082        )83        self.assertFilterIsValid(test_filter)84        self.assertFilterNotMatches(test_filter, {"a": {"b": 44}})85        self.assertFilterNotMatches(test_filter, {"a": {"b": 45}})86        self.assertFilterMatches(test_filter, {"a": {"b": 46}})87        self.assertFilterMatches(test_filter, {"a": {"b": 49}})88        self.assertFilterNotMatches(test_filter, {"a": {"b": 50}})89        self.assertFilterNotMatches(test_filter, {"a": {"b": 51}})90        self.assertRaises(91            RuntimeError, lambda: match_filters.deep_between_exclusive("x", 45, 45)92        )93        self.assertRaises(94            RuntimeError, lambda: match_filters.deep_between_exclusive("x", 45, 44)...test_filter.py
Source:test_filter.py  
1# Copyright 2018 The Chromium Authors. All rights reserved.2# Use of this source code is governed by a BSD-style license that can be3# found in the LICENSE file.4import os5import re6_CMDLINE_NAME_SEGMENT_RE = re.compile(7    r' with(?:out)? \{[^\}]*\}')8class ConflictingPositiveFiltersException(Exception):9  """Raised when both filter file and filter argument have positive filters."""10def ParseFilterFile(input_lines):11  """Converts test filter file contents to positive and negative pattern lists.12  See //testing/buildbot/filters/README.md for description of the13  syntax that |input_lines| are expected to follow.14  See15  https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md#running-a-subset-of-the-tests16  for description of the syntax that --gtest_filter argument should follow.17  Args:18    input_lines: An iterable (e.g. a list or a file) containing input lines.19  Returns:20    tuple containing the lists of positive patterns and negative patterns21  """22  # Strip comments and whitespace from each line and filter non-empty lines.23  stripped_lines = (l.split('#', 1)[0].strip() for l in input_lines)24  filter_lines = [l for l in stripped_lines if l]25  # Split the tests into positive and negative patterns (gtest treats26  # every pattern after the first '-' sign as an exclusion).27  positive_patterns = [l for l in filter_lines if l[0] != '-']28  negative_patterns = [l[1:] for l in filter_lines if l[0] == '-']29  return positive_patterns, negative_patterns30def AddFilterOptions(parser):31  """Adds filter command-line options to the provided parser.32  Args:33    parser: an argparse.ArgumentParser instance.34  """35  parser.add_argument(36      # Deprecated argument.37      '--gtest-filter-file',38      # New argument.39      '--test-launcher-filter-file',40      dest='test_filter_file',41      help='Path to file that contains googletest-style filter strings. '42      'See also //testing/buildbot/filters/README.md.')43  filter_group = parser.add_mutually_exclusive_group()44  filter_group.add_argument(45      '-f', '--test-filter', '--gtest_filter', '--gtest-filter',46      dest='test_filter',47      help='googletest-style filter string.',48      default=os.environ.get('GTEST_FILTER'))49  filter_group.add_argument(50      '--isolated-script-test-filter',51      help='isolated script filter string. '52           'Like gtest filter strings, but with :: separators instead of :')53def AppendPatternsToFilter(test_filter, positive_patterns=None,54                           negative_patterns=None):55  """Returns a test-filter string with additional patterns.56  Args:57    test_filter: test filter string58    positive_patterns: list of positive patterns to add to string59    negative_patterns: list of negative patterns to add to string60  """61  positives = []62  negatives = []63  positive = ''64  negative = ''65  split_filter = test_filter.split('-', 1)66  if len(split_filter) == 1:67    positive = split_filter[0]68  else:69    positive, negative = split_filter70  positives += [f for f in positive.split(':') if f]71  negatives += [f for f in negative.split(':') if f]72  positives += positive_patterns if positive_patterns else []73  negatives += negative_patterns if negative_patterns else []74  final_filter = ':'.join([p.replace('#', '.') for p in positives])75  if negatives:76    final_filter += '-' + ':'.join([n.replace('#', '.') for n in negatives])77  return final_filter78def HasPositivePatterns(test_filter):79  """Returns True if test_filter contains a positive pattern, else False80  Args:81    test_filter: test-filter style string82  """83  return bool(len(test_filter) > 0 and test_filter[0] != '-')84def InitializeFilterFromArgs(args):85  """Returns a filter string from the command-line option values.86  Args:87    args: an argparse.Namespace instance resulting from a using parser88      to which the filter options above were added.89  Raises:90    ConflictingPositiveFiltersException if both filter file and command line91    specify positive filters.92  """93  test_filter = ''94  if args.isolated_script_test_filter:95    args.test_filter = args.isolated_script_test_filter.replace('::', ':')96  if args.test_filter:97    test_filter = _CMDLINE_NAME_SEGMENT_RE.sub(98        '', args.test_filter.replace('#', '.'))99  if args.test_filter_file:100    for test_filter_file in args.test_filter_file.split(';'):101      with open(test_filter_file, 'r') as f:102        positive_file_patterns, negative_file_patterns = ParseFilterFile(f)103        if positive_file_patterns and HasPositivePatterns(test_filter):104          raise ConflictingPositiveFiltersException(105              'Cannot specify positive pattern in both filter file and ' +106              'filter command line argument')107        test_filter = AppendPatternsToFilter(108            test_filter,109            positive_patterns=positive_file_patterns,110            negative_patterns=negative_file_patterns)...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!!
