def test_libs_notifications_send_emails_error(self, mock_smtplib):
        mock_class = Mock()
        mock_class.sendmail = Mock(side_effect=Exception())
        mock_smtplib.SMTP = lambda *a: mock_class

        expected_emails = ["*****@*****.**"]
        self.assertEqual([], send_to_email_addresses(expected_emails, {"text": "test_template"}))
Ejemplo n.º 2
0
async def test_setup_entry_successful(hass):
    """Test setup entry is successful."""
    entry = Mock()
    entry.data = {'host': '1.2.3.4', 'port': 80, 'api_key': '1234567890ABCDEF'}
    with patch.object(hass, 'async_create_task') as mock_add_job, \
        patch.object(hass, 'config_entries') as mock_config_entries, \
        patch('pydeconz.DeconzSession.async_get_state',
              return_value=mock_coro(CONFIG)), \
        patch('pydeconz.DeconzSession.start', return_value=True), \
        patch('homeassistant.helpers.device_registry.async_get_registry',
              return_value=mock_coro(Mock())):
        assert await deconz.async_setup_entry(hass, entry) is True
    assert hass.data[deconz.DOMAIN]
    assert hass.data[deconz.DATA_DECONZ_ID] == {}
    assert len(hass.data[deconz.DATA_DECONZ_UNSUB]) == 1
    assert len(mock_add_job.mock_calls) == 5
    assert len(mock_config_entries.async_forward_entry_setup.mock_calls) == 5
    assert mock_config_entries.async_forward_entry_setup.mock_calls[0][1] == \
        (entry, 'binary_sensor')
    assert mock_config_entries.async_forward_entry_setup.mock_calls[1][1] == \
        (entry, 'light')
    assert mock_config_entries.async_forward_entry_setup.mock_calls[2][1] == \
        (entry, 'scene')
    assert mock_config_entries.async_forward_entry_setup.mock_calls[3][1] == \
        (entry, 'sensor')
    assert mock_config_entries.async_forward_entry_setup.mock_calls[4][1] == \
        (entry, 'switch')
Ejemplo n.º 3
0
async def test_add_new_device(hass):
    """Test adding a new device generates a signal for platforms."""
    entry = Mock()
    entry.data = {'host': '1.2.3.4', 'port': 80,
                  'api_key': '1234567890ABCDEF', 'allow_clip_sensor': False}
    new_event = {
        "t": "event",
        "e": "added",
        "r": "sensors",
        "id": "1",
        "sensor": {
            "config": {
                "on": "True",
                "reachable": "True"
            },
            "name": "event",
            "state": {},
            "type": "ZHASwitch"
        }
    }
    with patch.object(deconz, 'async_dispatcher_send') as mock_dispatch_send, \
            patch('pydeconz.DeconzSession.async_get_state',
                  return_value=mock_coro(CONFIG)), \
            patch('pydeconz.DeconzSession.start', return_value=True):
        assert await deconz.async_setup_entry(hass, entry) is True
        hass.data[deconz.DOMAIN].async_event_handler(new_event)
        await hass.async_block_till_done()
        assert len(mock_dispatch_send.mock_calls) == 1
        assert len(mock_dispatch_send.mock_calls[0]) == 3
Ejemplo n.º 4
0
def fake_supplier(seed, fake_data):
	result = Mock()
	result.metadata = {'entries' : len(fake_data)}
	result.data = {'data' : fake_data}
	result.kurfile.get_seed.return_value = seed
	result.downselect = partial(SpeechRecognitionSupplier.downselect, result)
	return result
Ejemplo n.º 5
0
async def test_setup_entry_no_available_bridge(hass):
    """Test setup entry fails if deCONZ is not available."""
    entry = Mock()
    entry.data = {'host': '1.2.3.4', 'port': 80, 'api_key': '1234567890ABCDEF'}
    with patch('pydeconz.DeconzSession.async_load_parameters',
               return_value=mock_coro(False)):
        assert await deconz.async_setup_entry(hass, entry) is False
Ejemplo n.º 6
0
def filter_by_mock_conceptscheme(**kwargs):
    filter_mock = Mock()
    concept_scheme = ConceptScheme()
    concept_scheme.id = 1
    concept_scheme.uri = "urn:test:test"
    filter_mock.one = Mock(return_value=concept_scheme)
    return filter_mock
Ejemplo n.º 7
0
def filter_by_mock_concept(**kwargs):
    filter_mock = Mock()
    concept_id = None
    conceptscheme_id = None
    if 'concept_id' in kwargs:
        concept_id = kwargs['concept_id']
    if 'conceptscheme_id' in kwargs:
        conceptscheme_id = kwargs['conceptscheme_id']
    if concept_id == '1':
        c = Concept(concept_id=concept_id, conceptscheme_id=conceptscheme_id)
        c.type = 'concept'
        filter_mock.one = Mock(return_value=c)
    elif concept_id == '3':
        c = Collection(concept_id=concept_id, conceptscheme_id=conceptscheme_id)
        c.type = 'collection'
        filter_mock.one = Mock(return_value=c)
    elif concept_id == '555':
        c = Thing(concept_id=concept_id, conceptscheme_id=conceptscheme_id)
        filter_mock.one = Mock(return_value=c)
    elif concept_id == '666':
        raise NoResultFound

    a_concept = Concept(concept_id=7895, conceptscheme_id=conceptscheme_id, type='concept')
    a_labels = [Label(label='De Paardekastanje', language_id='nl'), Label(label='The Chestnut', language_id='en'),
                Label(label='la châtaigne', language_id='fr')]
    a_concept.labels = a_labels
    b_concept = Concept(concept_id=9863, conceptscheme_id=conceptscheme_id, type='concept')
    b_labels = [Label(label='test', language_id='nl')]
    b_concept.labels = b_labels
    filter_mock.all = Mock(return_value=[a_concept, b_concept])
    return filter_mock
Ejemplo n.º 8
0
    def test_call(self):
        mock = Mock()
        self.assertTrue(is_instance(mock.return_value, Mock),
                        "Default return_value should be a Mock")

        result = mock()
        self.assertEqual(mock(), result,
                         "different result from consecutive calls")
        mock.reset_mock()

        ret_val = mock(sentinel.Arg)
        self.assertTrue(mock.called, "called not set")
        self.assertEqual(mock.call_count, 1, "call_count incoreect")
        self.assertEqual(mock.call_args, ((sentinel.Arg,), {}),
                         "call_args not set")
        self.assertEqual(mock.call_args_list, [((sentinel.Arg,), {})],
                         "call_args_list not initialised correctly")

        mock.return_value = sentinel.ReturnValue
        ret_val = mock(sentinel.Arg, key=sentinel.KeyArg)
        self.assertEqual(ret_val, sentinel.ReturnValue,
                         "incorrect return value")

        self.assertEqual(mock.call_count, 2, "call_count incorrect")
        self.assertEqual(mock.call_args,
                         ((sentinel.Arg,), {'key': sentinel.KeyArg}),
                         "call_args not set")
        self.assertEqual(mock.call_args_list, [
            ((sentinel.Arg,), {}),
            ((sentinel.Arg,), {'key': sentinel.KeyArg})
        ],
            "call_args_list not set")
Ejemplo n.º 9
0
async def test_alert_error():
    async with unit(1) as unit1:
        async with unit(2) as unit2:

            def err(x):
                raise RuntimeError("dad")

            error_me1 = Mock(side_effect=err)
            await unit1.register(error_me1, "my.error1", call_conv=CC_DATA, multiple=True)
            called = False
            async for d in unit2.poll("my.error1", min_replies=1, max_replies=2, max_delay=TIMEOUT,
                                      result_conv=CC_MSG, debug=True):
                assert not called
                assert d.error.cls == "RuntimeError"
                assert d.error.message == "dad"
                called = True
            error_me1.assert_called_with(None)

            with pytest.raises(RuntimeError):
                async for d in unit2.poll("my.error1", result_conv=CC_DATA, min_replies=1,
                                          max_replies=2, max_delay=TIMEOUT):
                    assert False

            with pytest.raises(RuntimeError):
                await unit2.poll_first("my.error1")
Ejemplo n.º 10
0
    def setUp(self):
        self.db = mock.create_autospec(Connection, instance=True)
        self.setup = Mock([])
        self.teardown = Mock([])
        self.table = table = CacheTableSpec(self.setup, self.teardown)

        self.manager = CacheTableManager(self.db, [table])
Ejemplo n.º 11
0
    def test_side_effect(self):
        mock = Mock()

        def effect(*args, **kwargs):
            raise SystemError('kablooie')

        mock.side_effect = effect
        self.assertRaises(SystemError, mock, 1, 2, fish=3)
        mock.assert_called_with(1, 2, fish=3)

        results = [1, 2, 3]
        def effect():
            return results.pop()
        mock.side_effect = effect

        self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
                          "side effect not used correctly")

        mock = Mock(side_effect=sentinel.SideEffect)
        self.assertEqual(mock.side_effect, sentinel.SideEffect,
                          "side effect in constructor not used")

        def side_effect():
            return DEFAULT
        mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN)
        self.assertEqual(mock(), sentinel.RETURN)
Ejemplo n.º 12
0
 def dummy_callback(self):
     from skorch.callbacks import Callback
     cb = Mock(spec=Callback)
     # make dummy behave like an estimator
     cb.get_params.return_value = {}
     cb.set_params = lambda **kwargs: cb
     return cb
Ejemplo n.º 13
0
 def test_fail_excess_multiple(self):
     # When multiple consumers require less than pg output
     # alone, but in sum want more than total output, it should
     # be erroneous situation
     item = self.ch.type_(type_id=1, attributes={Attribute.power: 0})
     holder1 = Mock(state=State.online, item=item, _domain=Domain.ship, spec_set=ModuleHigh(1))
     holder1.attributes = {Attribute.power: 25}
     self.track_holder(holder1)
     holder2 = Mock(state=State.online, item=item, _domain=Domain.ship, spec_set=ModuleHigh(1))
     holder2.attributes = {Attribute.power: 20}
     self.track_holder(holder2)
     self.fit.stats.powergrid.used = 45
     self.fit.stats.powergrid.output = 40
     restriction_error1 = self.get_restriction_error(holder1, Restriction.powergrid)
     self.assertIsNotNone(restriction_error1)
     self.assertEqual(restriction_error1.output, 40)
     self.assertEqual(restriction_error1.total_use, 45)
     self.assertEqual(restriction_error1.holder_use, 25)
     restriction_error2 = self.get_restriction_error(holder2, Restriction.powergrid)
     self.assertIsNotNone(restriction_error2)
     self.assertEqual(restriction_error2.output, 40)
     self.assertEqual(restriction_error2.total_use, 45)
     self.assertEqual(restriction_error2.holder_use, 20)
     self.untrack_holder(holder1)
     self.untrack_holder(holder2)
     self.assertEqual(len(self.log), 0)
     self.assert_restriction_buffers_empty()
Ejemplo n.º 14
0
async def test_import_with_existing_config(hass):
    """Test importing a host with an existing config file."""
    flow = config_flow.HueFlowHandler()
    flow.hass = hass

    bridge = Mock()
    bridge.username = '******'
    bridge.config.bridgeid = 'bridge-id-1234'
    bridge.config.name = 'Mock Bridge'
    bridge.host = '0.0.0.0'

    with patch.object(config_flow, '_find_username_from_config',
                      return_value='mock-user'), \
            patch.object(config_flow, 'get_bridge',
                         return_value=mock_coro(bridge)):
        result = await flow.async_step_import({
            'host': '0.0.0.0',
            'path': 'bla.conf'
        })

    assert result['type'] == 'create_entry'
    assert result['title'] == 'Mock Bridge'
    assert result['data'] == {
        'host': '0.0.0.0',
        'bridge_id': 'bridge-id-1234',
        'username': '******'
    }
Ejemplo n.º 15
0
def filter_by_mock_language(id):
    filter_mock = Mock()
    if id in ['af', 'flup']:
        filter_mock.count = Mock(return_value=0)
    else:
        filter_mock.count = Mock(return_value=1)
    return filter_mock
    def setUp(self):
        """setUp for all unit tests in this class"""
        self.__stored_hardware_types = [ht.HardwareType.from_dict({"name": "type1"})]
        self.__suggested_hardware_types = [ht.HardwareType.from_dict({"name": "type2"})]

        def create_interactor(interactor_type):
            """Mock for InteractorFactory.create"""
            interactor = None

            interactors = {
                "GetHardwareTypeListInteractor": (hi.GetHardwareTypeListInteractor, self.__stored_hardware_types),
                "GetSuggestedHardwareTypesInteractor": (hi.GetSuggestedHardwareTypesInteractor, self.__suggested_hardware_types)
            }

            if interactor_type in interactors:
                interactor_type, data = interactors[interactor_type]
                interactor = Mock(interactor_type)
                interactor.execute = Mock(return_value=data)

            return interactor

        factory = Mock(interactor_factory.InteractorFactory)        
        factory.create = Mock(side_effect=create_interactor)
        self.__renderer = Mock(tr.TemplateRenderer)

        self.__target = hth.HardwareTypesHandler(factory, self.__renderer)
        self.__target.session = Mock(session.Session)        
Ejemplo n.º 17
0
    def setUp(self):
        self.db = NonCallableMagicMock(SQLiteDB)
        self.setup = Mock([])
        self.teardown = Mock([])
        self.table = table = CacheTable(self.setup, self.teardown)

        self.manager = CacheTableManager(self.db, [table])
Ejemplo n.º 18
0
async def test_threaded_negative_lookup() -> None:
    loop = Mock()
    ips = []
    loop.getaddrinfo = fake_addrinfo(ips)
    resolver = ThreadedResolver(loop=loop)
    with pytest.raises(socket.gaierror):
        await resolver.resolve('doesnotexist.bla')
Ejemplo n.º 19
0
    def _assert_is_vouched_on_mozillians(self, expected_vouched, email,
                                         mock_api_data, mock_requests_get):

        expected_api_url = '%(base_url)s/users/?api-key=%(api_key)s&email=%(email)s' % dict(
            base_url='https://example.com',
            api_key='8675309',
            email=email
        )

        mock_json = Mock(return_value={
            'count': 1,
            'next': None,
            'previous': None,
            'results': [
                {
                    '_url': 'https://mozillians.org/api/v2/users/12345/',
                    'is_vouched': expected_vouched,
                    'username': '******'
                }
            ]
        })

        mock_response = Mock()
        mock_response.json = mock_json

        mock_requests_get.return_value = mock_response

        result_vouched = is_vouched_on_mozillians_org(User(email=email))
        self.assertEqual(expected_vouched, result_vouched)

        mock_json.assert_called_with()
        mock_requests_get.assert_called_with(expected_api_url)
Ejemplo n.º 20
0
 def main(argument_namespace_callback, **kwargs):
     from PyOpenWorm.context import Context
     argument_namespace_callback.output_mode = 'json'
     m = Mock(name='context_result', spec=Context())
     m.identifier = 'ident'
     m.base_namespace = 'base_namespace'
     return m
Ejemplo n.º 21
0
    def setUp(self):
        def get_games_data():
            games_data = [{'title': 'title1',
                          'platform': 'platform1'},
                          {'title': 'title2',
                           'platform': 'platform2'}]
            return [g.Game.from_dict(d) for d in games_data]

        def get_hardware_data():
            hardware_data = [{'name': 'hardware1',
                              'platform': 'platform1'},
                             {'name': 'hardware2',
                              'platform': 'platform2'}]
            return [h.Hardware.from_dict(d) for d in hardware_data]

        self.__interactor = Mock(ci.ExportCollectionInteractor)
        self.__interactor.execute = Mock(return_value={'games': get_games_data(),
                                                       'hardware': get_hardware_data()})

        self.__games_data = get_games_data()
        self.__hardware_data = get_hardware_data()
        
        self.__user_id = "user"

        interactor_factory = Mock(factory.InteractorFactory)
        interactor_factory.create = Mock(return_value=self.__interactor)

        self.__target = geh.GetExportHandler(interactor_factory, None)

        self.__session = Mock(sess.Session)
        self.__session.get_value = Mock(return_value=self.__user_id)

        self.__target.session = self.__session
Ejemplo n.º 22
0
 def testGet_namespaceClass(self):
     view = Mock()
     view.find = Mock()
     view.substr = Mock(side_effect=['namespace test1\\test2;','class test3'])
     window = Mock()
     window.active_view = Mock(return_value=view)
     assert get_namespace(window) == 'test1\\test2\\test3'
Ejemplo n.º 23
0
        def test_conflict_SSLContext_with_ws_url(self):
            '''
            ApplicationRunner must raise an exception if given an ssl value that is
            an instance of SSLContext, but only a "ws:" URL.
            '''
            import ssl
            try:
                # Try to create an SSLContext, to be as rigorous as we can be
                # by avoiding making assumptions about the ApplicationRunner
                # implementation. If we happen to be on a Python that has no
                # SSLContext, we pass ssl=True, which will simply cause this
                # test to degenerate to the behavior of
                # test_conflict_SSL_True_with_ws_url (above). In fact, at the
                # moment (2015-05-10), none of this matters because the
                # ApplicationRunner implementation does not check to require
                # that its ssl argument is either a bool or an SSLContext. But
                # that may change, so we should be careful.
                ssl.create_default_context
            except AttributeError:
                context = True
            else:
                context = ssl.create_default_context()

            loop = Mock()
            loop.run_until_complete = Mock(return_value=(Mock(), Mock()))
            with patch.object(asyncio, 'get_event_loop', return_value=loop):
                runner = ApplicationRunner(u'ws://127.0.0.1:8080/wss', u'realm',
                                           ssl=context)
                error = ('^ssl argument value passed to ApplicationRunner '
                         'conflicts with the "ws:" prefix of the url '
                         'argument\. Did you mean to use "wss:"\?$')
                self._assertRaisesRegex(Exception, error, runner.run, '_unused_')
    def test_data_route_match(self):
        endpoint = Mock(return_value="cats")

        f = self.app
        f.debug = True

        route = {
            "product": {
                (("year", None), ("location", "department")): {
                    "name": "department_product_year",
                    "action": endpoint
                },
            },
            "year": {
            }
        }

        routing.add_routes(f, route)

        factories.Location(level="department", id=2)
        db.session.commit()

        with f.test_client() as c:
            response = c.get("/product?location=2&year=2007")
            assert response.status_code == 200
            assert response.data == b"cats"
            endpoint.assert_called_with(location=2, year=2007)
Ejemplo n.º 25
0
    def test_input_text_callback(self):
        """An input text runs callback with the result as argument"""
        callback_fn = Mock()
        inter = InputText("Content", callback_fn)
        inter.run_callback("Foo Bar Baz")

        callback_fn.assert_called_once_with("Foo Bar Baz")
Ejemplo n.º 26
0
    def test_valid_both_no_reverse_links(self):
        """Verify an item can be checked against both (no reverse links)."""

        def mock_iter(self):  # pylint: disable=W0613
            """Mock Tree.__iter__ to yield a mock Document."""
            mock_document = Mock()
            mock_document.parent = 'RQ'

            def mock_iter2(self):  # pylint: disable=W0613
                """Mock Document.__iter__ to yield a mock Item."""
                mock_item = Mock()
                mock_item.id = 'TST001'
                mock_item.links = []
                yield mock_item

            mock_document.__iter__ = mock_iter2
            yield mock_document

        self.item.add_link('fake1')

        mock_document = Mock()
        mock_document.prefix = 'RQ'

        mock_tree = Mock()
        mock_tree.__iter__ = mock_iter
        mock_tree.find_item = lambda identifier: Mock(id='fake1')

        self.assertTrue(self.item.valid(document=mock_document,
                                        tree=mock_tree))
Ejemplo n.º 27
0
def test_calling_main(start_mock, monkeypatch):
    from bigchaindb.commands.bigchaindb import main

    argparser_mock = Mock()
    parser = Mock()
    subparsers = Mock()
    subsubparsers = Mock()
    subparsers.add_parser.return_value = subsubparsers
    parser.add_subparsers.return_value = subparsers
    argparser_mock.return_value = parser
    monkeypatch.setattr('argparse.ArgumentParser', argparser_mock)
    main()

    assert argparser_mock.called is True
    parser.add_subparsers.assert_called_with(title='Commands',
                                             dest='command')
    subparsers.add_parser.assert_any_call('configure',
                                          help='Prepare the config file.')
    subparsers.add_parser.assert_any_call('show-config',
                                          help='Show the current '
                                          'configuration')
    subparsers.add_parser.assert_any_call('init', help='Init the database')
    subparsers.add_parser.assert_any_call('drop', help='Drop the database')

    subparsers.add_parser.assert_any_call('start', help='Start BigchainDB')

    assert start_mock.called is True
Ejemplo n.º 28
0
def test_build_create():
    population_class = Mock()
    create_function = common.build_create(population_class)
    assert isfunction(create_function)

    p = create_function("cell class", "cell params", n=999)
    population_class.assert_called_with(999, "cell class", cellparams="cell params")
Ejemplo n.º 29
0
    def test_find_rlinks(self):
        """Verify an item's reverse links can be found."""

        mock_document_p = Mock()
        mock_document_p.prefix = 'RQ'

        mock_document_c = Mock()
        mock_document_c.parent = 'RQ'

        mock_item = Mock()
        mock_item.id = 'TST001'
        mock_item.links = ['RQ001']

        def mock_iter(self):  # pylint: disable=W0613
            """Mock Tree.__iter__ to yield a mock Document."""

            def mock_iter2(self):  # pylint: disable=W0613
                """Mock Document.__iter__ to yield a mock Item."""
                yield mock_item

            mock_document_c.__iter__ = mock_iter2
            yield mock_document_c

        self.item.add_link('fake1')
        mock_tree = Mock()
        mock_tree.__iter__ = mock_iter
        mock_tree.find_item = lambda identifier: Mock(id='fake1')
        rlinks, childrem = self.item.find_rlinks(mock_document_p, mock_tree)
        self.assertEqual(['TST001'], rlinks)
        self.assertEqual([mock_document_c], childrem)
Ejemplo n.º 30
0
 def testGet_namespaceInterface(self):
     view = Mock()
     view.find = Mock()
     view.substr = Mock(side_effect=['namespace test1\\test2\\test3;','interface test4'])
     window = Mock()
     window.active_view = Mock(return_value=view)
     assert get_namespace(window) == 'test1\\test2\\test3\\test4'
Ejemplo n.º 31
0
    def test_any_and_datetime(self):
        mock = Mock()
        mock(datetime.now(), foo=datetime.now())

        mock.assert_called_with(ANY, foo=ANY)
Ejemplo n.º 32
0
    'matplotlib.pyplot', 'matplotlib.ticker', 'mpl_toolkits',
    'mpl_toolkits.axes_grid1', 'numpy', 'numpy.ma', 'lems', 'lems.api',
    'brian2', 'brian2.core', 'brian2.core.magic', 'brian2.core.namespace',
    'brian2.core.network', 'brian2.core.variables', 'brian2.devices',
    'brian2.devices.device', 'brian2.equations', 'brian2.equations.equations',
    'brian2.groups', 'brian2.groups.neurongroup', 'brian2.input',
    'brian2.input.poissoninput', 'brian2.monitors',
    'brian2.monitors.statemonitor', 'brian2.monitors.spikemonitor',
    'brian2.parsing', 'brian2.parsing.rendering', 'brian2.spatialneuron',
    'brian2.spatialneuron.morphology', 'brian2.spatialneuron.spatialneuron',
    'brian2.synapses', 'brian2.synapses.synapses', 'brian2.units',
    'brian2.units.allunits', 'brian2.units.fundamentalunits',
    'brian2.units.stdunits', 'brian2.utils', 'brian2.utils.logger',
    'brian2.utils.stringtools'
]
sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES)
sys.modules['brian2.units.allunits'].all_units = MagicMock()
sys.modules['brian2.devices.device'].all_devices = MagicMock()

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
import brian2tools
version = brian2tools.__version__
if version is None:
    try:
        from setuptools_scm import get_version
        version = get_version(relative_to=brian2tools_dir)
    except ImportError:
        pass
Ejemplo n.º 33
0
def ecommerce_bridge_client(mock_connection):
    client = ecommerce_bridge.EcommerceBridgeClient(disable_auth=True)
    client.options["connection_type"] = Mock(return_value=mock_connection)
    return client
Ejemplo n.º 34
0
 def test_write_inactive_configuration_to_storage(self):
     storage = Mock()
     configuration_set = Mock()
     configuration_helper = ConfigurationHelper(storage, inactive_configuration=configuration_set)
     configuration_helper.write_inactive_configuration_to_storage()
     configuration_set.store.assert_called_once_with()
Ejemplo n.º 35
0
 def test_get_tag_by_label(self):
     storage = Mock()
     configuration_helper = ConfigurationHelper(storage)
     configuration_helper.get_tag_by_label('online')
     storage.load_data.assert_called_once_with(['labels', 'online'])
Ejemplo n.º 36
0
def core():
    c = Mock()
    c.executable = "/tmp/test/tahoe.exe"
    gateway = Mock()
    gateway.name = "TestGrid"
    gateway.newscap = "URI:NEWSCAP"
    storage_settings = OrderedDict()  # Because python3.5
    storage_settings["v0-22222"] = {
        "anonymous-storage-FURL": "pb://[email protected]:1234/5555"
    }
    storage_settings["v0-66666"] = {
        "anonymous-storage-FURL": "pb://[email protected]:1234/9999"
    }
    gateway.get_settings = Mock(
        return_value={
            "rootcap": "URI:000:111",
            "introducer": "pb://[email protected]:12345/ccc",
            "storage": storage_settings,
        }
    )
    gateway.magic_folders = OrderedDict()  # Because python3.5
    gateway.magic_folders["TestFolder"] = {
        "collective_dircap": "URI:aaa:bbb",
        "upload_dircap": "URI:ccc:ddd",
        "admin_dircap": "URI:eee:fff",
        "directory": "/tmp/test/TestFolder",
        "member": "Alice",
    }
    gateway.magic_folders["CatPics"] = {
        "collective_dircap": "URI:ggg:hhh",
        "upload_dircap": "URI:iii:jjj",
        "admin_dircap": "URI:kkk:lll",
        "directory": "/tmp/test/CatPics",
        "member": "Bob",
    }
    c.gui.main_window.gateways = [gateway]
    return c
Ejemplo n.º 37
0
    def prepare(self, reactor, clock, hs):
        mock_notifier = hs.get_notifier()
        self.on_new_event = mock_notifier.on_new_event

        self.handler = hs.get_typing_handler()

        self.event_source = hs.get_event_sources().sources["typing"]

        self.datastore = hs.get_datastore()
        retry_timings_res = {
            "destination": "",
            "retry_last_ts": 0,
            "retry_interval": 0,
            "failure_ts": None,
        }
        self.datastore.get_destination_retry_timings = Mock(
            return_value=defer.succeed(retry_timings_res))

        self.datastore.get_device_updates_by_remote = Mock(
            return_value=make_awaitable((0, [])))

        self.datastore.get_destination_last_successful_stream_ordering = Mock(
            return_value=make_awaitable(None))

        def get_received_txn_response(*args):
            return defer.succeed(None)

        self.datastore.get_received_txn_response = get_received_txn_response

        self.room_members = []

        async def check_user_in_room(room_id, user_id):
            if user_id not in [u.to_string() for u in self.room_members]:
                raise AuthError(401, "User is not in the room")
            return None

        hs.get_auth().check_user_in_room = check_user_in_room

        def get_joined_hosts_for_room(room_id):
            return {member.domain for member in self.room_members}

        self.datastore.get_joined_hosts_for_room = get_joined_hosts_for_room

        async def get_users_in_room(room_id):
            return {str(u) for u in self.room_members}

        self.datastore.get_users_in_room = get_users_in_room

        self.datastore.get_user_directory_stream_pos = Mock(side_effect=(
            # we deliberately return a non-None stream pos to avoid doing an initial_spam
            lambda: make_awaitable(1)))

        self.datastore.get_current_state_deltas = Mock(return_value=(0, None))

        self.datastore.get_to_device_stream_token = lambda: 0
        self.datastore.get_new_device_msgs_for_remote = (
            lambda *args, **kargs: make_awaitable(([], 0)))
        self.datastore.delete_device_msgs_for_remote = (
            lambda *args, **kargs: make_awaitable(None))
        self.datastore.set_received_txn_response = (
            lambda *args, **kwargs: make_awaitable(None))
Ejemplo n.º 38
0
 def test_golden_2(self):
     self.device = Mock(**self.golden_output_2)
     obj = ShowVtpPassword(device=self.device)
     parsed_output_2 = obj.parse()
     self.maxDiff = None
     self.assertEqual(parsed_output_2, self.golden_parsed_output_2)
Ejemplo n.º 39
0
 def test_golden_5(self):
     self.device = Mock(**self.golden_output_5)
     obj = ShowVtpStatus(device=self.device)
     parsed_output = obj.parse()
     self.maxDiff = None
     self.assertEqual(parsed_output, self.golden_parsed_output_5)
Ejemplo n.º 40
0
def test_get_country_by_ip(ip_data, expected_country, monkeypatch):
    monkeypatch.setattr('saleor.core.utils.georeader.get',
                        Mock(return_value=ip_data))
    country = get_country_by_ip('127.0.0.1')
    assert country == expected_country
Ejemplo n.º 41
0
    def test_action(self):
        # the harness doesn't (yet!) help much with actions themselves
        action_event = Mock(params={"fail": ""})
        self.harness.charm._on_fortune_action(action_event)

        self.assertTrue(action_event.set_results.called)
Ejemplo n.º 42
0
 def test_empty(self):
     self.device1 = Mock(**self.empty_output)
     obj = ShowVtpPassword(device=self.device1)
     with self.assertRaises(SchemaEmptyParserError):
         parsed_output = obj.parse()
Ejemplo n.º 43
0
expected_distance = 126
expected_geometry = [
    [34.5, 12.11],
    [34.6, 12.12],
    [34.7, 12.13],
    [34.8, 12.14],
]  # lon, lat
expected_date = datetime(2019, 1, 1, 1, 0)
expected_calc_time = 0.12
expected_test_name = "mytaxi-berlin-1"
expected_test_name_2 = "mytaxi-berlin-2"
expected_route_plan = {
    "name": expected_test_name,
    "waypoints": [[1.5, 0.11], [-112.11, 34.5]],
}
expected_route_plan_mock = Mock()
expected_route_plan_name = PropertyMock(return_value=expected_route_plan["name"])
expected_route_plan_mock.name = expected_route_plan_name

expected_route_plan_2 = {
    "name": expected_test_name_2,
    "waypoints": [[3.5, 1.11], [112.11, 35.5]],
}
expected_provider = {
    "name": "mapbox",
    "api": "mapbox",
    "type": "router",
    "params": {"vehicle": "car", "strategy": "fastest", "endpoint": "routing.mapbox.car"},
}
expected_provider_google = {
    "name": "google",
Ejemplo n.º 44
0
    def test_action_fail(self):
        action_event = Mock(params={"fail": "fail this"})
        self.harness.charm._on_fortune_action(action_event)

        self.assertEqual(action_event.fail.call_args, [("fail this", )])
 def __init__(self):
     self.setString = StrictMock()
     self.getString = Mock(return_value='')
Ejemplo n.º 46
0
def test_decode_calls_unknown_handler_on_bad_command_or_not_implemented():
    mock_unknown_handler = Mock()
    add_message_handler('unknown', mock_unknown_handler)
    message_decode('08XXtest28')
    mock_unknown_handler.assert_called_once_with(msg_code='XX', data='test')
 def test_wait_for_job_cloud_stack_exception(self):
     self.cs_instance.queryAsyncJobResult.side_effect = CloudStackException(
         response=Mock())
     self.assertRaises(CloudStackException, self.co.wait_for_job, 'job')
Ejemplo n.º 48
0
class TestTree(unittest.TestCase):

    """Unit tests for the Tree class."""

    def setUp(self):
        document = Document(SYS)
        self.tree = Tree(document)
        document.tree = self.tree
        document = Document(FILES)
        self.tree._place(document)  # pylint: disable=W0212
        document.tree = self.tree
        self.tree._vcs = Mock()  # pylint: disable=W0212

    @patch('doorstop.core.vcs.find_root', Mock(return_value=EMPTY))
    def test_palce_empty(self):
        """Verify a document can be placed in an empty tree."""
        tree = build(EMPTY)
        doc = MockDocumentSkip.new(tree,
                                   os.path.join(EMPTY, 'temp'), EMPTY, 'TEMP')
        tree._place(doc)  # pylint: disable=W0212
        self.assertEqual(1, len(tree))

    @patch('doorstop.core.vcs.find_root', Mock(return_value=EMPTY))
    def test_palce_empty_no_parent(self):
        """Verify a document with parent cannot be placed in an empty tree."""
        tree = build(EMPTY)
        doc = MockDocumentSkip.new(tree,
                                   os.path.join(EMPTY, 'temp'), EMPTY, 'TEMP',
                                   parent='REQ')
        self.assertRaises(DoorstopError, tree._place, doc)  # pylint: disable=W0212

    def test_documents(self):
        """Verify the documents in a tree can be accessed."""
        documents = self.tree.documents
        self.assertEqual(2, len(documents))
        for document in self.tree:
            logging.debug("document: {}".format(document))
            self.assertIs(self.tree, document.tree)

    @patch('doorstop.core.document.Document.get_issues')
    def test_validate(self, mock_get_issues):
        """Verify trees can be checked."""
        logging.info("tree: {}".format(self.tree))
        self.assertTrue(self.tree.validate())
        self.assertEqual(2, mock_get_issues.call_count)

    def test_validate_no_documents(self):
        """Verify an empty tree can be checked."""
        tree = Tree(None, root='.')
        self.assertTrue(tree.validate())

    @patch('doorstop.settings.REORDER', False)
    @patch('doorstop.core.document.Document.get_issues',
           Mock(return_value=[DoorstopError('error'),
                              DoorstopWarning('warning'),
                              DoorstopInfo('info')]))
    def test_validate_document(self):
        """Verify a document error fails the tree validation."""
        self.assertFalse(self.tree.validate())

    @patch('doorstop.core.document.Document.get_issues', Mock(return_value=[]))
    def test_validate_hook(self):
        """Verify a document hook can be called."""
        mock_hook = MagicMock()
        self.tree.validate(document_hook=mock_hook)
        self.assertEqual(2, mock_hook.call_count)

    @patch('doorstop.core.tree.Tree.get_issues', Mock(return_value=[]))
    def test_issues(self):
        """Verify an tree's issues convenience property can be accessed."""
        self.assertEqual(0, len(self.tree.issues))

    def test_get_traceability(self):
        """Verify traceability rows are correct."""
        rows = [
            (self.tree.find_item('SYS001'), self.tree.find_item('REQ001')),
            (self.tree.find_item('SYS002'), self.tree.find_item('REQ001')),
            (None, self.tree.find_item('REQ002')),
            (None, self.tree.find_item('REQ004')),
        ]
        # Act
        rows2 = self.tree.get_traceability()
        # Assert
        self.maxDiff = None
        self.assertListEqual(rows, rows2)

    def test_new_document(self):
        """Verify a new document can be created on a tree."""
        self.tree.create_document(EMPTY, '_TEST', parent='REQ')

    def test_new_document_unknown_parent(self):
        """Verify an exception is raised for an unknown parent."""
        temp = tempfile.mkdtemp()
        self.assertRaises(DoorstopError, self.tree.create_document,
                          temp, '_TEST', parent='UNKNOWN')
        self.assertFalse(os.path.exists(temp))

    @patch('doorstop.core.document.Document.add_item')
    def test_add_item(self, mock_add_item):
        """Verify an item can be added to a document."""
        self.tree.add_item('REQ')
        mock_add_item.assert_called_once_with(number=None, level=None,
                                              reorder=True)

    @patch('doorstop.core.document.Document.add_item')
    def test_add_item_level(self, mock_add):
        """Verify an item can be added to a document with a level."""
        self.tree.add_item('REQ', level='1.2.3')
        mock_add.assert_called_once_with(number=None, level='1.2.3',
                                         reorder=True)

    def test_add_item_unknown_prefix(self):
        """Verify an exception is raised for an unknown prefix (item)."""
        # Cache miss
        self.assertRaises(DoorstopError, self.tree.add_item, 'UNKNOWN')
        # Cache hit
        self.assertRaises(DoorstopError, self.tree.add_item, 'UNKNOWN')

    @patch('doorstop.settings.REORDER', False)
    @patch('doorstop.core.item.Item.delete')
    def test_remove_item(self, mock_delete):
        """Verify an item can be removed from a document."""
        self.tree.remove_item('req1', reorder=False)
        mock_delete.assert_called_once_with()

    def test_remove_item_unknown_item(self):
        """Verify an exception is raised removing an unknown item."""
        self.assertRaises(DoorstopError, self.tree.remove_item, 'req9999')

    @patch('doorstop.core.item.Item.link')
    def test_link_items(self, mock_link):
        """Verify two items can be linked."""
        self.tree.link_items('req1', 'req2')
        mock_link.assert_called_once_with('REQ002')

    def test_link_items_unknown_child_prefix(self):
        """Verify an exception is raised with an unknown child prefix."""
        self.assertRaises(DoorstopError,
                          self.tree.link_items, 'unknown1', 'req2')

    def test_link_items_unknown_child_number(self):
        """Verify an exception is raised with an unknown child number."""
        self.assertRaises(DoorstopError,
                          self.tree.link_items, 'req9999', 'req2')

    def test_link_items_unknown_parent_prefix(self):
        """Verify an exception is raised with an unknown parent prefix."""
        self.assertRaises(DoorstopError,
                          self.tree.link_items, 'req1', 'unknown1')

    def test_link_items_unknown_parent_number(self):
        """Verify an exception is raised with an unknown parent prefix."""
        self.assertRaises(DoorstopError,
                          self.tree.link_items, 'req1', 'req9999')

    @patch('doorstop.core.item.Item.unlink')
    def test_unlink_items(self, mock_unlink):
        """Verify two items can be unlinked."""
        self.tree.unlink_items('req3', 'req1')
        mock_unlink.assert_called_once_with('REQ001')

    def test_unlink_items_unknown_child_prefix(self):
        """Verify an exception is raised with an unknown child prefix."""
        self.assertRaises(DoorstopError,
                          self.tree.unlink_items, 'unknown1', 'req1')

    def test_unlink_items_unknown_child_number(self):
        """Verify an exception is raised with an unknown child number."""
        self.assertRaises(DoorstopError,
                          self.tree.unlink_items, 'req9999', 'req1')

    def test_unlink_items_unknown_parent_prefix(self):
        """Verify an exception is raised with an unknown parent prefix."""
        # Cache miss
        self.assertRaises(DoorstopError,
                          self.tree.unlink_items, 'req3', 'unknown1')
        # Cache hit
        self.assertRaises(DoorstopError,
                          self.tree.unlink_items, 'req3', 'unknown1')

    def test_unlink_items_unknown_parent_number(self):
        """Verify an exception is raised with an unknown parent prefix."""
        self.assertRaises(DoorstopError,
                          self.tree.unlink_items, 'req3', 'req9999')

    @patch('doorstop.core.editor.launch')
    def test_edit_item(self, mock_launch):
        """Verify an item can be edited in a tree."""
        self.tree.edit_item('req2', launch=True)
        path = os.path.join(FILES, 'REQ002.yml')
        mock_launch.assert_called_once_with(path, tool=None)

    def test_edit_item_unknown_prefix(self):
        """Verify an exception is raised for an unknown prefix (document)."""
        self.assertRaises(DoorstopError, self.tree.edit_item, 'unknown1')

    def test_edit_item_unknown_number(self):
        """Verify an exception is raised for an unknown number."""
        self.assertRaises(DoorstopError, self.tree.edit_item, 'req9999')

    def test_find_item(self):
        """Verify an item can be found by exact UID."""
        # Cache miss
        item = self.tree.find_item('req2-001')
        self.assertIsNot(None, item)
        # Cache hit
        item2 = self.tree.find_item('req2-001')
        self.assertIs(item2, item)

    def test_find_document(self):
        """Verify an document can be found by prefix"""
        # Cache miss
        document = self.tree.find_document('req')
        self.assertIsNot(None, document)
        # Cache hit
        document2 = self.tree.find_document('req')
        self.assertIs(document2, document)

    def test_load(self):
        """Verify an a tree can be reloaded."""
        self.tree.load()
        self.tree.load()  # should return immediately

    @patch('doorstop.core.document.Document.delete')
    def test_delete(self, mock_delete):
        """Verify a tree can be deleted."""
        self.tree.delete()
        self.assertEqual(0, len(self.tree))
        self.assertEqual(2, mock_delete.call_count)
        self.tree.delete()  # ensure a second delete is ignored
Ejemplo n.º 49
0
    # 'numpy',
    'pandas',
    'scipy',
    'scipy.interpolate',
    'scipy.linalg',
    'scipy.sparse',
    'scipy.sparse.linalg',
    'scipy.ndimage',
    'scipy.ndimage.interpolation',
    'scipy.signal',
    'scipy.stats',
    'sklearn',
    'sklearn.cluster',
]
for mod_name in MOCK_MODULES:
    sys.modules[mod_name] = Mock()


# -- Project information -----------------------------------------------------

project = 'cooltools'
copyright = '2020, cooltoolers'
author = 'cooltoolers'


# -- General configuration ---------------------------------------------------

# Apparently readthedocs looks for contents.rst by default if this isn't set.
master_doc = 'index'

# Add any paths that contain templates here, relative to this directory.
        self.interface_list = [
            'Direct', 'Indirect', 'Muon', 'Reflectometry', 'SANS'
        ]


algorithm_and_states = {
    'Arithmetic': False,
    'Arithmetic\\Errors': True,
    'Arithmetic\\FFT': False,
    'ISIS': False,
    'Workflow': True,
    'Workflow\\Diffraction\\DataHandling': True,
    'Workflow\\Diffraction': True
}

mock_get_category_and_state = Mock(return_value=algorithm_and_states)


@start_qapplication
class CategoriesSettingsTest(unittest.TestCase):
    CONFIG_SERVICE_CLASSPATH = "workbench.widgets.settings.categories.presenter.ConfigService"

    @patch.object(AlgorithmFactoryImpl, 'getCategoriesandState',
                  mock_get_category_and_state)
    def test_algorithm_state_correct_when_created(self):
        mock_view = MockCategoriesView()
        CategoriesSettings(None, mock_view)
        for category, state in algorithm_and_states.items():
            if "\\" in category:
                expected_calls = [
                    call(mock_view.algorithm_tree_widget,
Ejemplo n.º 51
0
 def __init__(self):
     super(MainWindowMock, self).__init__(None)
     self.statusbar = Mock()
     self.console = Mock()
    def test_get_all_vms(self):
        self.co._cs_get_all_results = Mock()

        self.co.get_all_vms()
        self.assertDictEqual({'listall': True},
                             self.co._cs_get_all_results.call_args[0][1])
Ejemplo n.º 53
0
 def test_golden_non_default_vrf(self):
     self.device = Mock(**self.golden_output_1)
     obj = ShowIpv6MldSsmMap(device=self.device)
     parsed_output = obj.parse(vrf='VRF1', group='ff35:1::1')
     self.assertEqual(parsed_output, self.golden_parsed_output_1)
Ejemplo n.º 54
0
 def setup_mock_fit_browser(self, workspace_creator, workspace_name, function, function_prefix):
     workspace_creator(workspace_name)
     self.fit_browser.workspaceName = Mock(return_value=workspace_name)
     self.fit_browser.currentHandler.return_value = self.create_mock_handler(function, function_prefix)
Ejemplo n.º 55
0
 def test_golden_non_default_vrf(self):
     self.device = Mock(**self.golden_output_1)
     obj = ShowIpv6MldGroupsDetail(device=self.device)
     parsed_output = obj.parse(vrf='VRF1')
     self.assertEqual(parsed_output, self.golden_parsed_output_1)
class TestProblemTypeAccess(SharedModuleStoreTestCase, MasqueradeMixin):

    PROBLEM_TYPES = [
        'problem', 'openassessment', 'drag-and-drop-v2', 'done', 'edx_sga'
    ]
    # 'html' is a component that just displays html, in these tests it is used to test that users who do not have access
    # to graded problems still have access to non-problems
    COMPONENT_TYPES = PROBLEM_TYPES + ['html']
    MODE_TYPES = [
        'credit', 'honor', 'audit', 'verified', 'professional',
        'no-id-professional'
    ]

    GRADED_SCORE_WEIGHT_TEST_CASES = [
        # graded, has_score, weight, is_gated
        (False, False, 0, False),
        (False, True, 0, False),
        (False, False, 1, False),
        (False, True, 1, False),
        (True, False, 0, False),
        (True, True, 0, False),
        (True, False, 1, False),
        (True, True, 1, True)
    ]

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.factory = RequestFactory()

        cls.courses = {}

        # default course is used for most tests, it includes an audit and verified track and all the problem types
        # defined in 'PROBLEM_TYPES' and 'GRADED_SCORE_WEIGHT_TEST_CASES'
        cls.courses['default'] = cls._create_course(
            run='testcourse1',
            display_name='Test Course Title',
            modes=['audit', 'verified'],
            component_types=cls.COMPONENT_TYPES)
        # because default course is used for most tests self.course and self.problem_dict are set for ease of reference
        cls.course = cls.courses['default']['course']
        cls.blocks_dict = cls.courses['default']['blocks']

        # Create components with the cartesian product of possible values of
        # graded/has_score/weight for the test_graded_score_weight_values test.
        cls.graded_score_weight_blocks = {}
        for graded, has_score, weight, gated in cls.GRADED_SCORE_WEIGHT_TEST_CASES:
            case_name = ' Graded: ' + str(graded) + ' Has Score: ' + str(
                has_score) + ' Weight: ' + str(weight)
            block = ItemFactory.create(
                parent=cls.blocks_dict['vertical'],
                # has_score is determined by XBlock type. It is not a value set on an instance of an XBlock.
                # Therefore, we create a problem component when has_score is True
                # and an html component when has_score is False.
                category='problem' if has_score else 'html',
                graded=graded,
                weight=weight,
                metadata=METADATA if (graded and has_score and weight) else {},
            )
            # Intersperse HTML so that the content-gating renders in all blocks
            ItemFactory.create(
                parent=cls.blocks_dict['vertical'],
                category='html',
                graded=False,
            )
            cls.graded_score_weight_blocks[(graded, has_score, weight)] = block

        host = os.environ.get('BOK_CHOY_HOSTNAME', '127.0.0.1')
        metadata_lti_xblock = {
            'lti_id':
            'correct_lti_id',
            'launch_url':
            'http://{}:{}/{}'.format(host, '8765', 'correct_lti_endpoint'),
            'open_in_a_new_page':
            False
        }

        scored_lti_metadata = {}
        scored_lti_metadata.update(metadata_lti_xblock)
        scored_lti_metadata.update(METADATA)

        # add LTI blocks to default course
        cls.blocks_dict['lti_block'] = ItemFactory.create(
            parent=cls.blocks_dict['vertical'],
            category='lti_consumer',
            has_score=True,
            graded=True,
            metadata=scored_lti_metadata,
        )
        # Intersperse HTML so that the content-gating renders in all blocks
        ItemFactory.create(
            parent=cls.blocks_dict['vertical'],
            category='html',
            graded=False,
        )
        cls.blocks_dict['lti_block_not_scored'] = ItemFactory.create(
            parent=cls.blocks_dict['vertical'],
            category='lti_consumer',
            has_score=False,
            metadata=metadata_lti_xblock,
        )

        # Intersperse HTML so that the content-gating renders in all blocks
        ItemFactory.create(
            parent=cls.blocks_dict['vertical'],
            category='html',
            graded=False,
        )

        # add ungraded problem for xblock_handler test
        cls.blocks_dict['graded_problem'] = ItemFactory.create(
            parent=cls.blocks_dict['vertical'],
            category='problem',
            graded=True,
            metadata=METADATA,
        )

        # Intersperse HTML so that the content-gating renders in all blocks
        ItemFactory.create(
            parent=cls.blocks_dict['vertical'],
            category='html',
            graded=False,
        )

        cls.blocks_dict['ungraded_problem'] = ItemFactory.create(
            parent=cls.blocks_dict['vertical'],
            category='problem',
            graded=False,
        )

        # Intersperse HTML so that the content-gating renders in all blocks
        ItemFactory.create(
            parent=cls.blocks_dict['vertical'],
            category='html',
            graded=False,
        )

        cls.blocks_dict['audit_visible_graded_problem'] = ItemFactory.create(
            parent=cls.blocks_dict['vertical'],
            category='problem',
            graded=True,
            group_access={
                CONTENT_GATING_PARTITION_ID: [
                    CONTENT_TYPE_GATE_GROUP_IDS['limited_access'],
                    CONTENT_TYPE_GATE_GROUP_IDS['full_access']
                ]
            },
        )

        # Intersperse HTML so that the content-gating renders in all blocks
        ItemFactory.create(
            parent=cls.blocks_dict['vertical'],
            category='html',
            graded=False,
        )

        # audit_only course only has an audit track available
        cls.courses['audit_only'] = cls._create_course(
            run='audit_only_course_run_1',
            display_name='Audit Only Test Course Title',
            modes=['audit'],
            component_types=['problem', 'html'])

        # all_track_types course has all track types defined in MODE_TYPES
        cls.courses['all_track_types'] = cls._create_course(
            run='all_track_types_run_1',
            display_name='All Track/Mode Types Test Course Title',
            modes=cls.MODE_TYPES,
            component_types=['problem', 'html'])

        cls.courses['expired_upgrade_deadline'] = cls._create_course(
            run='expired_upgrade_deadline_run_1',
            display_name='Expired Upgrade Deadline Course Title',
            modes=['audit', 'verified'],
            component_types=['problem', 'html'],
            expired_upgrade_deadline=True)

    def setUp(self):
        super().setUp()

        # enroll all users into the all track types course
        self.users = {}
        for mode_type in self.MODE_TYPES:
            self.users[mode_type] = UserFactory.create(username=mode_type)
            CourseEnrollmentFactory.create(
                user=self.users[mode_type],
                course_id=self.courses['all_track_types']['course'].id,
                mode=mode_type)

        # create audit_user for ease of reference
        self.audit_user = self.users['audit']

        # enroll audit and verified users into default course
        for mode_type in ['audit', 'verified']:
            CourseEnrollmentFactory.create(user=self.users[mode_type],
                                           course_id=self.course.id,
                                           mode=mode_type)

        # enroll audit user into the audit_only course
        CourseEnrollmentFactory.create(
            user=self.audit_user,
            course_id=self.courses['audit_only']['course'].id,
            mode='audit')
        # enroll audit user into the upgrade expired course
        CourseEnrollmentFactory.create(
            user=self.audit_user,
            course_id=self.courses['expired_upgrade_deadline']['course'].id,
            mode='audit')
        ContentTypeGatingConfig.objects.create(enabled=True,
                                               enabled_as_of=datetime(
                                                   2018, 1, 1))

    @classmethod
    def _create_course(cls,
                       run,
                       display_name,
                       modes,
                       component_types,
                       expired_upgrade_deadline=False):
        """
        Helper method to create a course
        Arguments:
            run (str): name of course run
            display_name (str): display name of course
            modes (list of str): list of modes/tracks this course should have
            component_types (list of str): list of problem types this course should have
        Returns:
             (dict): {
                'course': (CourseBlockWithMixins): course definition
                'blocks': (dict) {
                    'block_category_1': XBlock representing that block,
                    'block_category_2': XBlock representing that block,
                    ....
             }
        """
        start_date = timezone.now() - timedelta(weeks=1)
        course = CourseFactory.create(run=run,
                                      display_name=display_name,
                                      start=start_date)

        for mode in modes:
            if expired_upgrade_deadline and mode == 'verified':
                CourseModeFactory.create(
                    course_id=course.id,
                    mode_slug=mode,
                    expiration_datetime=start_date + timedelta(days=365),
                )
            else:
                CourseModeFactory.create(course_id=course.id, mode_slug=mode)

        with cls.store.bulk_operations(course.id):
            blocks_dict = {}
            chapter = ItemFactory.create(
                parent=course,
                display_name='Overview',
            )
            blocks_dict['chapter'] = ItemFactory.create(
                parent=course,
                category='chapter',
                display_name='Week 1',
            )
            blocks_dict['sequential'] = ItemFactory.create(
                parent=chapter,
                category='sequential',
                display_name='Lesson 1',
            )
            blocks_dict['vertical'] = ItemFactory.create(
                parent=blocks_dict['sequential'],
                category='vertical',
                display_name='Lesson 1 Vertical - Unit 1',
            )

            for component_type in component_types:
                block = ItemFactory.create(parent=blocks_dict['vertical'],
                                           category=component_type,
                                           graded=True,
                                           metadata={} if
                                           (component_type == 'html'
                                            or len(modes) == 1) else METADATA)
                blocks_dict[component_type] = block
                # Intersperse HTML so that the content-gating renders in all blocks
                ItemFactory.create(
                    parent=blocks_dict['vertical'],
                    category='html',
                    graded=False,
                )

            return {
                'course': course,
                'blocks': blocks_dict,
            }

    @ddt.data(
        ('problem', True),
        ('openassessment', True),
        ('drag-and-drop-v2', True),
        ('done', True),
        ('edx_sga', True),
        ('lti_block', True),
        ('ungraded_problem', False),
        ('lti_block_not_scored', False),
        ('audit_visible_graded_problem', False),
    )
    @ddt.unpack
    def test_access_to_problems(self, prob_type, is_gated):
        _assert_block_is_gated(
            block=self.blocks_dict[prob_type],
            user=self.users['audit'],
            course=self.course,
            is_gated=is_gated,
            request_factory=self.factory,
        )
        _assert_block_is_gated(
            block=self.blocks_dict[prob_type],
            user=self.users['verified'],
            course=self.course,
            is_gated=False,
            request_factory=self.factory,
        )

    @ddt.data(*GRADED_SCORE_WEIGHT_TEST_CASES)
    @ddt.unpack
    def test_graded_score_weight_values(self, graded, has_score, weight,
                                        is_gated):
        # Verify that graded, has_score and weight must all be true for a component to be gated
        block = self.graded_score_weight_blocks[(graded, has_score, weight)]
        _assert_block_is_gated(
            block=block,
            user=self.audit_user,
            course=self.course,
            is_gated=is_gated,
            request_factory=self.factory,
        )

    @ddt.data(
        ('audit', 'problem', 'default', True),
        ('verified', 'problem', 'default', False),
        ('audit', 'html', 'default', False),
        ('verified', 'html', 'default', False),
        ('audit', 'problem', 'audit_only', False),
        ('audit', 'html', 'audit_only', False),
        ('credit', 'problem', 'all_track_types', False),
        ('credit', 'html', 'all_track_types', False),
        ('honor', 'problem', 'all_track_types', False),
        ('honor', 'html', 'all_track_types', False),
        ('audit', 'problem', 'all_track_types', True),
        ('audit', 'html', 'all_track_types', False),
        ('verified', 'problem', 'all_track_types', False),
        ('verified', 'html', 'all_track_types', False),
        ('professional', 'problem', 'all_track_types', False),
        ('professional', 'html', 'all_track_types', False),
        ('no-id-professional', 'problem', 'all_track_types', False),
        ('no-id-professional', 'html', 'all_track_types', False),
    )
    @ddt.unpack
    def test_access_based_on_track(self, user_track, component_type, course,
                                   is_gated):
        """
         If a user is enrolled as an audit user they should not have access to graded problems, unless there is no paid
         track option.  All paid type tracks should have access to all types of content.
         All users should have access to non-problem component types, the 'html' components test that.
         """
        _assert_block_is_gated(
            block=self.courses[course]['blocks'][component_type],
            user=self.users[user_track],
            course=self.courses[course]['course'],
            is_gated=is_gated,
            request_factory=self.factory,
        )

    def test_access_expired_upgrade_deadline(self):
        """
        If a user is enrolled as an audit user and the upgrade deadline has passed
        the user will continue to see gated content, but the upgrade messaging will be removed.
        """
        _assert_block_is_gated(
            block=self.courses['expired_upgrade_deadline']['blocks']
            ['problem'],
            user=self.users['audit'],
            course=self.courses['expired_upgrade_deadline']['course'],
            is_gated=True,
            request_factory=self.factory,
            has_upgrade_link=False)

    @ddt.data(
        ('problem', 'graded_problem', 'audit', 404),
        ('problem', 'graded_problem', 'verified', 200),
        ('problem', 'ungraded_problem', 'audit', 200),
        ('problem', 'ungraded_problem', 'verified', 200),
    )
    @ddt.unpack
    def test_xblock_handlers(self, xblock_type, xblock_name, user,
                             status_code):
        """
        Test the ajax calls to the problem xblock to ensure the LMS is sending back
        the expected response codes on requests when content is gated for audit users
        (404) and when it is available to audit users (200). Content is always available
        to verified users.
        """
        problem_location = self.blocks_dict[xblock_name].scope_ids.usage_id
        url = reverse('xblock_handler',
                      kwargs={
                          'course_id': str(self.course.id),
                          'usage_id': quote_slashes(str(problem_location)),
                          'handler': 'xmodule_handler',
                          'suffix': 'problem_show',
                      })
        self.client.login(username=self.users[user].username,
                          password=TEST_PASSWORD)
        response = self.client.post(url)
        assert response.status_code == status_code

    @ddt.data(
        InstructorFactory,
        StaffFactory,
        BetaTesterFactory,
        OrgStaffFactory,
        OrgInstructorFactory,
        GlobalStaffFactory,
    )
    def test_access_course_team_users(self, role_factory):
        """
        Test that members of the course team do not lose access to graded content
        """
        # There are two types of course team members: instructor and staff
        # they have different privileges, but for the purpose of this test the important thing is that they should both
        # have access to all graded content
        if role_factory == GlobalStaffFactory:
            user = role_factory.create()
        else:
            user = role_factory.create(course_key=self.course.id)

        CourseEnrollmentFactory.create(
            user=user,
            course_id=self.course.id,
            mode='audit',
        )

        # assert that course team members have access to graded content
        _assert_block_is_gated(
            block=self.blocks_dict['problem'],
            user=user,
            course=self.course,
            is_gated=False,
            request_factory=self.factory,
        )

    @ddt.data(FORUM_ROLE_COMMUNITY_TA, FORUM_ROLE_ADMINISTRATOR,
              FORUM_ROLE_MODERATOR, FORUM_ROLE_GROUP_MODERATOR)
    def test_access_user_with_forum_role(self, role_name):
        """
        Test that users with a given forum role do not lose access to graded content
        """
        user = UserFactory.create()
        role = RoleFactory(name=role_name, course_id=self.course.id)
        role.users.add(user)

        CourseEnrollmentFactory.create(
            user=user,
            course_id=self.course.id,
            mode='audit',
        )
        _assert_block_is_gated(
            block=self.blocks_dict['problem'],
            user=user,
            course=self.course,
            is_gated=False,
            request_factory=self.factory,
        )

    @ddt.data(
        (False, True),
        (True, False),
    )
    @ddt.unpack
    def test_content_gating_holdback(self, put_user_in_holdback, is_gated):
        """
        Test that putting a user in the content gating holdback disables content gating.
        """
        user = UserFactory.create()
        enrollment = CourseEnrollment.enroll(user, self.course.id)
        if put_user_in_holdback:
            FBEEnrollmentExclusion.objects.create(enrollment=enrollment)

        graded, has_score, weight = True, True, 1
        block = self.graded_score_weight_blocks[(graded, has_score, weight)]
        _assert_block_is_gated(
            block=block,
            user=user,
            course=self.course,
            is_gated=is_gated,
            request_factory=self.factory,
        )

    @ddt.data(
        ({
            'user_partition_id': CONTENT_GATING_PARTITION_ID,
            'group_id': CONTENT_TYPE_GATE_GROUP_IDS['limited_access']
        }, True),
        ({
            'user_partition_id': CONTENT_GATING_PARTITION_ID,
            'group_id': CONTENT_TYPE_GATE_GROUP_IDS['full_access']
        }, False),
        ({
            'user_partition_id': ENROLLMENT_TRACK_PARTITION_ID,
            'group_id': settings.COURSE_ENROLLMENT_MODES['audit']['id']
        }, True),
        ({
            'user_partition_id': ENROLLMENT_TRACK_PARTITION_ID,
            'group_id': settings.COURSE_ENROLLMENT_MODES['verified']['id']
        }, False),
        ({
            'role': 'staff'
        }, False),
        ({
            'role': 'student'
        }, True),
        ({
            'username': '******'
        }, True),
        ({
            'username': '******'
        }, False),
    )
    @ddt.unpack
    def test_masquerade(self, masquerade_config, is_gated):
        instructor = UserFactory.create()
        CourseEnrollmentFactory.create(user=instructor,
                                       course_id=self.course.id,
                                       mode='audit')
        CourseInstructorRole(self.course.id).add_users(instructor)
        self.client.login(username=instructor.username, password=TEST_PASSWORD)

        self.update_masquerade(**masquerade_config)

        block = self.blocks_dict['problem']
        block_view_url = reverse(
            'render_xblock',
            kwargs={'usage_key_string': str(block.scope_ids.usage_id)})
        response = self.client.get(block_view_url)
        if is_gated:
            assert response.status_code == 404
        else:
            assert response.status_code == 200

    @ddt.data(
        InstructorFactory,
        StaffFactory,
        BetaTesterFactory,
        OrgStaffFactory,
        OrgInstructorFactory,
        GlobalStaffFactory,
    )
    def test_access_masquerade_as_course_team_users(self, role_factory):
        """
        Test that when masquerading as members of the course team you do not lose access to graded content
        """
        # There are two types of course team members: instructor and staff
        # they have different privileges, but for the purpose of this test the important thing is that they should both
        # have access to all graded content
        staff_user = StaffFactory.create(password=TEST_PASSWORD,
                                         course_key=self.course.id)
        CourseEnrollmentFactory.create(user=staff_user,
                                       course_id=self.course.id,
                                       mode='audit')
        self.client.login(username=staff_user.username, password=TEST_PASSWORD)

        if role_factory == GlobalStaffFactory:
            user = role_factory.create()
        else:
            user = role_factory.create(course_key=self.course.id)
        CourseEnrollment.enroll(user, self.course.id)
        self.update_masquerade(username=user.username)

        block = self.blocks_dict['problem']
        block_view_url = reverse(
            'render_xblock',
            kwargs={'usage_key_string': str(block.scope_ids.usage_id)})
        response = self.client.get(block_view_url)
        assert response.status_code == 200

    @ddt.data(FORUM_ROLE_COMMUNITY_TA, FORUM_ROLE_ADMINISTRATOR,
              FORUM_ROLE_MODERATOR, FORUM_ROLE_GROUP_MODERATOR)
    def test_access_masquerade_as_user_with_forum_role(self, role_name):
        """
        Test that when masquerading as a user with a given forum role you do not lose access to graded content
        """
        staff_user = StaffFactory.create(password=TEST_PASSWORD,
                                         course_key=self.course.id)
        CourseEnrollmentFactory.create(user=staff_user,
                                       course_id=self.course.id,
                                       mode='audit')
        self.client.login(username=staff_user.username, password=TEST_PASSWORD)

        user = UserFactory.create()
        role = RoleFactory(name=role_name, course_id=self.course.id)
        role.users.add(user)

        CourseEnrollmentFactory.create(user=user,
                                       course_id=self.course.id,
                                       mode='audit')

        self.update_masquerade(username=user.username)

        _assert_block_is_gated(
            block=self.blocks_dict['problem'],
            user=user,
            course=self.course,
            is_gated=False,
            request_factory=self.factory,
        )

    @patch(
        'openedx.features.content_type_gating.partitions.format_strikeout_price',
        Mock(return_value=(HTML("<span>DISCOUNT_PRICE</span>"), True)))
    def test_discount_display(self):

        with patch.object(ContentTypeGatingPartition,
                          '_get_checkout_link',
                          return_value='#'):
            block_content = _get_content_from_lms_index(
                block=self.blocks_dict['problem'],
                user_id=self.audit_user.id,
                course=self.course,
                request_factory=self.factory,
            )

        assert '<span>DISCOUNT_PRICE</span>' in block_content
Ejemplo n.º 57
0
 def test_golden_default_vrf(self):
     self.device = Mock(**self.golden_output)
     obj = ShowIpv6MldInterface(device=self.device)
     parsed_output = obj.parse()
     self.assertEqual(parsed_output, self.golden_parsed_output)
Ejemplo n.º 58
0
 def test_empty(self):
     self.device = Mock(**self.empty_output)
     obj = ShowIpv6MldSsmMap(device=self.device)
     with self.assertRaises(SchemaEmptyParserError):
         parsed_output = obj.parse(group='ff35:1::1')
Ejemplo n.º 59
0
 def inner(component_class: Type[GraphComponent], fn_name: Text) -> Mock:
     mock = Mock(wraps=getattr(component_class, fn_name))
     monkeypatch.setattr(component_class, fn_name, mock)
     return mock
Ejemplo n.º 60
0
 def test_empty(self):
     self.device = Mock(**self.empty_output)
     obj = ShowIpv6MldGroupsDetail(device=self.device)
     with self.assertRaises(SchemaEmptyParserError):
         parsed_output = obj.parse()