示例#1
0
    def can_update(self):
        model = TestModel()
        model.thing = 'bam'

        model.update(thing='other')

        expect(model.thing).to.equal('other')
示例#2
0
    def transmute_to_with_different_attr_naming(self):
        model = TestDifferentAttrNaming()
        model.my_thing = 'something'

        result = JsonTransmuter.transmute_to(model, to_string=False)

        expect(result['my-thing']).to.equal('something')
示例#3
0
 def cannot_be_instantiated(self):
     try:
         result = AbstractPlugin()
     except TypeError:
         # Expected
         result = None
     expect(result).to.be_none()
示例#4
0
    def transmute_to_and_from_with_expanded_type(self):
        class CustomType(object):
            def __init__(self, something):
                self.something = something

        class CustomDefinition(ExpandedType):
            cls = CustomType

            @classmethod
            def serialize(self, value):
                return {'something': value.something}

            @classmethod
            def deserialize(self, attr_type, value):
                return attr_type(**value)

        class TestMappedModel(JsonMappedModel):
            __mapping__ = {
                'test': Attr('test', CustomType),
            }

        model = TestMappedModel()
        model.test = CustomType('thing')

        serialized = '{"test": {"something": "thing"}}'

        alchemize.register_type(CustomDefinition)

        result = JsonTransmuter.transmute_to(model)
        expect(result).to.equal(serialized)

        result = JsonTransmuter.transmute_from(serialized, TestMappedModel)
        expect(result.test.something).to.equal('thing')

        alchemize.remove_type(CustomDefinition)
示例#5
0
    def transmute_to_and_from_with_excluded_items(self):
        class MixedMappedModel(JsonMappedModel):
            __mapping__ = {
                'test': Attr('test', int),
                'another': Attr('another', int, serialize=False)
            }

        mapping = MixedMappedModel()
        mapping.test = 1
        mapping.another = 2

        without_result = '{"test": 1}'
        result_without = JsonTransmuter.transmute_to(mapping)
        expect(result_without).to.equal(without_result)

        # Make sure we can override the serialization preferences
        result_with = JsonTransmuter.transmute_to(mapping,
                                                  to_string=False,
                                                  serialize_all=True)
        expect(result_with.get('test')).to.equal(1)
        expect(result_with.get('another')).to.equal(2)

        result = JsonTransmuter.transmute_from({
            'test': 100,
            'another': 200
        }, MixedMappedModel)
        expect(result.test).to.equal(100)
        expect(result.another).to.equal(200)
示例#6
0
    def transmute_from_with_inherited_mapping(self):
        data = '{"test": "sample", "second": "other"}'

        result = JsonTransmuter.transmute_from(data, TestExtendedModel)

        expect(result.test).to.equal('sample')
        expect(result.second).to.equal('other')
示例#7
0
    def transmute_from_with_child_mapping(self):
        data = '{"other": "sample", "child": {"test": "sample stuff"}}'

        result = JsonTransmuter.transmute_from(data, TestChildMapping)

        require(result.child).not_to.be_none()
        expect(result.child.test).to.equal('sample stuff')
        def can_authenticate(self, post_func):
            post_func.return_value = get_keystone_v2_auth_resp()

            creds = self.auth.authenticate()

            expect(creds.get('token', None)).to.equal('some_token')
            expect(creds.get('project_id', None)).to.equal('some_tenant')
示例#9
0
    def transmute_to_and_from_with_custom_serializer(self):
        mapping = TestWrappedModel()
        mapping.test = "bam"

        json_str = '{"#item": {"test": "bam"}}'

        class Custom(object):
            @classmethod
            def dumps(cls, value):
                value['#item']['test'] = 'allthethings'
                return json.dumps(value)

            @classmethod
            def loads(cls, value):
                loaded = json.loads(json_str)
                loaded['#item']['test'] = 'magic'
                return loaded

        result = JsonTransmuter.transmute_to(mapping, encoder=Custom)
        expect(result).to.equal('{"#item": {"test": "allthethings"}}')

        result = JsonTransmuter.transmute_from(json_str,
                                               TestWrappedModel,
                                               decoder=Custom)
        expect(result.test).to.equal('magic')
示例#10
0
    def transmute_to_with_empty_submodel(self):
        model = TestChildMapping()
        model.child = None

        result = JsonTransmuter.transmute_to(model, to_string=False)

        expect(result.get('child')).to.be_none()
示例#11
0
    def transmute_from_with_child_mapping(self):
        data = '{"other": "sample", "child": {"test": "sample stuff"}}'

        result = JsonTransmuter.transmute_from(data, TestChildMapping)

        require(result.child).not_to.be_none()
        expect(result.child.test).to.equal('sample stuff')
示例#12
0
    def transmute_to_with_empty_submodel(self):
        model = TestChildMapping()
        model.child = None

        result = JsonTransmuter.transmute_to(model, to_string=False)

        expect(result.get('child')).to.be_none()
示例#13
0
    def transmute_to_with_different_attr_naming(self):
        model = TestDifferentAttrNaming()
        model.my_thing = 'something'

        result = JsonTransmuter.transmute_to(model, to_string=False)

        expect(result['my-thing']).to.equal('something')
示例#14
0
文件: loader.py 项目: pyarmory/aumbry
    def can_use_yaml_cfg_with_handler_override(self):
        with mock_ssm():
            options = {
                'PARAMETER_STORE_AWS_REGION': 'us-west-2',
                'PARAMETER_STORE_PREFIX': '/aumbry-test',
            }

            expected_cfg = SampleYamlConfig()
            expected_cfg.nope = 'testing'

            handler = GenericHandler()

            # Save Sample Config
            aumbry.save(aumbry.PARAM_STORE,
                        expected_cfg,
                        options,
                        handler=handler)

            # Retrieve back the config
            cfg = aumbry.load(aumbry.PARAM_STORE,
                              SampleGenericConfig,
                              options,
                              handler=handler)

        expect(cfg.nope).to.equal(expected_cfg.nope)
示例#15
0
    def can_convert_to_dictionary(self):
        tmp_uuid = str(uuid.uuid4())
        tenant = Tenant(name=tmp_uuid, tenant_id=tmp_uuid)
        tenant_dict = tenant.as_dict()

        test_dict = Tenant.build_tenant_from_dict(tenant_dict).as_dict()
        expect(tenant_dict).to.equal(test_dict)
            def should_take_into_account_conditional_probability(self):
                user_tz = ['Eastern (US & Canada)', 'Pacific (US & Canada)']
                l1_time = [9, 9]
                l1_day = [0, 1]
                l2_time = [9, 9]
                l2_day = [3, 4]
                l3_time = [None, 9]
                l3_day = [None, 5]
                schedule_type = [2, 3]

                training_data = pd.DataFrame({ 'user_tz': user_tz,
                    'l1_time': l1_time,
                    'l1_day': l1_day,
                    'l2_time': l2_time,
                    'l2_day': l2_day,
                    'l3_time': l3_time,
                    'l3_day': l3_day,
                    'schedule_type': schedule_type
                    })

                business_forecast = [{'schedule_type': 2,
                         'user_tz': 'Eastern (US & Canada)',
                         'frequency': 1 },
                         {'schedule_type': 3,
                         'user_tz': 'Pacific (US & Canada)',
                         'frequency': 2 }]

                model = GeneralProbModel()

                model.fit(training_data)
                p = model.predict(business_forecast)
                expect(True).to.equal(True)
示例#17
0
文件: loader.py 项目: pyarmory/aumbry
    def can_load(self, raw, cls):
        temp, options = write_temp_file(raw)

        cfg = aumbry.load(aumbry.FILE, cls, options)
        os.remove(temp.name)

        expect(cfg.nope).to.equal('testing')
示例#18
0
    def transmute_to_and_from_with_custom_serializer(self):
        mapping = TestWrappedModel()
        mapping.test = "bam"

        json_str = '{"#item": {"test": "bam"}}'

        class Custom(object):
            @classmethod
            def dumps(cls, value):
                value['#item']['test'] = 'allthethings'
                return json.dumps(value)

            @classmethod
            def loads(cls, value):
                loaded = json.loads(json_str)
                loaded['#item']['test'] = 'magic'
                return loaded

        result = JsonTransmuter.transmute_to(
            mapping,
            encoder=Custom
        )
        expect(result).to.equal('{"#item": {"test": "allthethings"}}')

        result = JsonTransmuter.transmute_from(
            json_str,
            TestWrappedModel,
            decoder=Custom
        )
        expect(result.test).to.equal('magic')
示例#19
0
            def should_not_have_weird_hours(self):
                user_tz = ['Eastern (US & Canada)', 'Pacific (US & Canada)']
                l1_time = [9, 9]
                l2_time = [9, 9]
                l3_time = [None, 9]

                training_data = pd.DataFrame({
                    'user_tz': user_tz,
                    'l1_time': l1_time,
                    'l2_time': l2_time
                })

                business_forecast = [{
                    'schedule_type': 2,
                    'timezone': 'Eastern (US & Canada)',
                    'frequency': 1
                }, {
                    'schedule_type': 3,
                    'timezone': 'Pacific (US & Canada)',
                    'frequency': 2
                }]

                smart_heuristic_model = SmartHeuristicModel()
                smart_heuristic_model.fit(training_data)

                schedule = smart_heuristic_model.\
                        generate_sample_schedule(business_forecast)
                _sum = schedule._table_df.sum().sum()
                expect(_sum).to.equal(8)
            def handles_predicting_cases_it_has_not_seen_before(self):
                user_tz = ['Eastern (US & Canada)', 'Pacific (US & Canada)']
                l1_time = [9, 9]
                l1_day = [0, 1]
                l2_time = [9, 9]
                l2_day = [3, 4]
                l3_time = [None, 9]
                l3_day = [None, 5]
                schedule_type = [2, 3]

                training_data = pd.DataFrame({ 'user_tz': user_tz,
                    'l1_time': l1_time,
                    'l1_day': l1_day,
                    'l2_time': l2_time,
                    'l2_day': l2_day,
                    'l3_time': l3_time,
                    'l3_day': l3_day,
                    'schedule_type': schedule_type
                    })

                business_forecast = [{'schedule_type': 1,
                         'user_tz': 'Eastern (US & Canada)',
                         'frequency': 1 },
                         {'schedule_type': 4,
                         'user_tz': 'Pacific (US & Canada)',
                         'frequency': 2 }]

                model = GeneralProbModel()

                model.fit(training_data)
                p = model.predict(business_forecast)

                expect(True).to.equal(True)
示例#21
0
文件: jobs.py 项目: CloudRift/Rift
    def can_delete_job(self):
        post_resp = self._post_job()
        job_id = post_resp.json['job_id']

        resp = self.app.delete('/v1/tenant/jobs/{0}'.format(job_id),
                               expect_errors=True)
        expect(resp.status_int).to.equal(200)
示例#22
0
    def transmute_to_and_from_with_unknown_type(self):
        class CustomType(object):
            def __init__(self, something):
                self.something = something

        class TestMappedModel(JsonMappedModel):
            __mapping__ = {
                'test': Attr('test', CustomType),
            }

        model = TestMappedModel()
        model.test = CustomType('thing')

        serialized = '{}'

        result = JsonTransmuter.transmute_to(model)
        expect(result).to.equal(serialized)

        result = JsonTransmuter.transmute_from(
            '{"test": {"something": "thing"}}',
            TestMappedModel
        )

        attr = getattr(result, 'test', None)
        expect(attr).to.be_none()
示例#23
0
    def transmute_to_and_from_with_excluded_items(self):
        class MixedMappedModel(JsonMappedModel):
            __mapping__ = {
                'test': Attr('test', int),
                'another': Attr('another', int, serialize=False)
            }

        mapping = MixedMappedModel()
        mapping.test = 1
        mapping.another = 2

        without_result = '{"test": 1}'
        result_without = JsonTransmuter.transmute_to(mapping)
        expect(result_without).to.equal(without_result)

        # Make sure we can override the serialization preferences
        result_with = JsonTransmuter.transmute_to(
            mapping,
            to_string=False,
            serialize_all=True
        )
        expect(result_with.get('test')).to.equal(1)
        expect(result_with.get('another')).to.equal(2)

        result = JsonTransmuter.transmute_from(
            {'test': 100, 'another': 200},
            MixedMappedModel
        )
        expect(result.test).to.equal(100)
        expect(result.another).to.equal(200)
示例#24
0
    def transmute_from_with_inherited_mapping(self):
        data = '{"test": "sample", "second": "other"}'

        result = JsonTransmuter.transmute_from(data, TestExtendedModel)

        expect(result.test).to.equal('sample')
        expect(result.second).to.equal('other')
            def should_not_have_weird_hours(self):
                user_tz = ['Eastern (US & Canada)', 'Pacific (US & Canada)']
                l1_time = [9, 9]
                l2_time = [9, 9]
                l3_time = [None, 9]

                training_data = pd.DataFrame({ 'user_tz': user_tz,
                    'l1_time': l1_time,
                    'l2_time': l2_time
                    })

                business_forecast = [{'schedule_type': 2,
                         'timezone': 'Eastern (US & Canada)',
                         'frequency': 1 },
                         {'schedule_type': 3,
                         'timezone': 'Pacific (US & Canada)',
                         'frequency': 2 }]

                smart_heuristic_model = SmartHeuristicModel()
                smart_heuristic_model.fit(training_data)

                schedule = smart_heuristic_model.\
                        generate_sample_schedule(business_forecast)
                _sum = schedule._table_df.sum().sum()
                expect(_sum).to.equal(8)
示例#26
0
 def cannot_be_instantiated(self):
     try:
         result = AbstractPlugin()
     except TypeError:
         # Expected
         result = None
     expect(result).to.be_none()
示例#27
0
    def can_delete_job(self):
        post_resp = self._post_job()
        job_id = post_resp.json['job_id']

        resp = self.app.delete('/v1/tenant/jobs/{0}'.format(job_id),
                               expect_errors=True)
        expect(resp.status_int).to.equal(200)
示例#28
0
            def should_create_a_sample_that_meets_business_forecast_criteria(
                    self):
                user_tz = ['Eastern (US & Canada)', 'Pacific (US & Canada)']
                l1_time = [9, 9]
                l2_time = [9, 9]
                l3_time = [None, 9]

                training_data = pd.DataFrame({
                    'user_tz': user_tz,
                    'l1_time': l1_time,
                    'l2_time': l2_time
                })

                business_forecast = [{
                    'schedule_type': 2,
                    'timezone': 'Eastern (US & Canada)',
                    'frequency': 1
                }, {
                    'schedule_type': 3,
                    'timezone': 'Pacific (US & Canada)',
                    'frequency': 2
                }]

                dumb_model = DumbModel()
                dumb_model.fit(training_data)

                schedule = dumb_model.generate_sample_schedule(
                    business_forecast)
                _sum = schedule._table_df.sum().sum()
                expect(_sum).to.equal(8)
示例#29
0
    def transmute_from_with_different_attr_naming(self):
        test_json = '{"my-thing": "something"}'

        result = JsonTransmuter.transmute_from(test_json,
                                               TestDifferentAttrNaming)

        expect(result.my_thing).to.equal('something')
示例#30
0
    def can_connect_with_args(self):
        self.ssh_client.connect(host='sample.host',
                                port=80,
                                credentials=self.ssh_credentials)

        expect(self.ssh_client.host).to.equal('sample.host')
        expect(self.ssh_client.port).to.equal(80)
示例#31
0
文件: nova.py 项目: CloudRift/Rift
    def raises_exception_on_unsupported_provider(self, get_target, get_driver):
        target = self.TARGET_WITH_UNSUPPORTED_PROVIDER
        driver_stub = self._get_libcloud_driver_stub([])
        get_target.return_value = target
        get_driver.return_value = driver_stub

        expect(self.plugin.execute_action, [self.job, self.action]) \
            .to.raise_a(Exception)
示例#32
0
文件: nova.py 项目: CloudRift/Rift
    def raises_exception_on_invalid_address(self, get_target, get_driver):
        target = self.TARGET_WITH_IP_ADDRESS
        driver_stub = self._get_libcloud_driver_stub([])
        get_target.return_value = target
        get_driver.return_value = driver_stub

        expect(self.plugin.execute_action, [self.job, self.action]) \
            .to.raise_a(Exception)
示例#33
0
    def run_requires_a_project_cfg(self):
        config._config = None

        try:
            app.main(['run', 'bam'])
        except SystemExit:
            err_msg = 'Error: Could not file project configuration!'
            expect(err_msg).to.be_in(self.stdout.getvalue())
示例#34
0
    def can_extend(self):
        child = TestModel()
        child.thing = 'bam'

        model = TestListModel()
        model.extend([child])

        expect(model[0]).to.equal(child)
示例#35
0
    def raises_exception_on_unsupported_provider(self, get_target, get_driver):
        target = self.TARGET_WITH_UNSUPPORTED_PROVIDER
        driver_stub = self._get_libcloud_driver_stub([])
        get_target.return_value = target
        get_driver.return_value = driver_stub

        expect(self.plugin.execute_action, [self.job, self.action]) \
            .to.raise_a(Exception)
示例#36
0
文件: ssh.py 项目: CloudRift/Rift
    def can_connect_with_args(self):
        self.ssh_client.connect(
            host='sample.host',
            port=80,
            credentials=self.ssh_credentials)

        expect(self.ssh_client.host).to.equal('sample.host')
        expect(self.ssh_client.port).to.equal(80)
示例#37
0
    def transmute_from_with_all_required_attrs(self):
        result = JsonTransmuter.transmute_from(
            '{"test": 1, "other": 2}',
            TestRequiredMappedModel,
        )

        expect(result.test).to.equal(1)
        expect(result.other).to.equal(2)
示例#38
0
        def can_recreate(self):
            # Calling without an environment existing
            venv.argument_handler('recreate', None)
            expect(os.path.exists(venv.ENV_PATH)).to.be_true()

            # Calling again now that the environment exists
            venv.argument_handler('recreate', None)
            expect(os.path.exists(venv.ENV_PATH)).to.be_true()
示例#39
0
    def transmute_to_missing_required_attr_raises(self):
        model = TestRequiredMappedModel()
        model.test = 1

        expect(
            JsonTransmuter.transmute_to,
            [model]
        ).to.raise_a(RequiredAttributeError)
示例#40
0
    def can_build_a_target_from_a_dictionary(self):
        obj = build_target_obj()

        expect(obj.name).to.equal('bam')
        expect('play.yml').to.be_in(obj.playbooks)
        expect(obj.inventory).to.equal('inventory.ini')
        expect(obj.tags).to.equal('nope')
        expect(obj.options).to.equal('-vvvv')
示例#41
0
 def transmute_from_with_missing_required_attr_raises(self):
     expect(
         JsonTransmuter.transmute_from,
         [
             '{"test": 1}',
             TestRequiredMappedModel
         ]
     ).to.raise_a(RequiredAttributeError)
示例#42
0
        def transmute_attribute_with_type(self, attr_type, attr_data,
                                          attr_result):
            class FlexMapping(JsonMappedModel):
                __mapping__ = {'test': Attr('test', attr_type)}

            data = '{{"test": {0} }}'.format(attr_data)
            result = JsonTransmuter.transmute_from(data, FlexMapping)
            expect(result.test).to.equal(attr_result)
示例#43
0
    def can_build_a_target_from_a_dictionary(self):
        obj = build_target_obj()

        expect(obj.name).to.equal('bam')
        expect('play.yml').to.be_in(obj.playbooks)
        expect(obj.inventory).to.equal('inventory.ini')
        expect(obj.tags).to.equal('nope')
        expect(obj.options).to.equal('-vvvv')
示例#44
0
    def raises_exception_on_invalid_address(self, get_target, get_driver):
        target = self.TARGET_WITH_IP_ADDRESS
        driver_stub = self._get_libcloud_driver_stub([])
        get_target.return_value = target
        get_driver.return_value = driver_stub

        expect(self.plugin.execute_action, [self.job, self.action]) \
            .to.raise_a(Exception)
示例#45
0
    def transmute_from_with_all_required_attrs(self):
        result = JsonTransmuter.transmute_from(
            '{"test": 1, "other": 2}',
            TestRequiredMappedModel,
        )

        expect(result.test).to.equal(1)
        expect(result.other).to.equal(2)
示例#46
0
        def can_authenticate(self, post_func):
            r = get_keystone_v2_auth_resp()
            post_func.return_value = r

            self.auth(r)

            expect(r.headers.get('X-Auth-Token')).to.equal('some_token')
            expect(r.headers.get('X-Project-Id')).to.equal('some_tenant')
示例#47
0
    def can_get(self):
        child = TestModel()
        child.thing = 'bam'

        model = TestListModel()
        model.collection = [child]

        expect(model[0]).to.equal(child)
示例#48
0
    def can_build_a_target_from_a_dictionary(self):
        obj = build_target_obj()

        expect(obj.name).to.equal("bam")
        expect("play.yml").to.be_in(obj.playbooks)
        expect(obj.inventory).to.equal("inventory.ini")
        expect(obj.tags).to.equal("nope")
        expect(obj.options).to.equal("-vvvv")
示例#49
0
    def can_append(self):
        child = TestModel()
        child.thing = 'bam'

        model = TestListModel()
        model.append(child)

        expect(model[0]).to.equal(child)
示例#50
0
    def should_have_a_default_get_method(self):
        plugin = GenericPlugin()
        resp, req = Response(), object()

        plugin.on_get(req=req, resp=resp)
        json_body = json.loads(resp.body)

        expect(resp.status).to.equal(HTTP_200)
        expect(json_body['help']).to.equal(AbstractPlugin.API_HELP)
示例#51
0
    def run_requires_a_venv(self):
        config.get_config('./data/test_project.yml')

        try:
            app.main(['run', 'bam'])
        except SystemExit:
            err_msg = ('Virtual environment does not exist.. '
                       'Please run: ansible-flow venv create')
            expect(err_msg).to.be_in(self.stdout.getvalue())
示例#52
0
    def can_serialize(self):
        cfg = TestConfig()
        cfg.nope = 'testing'

        handler = generic.GenericHandler()
        raw = handler.serialize(cfg)

        expect(type(raw)).to.equal(dict)
        expect(raw['nope']).to.equal('testing')
示例#53
0
    def should_have_a_default_get_method(self):
        plugin = GenericPlugin()
        resp, req = Response(), object()

        plugin.on_get(req=req, resp=resp)
        json_body = json.loads(resp.body)

        expect(resp.status).to.equal(HTTP_200)
        expect(json_body['help']).to.equal(AbstractPlugin.API_HELP)