Python unittest.mock.mock_open() Examples

The following are 30 code examples of unittest.mock.mock_open(). 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 unittest.mock , or try the search function .
Example #1
Source File: test_uflash.py    From uflash with MIT License 7 votes vote down vote up
def test_flash_with_path_to_runtime():
    """
    Use the referenced runtime hex file when building the hex file to be
    flashed onto the device.
    """
    mock_o = mock.mock_open(read_data=b'script')
    with mock.patch.object(builtins, 'open', mock_o) as mock_open:
        with mock.patch('uflash.embed_hex', return_value='foo') as em_h:
            with mock.patch('uflash.find_microbit', return_value='bar'):
                with mock.patch('uflash.save_hex') as mock_save:
                    uflash.flash('tests/example.py',
                                 path_to_runtime='tests/fake.hex')
                    assert mock_open.call_args[0][0] == 'tests/fake.hex'
                    assert em_h.call_args[0][0] == b'script'
                    expected_hex_path = os.path.join('bar', 'micropython.hex')
                    mock_save.assert_called_once_with('foo', expected_hex_path) 
Example #2
Source File: test_local.py    From octavia with Apache License 2.0 6 votes vote down vote up
def test_get_secret(self):
        fd_mock = mock.mock_open()
        open_mock = mock.Mock()
        secret_id = uuidutils.generate_uuid()
        # Attempt to retrieve the secret
        with mock.patch('os.open', open_mock), mock.patch.object(
                os, 'fdopen', fd_mock):
            local_cert_mgr.LocalCertManager.get_secret(None, secret_id)

        # Verify the correct files were opened
        flags = os.O_RDONLY
        open_mock.assert_called_once_with('/tmp/{0}.crt'.format(secret_id),
                                          flags)

        # Test failure path
        with mock.patch('os.open', open_mock), mock.patch.object(
                os, 'fdopen', fd_mock) as mock_open:
            mock_open.side_effect = IOError
            self.assertRaises(exceptions.CertificateRetrievalException,
                              local_cert_mgr.LocalCertManager.get_secret,
                              None, secret_id) 
Example #3
Source File: test_utils.py    From designate with Apache License 2.0 6 votes vote down vote up
def test_render_template_to_file_with_makedirs(self, mock_makedirs,
                                                   mock_exists,
                                                   mock_open):
        mock_exists.return_value = False

        output_path = '/tmp/designate/resources/templates/hello.jinja2'

        template = jinja2.Template('Hello {{name}}')

        utils.render_template_to_file(
            template, makedirs=True, output_path=output_path, name='World'
        )

        mock_makedirs.assert_called_once_with(
            '/tmp/designate/resources/templates'
        )
        mock_open.assert_called_once_with(output_path, 'w')
        mock_open().write.assert_called_once_with('Hello World') 
Example #4
Source File: test_driver.py    From zun with Apache License 2.0 6 votes vote down vote up
def test_pull_image_success(self, mock_find_image, mock_download_image,
                                mock_should_pull_image, mock_search_on_host):
        mock_should_pull_image.return_value = True
        mock_search_on_host.return_value = {'image': 'nginx', 'path': 'xyz',
                                            'checksum': 'xxx'}
        image_meta = mock.MagicMock()
        image_meta.id = '1234'
        image_meta.name = 'image'
        image_meta.tags = ['latest']
        mock_find_image.return_value = image_meta
        mock_download_image.return_value = 'content'
        CONF.set_override('images_directory', self.test_dir, group='glance')
        out_path = os.path.join(self.test_dir, '1234' + '.tar')
        mock_open_file = mock.mock_open()
        with mock.patch('zun.image.glance.driver.open', mock_open_file):
            ret = self.driver.pull_image(None, 'image', 'latest', 'always',
                                         None)
        mock_open_file.assert_any_call(out_path, 'wb')
        self.assertTrue(mock_search_on_host.called)
        self.assertTrue(mock_should_pull_image.called)
        self.assertTrue(mock_find_image.called)
        self.assertTrue(mock_download_image.called)
        self.assertEqual(({'image': 'image', 'path': out_path,
                           'tags': ['latest']}, False), ret) 
Example #5
Source File: test_resctrl_measurements.py    From workload-collocation-agent with Apache License 2.0 6 votes vote down vote up
def test_resgroup_add_pids(makedirs_mock, set_effective_root_uid_mock,
                           resgroup_name, pids, mongroup_name,
                           expected_writes, expected_setuid_calls_count, expected_makedirs):
    """Test that for ResGroup created with resgroup_name, when add_pids() is called with
    pids and given mongroup_name, expected writes (filenames with expected bytes writes)
    will happen together with number of setuid calls and makedirs calls.
    """
    write_mocks = {filename: mock_open() for filename in expected_writes}
    resgroup = ResGroup(name=resgroup_name)

    # if expected_log:
    with patch('builtins.open', new=create_open_mock(write_mocks)):
        resgroup.add_pids(pids, mongroup_name)

    for filename, write_mock in write_mocks.items():
        expected_filename_writes = expected_writes[filename]
        expected_write_calls = [call().write(write_body) for write_body in expected_filename_writes]
        write_mock.assert_has_calls(expected_write_calls, any_order=True)

    # makedirs used
    makedirs_mock.assert_has_calls(expected_makedirs)

    # setuid used (at least number of times)
    expected_setuid_calls = [call.__enter__()] * expected_setuid_calls_count
    set_effective_root_uid_mock.assert_has_calls(expected_setuid_calls, any_order=True) 
Example #6
Source File: test_plug.py    From octavia with Apache License 2.0 6 votes vote down vote up
def test__interface_by_mac_not_found(self, mock_ipr):
        mock_ipr_instance = mock.MagicMock()
        mock_ipr_instance.link_lookup.return_value = []
        mock_ipr().__enter__.return_value = mock_ipr_instance

        fd_mock = mock.mock_open()
        open_mock = mock.Mock()
        isfile_mock = mock.Mock()
        with mock.patch('os.open', open_mock), mock.patch.object(
                os, 'fdopen', fd_mock), mock.patch.object(
                os.path, 'isfile', isfile_mock):
            self.assertRaises(wz_exceptions.HTTPException,
                              self.test_plug._interface_by_mac,
                              FAKE_MAC_ADDRESS.upper())
        open_mock.assert_called_once_with('/sys/bus/pci/rescan', os.O_WRONLY)
        fd_mock().write.assert_called_once_with('1') 
Example #7
Source File: test_engine_base_action.py    From marvin-python-toolbox with Apache License 2.0 6 votes vote down vote up
def test__serializer_dump_metrics(self, mocked_dump):
        obj = {"key", 1}
        object_reference = "_metrics"

        class _EAction(EngineBaseAction):
            _metrics = None

            def execute(self, params, **kwargs):
                pass

        mocked_open = mock.mock_open()
        with mock.patch('marvin_python_toolbox.engine_base.engine_base_action.open', mocked_open, create=False):
            _EAction(default_root_path="/tmp/.marvin", persistence_mode="local")._save_obj(object_reference, obj)

        mocked_dump.assert_called_once_with(obj, ANY, indent=4, separators=(u',', u': '), sort_keys=True)
        mocked_open.assert_called_once() 
Example #8
Source File: test_hive.py    From marvin-python-toolbox with Apache License 2.0 6 votes vote down vote up
def test_hive_generateconf_write_file_with_json(mocked_json):
    default_conf = [{
        "origin_host": "xxx_host_name",
        "origin_db": "xxx_db_name",
        "origin_queue": "marvin",
        "target_table_name": "xxx_table_name",
        "sample_sql": "SELECT * FROM XXX",
        "sql_id": "1"
    }]

    mocked_open = mock.mock_open()
    with mock.patch('marvin_python_toolbox.management.hive.open', mocked_open, create=True):
        hive.hive_generateconf(None)

    mocked_open.assert_called_once_with('hive_dataimport.conf', 'w')
    mocked_json.dump.assert_called_once_with(default_conf, mocked_open(), indent=2) 
Example #9
Source File: test_uflash.py    From uflash with MIT License 6 votes vote down vote up
def test_extract_paths():
    """
    Test the different paths of the extract() function.
    It should open and extract the contents of the file (input arg)
    When called with only an input it should print the output of extract_script
    When called with two arguments it should write the output to the output arg
    """
    mock_e = mock.MagicMock(return_value=b'print("hello, world!")')
    mock_o = mock.mock_open(read_data='script')

    with mock.patch('uflash.extract_script', mock_e) as mock_extract_script, \
            mock.patch.object(builtins, 'print') as mock_print, \
            mock.patch.object(builtins, 'open', mock_o) as mock_open:
        uflash.extract('foo.hex')
        mock_open.assert_called_once_with('foo.hex', 'r')
        mock_extract_script.assert_called_once_with('script')
        mock_print.assert_called_once_with(b'print("hello, world!")')

        uflash.extract('foo.hex', 'out.py')
        assert mock_open.call_count == 3
        mock_open.assert_called_with('out.py', 'w')
        assert mock_open.return_value.write.call_count == 1 
Example #10
Source File: test_lineparser.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def test_binary(self, mocker):
        """Test if _open and _write correctly handle binary files."""
        open_mock = mock.mock_open()
        mocker.patch('builtins.open', open_mock)

        testdata = b'\xf0\xff'

        lineparser = lineparsermod.BaseLineParser(
            self.CONFDIR, self.FILENAME, binary=True)
        with lineparser._open('r') as f:
            lineparser._write(f, [testdata])

        open_mock.assert_called_once_with(
            str(pathlib.Path(self.CONFDIR) / self.FILENAME), 'rb')

        open_mock().write.assert_has_calls([
            mock.call(testdata),
            mock.call(b'\n')
        ]) 
Example #11
Source File: test_html.py    From ciftify with MIT License 6 votes vote down vote up
def test_title_not_added_when_not_given(self, mock_open, mock_header):
        # Set up
        # fake page to 'open' and write to
        html_page = MagicMock()
        mock_open.return_value.__enter__.return_value = html_page
        # qc_config.Config stub
        class MockQCConfig(object):
            def __init__(self):
                pass

        # Call
        html.write_image_index(self.qc_dir, self.subjects, MockQCConfig(),
                self.page_subject, self.image_name)

        # Assert
        for call in html_page.write.call_args_list:
            assert '<h1>' not in call[0]
        assert mock_header.call_count == 1
        header_kword_args = mock_header.call_args_list[0][1]
        assert 'title' in header_kword_args.keys()
        assert header_kword_args['title'] == None 
Example #12
Source File: test_html.py    From ciftify with MIT License 6 votes vote down vote up
def test_title_changed_to_include_image_name_when_title_given(self,
            mock_open, mock_add_header, mock_add_img_subj, mock_index,
            mock_exists, mock_writable):
        mock_file = MagicMock(spec=io.IOBase)
        mock_open.return_value.__enter__.return_value = mock_file
        mock_exists.return_value = False
        mock_writable.return_value = True
        qc_config = self.get_config_stub()

        html.write_index_pages(self.qc_dir, qc_config, self.subject,
                title='QC mode for image {}')

        for image in qc_config.images:
            name = image.name
            found = False
            for call in mock_index.call_args_list:
                if name in call[1]['title']:
                    found = True
            assert found 
Example #13
Source File: test_models.py    From Python-GUI-Programming-with-Tkinter with MIT License 6 votes vote down vote up
def setUp(self):

        self.file1_open = mock_open(
            read_data=(
                "Date,Time,Technician,Lab,Plot,Seed sample,Humidity,Light,"
                "Temperature,Equipment Fault,Plants,Blossoms,Fruit,Min Height,"
                "Max Height,Median Height,Notes\r\n"
                "2018-06-01,8:00,J Simms,A,2,AX478,24.47,1.01,21.44,False,14,"
                "27,1,2.35,9.2,5.09,\r\n"
                "2018-06-01,8:00,J Simms,A,3,AX479,24.15,1,20.82,False,18,49,"
                "6,2.47,14.2,11.83,\r\n"
            )
        )
        self.file2_open = mock_open(
            read_data=''
        )

        self.model1 = models.CSVModel('file1')
        self.model2 = models.CSVModel('file2') 
Example #14
Source File: test_models.py    From Python-GUI-Programming-with-Tkinter with MIT License 6 votes vote down vote up
def setUp(self):

        self.file1_open = mock_open(
            read_data=(
                "Date,Time,Technician,Lab,Plot,Seed sample,Humidity,Light,"
                "Temperature,Equipment Fault,Plants,Blossoms,Fruit,Min Height,"
                "Max Height,Median Height,Notes\r\n"
                "2018-06-01,8:00,J Simms,A,2,AX478,24.47,1.01,21.44,False,14,"
                "27,1,2.35,9.2,5.09,\r\n"
                "2018-06-01,8:00,J Simms,A,3,AX479,24.15,1,20.82,False,18,49,"
                "6,2.47,14.2,11.83,\r\n"
            )
        )
        self.file2_open = mock_open(
            read_data=''
        )

        self.model1 = models.CSVModel('file1')
        self.model2 = models.CSVModel('file2') 
Example #15
Source File: test_models.py    From Python-GUI-Programming-with-Tkinter with MIT License 6 votes vote down vote up
def setUp(self):

        self.file1_open = mock_open(
            read_data=(
                "Date,Time,Technician,Lab,Plot,Seed sample,Humidity,Light,"
                "Temperature,Equipment Fault,Plants,Blossoms,Fruit,Min Height,"
                "Max Height,Median Height,Notes\r\n"
                "2018-06-01,8:00,J Simms,A,2,AX478,24.47,1.01,21.44,False,14,"
                "27,1,2.35,9.2,5.09,\r\n"
                "2018-06-01,8:00,J Simms,A,3,AX479,24.15,1,20.82,False,18,49,"
                "6,2.47,14.2,11.83,\r\n"
            )
        )
        self.file2_open = mock_open(
            read_data=''
        )

        self.model1 = models.CSVModel('file1')
        self.model2 = models.CSVModel('file2') 
Example #16
Source File: test_models.py    From Python-GUI-Programming-with-Tkinter with MIT License 6 votes vote down vote up
def setUp(self):

        self.file1_open = mock_open(
            read_data=(
                "Date,Time,Technician,Lab,Plot,Seed sample,Humidity,Light,"
                "Temperature,Equipment Fault,Plants,Blossoms,Fruit,Min Height,"
                "Max Height,Median Height,Notes\r\n"
                "2018-06-01,8:00,J Simms,A,2,AX478,24.47,1.01,21.44,False,14,"
                "27,1,2.35,9.2,5.09,\r\n"
                "2018-06-01,8:00,J Simms,A,3,AX479,24.15,1,20.82,False,18,49,"
                "6,2.47,14.2,11.83,\r\n"
            )
        )
        self.file2_open = mock_open(
            read_data=''
        )

        self.model1 = models.CSVModel('file1')
        self.model2 = models.CSVModel('file2') 
Example #17
Source File: test_data.py    From marvin-python-toolbox with Apache License 2.0 5 votes vote down vote up
def test_load_data_from_filesystem_exception(data_path_key, data_path):
    with mock.patch('marvin_python_toolbox.common.data.open') as mock_open:
        mock_open.side_effect = IOError

        # load_data should propagate IOError
        with pytest.raises(IOError):
            MarvinData.load_data(os.path.join('named_features', 'brands.json')) 
Example #18
Source File: test_plug.py    From octavia with Apache License 2.0 5 votes vote down vote up
def test_plug_vip_ipv6(self, mock_makedirs, mock_copytree,
                           mock_check_output, mock_netns, mock_netns_create,
                           mock_pyroute2, mock_webob, mock_nspopen,
                           mock_by_mac):
        conf = self.useFixture(oslo_fixture.Config(cfg.CONF))
        conf.config(group='controller_worker',
                    loadbalancer_topology=constants.TOPOLOGY_ACTIVE_STANDBY)
        m = mock.mock_open()
        with mock.patch('os.open'), mock.patch.object(os, 'fdopen', m):
            self.test_plug.plug_vip(
                vip=FAKE_IP_IPV6,
                subnet_cidr=FAKE_CIDR_IPV6,
                gateway=FAKE_GATEWAY_IPV6,
                mac_address=FAKE_MAC_ADDRESS
            )
        mock_webob.Response.assert_any_call(json={
            'message': 'OK',
            'details': 'VIP {vip} plugged on interface {interface}'.format(
                vip=FAKE_IP_IPV6_EXPANDED, interface='eth1')
        }, status=202)
        calls = [mock.call('amphora-haproxy', ['/sbin/sysctl', '--system'],
                           stdout=subprocess.PIPE),
                 mock.call('amphora-haproxy', ['modprobe', 'ip_vs'],
                           stdout=subprocess.PIPE),
                 mock.call('amphora-haproxy',
                           ['/sbin/sysctl', '-w',
                            'net.ipv6.conf.all.forwarding=1'],
                           stdout=subprocess.PIPE),
                 mock.call('amphora-haproxy',
                           ['/sbin/sysctl', '-w', 'net.ipv4.vs.conntrack=1'],
                           stdout=subprocess.PIPE)]
        mock_nspopen.assert_has_calls(calls, any_order=True) 
Example #19
Source File: test_plug.py    From octavia with Apache License 2.0 5 votes vote down vote up
def test_plug_vip_bad_ip(self, mock_makedirs, mock_copytree,
                             mock_check_output, mock_netns, mock_netns_create,
                             mock_pyroute2, mock_webob):
        m = mock.mock_open()
        with mock.patch('os.open'), mock.patch.object(os, 'fdopen', m):
            self.test_plug.plug_vip(
                vip="error",
                subnet_cidr=FAKE_CIDR_IPV4,
                gateway=FAKE_GATEWAY_IPV4,
                mac_address=FAKE_MAC_ADDRESS
            )
        mock_webob.Response.assert_any_call(json={'message': 'Invalid VIP'},
                                            status=400) 
Example #20
Source File: test_util.py    From octavia with Apache License 2.0 5 votes vote down vote up
def test_get_haproxy_vip_addresses(self, mock_cfg_path):
        FAKE_PATH = 'fake_path'
        mock_cfg_path.return_value = FAKE_PATH
        self.useFixture(
            test_utils.OpenFixture(FAKE_PATH, 'no match')).mock_open()

        # Test with no matching lines in the config file
        self.assertEqual([], util.get_haproxy_vip_addresses(LB_ID1))
        mock_cfg_path.assert_called_once_with(LB_ID1)

        # Test with a matching bind line
        mock_cfg_path.reset_mock()
        test_data = 'no match\nbind 203.0.113.43:1\nbogus line'
        self.useFixture(
            test_utils.OpenFixture(FAKE_PATH, test_data)).mock_open()
        expected_result = ['203.0.113.43']
        self.assertEqual(expected_result,
                         util.get_haproxy_vip_addresses(LB_ID1))
        mock_cfg_path.assert_called_once_with(LB_ID1)

        # Test with a matching bind line multiple binds
        mock_cfg_path.reset_mock()
        test_data = 'no match\nbind 203.0.113.44:1234, 203.0.113.45:4321'
        self.useFixture(
            test_utils.OpenFixture(FAKE_PATH, test_data)).mock_open()
        expected_result = ['203.0.113.44', '203.0.113.45']
        self.assertEqual(expected_result,
                         util.get_haproxy_vip_addresses(LB_ID1))
        mock_cfg_path.assert_called_once_with(LB_ID1)

        # Test with a bogus bind line
        mock_cfg_path.reset_mock()
        test_data = 'no match\nbind\nbogus line'
        self.useFixture(
            test_utils.OpenFixture(FAKE_PATH, test_data)).mock_open()
        self.assertEqual([], util.get_haproxy_vip_addresses(LB_ID1))
        mock_cfg_path.assert_called_once_with(LB_ID1) 
Example #21
Source File: test_utils.py    From designate with Apache License 2.0 5 votes vote down vote up
def test_render_template_to_file(self, mock_exists, mock_open):
        mock_exists.return_value = True

        output_path = '/tmp/designate/resources/templates/hello.jinja2'

        template = jinja2.Template('Hello {{name}}')

        utils.render_template_to_file(
            template, makedirs=False, output_path=output_path, name='World'
        )

        mock_open.assert_called_once_with(output_path, 'w')
        mock_open().write.assert_called_once_with('Hello World') 
Example #22
Source File: test_util.py    From octavia with Apache License 2.0 5 votes vote down vote up
def test_vrrp_check_script_update(self, mock_sock_path, mock_get_lbs,
                                      mock_join, mock_listdir, mock_exists,
                                      mock_makedirs, mock_get_listeners):
        mock_get_lbs.return_value = ['abc', LB_ID1]
        mock_sock_path.return_value = 'listener.sock'
        mock_exists.side_effect = [False, False, True]
        mock_get_lbs.side_effect = [['abc', LB_ID1], ['abc', LB_ID1], []]
        mock_get_listeners.return_value = []

        # Test the stop action path
        cmd = 'haproxy-vrrp-check ' + ' '.join(['listener.sock']) + '; exit $?'
        path = util.keepalived_dir()
        m = self.useFixture(test_utils.OpenFixture(path)).mock_open

        util.vrrp_check_script_update(LB_ID1, 'stop')

        handle = m()
        handle.write.assert_called_once_with(cmd)

        # Test the start action path
        cmd = ('haproxy-vrrp-check ' + ' '.join(['listener.sock',
                                                 'listener.sock']) + '; exit '
                                                                     '$?')
        m = self.useFixture(test_utils.OpenFixture(path)).mock_open
        util.vrrp_check_script_update(LB_ID1, 'start')
        handle = m()
        handle.write.assert_called_once_with(cmd)

        # Test the path with existing keepalived directory and no LBs
        mock_makedirs.reset_mock()
        cmd = 'exit 1'
        m = self.useFixture(test_utils.OpenFixture(path)).mock_open

        util.vrrp_check_script_update(LB_ID1, 'start')

        handle = m()
        handle.write.assert_called_once_with(cmd)
        mock_makedirs.assert_has_calls(
            [mock.call(util.keepalived_dir(), exist_ok=True),
             mock.call(util.keepalived_check_scripts_dir(), exist_ok=True)]) 
Example #23
Source File: test_util.py    From octavia with Apache License 2.0 5 votes vote down vote up
def test_install_netns_systemd_service(self, mock_get_os_util,
                                           mock_os_path, mock_jinja2_env,
                                           mock_fsloader):
        mock_os_util = mock.MagicMock()
        mock_os_util.has_ifup_all.return_value = True
        mock_get_os_util.return_value = mock_os_util

        mock_os_path.realpath.return_value = '/dir/file'
        mock_os_path.dirname.return_value = '/dir/'
        mock_os_path.exists.return_value = False
        mock_fsloader.return_value = 'fake_loader'
        mock_jinja_env = mock.MagicMock()
        mock_jinja2_env.return_value = mock_jinja_env
        mock_template = mock.MagicMock()
        mock_template.render.return_value = 'script'
        mock_jinja_env.get_template.return_value = mock_template

        m = mock.mock_open()
        with mock.patch('os.open'), mock.patch.object(os, 'fdopen', m):

            util.install_netns_systemd_service()

        mock_jinja2_env.assert_called_with(autoescape=True,
                                           loader='fake_loader')

        mock_jinja_env.get_template.assert_called_once_with(
            consts.AMP_NETNS_SVC_PREFIX + '.systemd.j2')
        mock_template.render.assert_called_once_with(
            amphora_nsname=consts.AMPHORA_NAMESPACE, HasIFUPAll=True)
        handle = m()
        handle.write.assert_called_with('script')

        # Test file exists path we don't over write
        mock_jinja_env.get_template.reset_mock()
        mock_os_path.exists.return_value = True
        util.install_netns_systemd_service()
        self.assertFalse(mock_jinja_env.get_template.called) 
Example #24
Source File: test_util.py    From octavia with Apache License 2.0 5 votes vote down vote up
def test_get_keepalivedlvs_pid(self, mock_path):
        fake_path = '/fake/path'
        mock_path.return_value = [fake_path]
        self.useFixture(test_utils.OpenFixture(
            fake_path, ' space data   ')).mock_open
        result = util.get_keepalivedlvs_pid(self.listener_id)
        self.assertEqual(' space data', result) 
Example #25
Source File: test_knapsack.py    From jMetalPy with MIT License 5 votes vote down vote up
def test_should_create_solution_from_file(self) -> None:
        filename = 'resources/Knapsack_instances/KnapsackInstance_50_0_0.kp'

        data = "50\n13629\n 865 445\n395 324\n777 626\n912 656\n431 935\n42 210 \n266 990\n989 566\n524 489\n" \
               "498 454\n415 887\n941 534\n803 267\n850 64 \n311 825\n992 941\n489 562\n367 938\n598 15 \n914 96 \n" \
               "930 737\n224 861\n517 409\n143 728\n289 845\n144 804\n774 685\n98 641 \n634 2  \n819 627\n257 506\n" \
               "932 848\n546 889\n723 342\n830 250\n617 748\n924 334\n151 721\n318 892\n102 65 \n748 196\n76 940 \n" \
               "921 582\n871 228\n701 245\n339 823\n484 991\n574 146\n104 823\n363 557"
        with mock.patch('jmetal.problem.singleobjective.knapsack.open', new=mock.mock_open(read_data=data)):
            problem = Knapsack(from_file=True, filename=filename)
            self.assertEqual(1, problem.number_of_variables)
            self.assertEqual(1, problem.number_of_objectives)
            self.assertEqual(1, problem.number_of_constraints)
            self.assertEqual(50, problem.number_of_bits) 
Example #26
Source File: test_utils.py    From os-net-config with Apache License 2.0 5 votes vote down vote up
def test_get_interface_driver_fail_empty(self):
        mocked_open = mock.mock_open(read_data='DRIVER\n')
        self.stub_out('os_net_config.utils.open', mocked_open)
        driver = utils.get_interface_driver('eth1')
        self.assertFalse(driver) 
Example #27
Source File: test_utils.py    From os-net-config with Apache License 2.0 5 votes vote down vote up
def test_get_interface_driver_fail_none(self):
        mocked_open = mock.mock_open(read_data='')
        self.stub_out('os_net_config.utils.open', mocked_open)
        driver = utils.get_interface_driver('eth1')
        self.assertFalse(driver) 
Example #28
Source File: test_utils.py    From os-net-config with Apache License 2.0 5 votes vote down vote up
def test_bind_dpdk_interfaces_same_driver(self):
        mocked_open = mock.mock_open(read_data='DRIVER=vfio-pci\n')
        self.stub_out('os_net_config.utils.open', mocked_open)
        mocked_logger = mock.Mock()
        self.stub_out('os_net_config.utils.logger.info', mocked_logger)
        try:
            utils.bind_dpdk_interfaces('eth1', 'vfio-pci', False)
        except utils.OvsDpdkBindException:
            self.fail("Received OvsDpdkBindException unexpectedly")
        msg = "Driver (vfio-pci) is already bound to the device (eth1)"
        mocked_logger.assert_called_with(msg) 
Example #29
Source File: test_utils.py    From os-net-config with Apache License 2.0 5 votes vote down vote up
def test_get_device_id_exception(self):
        mocked_open = mock.mock_open()
        mocked_open.side_effect = IOError
        with mock.patch('os_net_config.utils.open', mocked_open, create=True):
            device = utils.get_device_id('nic2')
            self.assertEqual(None, device) 
Example #30
Source File: test_utils.py    From os-net-config with Apache License 2.0 5 votes vote down vote up
def test_get_device_id_success(self):
        mocked_open = mock.mock_open(read_data='0x1003\n')
        with mock.patch('os_net_config.utils.open', mocked_open, create=True):
            device = utils.get_device_id('nic2')
            self.assertEqual('0x1003', device)