def get_config_object(self): if self.args.config is not None: return Config(os.path.abspath(self.args.config)) else: return Config( os.path.join('../../../../TestFramework/', Config.DEFAULT_CONFIG_FILE))
def test_connection(): """AWS Cognito Connection test.""" _config = Config() test_connection = boto3.client( _config.AWS_SERVICE, aws_access_key_id=_config.AWS_ACCESS_KEY_ID, aws_secret_access_key=_config.AWS_SECRET_ACCESS_KEY, region_name=_config.AWS_REGION_NAME)
def __init__(self): self._scheduler = Scheduler() self._bangumi = Bangumi() self._config = Config() # Memory Database for cache self._anime_db = CacheDB() self._danmaku_db = CacheDB() self._proxy_db = CacheDB() self._others_db = CacheDB()
def test_builder(self) -> None: self.assertIsInstance(Config(_EXAMPLE_CONFIG), Config) self.temp_config.write_text(_NOT_A_CONFIG) self.assertRaises(config.exception.InvalidConfiguration, Config._build, self.temp_config) self.temp_config.write_text(_BAD_YAML) self.assertRaises(config.exception.InvalidConfiguration, Config._build, self.temp_config)
def __init__(self, host: str, port: int): self._root = dirname(__file__) self._app = Quart(__name__) self._debug = False self._host = host self._port = port self._domain = f"http://{host}:{port}" self._agent = Agent() self._config = Config() self._proxy = RequestProxy()
def main() -> None: """Start the API for controlling mitmproxy.""" if sys.version_info < (3, 6): sys.exit("Python >= 3.6 required") config = Config(parse_args()) flow = Flow(config) proxy = Proxy(flow) http = Server(proxy) http.start()
def test_validator(self) -> None: self.assertTrue(Config(_EXAMPLE_CONFIG)._is_valid) self.temp_config.write_text(_ADDED_INFO_CONFIG) self.assertTrue(Config(self.temp_config)._is_valid) self.temp_config.write_text(_SCALAR_LIST_CONFIG) self.assertRaises(config.exception.InvalidSemantics, Config, self.temp_config) self.temp_config.write_text(_INCORRECT_TYPE_CONFIG) self.assertRaises(config.exception.InvalidSemantics, Config, self.temp_config) self.temp_config.write_text(_MISSING_KEY_CONFIG) self.assertRaises(config.exception.InvalidSemantics, Config, self.temp_config) self.temp_config.write_text(_MISSING_OPTIONAL_CONFIG) self.assertTrue((c := Config(self.temp_config))._is_valid) self.assertEqual(c.email.smtp.port, 25) self.temp_config.write_text(_MISSING_DELETION_LIMBO)
def __init__(self): # Anime self._config = Config() self._anime_searchers: Dict[str, AnimeSearcher] = {} self._anime_detail_parsers: Dict[str, AnimeDetailParser] = {} self._anime_url_parsers: Dict[str, AnimeUrlParser] = {} self._anime_proxy_cls: Dict[str, Type[StreamProxy]] = {} # Danmaku self._danmaku_searchers: Dict[str, DanmakuSearcher] = {} self._danmaku_detail_parsers: Dict[str, DanmakuDetailParser] = {} self._danmaku_data_parsers: Dict[str, DanmakuDataParser] = {} for module in self._config.get_enabled_modules(): self.load_full_module(module)
def aws_config(providers: dict): test = config.TEST_CONFIG config.TEST_CONFIG = True cfg = Config( providers={ "aws": dict( access_key_id="access", secret_access_key="secret", region="region", **providers, ) }, topics=[], boto=MockBoto(), ) config.TEST_CONFIG = test return cfg
def test_example_config(self) -> None: # NOTE This is coupled to eg/.vaultrc # Any changes there must be reflected in these tests config = Config(_EXAMPLE_CONFIG) self.assertEqual(config.identity.ldap.host, "ldap.example.com") self.assertEqual(config.identity.ldap.port, 389) self.assertEqual(config.identity.users.dn, "ou=users,dc=example,dc=com") self.assertEqual(config.identity.users.attributes.uid, "uidNumber") self.assertEqual(config.identity.users.attributes.name, "cn") self.assertEqual(config.identity.users.attributes.email, "mail") self.assertEqual(config.identity.groups.dn, "ou=groups,dc=example,dc=com") self.assertEqual(config.identity.groups.attributes.gid, "gidNumber") self.assertEqual(config.identity.groups.attributes.owners, "owner") self.assertEqual(config.identity.groups.attributes.members, "member") self.assertEqual(config.persistence.postgres.host, "postgres.example.com") self.assertEqual(config.persistence.postgres.port, 5432) self.assertEqual(config.persistence.database, "sandman") self.assertEqual(config.persistence.user, "a_db_user") self.assertEqual(config.persistence.password, "abc123") self.assertEqual(config.email.smtp.host, "mail.example.com") self.assertEqual(config.email.smtp.port, 25) self.assertEqual(config.email.sender, "*****@*****.**") self.assertEqual(config.deletion.threshold, time.delta(days=90)) self.assertEqual(config.deletion.warnings, [time.delta( days=10), time.delta(days=3), time.delta(days=1)]) self.assertEqual(config.deletion.limbo, time.delta(days=14)) self.assertEqual(config.archive.threshold, 1000) self.assertEqual(config.archive.handler, T.Path("/path/to/executable"))
def app(): """ Set up global app for functional tests """ class Response(APIResponse): @cached_property def json(self): return json.loads(self.data) class APIClient(FlaskClient): def open(self, *args, **kwargs): if 'json' in kwargs: kwargs['data'] = json.dumps(kwargs.pop('json')) kwargs['content_type'] = 'application/json' return super(APIClient, self).open(*args, **kwargs) _config = Config() app = create_app(_config) app.response_class = Response app.test_client_class = APIClient app.testing = True return app
def app(): """ Set up global app for functional testing """ class Response(APIResponse): @cached_property def json(self): return json.loads(self.data) class APIClient(FlaskClient): def open(self, *args, **kwargs): if 'json' in kwargs: kwargs['data'] = json.dumps(kwargs.pop('json')) kwargs['content_type'] = 'application/json' return super(APIClient, self).open(*args, **kwargs) _config = Config() app = create_app(_config) app.response_class = Response app.test_client_class = APIClient app.testing = True disconnect() # Disconnets the previous connection with MongoDB connect('mockDB', host='mongomock://localhost') # MongoDB mock connection return app
You should have received a copy of the GNU General Public License along with this program. If not, see https://www.gnu.org/licenses/ """ import unittest from unittest.mock import patch import core.idm from core import typing as T from api.config import Config from api.idm.idm import LDAPIdentityManager, LDAPUser, LDAPGroup from api.idm.ldap import NoResultsFound # NOTE This ties our tests to the example configuration _EXAMPLE_CONFIG = Config(T.Path("eg/.vaultrc")).identity def _DUMMY_PWUID(uid): # Dummy passwd interface, that acts as an identity function return T.SimpleNamespace(pw_uid=uid) def _DUMMY_GRGID(gid): # Dummy group interface, that acts as an identity function return T.SimpleNamespace(gr_name="foo", gr_gid=gid) def _DUMMY_PWNAM(username): # Dummy passwd-by-username interface: Take the bottom 10-bits from # the hash of the username string as the user ID
def __init__(self): self.session: Optional[ClientSession] = None self._domain_mapping: Dict[str, str] = Config().get("domain_mapping") self._dns_server = []
import pytest import requests from api.config import Config from api.providers import discord test_config = Config( providers={"discord": { "channels": { "alerts": "fake-webhook" } }}, topics=[]) def test_discord_message(): discord_message = discord.DiscordMessage(channel="alerts", message="test message", config=test_config) discord_message.send() assert True
def setUpClass(cls): cls.config = Config(os.path.dirname(__file__))
class DatabaseTest(unittest.TestCase): db = WeatherTalkDatabase(Config()) app = app def setUp(self): self.db = WeatherTalkDatabase(Config()) def tearDown(self): self.db.session.remove() @staticmethod def generate_observation(): observation = Observation(humidity=float(random.randrange(0, 100)), temperature=float(random.randrange(0, 100)), pressure=float(random.randrange(0, 100)), wind=float(random.randrange(0, 100)), condition=WeatherTypes.Sunny, location="test, test") return observation @staticmethod def generate_device(): return Device(name=str(uuid.uuid1().hex)) @staticmethod def generate_user(): return User(name=str(uuid.uuid1().hex), email=str(uuid.uuid1().hex), password=str(uuid.uuid1().hex)) def test_create_user(self): test_content = ENTRIES.get("user") user = None try: user = self.generate_user() self.db.session.add(user) except Exception as e: self.fail(f"Error {e}, {e.__class__}") self.assertIsNotNone(user) for _ in range(0, random.randrange(1, 10)): try: device = self.generate_device() user.devices.append(device) self.db.session.add(device) except Exception as e: self.fail(f"Error {e}, {e.__class__}") self.db.session.commit() def test_delete_user(self): db_users = self.db.session.query(User).all() if not db_users: for _ in range(0, random.randrange(1, 10)): user = self.generate_user() self.db.session.add(user) self.db.session.commit() db_users = self.db.session.query(User).all() for user in db_users: try: self.db.session.delete(user) self.db.session.commit() except Exception as e: self.fail(f"Error {e}, {e.__class__}") def test_create_device(self): device = None try: device = self.generate_device() self.db.session.add(device) self.db.session.commit() except Exception as e: self.fail(f"Error {e}, {e.__class__}") self.assertIsNotNone(device) def test_delete_device(self): devices = self.db.session.query(Device).all() if not devices: for _ in range(0, random.randrange(1, 10)): device = self.generate_device() self.db.session.add(device) self.db.session.commit() devices = self.db.session.query(Device).all() for device in devices: try: self.db.session.delete(device) self.db.session.commit() except Exception as e: self.fail(f"Error {e}, {e.__class__}") def test_create_device_group(self): try: user = self.generate_user() group = DeviceGroup(name=str(uuid.uuid1().hex), user_id=user.id) for _ in range(0, random.randrange(1, 10)): device = self.generate_device() group.members.append(device) self.db.session.add(device) self.db.session.add(user) self.db.session.add(group) self.db.session.commit() except Exception as e: self.fail(f"Error {e}, {e.__class__}") def test_delete_device_group(self): groups = self.db.session.query(DeviceGroup).all() if not groups: user = self.generate_user() group = DeviceGroup(name=str(uuid.uuid1().hex), user_id=user.id) for _ in range(0, random.randrange(1, 10)): device = self.generate_device() group.members.append(device) self.db.session.add(device) self.db.session.add(user) self.db.session.add(group) self.db.session.commit() groups = self.db.session.query(DeviceGroup).all() for group in groups: try: self.db.session.delete(group) self.db.session.commit() except Exception as e: self.fail(f"Error {e}, {e.__class__}") def test_create_observation(self): try: observation = self.generate_observation() self.db.session.add(observation) self.db.session.commit() except Exception as e: self.fail(f"Error {e}, {e.__class__}") def test_delete_observation(self): observations = self.db.session.query(Observation).all() if not observations: for _ in range(0, random.randrange(1, 10)): observation = self.generate_observation() self.db.session.add(observation) self.db.session.commit() for observation in observations: try: self.db.session.delete(observation) self.db.session.commit() except Exception as e: self.fail(f"Error {e}, {e.__class__}")
def create_app(): app = Flask(__name__) app.config.from_object(Config()) return app
def setUp(self): self.db = WeatherTalkDatabase(Config())
self.sent_messages = [] def create(self, to: str, body: str, *args, **from_parameter): message = self.FakeTwilioMessage() self.sent_messages.append(message) return message def __init__(self): self.messages = self.TwilioMessages() test_config = Config( providers={ "twilio": { "account_sid": "fake_sid", "auth_token": "fake_token", "messaging_service_sid": "fake_sid", } }, topics=[], ) twilio_client = MockTwilioClient() test_config.twilio = twilio_client def test_twilio_message(): twilio_message = twilio.TwilioMessage( to_phone_number="4847443806", message="test message", config=test_config ) twilio_message.send() assert True
# Copyright 2019 by Mihail Butnaru # All rights reserved. from api.app import create_app from api.config import Config _config = Config() app = create_app(_config)
parser.add_argument('--recorder_fs_ready', action='store_true', help='Recorder folders and files already created') parser.add_argument( '--preserve_player_fs', action='store_true', help='Do not remove player folders and files after test') parser.add_argument( '--preserve_recorder_fs', action='store_true', help='Do not remove recorder folders and files after test') args = parser.parse_args() if args.config is not None: config = Config(os.path.abspath(args.config)) else: config = Config(os.path.join('../../../', Config.DEFAULT_CONFIG_FILE)) # Create Device Manager dev_manager = DeviceManager(config) # Assign devices according to role player, recorder = dev_manager.get_devices_by_serials( args.player, args.recorder) # Create test runner instance tc_runner = AdnPlayerRecorderExampleTestTcRunner(config, player=player, recorder=recorder)
from core import config, typing as T from api.config import Config from api.idm import IdentityManager from api.logging import log # Executable versioning class version(T.SimpleNamespace): vault = "0.0.9" sandman = "0.0.7" # Common configuration try: if 'unittest' in sys.modules: os.environ["VAULTRC"] = "eg/.vaultrc" _cfg_path = config.utils.path("VAULTRC", T.Path("~/.vaultrc"), T.Path("/etc/vaultrc")) config = Config(_cfg_path) except (config.exception.ConfigurationNotFound, config.exception.InvalidConfiguration) as e: log.critical(e) sys.exit(1) # Common identity manager # NOTE This is mutable global state...which is not cool, but "should be # fine"™ provided we maintain serial execution idm = IdentityManager(config.identity)