Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
import unittest
from mock import MagicMock, patch, ANY, call
from pyfakefs import fake_filesystem_unittest
from io import open
from __builtin__ import True as builtin_True, False as builtin_False
from xosconfig import Config
def mock_make_backup(fn):
with open(fn, "w") as backup_f:
backup_f.write("stuff")
class TestBackupProcessor(fake_filesystem_unittest.TestCase):
def setUp(self):
config = os.path.abspath(
os.path.dirname(os.path.realpath(__file__)) + "/test_config.yaml"
)
Config.clear() # in case left unclean by a previous test case
Config.init(config)
import backupprocessor
self.backupprocessor = backupprocessor
self.setUpPyfakefs()
self.processor = backupprocessor.BackupProcessor()
self.mock_backuphandler = MagicMock(backup=MagicMock(), restore=MagicMock())
def tearDown(self):
self.app = MDTestSite(
"MDWeb",
app_options={}
)
self.app.start()
def test_basic_asset_request(self):
"""Request to "/contentassets/logo.png" should return 200."""
with self.app.test_client() as client:
result = client.get('/contentassets/logo.png')
self.assertEqual(result.status_code, 200)
class TestMissingAssets(fake_filesystem_unittest.TestCase):
"""Index object tests."""
def setUp(self):
"""Create fake filesystem and flask app."""
self.setUpPyfakefs()
self.fake_os = fake_filesystem.FakeOsModule(self.fs)
self.fs.CreateFile('/my/content/index.md')
self.fs.CreateFile('/my/content/about/index.md')
self.fs.CreateFile('/my/content/contact/index.md')
self.fs.CreateFile('/my/content/assets/logo.png')
self.fs.CreateFile('/my/theme/assets/robots.txt')
self.fs.CreateFile('/my/theme/assets/css/style.css')
self.fs.CreateFile('/my/theme/assets/js/site.js')
self.fs.CreateFile('/my/theme/templates/layout.html')
super(TestLaunchServicesTestCaseSetUpAndTearDown, self).setUp()
super(TestLaunchServicesTestCaseSetUpAndTearDown, self).tearDown()
self.assertFalse(os.path.exists(self.tmp))
class TestLaunchServicesTestCaseMethods(LaunchServicesTestCase):
def test_seed_plist_copies_plist_into_tmp(self):
self.assertTrue(os.path.exists(os.path.join(
THIS_FILE, 'assets', SIMPLE_BINARY_PLIST,
)))
tmp_path = self.seed_plist(SIMPLE_BINARY_PLIST)
self.assertTrue(os.path.exists(tmp_path))
class TestLSHandlerObject(TestCase):
def test_LSHandler_can_be_converted_to_dict(self):
sample_lshandler = LSHandlerFactory()
self.assertIsInstance(dict(sample_lshandler), dict)
def test_can_generate_LSHandler_for_uti(self):
sample_lshandler = LSHandlerFactory(uti_only=True)
sample_dict = dict(sample_lshandler)
self.assertIn(sample_lshandler.app_id, sample_dict.values())
self.assertIn(sample_lshandler.uti, sample_dict.values())
self.assertIn(
'LSHandlerRole' + sample_lshandler.role.capitalize(),
sample_dict.keys()
)
def test_can_generate_LSHandler_for_protocol(self):
# -*- coding: utf-8 -*-
"""Tests for the MDWeb Navigation parser."""
from pyfakefs import fake_filesystem_unittest, fake_filesystem
from unittest import skip
from mdweb.Navigation import Navigation, NavigationMetaInf
from mdweb.Exceptions import ContentException, ContentStructureException
class TestNavigation(fake_filesystem_unittest.TestCase):
"""Navigation object tests."""
def setUp(self):
"""Create fake filesystem."""
self.setUpPyfakefs()
self.fake_os = fake_filesystem.FakeOsModule(self.fs)
def test_empty_content_directory(self):
"""An empty content directory should create an empty nav structure."""
self.fs.CreateDirectory('/my/content')
self.assertRaises(ContentException, Navigation, '/my/content')
def test_single_page(self):
"""A single index page should generate a single-page nav structure."""
3) Log reader:
==============
3.1: Values are read properly
3.2: Key filtering is working properly
3.3: Date filtering is working properly
"""
import os
import unittest
from pyfakefs import fake_filesystem_unittest
from qiskit.ignis.logging import IgnisLogging, IgnisLogReader
class TestLogging(fake_filesystem_unittest.TestCase):
"""Test logging module"""
_config_file = ""
_default_log = "ignis.log"
def setUp(self):
"""
Basic setup - making the .qiskit dir and preserving any existing files
:return:
"""
self.setUpPyfakefs()
super().setUp()
qiskit_dir = os.path.join(os.path.expanduser('~'), ".qiskit")
self._config_file = os.path.join(qiskit_dir, "logging.yaml")
os.makedirs(qiskit_dir, exist_ok=True)
def tearDown(self):
def input_to_file(self, path_to_file, temporary=True):
content.write_file(path_to_file, self())
def add_input(self, inp):
self.inputs.append(inp)
def __call__(self, *args, **kwargs):
try:
inp = self.inputs[self._cursor]
self._cursor += 1
return inp
except IndexError:
raise self.UnexpectedInput('Unexpected user input in test.')
class TestFakeFs(fake_filesystem_unittest.TestCase):
def setUp(self):
self.rootpath = os.path.abspath(os.path.dirname(__file__))
self.homepath = os.path.expanduser('~')
self.setUpPyfakefs()
self.reset_fs()
def reset_fs(self):
"""Reset the fake filesystem"""
for dir_name in self.fs.listdir('/'):
if dir_name not in ['var', 'tmp']:
self.fs.remove_object(os.path.join('/', dir_name))
self.fs.create_dir(os.path.expanduser('~'))
self.fs.create_dir(self.rootpath)
os.chdir(self.rootpath)
def get_mock_lambda_context(func_name, milliseconds=100):
"""Helper function to create a fake context object using Mock"""
arn = 'arn:aws:lambda:us-east-1:123456789012:function:{}:development'
context = Mock(
invoked_function_arn=(arn.format(func_name)),
function_name=func_name,
function_version='production',
get_remaining_time_in_millis=Mock(return_value=milliseconds)
)
return context
class TestConfigLoading(fake_filesystem_unittest.TestCase):
"""Test config loading logic with a mocked filesystem."""
# pylint: disable=protected-access
def setUp(self):
self.setUpPyfakefs()
config_data = basic_streamalert_config()
# Add config files which should be loaded
self.fs.create_file('conf/clusters/prod.json', contents='{}')
self.fs.create_file('conf/clusters/dev.json', contents='{}')
self.fs.create_file('conf/global.json', contents='{}')
self.fs.create_file('conf/lambda.json', contents='{}')
self.fs.create_file('conf/logs.json', contents='{}')
self.fs.create_file('conf/outputs.json', contents='{}')
self.fs.create_file('conf/sources.json', contents='{}')
import time
from pyfakefs import fake_filesystem_unittest
from needy.caches.directory import DirectoryCache
class DirectoryTest(fake_filesystem_unittest.TestCase):
def setUp(self):
self.setUpPyfakefs()
def test_directory_cache(self):
cache = DirectoryCache('cache')
self.assertEquals(cache.type(), 'directory')
self.assertEquals(cache.description(), 'cache')
self.assertFalse(cache.get('key', 'obj'))
self.fs.CreateFile('a', contents='AAA')
self.assertTrue(cache.set('a', 'a'))
self.assertTrue(cache.get('a', 'obj'))
with open('obj', 'r') as f:
self.assertEquals(f.read(), 'AAA')
class MDTestSite(MDSite):
"""Site to use for testing."""
class MDConfig: # pylint: disable=R0903
"""Config class for testing."""
DEBUG = False
CONTENT_PATH = '/my/content/'
THEME = '/my/theme/'
TESTING = True
class TestSiteMapView(fake_filesystem_unittest.TestCase, TestCase):
"""Navigation object tests."""
def create_app(self):
"""Create fake filesystem."""
self.setUpPyfakefs()
self.fake_os = fake_filesystem.FakeOsModule(self.fs)
file_string = u"""/*
Title: MDWeb
Description: The minimalistic markdown NaCMS
Date: February 1st, 2016
Sitemap Priority: 0.9
Sitemap ChangeFreq: daily
*/
"""