test_config.py 21.2 KB
Newer Older
1
# Copyright (c) OpenMMLab. All rights reserved.
2
import argparse
Ma Zerun's avatar
Ma Zerun committed
3
import copy
Jerry Jiarui XU's avatar
Jerry Jiarui XU committed
4
import json
5
import os
Kai Chen's avatar
Kai Chen committed
6
import os.path as osp
7
import shutil
Jerry Jiarui XU's avatar
Jerry Jiarui XU committed
8
import tempfile
9
from pathlib import Path
Kai Chen's avatar
Kai Chen committed
10
11

import pytest
12
import yaml
13
from mmengine import dump, load
Kai Chen's avatar
Kai Chen committed
14

15
from mmcv import Config, ConfigDict, DictAction
Kai Chen's avatar
Kai Chen committed
16

17
18
data_path = osp.join(osp.dirname(osp.dirname(__file__)), 'data')

Kai Chen's avatar
Kai Chen committed
19

Kai Chen's avatar
Kai Chen committed
20
def test_construct():
Kai Chen's avatar
Kai Chen committed
21
22
23
24
25
26
    cfg = Config()
    assert cfg.filename is None
    assert cfg.text == ''
    assert len(cfg) == 0
    assert cfg._cfg_dict == {}

Kai Chen's avatar
Kai Chen committed
27
28
29
    with pytest.raises(TypeError):
        Config([0, 1])

Jerry Jiarui XU's avatar
Jerry Jiarui XU committed
30
    cfg_dict = dict(item1=[1, 2], item2=dict(a=0), item3=True, item4='test')
31
    # test a.py
32
    cfg_file = osp.join(data_path, 'config/a.py')
33
34
35
36
37
38
    cfg_file_path = Path(cfg_file)
    file_list = [cfg_file, cfg_file_path]
    for item in file_list:
        cfg = Config(cfg_dict, filename=item)
        assert isinstance(cfg, Config)
        assert isinstance(cfg.filename, str) and cfg.filename == str(item)
39
        assert cfg.text == open(item).read()
40
41
42
43
        assert cfg.dump() == cfg.pretty_text
        with tempfile.TemporaryDirectory() as temp_config_dir:
            dump_file = osp.join(temp_config_dir, 'a.py')
            cfg.dump(dump_file)
44
            assert cfg.dump() == open(dump_file).read()
45
            assert Config.fromfile(dump_file)
46
47

    # test b.json
48
    cfg_file = osp.join(data_path, 'config/b.json')
49
50
51
    cfg = Config(cfg_dict, filename=cfg_file)
    assert isinstance(cfg, Config)
    assert cfg.filename == cfg_file
52
    assert cfg.text == open(cfg_file).read()
53
54
55
56
    assert cfg.dump() == json.dumps(cfg_dict)
    with tempfile.TemporaryDirectory() as temp_config_dir:
        dump_file = osp.join(temp_config_dir, 'b.json')
        cfg.dump(dump_file)
57
        assert cfg.dump() == open(dump_file).read()
58
59
60
        assert Config.fromfile(dump_file)

    # test c.yaml
61
    cfg_file = osp.join(data_path, 'config/c.yaml')
62
63
64
    cfg = Config(cfg_dict, filename=cfg_file)
    assert isinstance(cfg, Config)
    assert cfg.filename == cfg_file
65
    assert cfg.text == open(cfg_file).read()
66
67
68
69
    assert cfg.dump() == yaml.dump(cfg_dict)
    with tempfile.TemporaryDirectory() as temp_config_dir:
        dump_file = osp.join(temp_config_dir, 'c.yaml')
        cfg.dump(dump_file)
70
        assert cfg.dump() == open(dump_file).read()
71
        assert Config.fromfile(dump_file)
Jerry Jiarui XU's avatar
Jerry Jiarui XU committed
72

73
    # test h.py
74
    cfg_file = osp.join(data_path, 'config/h.py')
75
76
77
78
79
80
81
82
    path = osp.join(osp.dirname(__file__), 'data', 'config')
    # the value of osp.dirname(__file__) may be `D:\a\xxx` in windows
    # environment. When dumping the cfg_dict to file, `D:\a\xxx` will be
    # converted to `D:\x07\xxx` and it will cause unexpected result when
    # checking whether `D:\a\xxx` equals to `D:\x07\xxx`. Therefore, we forcely
    # convert a string representation of the path with forward slashes (/)
    path = Path(path).as_posix()
    cfg_dict = dict(item1='h.py', item2=path, item3='abc_h')
83
84
85
    cfg = Config(cfg_dict, filename=cfg_file)
    assert isinstance(cfg, Config)
    assert cfg.filename == cfg_file
86
    assert cfg.text == open(cfg_file).read()
87
88
89
90
    assert cfg.dump() == cfg.pretty_text
    with tempfile.TemporaryDirectory() as temp_config_dir:
        dump_file = osp.join(temp_config_dir, 'h.py')
        cfg.dump(dump_file)
91
        assert cfg.dump() == open(dump_file).read()
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
        assert Config.fromfile(dump_file)
        assert Config.fromfile(dump_file)['item1'] == cfg_dict['item1']
        assert Config.fromfile(dump_file)['item2'] == cfg_dict['item2']
        assert Config.fromfile(dump_file)['item3'] == cfg_dict['item3']

    # test no use_predefined_variable
    cfg_dict = dict(
        item1='{{fileBasename}}',
        item2='{{ fileDirname}}',
        item3='abc_{{ fileBasenameNoExtension }}')
    assert Config.fromfile(cfg_file, False)
    assert Config.fromfile(cfg_file, False)['item1'] == cfg_dict['item1']
    assert Config.fromfile(cfg_file, False)['item2'] == cfg_dict['item2']
    assert Config.fromfile(cfg_file, False)['item3'] == cfg_dict['item3']

    # test p.yaml
108
    cfg_file = osp.join(data_path, 'config/p.yaml')
109
    cfg_dict = dict(item1=osp.join(osp.dirname(__file__), 'data', 'config'))
110
111
112
    cfg = Config(cfg_dict, filename=cfg_file)
    assert isinstance(cfg, Config)
    assert cfg.filename == cfg_file
113
    assert cfg.text == open(cfg_file).read()
114
115
116
117
    assert cfg.dump() == yaml.dump(cfg_dict)
    with tempfile.TemporaryDirectory() as temp_config_dir:
        dump_file = osp.join(temp_config_dir, 'p.yaml')
        cfg.dump(dump_file)
118
        assert cfg.dump() == open(dump_file).read()
119
120
121
122
123
124
125
126
        assert Config.fromfile(dump_file)
        assert Config.fromfile(dump_file)['item1'] == cfg_dict['item1']

    # test no use_predefined_variable
    assert Config.fromfile(cfg_file, False)
    assert Config.fromfile(cfg_file, False)['item1'] == '{{ fileDirname }}'

    # test o.json
127
    cfg_file = osp.join(data_path, 'config/o.json')
128
    cfg_dict = dict(item1=osp.join(osp.dirname(__file__), 'data', 'config'))
129
130
131
    cfg = Config(cfg_dict, filename=cfg_file)
    assert isinstance(cfg, Config)
    assert cfg.filename == cfg_file
132
    assert cfg.text == open(cfg_file).read()
133
134
135
136
    assert cfg.dump() == json.dumps(cfg_dict)
    with tempfile.TemporaryDirectory() as temp_config_dir:
        dump_file = osp.join(temp_config_dir, 'o.json')
        cfg.dump(dump_file)
137
        assert cfg.dump() == open(dump_file).read()
138
139
140
141
142
143
144
        assert Config.fromfile(dump_file)
        assert Config.fromfile(dump_file)['item1'] == cfg_dict['item1']

    # test no use_predefined_variable
    assert Config.fromfile(cfg_file, False)
    assert Config.fromfile(cfg_file, False)['item1'] == '{{ fileDirname }}'

Kai Chen's avatar
Kai Chen committed
145
146

def test_fromfile():
lizz's avatar
lizz committed
147
    for filename in ['a.py', 'a.b.py', 'b.json', 'c.yaml']:
148
        cfg_file = osp.join(data_path, 'config', filename)
149
150
151
152
153
154
155
        cfg_file_path = Path(cfg_file)
        file_list = [cfg_file, cfg_file_path]
        for item in file_list:
            cfg = Config.fromfile(item)
            assert isinstance(cfg, Config)
            assert isinstance(cfg.filename, str) and cfg.filename == str(item)
            assert cfg.text == osp.abspath(osp.expanduser(item)) + '\n' + \
156
                open(item).read()
Kai Chen's avatar
Kai Chen committed
157

158
159
160
161
162
163
164
165
166
167
168
169
170
    # test custom_imports for Config.fromfile
    cfg_file = osp.join(data_path, 'config', 'q.py')
    imported_file = osp.join(data_path, 'config', 'r.py')
    target_pkg = osp.join(osp.dirname(__file__), 'r.py')

    # Since the imported config will be regarded as a tmp file
    # it should be copied to the directory at the same level
    shutil.copy(imported_file, target_pkg)
    Config.fromfile(cfg_file, import_custom_modules=True)

    assert os.environ.pop('TEST_VALUE') == 'test'
    os.remove(target_pkg)

171
172
    with pytest.raises(FileNotFoundError):
        Config.fromfile('no_such_file.py')
Kai Chen's avatar
Kai Chen committed
173
    with pytest.raises(IOError):
174
        Config.fromfile(osp.join(data_path, 'color.jpg'))
Kai Chen's avatar
Kai Chen committed
175
176


177
178
179
180
181
182
183
184
185
def test_fromstring():
    for filename in ['a.py', 'a.b.py', 'b.json', 'c.yaml']:
        cfg_file = osp.join(data_path, 'config', filename)
        file_format = osp.splitext(filename)[-1]
        in_cfg = Config.fromfile(cfg_file)

        out_cfg = Config.fromstring(in_cfg.pretty_text, '.py')
        assert in_cfg._cfg_dict == out_cfg._cfg_dict

186
        cfg_str = open(cfg_file).read()
187
188
189
190
191
192
193
194
195
196
        out_cfg = Config.fromstring(cfg_str, file_format)
        assert in_cfg._cfg_dict == out_cfg._cfg_dict

    # test pretty_text only supports py file format
    cfg_file = osp.join(data_path, 'config', 'b.json')
    in_cfg = Config.fromfile(cfg_file)
    with pytest.raises(Exception):
        Config.fromstring(in_cfg.pretty_text, '.json')

    # test file format error
197
    cfg_str = open(cfg_file).read()
198
199
200
201
    with pytest.raises(Exception):
        Config.fromstring(cfg_str, '.py')


Jerry Jiarui XU's avatar
Jerry Jiarui XU committed
202
def test_merge_from_base():
203
    cfg_file = osp.join(data_path, 'config/d.py')
Jerry Jiarui XU's avatar
Jerry Jiarui XU committed
204
205
206
    cfg = Config.fromfile(cfg_file)
    assert isinstance(cfg, Config)
    assert cfg.filename == cfg_file
207
    base_cfg_file = osp.join(data_path, 'config/base.py')
Jerry Jiarui XU's avatar
Jerry Jiarui XU committed
208
    merge_text = osp.abspath(osp.expanduser(base_cfg_file)) + '\n' + \
209
        open(base_cfg_file).read()
Jerry Jiarui XU's avatar
Jerry Jiarui XU committed
210
    merge_text += '\n' + osp.abspath(osp.expanduser(cfg_file)) + '\n' + \
211
                  open(cfg_file).read()
Jerry Jiarui XU's avatar
Jerry Jiarui XU committed
212
213
214
215
216
217
218
    assert cfg.text == merge_text
    assert cfg.item1 == [2, 3]
    assert cfg.item2.a == 1
    assert cfg.item3 is False
    assert cfg.item4 == 'test_base'

    with pytest.raises(TypeError):
219
        Config.fromfile(osp.join(data_path, 'config/e.py'))
Jerry Jiarui XU's avatar
Jerry Jiarui XU committed
220
221
222


def test_merge_from_multiple_bases():
223
    cfg_file = osp.join(data_path, 'config/l.py')
Jerry Jiarui XU's avatar
Jerry Jiarui XU committed
224
225
226
227
228
229
230
231
    cfg = Config.fromfile(cfg_file)
    assert isinstance(cfg, Config)
    assert cfg.filename == cfg_file
    # cfg.field
    assert cfg.item1 == [1, 2]
    assert cfg.item2.a == 0
    assert cfg.item3 is False
    assert cfg.item4 == 'test'
Jerry Jiarui XU's avatar
Jerry Jiarui XU committed
232
233
234
    assert cfg.item5 == dict(a=0, b=1)
    assert cfg.item6 == [dict(a=0), dict(b=1)]
    assert cfg.item7 == dict(a=[0, 1, 2], b=dict(c=[3.1, 4.2, 5.3]))
Jerry Jiarui XU's avatar
Jerry Jiarui XU committed
235
236

    with pytest.raises(KeyError):
237
        Config.fromfile(osp.join(data_path, 'config/m.py'))
Jerry Jiarui XU's avatar
Jerry Jiarui XU committed
238
239


240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
def test_base_variables():
    for file in ['t.py', 't.json', 't.yaml']:
        cfg_file = osp.join(data_path, f'config/{file}')
        cfg = Config.fromfile(cfg_file)
        assert isinstance(cfg, Config)
        assert cfg.filename == cfg_file
        # cfg.field
        assert cfg.item1 == [1, 2]
        assert cfg.item2.a == 0
        assert cfg.item3 is False
        assert cfg.item4 == 'test'
        assert cfg.item5 == dict(a=0, b=1)
        assert cfg.item6 == [dict(a=0), dict(b=1)]
        assert cfg.item7 == dict(a=[0, 1, 2], b=dict(c=[3.1, 4.2, 5.3]))
        assert cfg.item8 == file
        assert cfg.item9 == dict(a=0)
        assert cfg.item10 == [3.1, 4.2, 5.3]

    # test nested base
    for file in ['u.py', 'u.json', 'u.yaml']:
        cfg_file = osp.join(data_path, f'config/{file}')
        cfg = Config.fromfile(cfg_file)
        assert isinstance(cfg, Config)
        assert cfg.filename == cfg_file
        # cfg.field
        assert cfg.base == '_base_.item8'
        assert cfg.item1 == [1, 2]
        assert cfg.item2.a == 0
        assert cfg.item3 is False
        assert cfg.item4 == 'test'
        assert cfg.item5 == dict(a=0, b=1)
        assert cfg.item6 == [dict(a=0), dict(b=1)]
        assert cfg.item7 == dict(a=[0, 1, 2], b=dict(c=[3.1, 4.2, 5.3]))
        assert cfg.item8 == 't.py'
        assert cfg.item9 == dict(a=0)
        assert cfg.item10 == [3.1, 4.2, 5.3]
        assert cfg.item11 == 't.py'
        assert cfg.item12 == dict(a=0)
        assert cfg.item13 == [3.1, 4.2, 5.3]
        assert cfg.item14 == [1, 2]
        assert cfg.item15 == dict(
            a=dict(b=dict(a=0)),
            b=[False],
            c=['test'],
            d=[[{
                'e': 0
            }], [{
                'a': 0
            }, {
                'b': 1
            }]],
            e=[1, 2])

    # test reference assignment for py
    cfg_file = osp.join(data_path, 'config/v.py')
    cfg = Config.fromfile(cfg_file)
    assert isinstance(cfg, Config)
    assert cfg.filename == cfg_file
    assert cfg.item21 == 't.py'
    assert cfg.item22 == 't.py'
    assert cfg.item23 == [3.1, 4.2, 5.3]
    assert cfg.item24 == [3.1, 4.2, 5.3]
    assert cfg.item25 == dict(
        a=dict(b=[3.1, 4.2, 5.3]),
        b=[[3.1, 4.2, 5.3]],
        c=[[{
            'e': 't.py'
        }], [{
            'a': 0
        }, {
            'b': 1
        }]],
        e='t.py')


Jerry Jiarui XU's avatar
Jerry Jiarui XU committed
315
def test_merge_recursive_bases():
316
    cfg_file = osp.join(data_path, 'config/f.py')
Jerry Jiarui XU's avatar
Jerry Jiarui XU committed
317
318
319
320
321
322
323
324
325
326
327
    cfg = Config.fromfile(cfg_file)
    assert isinstance(cfg, Config)
    assert cfg.filename == cfg_file
    # cfg.field
    assert cfg.item1 == [2, 3]
    assert cfg.item2.a == 1
    assert cfg.item3 is False
    assert cfg.item4 == 'test_recursive_bases'


def test_merge_from_dict():
328
    cfg_file = osp.join(data_path, 'config/a.py')
Jerry Jiarui XU's avatar
Jerry Jiarui XU committed
329
    cfg = Config.fromfile(cfg_file)
330
    input_options = {'item2.a': 1, 'item2.b': 0.1, 'item3': False}
Jerry Jiarui XU's avatar
Jerry Jiarui XU committed
331
    cfg.merge_from_dict(input_options)
332
    assert cfg.item2 == dict(a=1, b=0.1)
Jerry Jiarui XU's avatar
Jerry Jiarui XU committed
333
334
    assert cfg.item3 is False

335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
    cfg_file = osp.join(data_path, 'config/s.py')
    cfg = Config.fromfile(cfg_file)

    # Allow list keys
    input_options = {'item.0.a': 1, 'item.1.b': 1}
    cfg.merge_from_dict(input_options, allow_list_keys=True)
    assert cfg.item == [{'a': 1}, {'b': 1, 'c': 0}]

    # allow_list_keys is False
    input_options = {'item.0.a': 1, 'item.1.b': 1}
    with pytest.raises(TypeError):
        cfg.merge_from_dict(input_options, allow_list_keys=False)

    # Overflowed index number
    input_options = {'item.2.a': 1}
    with pytest.raises(KeyError):
        cfg.merge_from_dict(input_options, allow_list_keys=True)

Jerry Jiarui XU's avatar
Jerry Jiarui XU committed
353
354

def test_merge_delete():
355
    cfg_file = osp.join(data_path, 'config/delete.py')
Jerry Jiarui XU's avatar
Jerry Jiarui XU committed
356
357
    cfg = Config.fromfile(cfg_file)
    # cfg.field
358
359
    assert cfg.item1 == dict(a=0)
    assert cfg.item2 == dict(a=0, b=0)
Jerry Jiarui XU's avatar
Jerry Jiarui XU committed
360
361
362
363
    assert cfg.item3 is True
    assert cfg.item4 == 'test'
    assert '_delete_' not in cfg.item2

364
365
366
367
    # related issue: https://github.com/open-mmlab/mmcv/issues/1570
    assert type(cfg.item1) == ConfigDict
    assert type(cfg.item2) == ConfigDict

Jerry Jiarui XU's avatar
Jerry Jiarui XU committed
368

369
370
def test_merge_intermediate_variable():

371
    cfg_file = osp.join(data_path, 'config/i_child.py')
372
373
374
375
376
377
378
379
380
381
382
    cfg = Config.fromfile(cfg_file)
    # cfg.field
    assert cfg.item1 == [1, 2]
    assert cfg.item2 == dict(a=0)
    assert cfg.item3 is True
    assert cfg.item4 == 'test'
    assert cfg.item_cfg == dict(b=2)
    assert cfg.item5 == dict(cfg=dict(b=1))
    assert cfg.item6 == dict(cfg=dict(b=2))


383
def test_fromfile_in_config():
384
    cfg_file = osp.join(data_path, 'config/code.py')
385
386
387
388
389
390
391
392
393
    cfg = Config.fromfile(cfg_file)
    # cfg.field
    assert cfg.cfg.item1 == [1, 2]
    assert cfg.cfg.item2 == dict(a=0)
    assert cfg.cfg.item3 is True
    assert cfg.cfg.item4 == 'test'
    assert cfg.item5 == 1


Kai Chen's avatar
Kai Chen committed
394
395
396
397
def test_dict():
    cfg_dict = dict(item1=[1, 2], item2=dict(a=0), item3=True, item4='test')

    for filename in ['a.py', 'b.json', 'c.yaml']:
398
        cfg_file = osp.join(data_path, 'config', filename)
Kai Chen's avatar
Kai Chen committed
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
        cfg = Config.fromfile(cfg_file)

        # len(cfg)
        assert len(cfg) == 4
        # cfg.keys()
        assert set(cfg.keys()) == set(cfg_dict.keys())
        assert set(cfg._cfg_dict.keys()) == set(cfg_dict.keys())
        # cfg.values()
        for value in cfg.values():
            assert value in cfg_dict.values()
        # cfg.items()
        for name, value in cfg.items():
            assert name in cfg_dict
            assert value in cfg_dict.values()
        # cfg.field
        assert cfg.item1 == cfg_dict['item1']
        assert cfg.item2 == cfg_dict['item2']
        assert cfg.item2.a == 0
        assert cfg.item3 == cfg_dict['item3']
        assert cfg.item4 == cfg_dict['item4']
419
420
        with pytest.raises(AttributeError):
            cfg.not_exist
Kai Chen's avatar
Kai Chen committed
421
422
423
424
425
        # field in cfg, cfg[field], cfg.get()
        for name in ['item1', 'item2', 'item3', 'item4']:
            assert name in cfg
            assert cfg[name] == cfg_dict[name]
            assert cfg.get(name) == cfg_dict[name]
426
            assert cfg.get('not_exist') is None
Kai Chen's avatar
Kai Chen committed
427
            assert cfg.get('not_exist', 0) == 0
428
429
430
            with pytest.raises(KeyError):
                cfg['not_exist']
        assert 'item1' in cfg
Kai Chen's avatar
Kai Chen committed
431
432
433
434
435
436
437
438
        assert 'not_exist' not in cfg
        # cfg.update()
        cfg.update(dict(item1=0))
        assert cfg.item1 == 0
        cfg.update(dict(item2=dict(a=1)))
        assert cfg.item2.a == 1


439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
@pytest.mark.parametrize('file', ['a.json', 'b.py', 'c.yaml', 'd.yml', None])
def test_dump(file):
    # config loaded from dict
    cfg_dict = dict(item1=[1, 2], item2=dict(a=0), item3=True, item4='test')
    cfg = Config(cfg_dict=cfg_dict)
    assert cfg.item1 == cfg_dict['item1']
    assert cfg.item2 == cfg_dict['item2']
    assert cfg.item3 == cfg_dict['item3']
    assert cfg.item4 == cfg_dict['item4']
    assert cfg._filename is None
    if file is not None:
        # dump without a filename argument is only returning pretty_text.
        with tempfile.TemporaryDirectory() as temp_config_dir:
            cfg_file = osp.join(temp_config_dir, file)
            cfg.dump(cfg_file)
            dumped_cfg = Config.fromfile(cfg_file)
            assert dumped_cfg._cfg_dict == cfg._cfg_dict
    else:
        assert cfg.dump() == cfg.pretty_text

    # The key of json must be a string, so key `1` will be converted to `'1'`.
    def compare_json_cfg(ori_cfg, dumped_json_cfg):
        for key, value in ori_cfg.items():
            assert str(key) in dumped_json_cfg
            if not isinstance(value, dict):
                assert ori_cfg[key] == dumped_json_cfg[str(key)]
            else:
                compare_json_cfg(value, dumped_json_cfg[str(key)])

    # config loaded from file
    cfg_file = osp.join(data_path, 'config/n.py')
    cfg = Config.fromfile(cfg_file)
    if file is not None:
        with tempfile.TemporaryDirectory() as temp_config_dir:
            cfg_file = osp.join(temp_config_dir, file)
            cfg.dump(cfg_file)
            dumped_cfg = Config.fromfile(cfg_file)
        if not file.endswith('.json'):
            assert dumped_cfg._cfg_dict == cfg._cfg_dict
        else:
            compare_json_cfg(cfg._cfg_dict, dumped_cfg._cfg_dict)
    else:
        assert cfg.dump() == cfg.pretty_text


Kai Chen's avatar
Kai Chen committed
484
485
486
487
488
489
490
491
492
493
494
def test_setattr():
    cfg = Config()
    cfg.item1 = [1, 2]
    cfg.item2 = {'a': 0}
    cfg['item5'] = {'a': {'b': None}}
    assert cfg._cfg_dict['item1'] == [1, 2]
    assert cfg.item1 == [1, 2]
    assert cfg._cfg_dict['item2'] == {'a': 0}
    assert cfg.item2.a == 0
    assert cfg._cfg_dict['item5'] == {'a': {'b': None}}
    assert cfg.item5.a.b is None
Jerry Jiarui XU's avatar
Jerry Jiarui XU committed
495
496
497


def test_pretty_text():
498
    cfg_file = osp.join(data_path, 'config/l.py')
Jerry Jiarui XU's avatar
Jerry Jiarui XU committed
499
500
501
502
503
504
505
    cfg = Config.fromfile(cfg_file)
    with tempfile.TemporaryDirectory() as temp_config_dir:
        text_cfg_filename = osp.join(temp_config_dir, '_text_config.py')
        with open(text_cfg_filename, 'w') as f:
            f.write(cfg.pretty_text)
        text_cfg = Config.fromfile(text_cfg_filename)
    assert text_cfg._cfg_dict == cfg._cfg_dict
506
507
508
509
510
511


def test_dict_action():
    parser = argparse.ArgumentParser(description='Train a detector')
    parser.add_argument(
        '--options', nargs='+', action=DictAction, help='custom options')
512
513
514
515
516
517
518
519
520
521
522
523
524
    # Nested brackets
    args = parser.parse_args(
        ['--options', 'item2.a=a,b', 'item2.b=[(a,b), [1,2], false]'])
    out_dict = {'item2.a': ['a', 'b'], 'item2.b': [('a', 'b'), [1, 2], False]}
    assert args.options == out_dict
    # Single Nested brackets
    args = parser.parse_args(['--options', 'item2.a=[[1]]'])
    out_dict = {'item2.a': [[1]]}
    assert args.options == out_dict
    # Imbalance bracket
    with pytest.raises(AssertionError):
        parser.parse_args(['--options', 'item2.a=[(a,b), [1,2], false'])
    # Normal values
525
526
527
528
529
530
531
532
533
534
535
536
    args = parser.parse_args([
        '--options', 'item2.a=1', 'item2.b=0.1', 'item2.c=x', 'item3=false',
        'item4=none', 'item5=None'
    ])
    out_dict = {
        'item2.a': 1,
        'item2.b': 0.1,
        'item2.c': 'x',
        'item3': False,
        'item4': 'none',
        'item5': None,
    }
537
    assert args.options == out_dict
538
    cfg_file = osp.join(data_path, 'config/a.py')
539
540
541
542
    cfg = Config.fromfile(cfg_file)
    cfg.merge_from_dict(args.options)
    assert cfg.item2 == dict(a=1, b=0.1, c='x')
    assert cfg.item3 is False
543
544


545
def test_reserved_key():
546
    cfg_file = osp.join(data_path, 'config/g.py')
547
548
    with pytest.raises(KeyError):
        Config.fromfile(cfg_file)
549
550
551


def test_syntax_error():
552
553
554
555
    # the name can not be used to open the file a second time in windows,
    # so `delete` should be set as `False` and we need to manually remove it
    # more details can be found at https://github.com/open-mmlab/mmcv/pull/1077
    temp_cfg_file = tempfile.NamedTemporaryFile(suffix='.py', delete=False)
556
557
558
559
560
    temp_cfg_path = temp_cfg_file.name
    # write a file with syntax error
    with open(temp_cfg_path, 'w') as f:
        f.write('a=0b=dict(c=1)')
    with pytest.raises(
561
            SyntaxError, match='There are syntax errors in config file'):
562
563
        Config.fromfile(temp_cfg_path)
    temp_cfg_file.close()
564
    os.remove(temp_cfg_path)
Kevin's avatar
Kevin committed
565
566
567


def test_pickle_support():
568
    cfg_file = osp.join(data_path, 'config/n.py')
Kevin's avatar
Kevin committed
569
570
571
572
573
574
575
576
    cfg = Config.fromfile(cfg_file)

    with tempfile.TemporaryDirectory() as temp_config_dir:
        pkl_cfg_filename = osp.join(temp_config_dir, '_pickle.pkl')
        dump(cfg, pkl_cfg_filename)
        pkl_cfg = load(pkl_cfg_filename)

    assert pkl_cfg._cfg_dict == cfg._cfg_dict
577
578
579
580
581
582
583
584
585


def test_deprecation():
    deprecated_cfg_files = [
        osp.join(data_path, 'config/deprecated.py'),
        osp.join(data_path, 'config/deprecated_as_base.py')
    ]

    for cfg_file in deprecated_cfg_files:
586
        with pytest.warns(DeprecationWarning):
587
588
            cfg = Config.fromfile(cfg_file)
        assert cfg.item1 == 'expected'
Ma Zerun's avatar
Ma Zerun committed
589
590
591
592
593
594
595
596
597
598
599
600


def test_deepcopy():
    cfg_file = osp.join(data_path, 'config/n.py')
    cfg = Config.fromfile(cfg_file)
    new_cfg = copy.deepcopy(cfg)

    assert isinstance(new_cfg, Config)
    assert new_cfg._cfg_dict == cfg._cfg_dict
    assert new_cfg._cfg_dict is not cfg._cfg_dict
    assert new_cfg._filename == cfg._filename
    assert new_cfg._text == cfg._text
601
602
603
604
605
606
607
608
609
610
611
612


def test_copy():
    cfg_file = osp.join(data_path, 'config/n.py')
    cfg = Config.fromfile(cfg_file)
    new_cfg = copy.copy(cfg)

    assert isinstance(new_cfg, Config)
    assert new_cfg is not cfg
    assert new_cfg._cfg_dict is cfg._cfg_dict
    assert new_cfg._filename == cfg._filename
    assert new_cfg._text == cfg._text