Python mock.MagicMock() Examples

The following are 30 code examples of mock.MagicMock(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module mock , or try the search function .
Example #1
Source File: profiles_test.py    From macops with Apache License 2.0 7 votes vote down vote up
def testAddMachineCertificateInvalidKey(self, mock_certificate, mock_pkcs12,
                                          mock_loadcert, mock_loadkey):
    mock_certobj = mock.MagicMock()
    mock_certobj.subject_cn = 'My Cert Subject'
    mock_certobj.osx_fingerprint = '0011223344556677889900'
    mock_certificate.return_value = mock_certobj

    mock_pkcs12obj = mock.MagicMock()
    mock_pkcs12obj.export.side_effect = profiles.crypto.Error
    mock_pkcs12.return_value = mock_pkcs12obj

    mock_loadcert.return_value = 'certobj'
    mock_loadkey.return_value = 'keyobj_from_different_cert'

    profile = profiles.NetworkProfile('testuser')
    with self.assertRaises(profiles.CertificateError):
      profile.AddMachineCertificate('fakecert', 'otherfakekey') 
Example #2
Source File: scope_check.py    From opentracing-python with Apache License 2.0 6 votes vote down vote up
def test_activate_nested(self):
        def fn():
            # when a Scope is closed, the previous one must be re-activated.
            scope_manager = self.scope_manager()
            parent_span = mock.MagicMock(spec=Span)
            child_span = mock.MagicMock(spec=Span)

            with scope_manager.activate(parent_span, True) as parent:
                assert parent is not None
                assert scope_manager.active is parent

                with scope_manager.activate(child_span, True) as child:
                    assert child is not None
                    assert scope_manager.active is child

                assert scope_manager.active is parent

            assert parent_span.finish.call_count == 1
            assert child_span.finish.call_count == 1

            assert scope_manager.active is None

        self.run_test(fn) 
Example #3
Source File: test_audio_api.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def test_get_sources(self):
        request = MagicMock()

        source = MagicMock()
        source.channel_count = 2
        source.channel_list = ["front-left", "front-right"]
        source.description = "test"
        source.index = 0
        source.name = "test"
        source.volume = MagicMock()
        source.volume.values = [1.0, 1.0]
        self.pulse.source_list.return_value = [source]

        response = self.api.get_sources(request)
        data = json.loads(response)
        assert len(data) == 1
        assert data[0]['name'] == "test" 
Example #4
Source File: test_audio_api.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def test_get_sinks(self):
        request = MagicMock()

        sink = MagicMock()
        sink.channel_count = 2
        sink.channel_list = ["front-left", "front-right"]
        sink.description = "test"
        sink.index = 0
        sink.name = "test"
        sink.volume = MagicMock()
        sink.volume.values = [1.0, 1.0]
        self.pulse.sink_list.return_value = [sink]

        response = self.api.get_sinks(request)
        data = json.loads(response)
        assert len(data) == 1
        assert data[0]['name'] == "test" 
Example #5
Source File: test_audio_api.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def test_set_source_volume(self):
        request = MagicMock()

        data = [1.0, 1.0]
        request.content.read.return_value = json.dumps(data)

        # This source does not exist.
        response = self.api.set_source_volume(request, "not-found")
        assert response == "{}"

        source = MagicMock()
        source.name = "test"
        self.pulse.source_list.return_value = [source]

        # This source exists, so setting the volume should succeed.
        response = self.api.set_source_volume(request, "test")
        assert response != "{}" 
Example #6
Source File: test_chute_api.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def test_ChuteApi_get_chute_cache(ChuteStorage):
    update_manager = MagicMock()
    update_manager.assign_change_id.return_value = 1

    api = chute_api.ChuteApi(update_manager)

    chute = MagicMock()
    chute.getCacheContents.return_value = {}

    ChuteStorage.chuteList = {
        "test": chute
    }

    request = MagicMock()
    request.user = User.get_internal_user()

    result = api.get_chute_cache(request, "test")
    assert result == "{}" 
Example #7
Source File: test_unique_constraint.py    From goodtables-py with MIT License 6 votes vote down vote up
def test_check_unique_constraint(log):
    mock_field = mock.MagicMock()
    mock_field.descriptor = {'primaryKey': True}
    mock_field.constraints['unique'] = True
    cells1 = [
        goodtables.cells.create_cell('name', 'value', mock_field, row_number=1, column_number=1),
        goodtables.cells.create_cell('value', '50', mock_field, row_number=1, column_number=2),
    ]
    cells2 = [
        goodtables.cells.create_cell('name', 'value', mock_field, row_number=2, column_number=1),
        goodtables.cells.create_cell('value', '100', mock_field, row_number=2, column_number=2),
    ]
    duplicate_row = UniqueConstraint()
    errors = duplicate_row.check_row(cells1)
    errors += duplicate_row.check_row(cells2)

    assert log(errors) == [
        (2, 1, 'unique-constraint'),
    ] 
Example #8
Source File: test_chute_api.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def __init__(self):
        self.update_manager = MagicMock()
        self.update_manager.assign_change_id.return_value = 1

        self.api = chute_api.ChuteApi(self.update_manager)

        self.interface = {
            'name': 'testing',
            'type': 'wifi',
            'internalIntf': 'wlan0',
            'externalIntf': 'vwlan0'
        }

        chute = Chute(name="test")
        chute.setCache("networkInterfaces", [self.interface])
        chute.setCache("externalSystemDir", "/tmp")
        chute.config = {
            "web": {
                "port": 5000
            }
        }

        self.chute = chute 
Example #9
Source File: test_pdinstall.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def test_sendCommand(socket):
    from paradrop.lib.misc.pdinstall import sendCommand

    command = "install"
    data = {
        'sources': ["paradrop_0.1.0_all.snap"]
    }

    sock = MagicMock()
    socket.return_value = sock

    assert sendCommand(command, data)
    assert sock.connect.called
    assert sock.send.called
    assert sock.close.called

    sock.reset_mock
    sock.connect.side_effect = Exception("Boom!")

    assert sendCommand(command, data) is False
    assert sock.close.called 
Example #10
Source File: test_procmon.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def test_ProcessMonitor(psutil, glob, os, mock_open):
    mon = ProcessMonitor("foo")

    # No process or pid file.
    psutil.process_iter.return_value = []
    glob.iglob.return_value = []
    assert mon.check() is False

    proc = MagicMock()
    proc.pid = 1
    proc.name.return_value = "foo"

    # Found process but no pid file.
    psutil.process_iter.return_value = [proc]
    assert mon.check() is False

    pidfile = MagicMock(spec=file)
    pidfile.read.return_value = "2"
    mock_open.return_value = pidfile
    glob.iglob.return_value = ["ignored"]

    # Found process and stale pid file.  It should try to remove the pid file.
    assert mon.check() is False
    assert os.remove.called 
Example #11
Source File: test_dockerapi.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def test_build_host_config(getBridgeGateway, ChuteContainer):
    """
    Test that the build_host_config function does it's job.
    """
    # We don't want to open an actual Docker client connection to do this unit
    # test, so mock out the create_host_config to return whatever is passed to
    # it.
    client = MagicMock()
    client.create_host_config = fake_create_host_config

    update = MagicMock()

    service = MagicMock()
    service.requests = {}

    #Check that an empty host_config gives us certain default settings
    res = dockerapi.build_host_config(update, service)
    assert res['network_mode'] == 'bridge'

    #Check that passing things through host_config works
    service.requests['port-bindings'] = {80: 9000}
    service.requests['privileged'] = True
    res = dockerapi.build_host_config(update, service)
    assert res['privileged'] is True 
Example #12
Source File: test_command.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def test_Command_execute(Popen, out):
    """
    Test the Command.execute method
    """
    from paradrop.confd.command import Command

    proc = MagicMock()
    proc.stdout = ["output"]
    proc.stderr = ["error"]
    Popen.return_value = proc

    command = Command(["callme"])
    command.parent = MagicMock()

    command.execute()
    assert out.verbose.called_once_with("callme: output")
    assert out.verbose.called_once_with("callme: error")
    assert command.parent.executed.append.called

    Popen.side_effect = Exception("Boom!")
    command.execute()
    assert out.info.called 
Example #13
Source File: profiles_test.py    From macops with Apache License 2.0 6 votes vote down vote up
def testAddAnchorCertificateSuccess(self, mock_certificate, mock_addpayload):
    mock_certobj = mock.MagicMock()
    mock_certobj.subject_cn = 'My Cert Subject'
    mock_certobj.osx_fingerprint = '0011223344556677889900'
    mock_certificate.return_value = mock_certobj

    profile = profiles.NetworkProfile('testuser')
    profile.AddAnchorCertificate('my_cert')

    mock_certificate.assert_called_once_with('my_cert')
    mock_addpayload.assert_called_once_with(
        {profiles.PAYLOADKEYS_IDENTIFIER:
             'com.megacorp.networkprofile.0011223344556677889900',
         profiles.PAYLOADKEYS_TYPE: 'com.apple.security.pkcs1',
         profiles.PAYLOADKEYS_DISPLAYNAME: 'My Cert Subject',
         profiles.PAYLOADKEYS_CONTENT: profiles.plistlib.Data('my_cert'),
         profiles.PAYLOADKEYS_ENABLED: True,
         profiles.PAYLOADKEYS_VERSION: 1,
         profiles.PAYLOADKEYS_UUID: mock.ANY}) 
Example #14
Source File: test_wireless.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def test_HostapdConfGenerator_get11rOptions():
    wifiIface = ConfigWifiIface()
    wifiIface.r0kh = [
        "02:01:02:03:04:05 r0kh-1.example.com 000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f",
        "02:01:02:03:04:06 r0kh-2.example.com 00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"
    ]
    wifiIface.r1kh = [
        "00:00:00:00:00:00 00:00:00:00:00:00 00112233445566778899aabbccddeeff"
    ]

    wifiDevice = MagicMock()
    interface = MagicMock()

    generator = HostapdConfGenerator(wifiIface, wifiDevice, interface)

    # Should raise an exception because nasid is not set.
    assert_raises(Exception, generator.get11rOptions)

    wifiIface.nasid = "ap.example.com"

    options = generator.get11rOptions()

    # There should be two r0kh entries and one r1kh entry.
    assert sum(k[0] == 'r0kh' for k in options) == 2
    assert sum(k[0] == 'r1kh' for k in options) == 1 
Example #15
Source File: test_firewall.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def test_ConfigForwarding():
    wanInterface = MagicMock()

    lanZone = MagicMock()

    wanZone = MagicMock()
    wanZone.network = ["wan"]

    allConfigs = {
        ("firewall", "zone", "wan"): wanZone,
        ("firewall", "zone", "lan"): lanZone,
        ("network", "interface", "wan"): wanInterface
    }

    config = firewall.ConfigForwarding()
    config.src = "lan"
    config.dest = "wan"

    commands = config.apply(allConfigs)
    assert len(commands) == 1

    commands = config.revert(allConfigs)
    assert len(commands) == 1 
Example #16
Source File: airport_test.py    From macops with Apache License 2.0 6 votes vote down vote up
def testScanForNetworksNoSSID(self):
    mock_network = mock.MagicMock()
    mock_network.ssid.return_value = 'GuestSSID'
    mock_network.rssiValue.return_value = -78

    mock_network2 = mock.MagicMock()
    mock_network2.ssid.return_value = 'GuestSSID'
    mock_network2.rssiValue.return_value = -62

    mock_network3 = mock.MagicMock()
    mock_network3.ssid.return_value = 'SSID'
    mock_network3.rssiValue.return_value = -25

    networks = [mock_network, mock_network2, mock_network3]

    self.mock_intf.scanForNetworksWithName_error_.return_value = [
        networks, None]
    retval = airport.ScanForNetworks(None)

    self.mock_intf.scanForNetworksWithName_error_.assert_called_once_with(None,
                                                                          None)
    self.assertEqual(retval, {'GuestSSID': mock_network2,
                              'SSID': mock_network3}) 
Example #17
Source File: test_firewall.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def test_ConfigZone():
    wanInterface = MagicMock()
    wanInterface.config_ifname = "eth0"

    allConfigs = {
        ("network", "interface", "wan"): wanInterface
    }

    config = firewall.ConfigZone()
    config.name = "wan"
    config.network = ["wan"]
    config.conntrack = True
    config.masq = True

    config.manager = MagicMock()
    config.manager.forwardingCount = 0
    config.manager.conntrackLoaded = False

    commands = config.apply(allConfigs)
    assert len(commands) >= 17

    commands = config.revert(allConfigs)
    assert len(commands) >= 16 
Example #18
Source File: scope_check.py    From opentracing-python with Apache License 2.0 6 votes vote down vote up
def test_activate_finish_on_close_nested(self):
        def fn():
            # finish_on_close must be correctly handled
            scope_manager = self.scope_manager()
            parent_span = mock.MagicMock(spec=Span)
            child_span = mock.MagicMock(spec=Span)

            parent = scope_manager.activate(parent_span, False)
            with scope_manager.activate(child_span, True):
                pass
            parent.close()

            assert parent_span.finish.call_count == 0
            assert child_span.finish.call_count == 1
            assert scope_manager.active is None

        self.run_test(fn) 
Example #19
Source File: test_audio_api.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def test_get_info(self):
        request = MagicMock()

        info = MagicMock()
        info.default_sink_name = "test"
        info.server_name = "test"
        info.default_source_name = "test"
        info.user_name = "test"
        info.server_version = "test"
        info.host_name = "test"
        self.pulse.server_info.return_value = info

        response = self.api.get_info(request)
        data = json.loads(response)
        assert data['default_sink_name'] == "test" 
Example #20
Source File: test_chute_api.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def test_ChuteApi_get_chutes(ChuteStorage, ChuteContainer):
    update_manager = MagicMock()
    api = chute_api.ChuteApi(update_manager)

    request = MagicMock()

    container = MagicMock()
    container.getStatus.return_value = "running"
    ChuteContainer.return_value = container

    storage = MagicMock()
    ChuteStorage.return_value = storage

    chute = MagicMock()
    chute.environment = {}
    chute.name = "test"
    chute.state = "running"
    chute.resources = {}
    chute.version = 5
    chute.get_owner.return_value = "paradrop"

    storage.getChuteList.return_value = [chute]

    data = api.get_chutes(request)
    assert isinstance(data, basestring)

    result = json.loads(data)
    assert result[0]['name'] == chute.name
    assert result[0]['version'] == chute.version 
Example #21
Source File: test_network_api.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def test_read_leases(open):
    file_object = MagicMock()
    file_object.__enter__.return_value = [
        "1480650200 00:11:22:33:44:55 192.168.128.130 android-ffeeddccbbaa9988 *",
        "1480640500 00:22:44:66:88:aa 192.168.128.170 someones-iPod 01:00:22:44:66:88:aa"
    ]
    open.return_value = file_object

    leases = network_api.read_leases("/")
    assert len(leases) == 2
    assert leases[0]['ip_addr'] == "192.168.128.130" 
Example #22
Source File: test_wireless.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def test_HostapdConfGenerator_getRadiusOptions():
    wifiIface = ConfigWifiIface()
    wifiIface.ssid = "Paradrop"
    wifiIface.maxassoc = 200
    wifiIface.wmm = True
    wifiIface.ifname = "wlan0"
    wifiIface.auth_server = "10.42.0.1"
    wifiIface.auth_secret = "secret"
    wifiIface.acct_server = "10.42.0.1"
    wifiIface.acct_secret = "secret"

    wifiDevice = MagicMock()
    wifiDevice.country = "US"
    wifiDevice.hwmode = "11a"
    wifiDevice.channel = 36
    wifiDevice.beacon_int = 100
    wifiDevice.rts = -1
    wifiDevice.frag = -1

    interface = MagicMock()
    interface.type = "bridge"
    interface.config_ifname = "br-lan"

    generator = HostapdConfGenerator(wifiIface, wifiDevice, interface)

    options = generator.getRadiusOptions()
    print(options) 
Example #23
Source File: test_wireless.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def test_HostapdConfGenerator_get11acOptions():
    wifiDevice = MagicMock()
    wifiDevice.enable11ac = True
    wifiDevice.htmode = "VHT40"
    wifiDevice.short_gi_80 = True
    wifiDevice.short_gi_160 = True
    wifiDevice.tx_stbc = 1
    wifiDevice.rx_stbc = 2
    wifiDevice.require_mode = "ac"
    wifiDevice.channel = 36

    wifiIface = MagicMock()
    interface = MagicMock()

    generator = HostapdConfGenerator(wifiIface, wifiDevice, interface)

    options = generator.get11acOptions()
    print(options)
    assert ("ieee80211ac", 1) in options
    assert ("vht_capab", "[RXLDPC][SHORT-GI-80][SHORT-GI-160][TX-STBC-2BY1][RX-ANTENNA-PATTERN][TX-ANTENNA-PATTERN][RX-STBC-12]") in options
    assert ("vht_oper_chwidth", 0) in options
    assert ("vht_oper_centr_freq_seg0_idx", 38) in options

    # Try 80 MHz channel.
    wifiDevice.htmode = "VHT80"
    options = generator.get11acOptions()
    assert ("vht_oper_chwidth", 1) in options
    assert ("vht_oper_centr_freq_seg0_idx", 42) in options

    # Try 160 MHz channel.
    wifiDevice.htmode = "VHT160"
    options = generator.get11acOptions()
    assert ("vht_oper_chwidth", 2) in options
    assert ("vht_oper_centr_freq_seg0_idx", 50) in options 
Example #24
Source File: test_wireless.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def test_ConfigWifiIface_apply():
    """
    Test the ConfigWifiIface apply method
    """
    wifiDevice = MagicMock()
    interface = MagicMock()

    allConfigs = {
        ("wireless", "wifi-device", "phy0"): wifiDevice,
        ("network", "interface", "lan"): interface
    }

    config = ConfigWifiIface()
    config.manager = MagicMock()
    config.makeHostapdConf = MagicMock()

    config.device = "phy0"
    config.mode = "ap"
    config.ssid = "Paradrop"
    config.network = "lan"
    config.encryption = "psk2"
    config.key = "password"

    wifiDevice.name = "phy0"
    interface.config_ifname = "wlan0"

    commands = config.apply(allConfigs) 
Example #25
Source File: test_chute_api.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def test_ChuteApi_get_chute(ChuteStorage, ChuteContainer):
    update_manager = MagicMock()
    api = chute_api.ChuteApi(update_manager)

    request = MagicMock()
    request.user = User.get_internal_user()

    container = MagicMock()
    container.getStatus.return_value = "running"
    ChuteContainer.return_value = container

    chute = MagicMock()
    chute.name = "test"
    chute.state = "running"
    chute.version = 5
    chute.environment = {}
    chute.resources = {}

    ChuteStorage.chuteList = {
        "test": chute
    }

    data = api.get_chute(request, chute.name)
    assert isinstance(data, basestring)

    result = json.loads(data)
    assert result['name'] == chute.name
    assert result['version'] == chute.version 
Example #26
Source File: test_chute_api.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def test_ChuteApi_operations():
    update_manager = MagicMock()
    update_manager.assign_change_id.return_value = 1

    api = chute_api.ChuteApi(update_manager)

    body = {
        'config': {}
    }

    request = MagicMock()
    request.content.read.return_value = json.dumps(body)
    request.user = User.get_internal_user()

    functions = [
        api.update_chute,
        api.stop_chute,
        api.start_chute,
        api.restart_chute,
        api.delete_chute
    ]
    for func in functions:
        print("Calling ChuteApi {}".format(func.__name__))

        data = func(request, "test")
        assert isinstance(data, basestring)

        result = json.loads(data)
        assert result['change_id'] == 1 
Example #27
Source File: test_chute_api.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def test_ChuteApi_get_network(ChuteStorage):
    update_manager = MagicMock()
    update_manager.assign_change_id.return_value = 1

    api = chute_api.ChuteApi(update_manager)

    iface = {
        'name': 'vwlan0',
        'type': 'wifi',
        'internalIntf': 'wlan0'
    }

    chute = Chute(name="test")
    chute.setCache("networkInterfaces", [iface])

    ChuteStorage.chuteList = {
        "test": chute
    }

    request = MagicMock()
    request.user = User.get_internal_user()

    result = api.get_network(request, "test", "nomatch")
    assert result == "{}"

    result = api.get_network(request, "test", "vwlan0")
    data = json.loads(result)
    assert data['name'] == iface['name']
    assert data['type'] == iface['type']
    assert data['interface'] == iface['internalIntf'] 
Example #28
Source File: scope_check.py    From opentracing-python with Apache License 2.0 5 votes vote down vote up
def test_activate_finish_on_close(self):
        def fn():
            scope_manager = self.scope_manager()
            span = mock.MagicMock(spec=Span)

            scope = scope_manager.activate(span, True)
            assert scope is not None
            assert scope_manager.active is scope

            scope.close()
            assert span.finish.call_count == 1
            assert scope_manager.active is None

        self.run_test(fn) 
Example #29
Source File: test_setup.py    From unicorn-hat-hd with MIT License 5 votes vote down vote up
def test_setup():
    """Test that the library sets up correctly with numpy and spidev."""
    sys.modules['spidev'] = mock.MagicMock()
    import unicornhathd
    unicornhathd.setup() 
Example #30
Source File: test_addresses.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def test_addresses():
    ch = MagicMock()
    ch.getCache.return_value = [{'type': 'test'}]
    assert addresses.getGatewayIntf(ch) == (None, None)
    assert addresses.getWANIntf(ch) == None