def test_interface_switchport_port_security(self): with fake_filesystem_unittest.Patcher() as patcher: patcher.fs.create_file( '/mock', contents=test_interface_switchport_port_security["input"]) self.assertEqual(convert_to_yaml(CiscoConfParse('/mock')), test_interface_switchport_port_security["output"])
def setup(self): """Setup before each method""" config_data = basic_streamalert_config() self.fs_patcher = fake_filesystem_unittest.Patcher() self.fs_patcher.setUp() self.fs_patcher.fs.create_file('./conf/global.json', contents=json.dumps( config_data['global'])) self.fs_patcher.fs.create_file('./conf/threat_intel.json', contents=json.dumps( config_data['threat_intel'])) self.fs_patcher.fs.create_file('./conf/normalized_types.json', contents=json.dumps( config_data['normalized_types'])) self.fs_patcher.fs.create_file('./conf/lambda.json', contents=json.dumps( config_data['lambda'])) self.fs_patcher.fs.create_file('./conf/clusters/prod.json', contents=json.dumps( config_data['clusters']['prod'])) # Create the config instance after creating the fake filesystem so that # CLIConfig uses our mocked config files instead of the real ones. self.config = CLIConfig('./conf/')
def system_mock(): """Mock system-level functions. Functions from fcntl, pickle, select, socket, subprocess are mocked to avoid tests touching the system state. """ calls = { 'fcntl': ['fcntl'], 'select': ['select'], 'socket': ['socket'], 'subprocess': ['Popen', 'call'] } @contextmanager def make_patch_group(name): with nest_mgrs([ patch('{}.{}'.format(name, item)) for item in calls[name] ]) as mgrs: yield dict(zip(calls[name], reversed(mgrs))) with nest_mgrs([make_patch_group(name) for name in calls]) as patchlist: with ffs.Patcher() as ff_patcher: # os.environ needs special care with patch.dict('os.environ', {'NCS_DIR': 'tmp_ncs_dir'}): patches = dict(zip(calls.keys(), reversed(patchlist))) yield SystemMock(ff_patcher, patches)
def _parse_and_test(self, program: Text, trace_all: bool = False, compare_jit: bool = True) -> None: with ffu.Patcher() as patcher: filename = '/fake/test_module.x' patcher.fs.CreateFile(filename, contents=program) self.assertFalse( parse_and_interpret.parse_and_test(program, 'test_module', trace_all=trace_all, filename=filename, compare_jit=compare_jit))
def test_delete_upload_file(self, mock_open): resource_id = str(uuid.uuid4()) path = '/doesnt_exist/resources/{}/{}/{}'.format( resource_id[0:3], resource_id[3:6], resource_id[6:]) patcher = fake_filesystem_unittest.Patcher() patcher.setUp() patcher.fs.CreateFile(path) assert os.path.exists(path) delete_local_uploaded_file(resource_id) assert not os.path.exists(path) patcher.tearDown()
def test_delete_passes_if_os_exeception(self, mock_open): resource_id = str(uuid.uuid4()) path = '/doesnt_exist/resources/{}/{}/{}'.format( resource_id[0:3], resource_id[3:6], resource_id[6:]) patcher = fake_filesystem_unittest.Patcher() patcher.setUp() patcher.fs.CreateFile(path) assert os.path.exists(path) with mock.patch('ckanext.validation.utils.os.remove', side_effect=OSError): delete_local_uploaded_file(resource_id) patcher.tearDown()
def test_delete_file_not_deleted_if_resources_second(self, mock_open): resource_id = str(uuid.uuid4()) path = '/doesnt_exist/resources/data/{}'.format(resource_id) patcher = fake_filesystem_unittest.Patcher() patcher.setUp() patcher.fs.CreateFile(path) assert os.path.exists(path) with mock.patch('ckanext.validation.utils.get_local_upload_path', return_value=path): delete_local_uploaded_file(resource_id) assert not os.path.exists(path) assert os.path.exists('/doesnt_exist/resources') patcher.tearDown()
def test_assertion_failure_prints_positionally(self): program = """ test foo { assert_eq(false, true) } """ mock_stderr = io.StringIO() filename = 'test_filename.x' with ffu.Patcher() as patcher: patcher.fs.CreateFile(filename, contents=program) with mock.patch('sys.stderr', mock_stderr): parse_and_interpret.parse_and_test( program, 'test_program', filename=filename, raise_on_error=False) self.assertIn('* 0003: assert_eq(false, true)', mock_stderr.getvalue()) self.assertIn( ' ~~~~~~~~~~~~~~~^-----------^ The program being interpreted failed!', mock_stderr.getvalue())
def setUp(self): self.runner = CliRunner() self.config_patcher = ConfigPatcher().any().start() self.fakefs_patcher = fake_filesystem_unittest.Patcher() self.fakefs_patcher.setUp()
def scoped_fakefs(path: Text, contents: Text): with ffu.Patcher() as patcher: create_file = getattr(patcher.fs, 'create_file', None) or getattr( patcher.fs, 'CreateFile') create_file(path, contents=contents) yield
def testCreate_Retries_DevToolsActivePort(self): """Tests that the retries that Create() does delete the devtools file. If the retries do not delete this file, then we can have a race condition between a second run of Chrome creating overwriting the last run's file and Telemetry finding it. """ self.assertGreater( desktop_browser_finder._BROWSER_STARTUP_TRIES, 1, "This test should be deleted if we turn off retries.") fs_patcher = fake_filesystem_unittest.Patcher() fs_patcher.setUp() try: possible_browser = desktop_browser_finder.PossibleDesktopBrowser( 'exact', None, None, None, None, None) fake_options = mock.MagicMock() # It is necessary to put the "run" variable inside self. # Otherwise I get an UnboundLocalError inside the function when I try # to increment it. # This can be replaced by using "nonlocal" once we move to python3. self.run = 0 def FakeBrowserInit_FailUntilLastTry(*args, **kwargs): del args del kwargs self.assertTrue(possible_browser._profile_directory) self.assertTrue( desktop_browser_backend.DEVTOOLS_ACTIVE_PORT_FILE) devtools_file_path = os.path.join( possible_browser._profile_directory, desktop_browser_backend.DEVTOOLS_ACTIVE_PORT_FILE) self.assertFalse( os.path.exists(devtools_file_path), "SetUpEnvironment should delete the devtools file") fs_patcher.fs.CreateFile(devtools_file_path) self.assertTrue( os.path.exists(devtools_file_path), "Smoke check to make sure that CreateFile worked") self.run += 1 if self.run < desktop_browser_finder._BROWSER_STARTUP_TRIES: raise Exception startup_args = ( 'telemetry.internal.backends.chrome.desktop_browser_finder.' 'PossibleDesktopBrowser.GetBrowserStartupArgs') browser_backend = ( 'telemetry.internal.backends.chrome.desktop_browser_backend.' 'DesktopBrowserBackend') with mock.patch(startup_args), \ mock.patch(browser_backend): fake_options.dont_override_profile = False fake_options.profile_dir = None possible_browser.SetUpEnvironment(fake_options) with mock.patch('telemetry.internal.browser.browser.Browser', side_effect=FakeBrowserInit_FailUntilLastTry): possible_browser.Create() self.assertEqual(self.run, desktop_browser_finder._BROWSER_STARTUP_TRIES) finally: fs_patcher.tearDown()
def test_interface_name_identification(self): with fake_filesystem_unittest.Patcher() as patcher: patcher.fs.create_file( '/mock', contents=test_interface_name_identification["input"]) self.assertEqual(convert_to_yaml(CiscoConfParse('/mock')), test_interface_name_identification["output"])
def test_interface_power_inline_police(self): with fake_filesystem_unittest.Patcher() as patcher: patcher.fs.create_file( '/mock', contents=test_interface_power_inline_police["input"]) self.assertEqual(convert_to_yaml(CiscoConfParse('/mock')), test_interface_power_inline_police["output"])
from pathlib import Path from pyfakefs import fake_filesystem_unittest # Set the module constant within Patcher to use the fake filesystem # https://jmcgeheeiv.github.io/pyfakefs/master/usage.html#modules-to-reload with fake_filesystem_unittest.Patcher() as _: BASE_PATH = Path("res") # Valid markdown content with YAML metadata MARKDOWN_WITH_METADATA = """ --- title: TestTitle description: TestDescription relevant_links: Python Discord: https://pythondiscord.com Discord: https://discord.com toc: 0 --- # This is a header. """ MARKDOWN_WITHOUT_METADATA = """#This is a header.""" # Valid YAML in a _info.yml file CATEGORY_INFO = """ title: Category Name description: Description """ # The HTML generated from the above markdown data
def scoped_fakefs(path: str, contents: str): with ffu.Patcher() as patcher: yield create_file(patcher.fs, path, contents=contents)
def create_mock_files(self, mock_files): with fake_filesystem_unittest.Patcher() as patcher: [patcher.fs.create_file(file) for file in mock_files] yield [pathlib.Path(os.path.commonprefix(mock_files or []))]