How to use monkeypatch method in Pytest

Best Python code snippet using pytest

test_config.py

Source:test_config.py Github

copy

Full Screen

1import pytest2from conftest import abort3from fabric.api import env4from fabrix.config import read_config, conf, local_conf5def test_conf_is_env_host_string_is_none(tmpdir, monkeypatch):6 assert len(conf) == 07 assert conf['test'] is None8def test_read_config_default_config_name_nox_exists(tmpdir, monkeypatch):9 fabfile = tmpdir.join("fabfile.py")10 monkeypatch.setitem(env, "real_fabfile", str(fabfile))11 read_config()12 assert env.hosts == list()13def test_read_config_default_config_name_exists(tmpdir, monkeypatch):14 fabfile = tmpdir.join("fabfile.py")15 config_filename = tmpdir.join("fabfile.yaml")16 config_filename.write("""17 hosts:18 - 172.22.22.9919 """)20 monkeypatch.setitem(env, "real_fabfile", str(fabfile))21 read_config()22 assert env.hosts == ['172.22.22.99']23def test_read_config_explicit_relative_config_name(tmpdir, monkeypatch):24 fabfile = tmpdir.join("fabfile.py")25 config_filename = tmpdir.join("stage.yaml")26 config_filename.write("""27 hosts:28 - 10.10.10.1029 """)30 monkeypatch.setitem(env, "real_fabfile", str(fabfile))31 read_config("stage.yaml")32 assert env.hosts == ['10.10.10.10']33def test_read_config_explicit_absolute_config_name(tmpdir, monkeypatch):34 fabfile = tmpdir.join("fabfile.py")35 config_filename = tmpdir.join("stage.yaml")36 config_filename.write("""37 hosts:38 - 10.20.30.4039 """)40 monkeypatch.setitem(env, "real_fabfile", str(fabfile))41 read_config(str(config_filename))42 assert env.hosts == ['10.20.30.40']43def test_read_config_explicit_relative_config_name_not_exists(tmpdir, monkeypatch):44 fabfile = tmpdir.join("fabfile.py")45 config_filename = tmpdir.join("stage.yaml")46 monkeypatch.setitem(env, "real_fabfile", str(fabfile))47 with abort('read_config: config \'%s\' not exists' % str(config_filename)):48 read_config("stage.yaml")49def test_hosts_and_roles_not_defined(tmpdir, monkeypatch):50 fabfile = tmpdir.join("fabfile.py")51 config_file = tmpdir.join("fabfile.yaml")52 monkeypatch.setitem(env, "real_fabfile", str(fabfile))53 config_file.write("""54 defaults:55 hosts_defined: False56 roles_defined: False57 """)58 with abort('read_config: hosts or roles must be defined in config'):59 read_config()60def test_hosts_and_roles_defined(tmpdir, monkeypatch):61 fabfile = tmpdir.join("fabfile.py")62 config_file = tmpdir.join("fabfile.yaml")63 monkeypatch.setitem(env, "real_fabfile", str(fabfile))64 config_file.write("""65 hosts:66 - 172.22.22.9967 roles:68 - role: test69 hosts:70 - 11.11.11.1171 """)72 with abort('read_config: hosts and roles can\'t be simultaneously defined in config'):73 read_config()74def test_hosts_is_not_list(tmpdir, monkeypatch):75 fabfile = tmpdir.join("fabfile.py")76 config_file = tmpdir.join("fabfile.yaml")77 monkeypatch.setitem(env, "real_fabfile", str(fabfile))78 config_file.write("""79 hosts:80 host:172.22.22.9981 """)82 with abort('read_config: hosts must be list type'):83 read_config()84def test_hosts_must_not_be_empty(tmpdir, monkeypatch):85 fabfile = tmpdir.join("fabfile.py")86 config_file = tmpdir.join("fabfile.yaml")87 monkeypatch.setitem(env, "real_fabfile", str(fabfile))88 config_file.write("""89 hosts: []90 """)91 with abort('read_config: hosts must not be empty'):92 read_config()93def test_hosts_must_be_list_of_strings(tmpdir, monkeypatch):94 fabfile = tmpdir.join("fabfile.py")95 config_file = tmpdir.join("fabfile.yaml")96 monkeypatch.setitem(env, "real_fabfile", str(fabfile))97 config_file.write("""98 hosts:99 - host: 172.22.22.99100 """)101 with abort('read_config: hosts must be list of strings'):102 read_config()103def test_hosts_entry_none(tmpdir, monkeypatch):104 fabfile = tmpdir.join("fabfile.py")105 config_file = tmpdir.join("fabfile.yaml")106 monkeypatch.setitem(env, "real_fabfile", str(fabfile))107 config_file.write("""108 hosts:109 -110 """)111 with abort('read_config: hosts host can\'t be empty string'):112 read_config()113def test_hosts_host_cant_be_empty_string(tmpdir, monkeypatch):114 fabfile = tmpdir.join("fabfile.py")115 config_file = tmpdir.join("fabfile.yaml")116 monkeypatch.setitem(env, "real_fabfile", str(fabfile))117 config_file.write("""118 hosts:119 - ""120 """)121 with abort('read_config: hosts host can\'t be empty string'):122 read_config()123def test_host_already_defined(tmpdir, monkeypatch):124 fabfile = tmpdir.join("fabfile.py")125 config_file = tmpdir.join("fabfile.yaml")126 monkeypatch.setitem(env, "real_fabfile", str(fabfile))127 config_file.write("""128 hosts:129 - 11.11.11.11130 - 10.10.10.10131 - 11.11.11.11132 """)133 with abort('read_config: host \'%s\' already defined in hosts list' % '11.11.11.11'):134 read_config()135def test_roles_is_not_list(tmpdir, monkeypatch):136 fabfile = tmpdir.join("fabfile.py")137 config_file = tmpdir.join("fabfile.yaml")138 monkeypatch.setitem(env, "real_fabfile", str(fabfile))139 config_file.write("""140 roles:141 role: test142 """)143 with abort('read_config: roles must be list type'):144 read_config()145def test_roles_must_not_be_empty(tmpdir, monkeypatch):146 fabfile = tmpdir.join("fabfile.py")147 config_file = tmpdir.join("fabfile.yaml")148 monkeypatch.setitem(env, "real_fabfile", str(fabfile))149 config_file.write("""150 roles: []151 """)152 with abort('read_config: roles must not be empty'):153 read_config()154def test_roles_role_cant_be_empty_string(tmpdir, monkeypatch):155 fabfile = tmpdir.join("fabfile.py")156 config_file = tmpdir.join("fabfile.yaml")157 monkeypatch.setitem(env, "real_fabfile", str(fabfile))158 config_file.write("""159 roles:160 - role: ""161 hosts:162 - 11.11.11.11163 """)164 with abort('read_config: roles role can\'t be empty string'):165 read_config()166def test_roles_role_is_none(tmpdir, monkeypatch):167 fabfile = tmpdir.join("fabfile.py")168 config_file = tmpdir.join("fabfile.yaml")169 monkeypatch.setitem(env, "real_fabfile", str(fabfile))170 config_file.write("""171 roles:172 - role:173 hosts:174 - 11.11.11.11175 """)176 with abort('read_config: roles role can\'t be empty string'):177 read_config()178def test_roles_role_required(tmpdir, monkeypatch):179 fabfile = tmpdir.join("fabfile.py")180 config_file = tmpdir.join("fabfile.yaml")181 monkeypatch.setitem(env, "real_fabfile", str(fabfile))182 config_file.write("""183 roles:184 - hosts:185 - 11.11.11.11186 """)187 with abort('read_config: roles role required'):188 read_config()189def test_roles_role_must_be_string_type(tmpdir, monkeypatch):190 fabfile = tmpdir.join("fabfile.py")191 config_file = tmpdir.join("fabfile.yaml")192 monkeypatch.setitem(env, "real_fabfile", str(fabfile))193 config_file.write("""194 roles:195 - role: ['test']196 - hosts:197 - 11.11.11.11198 """)199 with abort('read_config: roles role must be string type'):200 read_config()201def test_roles_hosts_required(tmpdir, monkeypatch):202 fabfile = tmpdir.join("fabfile.py")203 config_file = tmpdir.join("fabfile.yaml")204 monkeypatch.setitem(env, "real_fabfile", str(fabfile))205 config_file.write("""206 roles:207 - role: test208 """)209 with abort('read_config: role \'%s\' hosts required' % 'test'):210 read_config()211def test_roles_hosts_must_be_list_type(tmpdir, monkeypatch):212 fabfile = tmpdir.join("fabfile.py")213 config_file = tmpdir.join("fabfile.yaml")214 monkeypatch.setitem(env, "real_fabfile", str(fabfile))215 config_file.write("""216 roles:217 - role: test218 hosts: 10.10.10.10219 """)220 with abort('read_config: role \'%s\' hosts must be list type' % 'test'):221 read_config()222def test_roles_hosts_host_cant_be_empty_string(tmpdir, monkeypatch):223 fabfile = tmpdir.join("fabfile.py")224 config_file = tmpdir.join("fabfile.yaml")225 monkeypatch.setitem(env, "real_fabfile", str(fabfile))226 config_file.write("""227 roles:228 - role: test229 hosts:230 - ""231 """)232 with abort('read_config: role \'%s\' hosts host can\'t be empty string' % 'test'):233 read_config()234def test_roles_hosts_host_is_none(tmpdir, monkeypatch):235 fabfile = tmpdir.join("fabfile.py")236 config_file = tmpdir.join("fabfile.yaml")237 monkeypatch.setitem(env, "real_fabfile", str(fabfile))238 config_file.write("""239 roles:240 - role: test241 hosts:242 -243 """)244 with abort('read_config: role \'%s\' hosts host can\'t be empty string' % 'test'):245 read_config()246def test_role_hosts_must_be_list_of_strings(tmpdir, monkeypatch):247 fabfile = tmpdir.join("fabfile.py")248 config_file = tmpdir.join("fabfile.yaml")249 monkeypatch.setitem(env, "real_fabfile", str(fabfile))250 config_file.write("""251 roles:252 - role: test253 hosts:254 - ['10.10.10.10', '11.11.11.11']255 """)256 with abort('read_config: role \'%s\' hosts must be list of strings' % 'test'):257 read_config()258def test_roles_hosts_already_defined(tmpdir, monkeypatch):259 fabfile = tmpdir.join("fabfile.py")260 config_file = tmpdir.join("fabfile.yaml")261 monkeypatch.setitem(env, "real_fabfile", str(fabfile))262 config_file.write("""263 roles:264 - role: test265 hosts:266 - 11.11.11.11267 - 10.10.10.10268 - 11.11.11.11269 """)270 with abort('read_config: host \'%s\' already defined in role \'%s\' hosts list' % ('11.11.11.11', 'test')):271 read_config()272def test_role_already_defined(tmpdir, monkeypatch):273 fabfile = tmpdir.join("fabfile.py")274 config_file = tmpdir.join("fabfile.yaml")275 monkeypatch.setitem(env, "real_fabfile", str(fabfile))276 config_file.write("""277 roles:278 - role: test279 hosts:280 - 11.11.11.11281 - 10.10.10.10282 - role: other-role283 hosts:284 - 172.22.22.99285 - 11.11.11.11286 - role: test287 hosts:288 - 22.22.22.22289 """)290 with abort('read_config: role \'%s\' already defined' % 'test'):291 read_config()292def test_unexpected_roles_entry(tmpdir, monkeypatch):293 fabfile = tmpdir.join("fabfile.py")294 config_file = tmpdir.join("fabfile.yaml")295 monkeypatch.setitem(env, "real_fabfile", str(fabfile))296 config_file.write("""297 roles:298 - role: test299 hosts:300 - 11.11.11.11301 - 10.10.10.10302 vars:303 foo: bar304 """)305 with abort(r'read_config: unexpected roles entry:.*'):306 read_config()307def test_roles_empty_hosts_list(tmpdir, monkeypatch):308 fabfile = tmpdir.join("fabfile.py")309 config_file = tmpdir.join("fabfile.yaml")310 monkeypatch.setitem(env, "real_fabfile", str(fabfile))311 config_file.write("""312 roles:313 - role: test2314 hosts:315 - 11.11.11.11316 - role: test317 hosts: []318 """)319 with abort('read_config: role \'%s\' hosts must not be empty' % 'test'):320 read_config()321def test_error_parsing_yaml(tmpdir, monkeypatch):322 fabfile = tmpdir.join("fabfile.py")323 config_file = tmpdir.join("fabfile.yaml")324 monkeypatch.setitem(env, "real_fabfile", str(fabfile))325 config_file.write("""326 roles:327 - role: test328 hosts:329 - 11.11.11.11330 host_vars: []331 """)332 with abort('read_config: error parsing config.*'):333 read_config()334def test_host_vars_must_be_list_type(tmpdir, monkeypatch):335 fabfile = tmpdir.join("fabfile.py")336 config_file = tmpdir.join("fabfile.yaml")337 monkeypatch.setitem(env, "real_fabfile", str(fabfile))338 config_file.write("""339 roles:340 - role: test341 hosts:342 - 11.11.11.11343 host_vars:344 foo: bar345 """)346 with abort('read_config: host_vars must be list type'):347 read_config()348def test_host_vars_host_required(tmpdir, monkeypatch):349 fabfile = tmpdir.join("fabfile.py")350 config_file = tmpdir.join("fabfile.yaml")351 monkeypatch.setitem(env, "real_fabfile", str(fabfile))352 config_file.write("""353 roles:354 - role: test355 hosts:356 - 11.11.11.11357 host_vars:358 - foo: bar359 """)360 with abort('read_config: host_vars host required'):361 read_config()362def test_host_vars_host_cant_be_empty_string(tmpdir, monkeypatch):363 fabfile = tmpdir.join("fabfile.py")364 config_file = tmpdir.join("fabfile.yaml")365 monkeypatch.setitem(env, "real_fabfile", str(fabfile))366 config_file.write("""367 roles:368 - role: test369 hosts:370 - 11.11.11.11371 host_vars:372 - host: ""373 """)374 with abort('read_config: host_vars host can\'t be empty string'):375 read_config()376def test_host_vars_host_is_none(tmpdir, monkeypatch):377 fabfile = tmpdir.join("fabfile.py")378 config_file = tmpdir.join("fabfile.yaml")379 monkeypatch.setitem(env, "real_fabfile", str(fabfile))380 config_file.write("""381 roles:382 - role: test383 hosts:384 - 11.11.11.11385 host_vars:386 - host:387 """)388 with abort('read_config: host_vars host can\'t be empty string'):389 read_config()390def test_host_vars_host_must_be_string_type(tmpdir, monkeypatch):391 fabfile = tmpdir.join("fabfile.py")392 config_file = tmpdir.join("fabfile.yaml")393 monkeypatch.setitem(env, "real_fabfile", str(fabfile))394 config_file.write("""395 roles:396 - role: test397 hosts:398 - 11.11.11.11399 host_vars:400 - host: []401 """)402 with abort('read_config: host_vars host must be string type'):403 read_config()404def test_host_vars_host_not_defined_in_hosts_list(tmpdir, monkeypatch):405 fabfile = tmpdir.join("fabfile.py")406 config_file = tmpdir.join("fabfile.yaml")407 monkeypatch.setitem(env, "real_fabfile", str(fabfile))408 config_file.write("""409 hosts:410 - 10.10.10.10411 host_vars:412 - host: 11.11.11.11413 vars: {}414 """)415 with abort('read_config: host_vars host \'%s\' not defined in hosts list' % '11.11.11.11'):416 read_config()417def test_host_vars_host_not_defined_in_roles_hosts_list(tmpdir, monkeypatch):418 fabfile = tmpdir.join("fabfile.py")419 config_file = tmpdir.join("fabfile.yaml")420 monkeypatch.setitem(env, "real_fabfile", str(fabfile))421 config_file.write("""422 roles:423 - role: test424 hosts:425 - 10.10.10.10426 host_vars:427 - host: 11.11.11.11428 vars: {}429 """)430 with abort('read_config: host_vars host \'%s\' not defined in roles hosts list' % '11.11.11.11'):431 read_config()432def test_host_vars_vars_required(tmpdir, monkeypatch):433 fabfile = tmpdir.join("fabfile.py")434 config_file = tmpdir.join("fabfile.yaml")435 monkeypatch.setitem(env, "real_fabfile", str(fabfile))436 config_file.write("""437 roles:438 - role: test439 hosts:440 - 11.11.11.11441 host_vars:442 - host: 11.11.11.11443 vsar:444 """)445 with abort('read_config: host_vars host \'%s\' vars required' % '11.11.11.11'):446 read_config()447def test_host_vars_vars_must_be_dict(tmpdir, monkeypatch):448 fabfile = tmpdir.join("fabfile.py")449 config_file = tmpdir.join("fabfile.yaml")450 monkeypatch.setitem(env, "real_fabfile", str(fabfile))451 config_file.write("""452 roles:453 - role: test454 hosts:455 - 11.11.11.11456 host_vars:457 - host: 11.11.11.11458 vars: ['a', 'b', 'c']459 """)460 with abort('read_config: host_vars host \'%s\' vars must be dictionary type' % '11.11.11.11'):461 read_config()462def test_host_vars_host_already_defined(tmpdir, monkeypatch):463 fabfile = tmpdir.join("fabfile.py")464 config_file = tmpdir.join("fabfile.yaml")465 monkeypatch.setitem(env, "real_fabfile", str(fabfile))466 config_file.write("""467 roles:468 - role: test469 hosts:470 - 11.11.11.11471 host_vars:472 - host: 11.11.11.11473 vars:474 foo: bar475 - host: 11.11.11.11476 vars:477 foo: baz478 """)479 with abort('read_config: host_vars host \'%s\' already defined' % '11.11.11.11'):480 read_config()481def test_host_vars_unexpected_entry(tmpdir, monkeypatch):482 fabfile = tmpdir.join("fabfile.py")483 config_file = tmpdir.join("fabfile.yaml")484 monkeypatch.setitem(env, "real_fabfile", str(fabfile))485 config_file.write("""486 roles:487 - role: test488 hosts:489 - 11.11.11.11490 host_vars:491 - host: 11.11.11.11492 vars:493 foo: baz494 vras:495 foo: bar496 """)497 with abort(r'read_config: unexpected host_vars entry:.*'):498 read_config()499def test_roles_vars_with_roles_not_defined(tmpdir, monkeypatch):500 fabfile = tmpdir.join("fabfile.py")501 config_file = tmpdir.join("fabfile.yaml")502 monkeypatch.setitem(env, "real_fabfile", str(fabfile))503 config_file.write("""504 hosts:505 - 11.11.11.11506 role_vars:507 - role: test508 vars:509 foo: baz510 """)511 with abort('read_config: unexpected role_vars, because roles is not defined'):512 read_config()513def test_role_vars_must_be_list_type(tmpdir, monkeypatch):514 fabfile = tmpdir.join("fabfile.py")515 config_file = tmpdir.join("fabfile.yaml")516 monkeypatch.setitem(env, "real_fabfile", str(fabfile))517 config_file.write("""518 roles:519 - role: test520 hosts:521 - 11.11.11.11522 role_vars:523 foo: baz524 """)525 with abort('read_config: role_vars must be list type'):526 read_config()527def test_role_vars_role_required(tmpdir, monkeypatch):528 fabfile = tmpdir.join("fabfile.py")529 config_file = tmpdir.join("fabfile.yaml")530 monkeypatch.setitem(env, "real_fabfile", str(fabfile))531 config_file.write("""532 roles:533 - role: test534 hosts:535 - 11.11.11.11536 role_vars:537 - rloe: test538 vars:539 foo: baz540 """)541 with abort('read_config: role_vars role required'):542 read_config()543def test_role_vars_role_is_none(tmpdir, monkeypatch):544 fabfile = tmpdir.join("fabfile.py")545 config_file = tmpdir.join("fabfile.yaml")546 monkeypatch.setitem(env, "real_fabfile", str(fabfile))547 config_file.write("""548 roles:549 - role: test550 hosts:551 - 11.11.11.11552 role_vars:553 - role:554 vars:555 foo: baz556 """)557 with abort('read_config: role_vars role can\'t be empty string'):558 read_config()559def test_role_vars_role_is_not_list(tmpdir, monkeypatch):560 fabfile = tmpdir.join("fabfile.py")561 config_file = tmpdir.join("fabfile.yaml")562 monkeypatch.setitem(env, "real_fabfile", str(fabfile))563 config_file.write("""564 roles:565 - role: test566 hosts:567 - 11.11.11.11568 role_vars:569 - role: [ 'test']570 vars:571 foo: baz572 """)573 with abort('read_config: role_vars role must be string type'):574 read_config()575def test_role_vars_role_is_empty_string(tmpdir, monkeypatch):576 fabfile = tmpdir.join("fabfile.py")577 config_file = tmpdir.join("fabfile.yaml")578 monkeypatch.setitem(env, "real_fabfile", str(fabfile))579 config_file.write("""580 roles:581 - role: test582 hosts:583 - 11.11.11.11584 role_vars:585 - role: ""586 vars:587 foo: baz588 """)589 with abort('read_config: role_vars role can\'t be empty string'):590 read_config()591def test_role_vars_role_not_in_roles(tmpdir, monkeypatch):592 fabfile = tmpdir.join("fabfile.py")593 config_file = tmpdir.join("fabfile.yaml")594 monkeypatch.setitem(env, "real_fabfile", str(fabfile))595 config_file.write("""596 roles:597 - role: test598 hosts:599 - 11.11.11.11600 role_vars:601 - role: text602 vars:603 foo: baz604 """)605 with abort('read_config: role_vars role \'%s\' not defined in roles' % 'text'):606 read_config()607def test_role_vars_role_vars_not_defined(tmpdir, monkeypatch):608 fabfile = tmpdir.join("fabfile.py")609 config_file = tmpdir.join("fabfile.yaml")610 monkeypatch.setitem(env, "real_fabfile", str(fabfile))611 config_file.write("""612 roles:613 - role: test614 hosts:615 - 11.11.11.11616 role_vars:617 - role: test618 """)619 with abort('read_config: role_vars role \'%s\' vars required' % 'test'):620 read_config()621def test_role_vars_role_vars_must_be_list(tmpdir, monkeypatch):622 fabfile = tmpdir.join("fabfile.py")623 config_file = tmpdir.join("fabfile.yaml")624 monkeypatch.setitem(env, "real_fabfile", str(fabfile))625 config_file.write("""626 roles:627 - role: test628 hosts:629 - 11.11.11.11630 role_vars:631 - role: test632 vars: ['a', 'b', 'c']633 """)634 with abort('read_config: role_vars role \'%s\' vars must be dictionary type' % 'test'):635 read_config()636def test_role_vars_role_already_defined(tmpdir, monkeypatch):637 fabfile = tmpdir.join("fabfile.py")638 config_file = tmpdir.join("fabfile.yaml")639 monkeypatch.setitem(env, "real_fabfile", str(fabfile))640 config_file.write("""641 roles:642 - role: test643 hosts:644 - 11.11.11.11645 role_vars:646 - role: test647 vars: {}648 - role: test649 vars: {}650 """)651 with abort('read_config: role_vars role \'%s\' already defined' % 'test'):652 read_config()653def test_role_vars_unknown_entry(tmpdir, monkeypatch):654 fabfile = tmpdir.join("fabfile.py")655 config_file = tmpdir.join("fabfile.yaml")656 monkeypatch.setitem(env, "real_fabfile", str(fabfile))657 config_file.write("""658 roles:659 - role: test660 hosts:661 - 11.11.11.11662 role_vars:663 - role: test664 vars: {}665 vras: {foo: bar}666 """)667 with abort(r'read_config: unexpected role_vars entry:.*'):668 read_config()669def test_defaults_must_be_list_type(tmpdir, monkeypatch):670 fabfile = tmpdir.join("fabfile.py")671 config_file = tmpdir.join("fabfile.yaml")672 monkeypatch.setitem(env, "real_fabfile", str(fabfile))673 config_file.write("""674 roles:675 - role: test676 hosts:677 - 11.11.11.11678 role_vars:679 - role: test680 vars: {}681 defaults: []682 """)683 with abort('read_config: defaults must be dictionary type'):684 read_config()685def test_local_vars_must_be_list_type(tmpdir, monkeypatch):686 fabfile = tmpdir.join("fabfile.py")687 config_file = tmpdir.join("fabfile.yaml")688 monkeypatch.setitem(env, "real_fabfile", str(fabfile))689 config_file.write("""690 hosts:691 - 11.11.11.11692 host_vars:693 - host: 11.11.11.11694 vars: {}695 local_vars: []696 """)697 with abort('read_config: local_vars must be dictionary type'):698 read_config()699def test_unexpected_entry(tmpdir, monkeypatch):700 fabfile = tmpdir.join("fabfile.py")701 config_file = tmpdir.join("fabfile.yaml")702 monkeypatch.setitem(env, "real_fabfile", str(fabfile))703 config_file.write("""704 hosts:705 - 11.11.11.11706 host_vars:707 - host: 11.11.11.11708 vars: {}709 lcal_vars: {foo: bar}710 """)711 with abort(r'read_config: unexpected config entry:.*'):712 read_config()713def test_defaults_and_local_vars(tmpdir, monkeypatch):714 fabfile = tmpdir.join("fabfile.py")715 config_file = tmpdir.join("fabfile.yaml")716 monkeypatch.setitem(env, "real_fabfile", str(fabfile))717 monkeypatch.setitem(env, "host_string", '11.11.11.11')718 config_file.write("""719 hosts:720 - 11.11.11.11721 host_vars:722 - host: 11.11.11.11723 vars: {}724 defaults:725 nginx: True726 local_vars: {foo: bar}727 """)728 read_config()729 assert conf.nginx is True730 assert local_conf.foo == 'bar'731 local_conf['foo'] = 'baz'732 assert local_conf.foo == 'baz'733 local_conf.foo = True734 assert local_conf.foo is True735def test_host_vars(tmpdir, monkeypatch):736 fabfile = tmpdir.join("fabfile.py")737 config_file = tmpdir.join("fabfile.yaml")738 monkeypatch.setitem(env, "real_fabfile", str(fabfile))739 monkeypatch.setitem(env, "host_string", '11.11.11.11')740 config_file.write("""741 hosts:742 - 11.11.11.11743 - 22.22.22.22744 host_vars:745 - host: 11.11.11.11746 vars:747 override: new748 defaults:749 nginx: True750 override: old751 local_vars: {foo: bar}752 """)753 read_config()754 assert conf.override == 'new'755 monkeypatch.setitem(env, "host_string", '22.22.22.22')756 assert conf.override == 'old'757def test_conf(tmpdir, monkeypatch):758 fabfile = tmpdir.join("fabfile.py")759 config_file = tmpdir.join("fabfile.yaml")760 monkeypatch.setitem(env, "real_fabfile", str(fabfile))761 monkeypatch.setitem(env, "host_string", '11.11.11.11')762 config_file.write("""763 hosts:764 - 11.11.11.11765 - 22.22.22.22766 host_vars:767 - host: 11.11.11.11768 vars:769 override: new770 defaults:771 nginx: True772 override: old773 local_vars: {foo: bar}774 """)775 read_config()776 conf.test = 'beta'777 assert conf['test'] == 'beta'778 conf['override'] = 'disable'779 assert conf.override == 'disable'780def test_roles(tmpdir, monkeypatch):781 fabfile = tmpdir.join("fabfile.py")782 config_file = tmpdir.join("fabfile.yaml")783 monkeypatch.setitem(env, "real_fabfile", str(fabfile))784 monkeypatch.setitem(env, "host_string", '11.11.11.11')785 config_file.write("""786 roles:787 - role: web788 hosts:789 - 11.11.11.11790 - 22.22.22.22791 - 33.33.33.33792 - role: db793 hosts:794 - 7.7.7.7795 - 9.9.9.9796 - role: rest797 hosts:798 - 44.44.44.44799 defaults:800 var1: def1801 var2: def2802 var3: def3803 var4: def4804 var5: def5805 host_vars:806 - host: 11.11.11.11807 vars:808 var1: special_value_for_host_11809 - host: 9.9.9.9810 vars:811 type: mysql812 role_vars:813 - role: web814 vars:815 var1: from_web_role816 var2: from_web_role817 - role: db818 vars:819 var3: from_db_role820 local_vars:821 var1: loc1822 var2: loc2823 var3: loc3824 var4: loc4825 var5: loc5826 """)827 read_config()828 assert local_conf.var1 == 'loc1'829 assert local_conf.var2 == 'loc2'830 assert local_conf.var3 == 'loc3'831 monkeypatch.setitem(env, "host_string", '11.11.11.11')832 assert conf.var1 == 'special_value_for_host_11'833 assert conf.var2 == 'from_web_role'834 assert conf.var3 == 'def3'835 monkeypatch.setitem(env, "host_string", '22.22.22.22')836 assert conf.var1 == 'from_web_role'837 assert conf.var2 == 'from_web_role'838 assert conf.var3 == 'def3'839 monkeypatch.setitem(env, "host_string", '44.44.44.44')840 assert conf.var1 == 'def1'841 assert conf.var2 == 'def2'842 assert conf.var3 == 'def3'843def test_roles_without_defaults(tmpdir, monkeypatch):844 fabfile = tmpdir.join("fabfile.py")845 config_file = tmpdir.join("fabfile.yaml")846 monkeypatch.setitem(env, "real_fabfile", str(fabfile))847 monkeypatch.setitem(env, "host_string", '11.11.11.11')848 config_file.write("""849 roles:850 - role: web851 hosts:852 - 11.11.11.11853 - 22.22.22.22854 - 33.33.33.33855 - role: db856 hosts:857 - 7.7.7.7858 - 9.9.9.9859 - role: rest860 hosts:861 - 44.44.44.44862 host_vars:863 - host: 11.11.11.11864 vars:865 var1: special_value_for_host_11866 - host: 9.9.9.9867 vars:868 type: mysql869 role_vars:870 - role: web871 vars:872 var1: from_web_role873 var2: from_web_role874 - role: db875 vars:876 var3: from_db_role877 """)878 read_config()879 monkeypatch.setitem(env, "host_string", '11.11.11.11')880 assert conf.var1 == 'special_value_for_host_11'881 assert conf.var2 == 'from_web_role'882 with pytest.raises(AttributeError):883 conf.var3884 monkeypatch.setitem(env, "host_string", '22.22.22.22')885 assert conf.var1 == 'from_web_role'886 assert conf.var2 == 'from_web_role'887 with pytest.raises(AttributeError):888 conf.var3889 monkeypatch.setitem(env, "host_string", '44.44.44.44')890 with pytest.raises(AttributeError):891 conf.var1892 with pytest.raises(AttributeError):893 conf.var2894 with pytest.raises(AttributeError):895 conf.var3896def test_dict_methods(tmpdir, monkeypatch):897 fabfile = tmpdir.join("fabfile.py")898 config_file = tmpdir.join("fabfile.yaml")899 monkeypatch.setitem(env, "real_fabfile", str(fabfile))900 monkeypatch.setitem(env, "host_string", '11.11.11.11')901 config_file.write("""902 roles:903 - role: web904 hosts:905 - 11.11.11.11906 - 22.22.22.22907 - 33.33.33.33908 - role: db909 hosts:910 - 7.7.7.7911 - 9.9.9.9912 - role: rest913 hosts:914 - 44.44.44.44915 host_vars:916 - host: 11.11.11.11917 vars:918 var1: special_value_for_host_11919 - host: 9.9.9.9920 vars:921 type: mysql922 role_vars:923 - role: web924 vars:925 var1: from_web_role926 var2: from_web_role927 var3: value3928 var4: value4929 var5: value5930 - role: db931 vars:932 var3: from_db_role933 local_vars:934 var1: value1935 """)936 read_config()937 assert local_conf.var1 == 'value1'938 del local_conf.var1939 with pytest.raises(AttributeError):940 local_conf.var1941 monkeypatch.setitem(env, "host_string", '11.11.11.11')942 del conf.var1943 with pytest.raises(AttributeError):944 conf.var1945 del conf['var2']946 with pytest.raises(AttributeError):947 conf.var2948 conf.var1 = 'value1'949 conf.var2 = 'value2'950 assert len(repr(conf)) == len("{'var1': 'value1', 'var2': 'value2', 'var3': 'value3', 'var4': 'value4', 'var5': 'value5'}")951 assert repr(conf) == str(conf)952 conf_copy = conf.copy()953 assert conf == conf_copy954 assert conf == {'var1': 'value1', 'var2': 'value2', 'var3': 'value3', 'var4': 'value4', 'var5': 'value5'}955 assert conf != {'VAR1': 'value1', 'var2': 'value2', 'var3': 'value3', 'var4': 'value4', 'var5': 'value5'}956 assert conf.__hash__ is None957 assert len(conf) == 5958 for key in conf:959 assert key[0:3] == 'var'960 assert 'var3' in conf961 assert 'bar3' not in conf962 assert len(conf.keys()) == 5963 assert sorted(conf.keys()) == ['var1', 'var2', 'var3', 'var4', 'var5']964 for key, value in conf.items():965 assert key[0:3] == 'var'966 assert value[0:5] == 'value'967 for key, value in conf.iteritems():968 assert key[0:3] == 'var'969 assert value[0:5] == 'value'970 for key in conf.iterkeys():971 assert key[0:3] == 'var'972 for value in conf.itervalues():973 assert value[0:5] == 'value'974 assert sorted(conf.values()) == ['value1', 'value2', 'value3', 'value4', 'value5']975 assert conf.has_key('var5') # noqa976 assert not conf.has_key('var7') # noqa977 conf.update(dict(var6='oldvalue6', var7='oldvalue7'))978 assert conf.var6 == 'oldvalue6'979 assert conf.var7 == 'oldvalue7'980 conf.update(var6='value6', var7='value7')981 assert conf.var6 == 'value6'982 assert conf.var7 == 'value7'983 assert conf.get('var8') is None984 assert conf.get('var8', 'provided-default') == 'provided-default'985 assert conf.get('var5') == 'value5'986 assert conf.setdefault('var7') == 'value7'987 assert conf.var7 == 'value7'988 assert 'var8' not in conf989 assert conf.setdefault('var8', 'value8') == 'value8'990 assert conf.var8 == 'value8'991 with pytest.raises(KeyError):992 conf.pop('var9')993 before = conf.copy()994 assert conf.pop('var9', 'value9') == 'value9'995 after = conf.copy()996 assert before == after997 assert conf.__cmp__(before) == 0998 assert conf.__cmp__(after) == 0999 assert conf.pop('var8') == 'value8'1000 assert len(conf) == 71001 for i in range(0, 7):1002 key, value = conf.popitem()1003 assert key[0:3] == 'var'1004 assert value[0:5] == 'value'1005 assert len(conf) == 01006 with pytest.raises(KeyError):1007 conf.popitem()1008 conf.var1 = 'value1'1009 conf.var2 = 'value2'1010 conf.var3 = 'value3'1011 conf.var4 = 'value4'1012 conf.var5 = 'value5'1013 assert len(conf) == 51014 assert len(conf.viewitems()) == 51015 assert len(conf.viewkeys()) == 51016 assert len(conf.viewvalues()) == 51017 conf.clear()1018 assert len(conf) == 0...

Full Screen

Full Screen

test_monkeypatch.py

Source:test_monkeypatch.py Github

copy

Full Screen

1import os2import re3import sys4import textwrap5import pytest6from _pytest.monkeypatch import MonkeyPatch7@pytest.fixture8def mp():9 cwd = os.getcwd()10 sys_path = list(sys.path)11 yield MonkeyPatch()12 sys.path[:] = sys_path13 os.chdir(cwd)14def test_setattr():15 class A:16 x = 117 monkeypatch = MonkeyPatch()18 pytest.raises(AttributeError, monkeypatch.setattr, A, "notexists", 2)19 monkeypatch.setattr(A, "y", 2, raising=False)20 assert A.y == 221 monkeypatch.undo()22 assert not hasattr(A, "y")23 monkeypatch = MonkeyPatch()24 monkeypatch.setattr(A, "x", 2)25 assert A.x == 226 monkeypatch.setattr(A, "x", 3)27 assert A.x == 328 monkeypatch.undo()29 assert A.x == 130 A.x = 531 monkeypatch.undo() # double-undo makes no modification32 assert A.x == 533class TestSetattrWithImportPath:34 def test_string_expression(self, monkeypatch):35 monkeypatch.setattr("os.path.abspath", lambda x: "hello2")36 assert os.path.abspath("123") == "hello2"37 def test_string_expression_class(self, monkeypatch):38 monkeypatch.setattr("_pytest.config.Config", 42)39 import _pytest40 assert _pytest.config.Config == 4241 def test_unicode_string(self, monkeypatch):42 monkeypatch.setattr("_pytest.config.Config", 42)43 import _pytest44 assert _pytest.config.Config == 4245 monkeypatch.delattr("_pytest.config.Config")46 def test_wrong_target(self, monkeypatch):47 pytest.raises(TypeError, lambda: monkeypatch.setattr(None, None))48 def test_unknown_import(self, monkeypatch):49 pytest.raises(ImportError, lambda: monkeypatch.setattr("unkn123.classx", None))50 def test_unknown_attr(self, monkeypatch):51 pytest.raises(52 AttributeError, lambda: monkeypatch.setattr("os.path.qweqwe", None)53 )54 def test_unknown_attr_non_raising(self, monkeypatch):55 # https://github.com/pytest-dev/pytest/issues/74656 monkeypatch.setattr("os.path.qweqwe", 42, raising=False)57 assert os.path.qweqwe == 4258 def test_delattr(self, monkeypatch):59 monkeypatch.delattr("os.path.abspath")60 assert not hasattr(os.path, "abspath")61 monkeypatch.undo()62 assert os.path.abspath63def test_delattr():64 class A:65 x = 166 monkeypatch = MonkeyPatch()67 monkeypatch.delattr(A, "x")68 assert not hasattr(A, "x")69 monkeypatch.undo()70 assert A.x == 171 monkeypatch = MonkeyPatch()72 monkeypatch.delattr(A, "x")73 pytest.raises(AttributeError, monkeypatch.delattr, A, "y")74 monkeypatch.delattr(A, "y", raising=False)75 monkeypatch.setattr(A, "x", 5, raising=False)76 assert A.x == 577 monkeypatch.undo()78 assert A.x == 179def test_setitem():80 d = {"x": 1}81 monkeypatch = MonkeyPatch()82 monkeypatch.setitem(d, "x", 2)83 monkeypatch.setitem(d, "y", 1700)84 monkeypatch.setitem(d, "y", 1700)85 assert d["x"] == 286 assert d["y"] == 170087 monkeypatch.setitem(d, "x", 3)88 assert d["x"] == 389 monkeypatch.undo()90 assert d["x"] == 191 assert "y" not in d92 d["x"] = 593 monkeypatch.undo()94 assert d["x"] == 595def test_setitem_deleted_meanwhile():96 d = {}97 monkeypatch = MonkeyPatch()98 monkeypatch.setitem(d, "x", 2)99 del d["x"]100 monkeypatch.undo()101 assert not d102@pytest.mark.parametrize("before", [True, False])103def test_setenv_deleted_meanwhile(before):104 key = "qwpeoip123"105 if before:106 os.environ[key] = "world"107 monkeypatch = MonkeyPatch()108 monkeypatch.setenv(key, "hello")109 del os.environ[key]110 monkeypatch.undo()111 if before:112 assert os.environ[key] == "world"113 del os.environ[key]114 else:115 assert key not in os.environ116def test_delitem():117 d = {"x": 1}118 monkeypatch = MonkeyPatch()119 monkeypatch.delitem(d, "x")120 assert "x" not in d121 monkeypatch.delitem(d, "y", raising=False)122 pytest.raises(KeyError, monkeypatch.delitem, d, "y")123 assert not d124 monkeypatch.setitem(d, "y", 1700)125 assert d["y"] == 1700126 d["hello"] = "world"127 monkeypatch.setitem(d, "x", 1500)128 assert d["x"] == 1500129 monkeypatch.undo()130 assert d == {"hello": "world", "x": 1}131def test_setenv():132 monkeypatch = MonkeyPatch()133 with pytest.warns(pytest.PytestWarning):134 monkeypatch.setenv("XYZ123", 2)135 import os136 assert os.environ["XYZ123"] == "2"137 monkeypatch.undo()138 assert "XYZ123" not in os.environ139def test_delenv():140 name = "xyz1234"141 assert name not in os.environ142 monkeypatch = MonkeyPatch()143 pytest.raises(KeyError, monkeypatch.delenv, name, raising=True)144 monkeypatch.delenv(name, raising=False)145 monkeypatch.undo()146 os.environ[name] = "1"147 try:148 monkeypatch = MonkeyPatch()149 monkeypatch.delenv(name)150 assert name not in os.environ151 monkeypatch.setenv(name, "3")152 assert os.environ[name] == "3"153 monkeypatch.undo()154 assert os.environ[name] == "1"155 finally:156 if name in os.environ:157 del os.environ[name]158class TestEnvironWarnings:159 """160 os.environ keys and values should be native strings, otherwise it will cause problems with other modules (notably161 subprocess). On Python 2 os.environ accepts anything without complaining, while Python 3 does the right thing162 and raises an error.163 """164 VAR_NAME = "PYTEST_INTERNAL_MY_VAR"165 def test_setenv_non_str_warning(self, monkeypatch):166 value = 2167 msg = (168 "Value of environment variable PYTEST_INTERNAL_MY_VAR type should be str, "169 "but got 2 (type: int); converted to str implicitly"170 )171 with pytest.warns(pytest.PytestWarning, match=re.escape(msg)):172 monkeypatch.setenv(str(self.VAR_NAME), value)173def test_setenv_prepend():174 import os175 monkeypatch = MonkeyPatch()176 with pytest.warns(pytest.PytestWarning):177 monkeypatch.setenv("XYZ123", 2, prepend="-")178 assert os.environ["XYZ123"] == "2"179 with pytest.warns(pytest.PytestWarning):180 monkeypatch.setenv("XYZ123", 3, prepend="-")181 assert os.environ["XYZ123"] == "3-2"182 monkeypatch.undo()183 assert "XYZ123" not in os.environ184def test_monkeypatch_plugin(testdir):185 reprec = testdir.inline_runsource(186 """187 def test_method(monkeypatch):188 assert monkeypatch.__class__.__name__ == "MonkeyPatch"189 """190 )191 res = reprec.countoutcomes()192 assert tuple(res) == (1, 0, 0), res193def test_syspath_prepend(mp):194 old = list(sys.path)195 mp.syspath_prepend("world")196 mp.syspath_prepend("hello")197 assert sys.path[0] == "hello"198 assert sys.path[1] == "world"199 mp.undo()200 assert sys.path == old201 mp.undo()202 assert sys.path == old203def test_syspath_prepend_double_undo(mp):204 old_syspath = sys.path[:]205 try:206 mp.syspath_prepend("hello world")207 mp.undo()208 sys.path.append("more hello world")209 mp.undo()210 assert sys.path[-1] == "more hello world"211 finally:212 sys.path[:] = old_syspath213def test_chdir_with_path_local(mp, tmpdir):214 mp.chdir(tmpdir)215 assert os.getcwd() == tmpdir.strpath216def test_chdir_with_str(mp, tmpdir):217 mp.chdir(tmpdir.strpath)218 assert os.getcwd() == tmpdir.strpath219def test_chdir_undo(mp, tmpdir):220 cwd = os.getcwd()221 mp.chdir(tmpdir)222 mp.undo()223 assert os.getcwd() == cwd224def test_chdir_double_undo(mp, tmpdir):225 mp.chdir(tmpdir.strpath)226 mp.undo()227 tmpdir.chdir()228 mp.undo()229 assert os.getcwd() == tmpdir.strpath230def test_issue185_time_breaks(testdir):231 testdir.makepyfile(232 """233 import time234 def test_m(monkeypatch):235 def f():236 raise Exception237 monkeypatch.setattr(time, "time", f)238 """239 )240 result = testdir.runpytest()241 result.stdout.fnmatch_lines(242 """243 *1 passed*244 """245 )246def test_importerror(testdir):247 p = testdir.mkpydir("package")248 p.join("a.py").write(249 textwrap.dedent(250 """\251 import doesnotexist252 x = 1253 """254 )255 )256 testdir.tmpdir.join("test_importerror.py").write(257 textwrap.dedent(258 """\259 def test_importerror(monkeypatch):260 monkeypatch.setattr('package.a.x', 2)261 """262 )263 )264 result = testdir.runpytest()265 result.stdout.fnmatch_lines(266 """267 *import error in package.a: No module named 'doesnotexist'*268 """269 )270class SampleNew:271 @staticmethod272 def hello():273 return True274class SampleNewInherit(SampleNew):275 pass276class SampleOld:277 # oldstyle on python2278 @staticmethod279 def hello():280 return True281class SampleOldInherit(SampleOld):282 pass283@pytest.mark.parametrize(284 "Sample",285 [SampleNew, SampleNewInherit, SampleOld, SampleOldInherit],286 ids=["new", "new-inherit", "old", "old-inherit"],287)288def test_issue156_undo_staticmethod(Sample):289 monkeypatch = MonkeyPatch()290 monkeypatch.setattr(Sample, "hello", None)291 assert Sample.hello is None292 monkeypatch.undo()293 assert Sample.hello()294def test_undo_class_descriptors_delattr():295 class SampleParent:296 @classmethod297 def hello(_cls):298 pass299 @staticmethod300 def world():301 pass302 class SampleChild(SampleParent):303 pass304 monkeypatch = MonkeyPatch()305 original_hello = SampleChild.hello306 original_world = SampleChild.world307 monkeypatch.delattr(SampleParent, "hello")308 monkeypatch.delattr(SampleParent, "world")309 assert getattr(SampleParent, "hello", None) is None310 assert getattr(SampleParent, "world", None) is None311 monkeypatch.undo()312 assert original_hello == SampleChild.hello313 assert original_world == SampleChild.world314def test_issue1338_name_resolving():315 pytest.importorskip("requests")316 monkeypatch = MonkeyPatch()317 try:318 monkeypatch.delattr("requests.sessions.Session.request")319 finally:320 monkeypatch.undo()321def test_context():322 monkeypatch = MonkeyPatch()323 import functools324 import inspect325 with monkeypatch.context() as m:326 m.setattr(functools, "partial", 3)327 assert not inspect.isclass(functools.partial)328 assert inspect.isclass(functools.partial)329def test_syspath_prepend_with_namespace_packages(testdir, monkeypatch):330 for dirname in "hello", "world":331 d = testdir.mkdir(dirname)332 ns = d.mkdir("ns_pkg")333 ns.join("__init__.py").write(334 "__import__('pkg_resources').declare_namespace(__name__)"335 )336 lib = ns.mkdir(dirname)337 lib.join("__init__.py").write("def check(): return %r" % dirname)338 monkeypatch.syspath_prepend("hello")339 import ns_pkg.hello340 assert ns_pkg.hello.check() == "hello"341 with pytest.raises(ImportError):342 import ns_pkg.world343 # Prepending should call fixup_namespace_packages.344 monkeypatch.syspath_prepend("world")345 import ns_pkg.world346 assert ns_pkg.world.check() == "world"347 # Should invalidate caches via importlib.invalidate_caches.348 tmpdir = testdir.tmpdir349 modules_tmpdir = tmpdir.mkdir("modules_tmpdir")350 monkeypatch.syspath_prepend(str(modules_tmpdir))351 modules_tmpdir.join("main_app.py").write("app = True")...

Full Screen

Full Screen

test_saucelabs.py

Source:test_saucelabs.py Github

copy

Full Screen

1# This Source Code Form is subject to the terms of the Mozilla Public2# License, v. 2.0. If a copy of the MPL was not distributed with this3# file, You can obtain one at http://mozilla.org/MPL/2.0/.4from functools import partial5import os6import json7import pytest8from pytest_selenium.drivers.cloud import Provider9pytestmark = [pytest.mark.skip_selenium, pytest.mark.nondestructive]10@pytest.fixture11def testfile(testdir):12 return testdir.makepyfile(13 """14 import pytest15 @pytest.mark.nondestructive16 def test_pass(selenium): pass17 """18 )19def failure_with_output(testdir, *args, **kwargs):20 reprec = testdir.inline_run(*args, **kwargs)21 passed, skipped, failed = reprec.listoutcomes()22 assert len(failed) == 123 out = failed[0].longrepr.reprcrash.message24 return out25@pytest.fixture26def failure(testdir, testfile, httpserver_base_url):27 return partial(28 failure_with_output,29 testdir,30 testfile,31 httpserver_base_url,32 "--driver",33 "SauceLabs",34 )35def test_missing_username(failure, monkeypatch, tmpdir):36 monkeypatch.setattr(os.path, "expanduser", lambda p: str(tmpdir))37 assert "SauceLabs username must be set" in failure()38def test_missing_api_key_env(failure, monkeypatch, tmpdir):39 monkeypatch.setattr(os.path, "expanduser", lambda p: str(tmpdir))40 monkeypatch.setenv("SAUCELABS_USERNAME", "foo")41 assert "SauceLabs key must be set" in failure()42def test_missing_api_key_file(failure, monkeypatch, tmpdir):43 monkeypatch.setattr(os.path, "expanduser", lambda p: str(tmpdir))44 tmpdir.join(".saucelabs").write("[credentials]\nusername=foo")45 assert "SauceLabs key must be set" in failure()46@pytest.mark.parametrize(47 ("username", "key"),48 [49 ("SAUCELABS_USERNAME", "SAUCELABS_API_KEY"),50 ("SAUCELABS_USR", "SAUCELABS_PSW"),51 ("SAUCE_USERNAME", "SAUCE_ACCESS_KEY"),52 ],53)54def test_invalid_credentials_env(failure, monkeypatch, tmpdir, username, key):55 monkeypatch.setenv(username, "foo")56 monkeypatch.setenv(key, "bar")57 out = failure()58 messages = ["Sauce Labs Authentication Error", "basic auth failed", "Unauthorized"]59 assert any(message in out for message in messages)60def test_invalid_credentials_file(failure, monkeypatch, tmpdir):61 cfg_file = tmpdir.join(".saucelabs")62 cfg_file.write("[credentials]\nusername=foo\nkey=bar")63 monkeypatch.setattr(Provider, "config_file_path", str(cfg_file))64 out = failure()65 messages = ["Sauce Labs Authentication Error", "basic auth failed", "Unauthorized"]66 assert any(message in out for message in messages)67def test_credentials_in_capabilities(monkeypatch, testdir):68 file_test = testdir.makepyfile(69 """70 import pytest71 @pytest.mark.nondestructive72 def test_sauce_capabilities(driver_kwargs):73 assert driver_kwargs['desired_capabilities']['username'] == 'foo'74 assert driver_kwargs['desired_capabilities']['accessKey'] == 'bar'75 """76 )77 run_sauce_test(monkeypatch, testdir, file_test)78def test_no_sauce_options(monkeypatch, testdir):79 file_test = testdir.makepyfile(80 """81 import pytest82 @pytest.mark.nondestructive83 def test_sauce_capabilities(driver_kwargs):84 try:85 driver_kwargs['desired_capabilities']['sauce:options']86 raise AssertionError('<sauce:options> should not be present!')87 except KeyError:88 pass89 """90 )91 run_sauce_test(monkeypatch, testdir, file_test)92def run_sauce_test(monkeypatch, testdir, file_test):93 monkeypatch.setenv("SAUCELABS_USERNAME", "foo")94 monkeypatch.setenv("SAUCELABS_API_KEY", "bar")95 capabilities = {"browserName": "chrome"}96 variables = testdir.makefile(97 ".json", '{{"capabilities": {}}}'.format(json.dumps(capabilities))98 )99 testdir.quick_qa(100 "--driver", "saucelabs", "--variables", variables, file_test, passed=1101 )102def test_empty_sauce_options(monkeypatch, testdir):103 capabilities = {"browserName": "chrome"}104 expected = {"name": "test_empty_sauce_options.test_sauce_capabilities"}105 run_w3c_sauce_test(capabilities, expected, monkeypatch, testdir)106def test_merge_sauce_options(monkeypatch, testdir):107 version = {"seleniumVersion": "3.8.1"}108 capabilities = {"browserName": "chrome", "sauce:options": version}109 expected = {"name": "test_merge_sauce_options.test_sauce_capabilities"}110 expected.update(version)111 run_w3c_sauce_test(capabilities, expected, monkeypatch, testdir)112def test_merge_sauce_options_with_conflict(monkeypatch, testdir):113 name = "conflict"114 capabilities = {"browserName": "chrome", "sauce:options": {"name": name}}115 expected = {"name": name}116 run_w3c_sauce_test(capabilities, expected, monkeypatch, testdir)117def run_w3c_sauce_test(capabilities, expected_result, monkeypatch, testdir):118 username = "foo"119 access_key = "bar"120 monkeypatch.setenv("SAUCELABS_USERNAME", username)121 monkeypatch.setenv("SAUCELABS_API_KEY", access_key)122 monkeypatch.setenv("SAUCELABS_W3C", "true")123 expected_result.update(124 {"username": username, "accessKey": access_key, "tags": ["nondestructive"]}125 )126 variables = testdir.makefile(127 ".json", '{{"capabilities": {}}}'.format(json.dumps(capabilities))128 )129 file_test = testdir.makepyfile(130 """131 import pytest132 @pytest.mark.nondestructive133 def test_sauce_capabilities(driver_kwargs):134 actual = driver_kwargs['desired_capabilities']['sauce:options']135 assert actual == {}136 """.format(137 expected_result138 )139 )140 testdir.quick_qa(141 "--driver", "saucelabs", "--variables", variables, file_test, passed=1142 )143def test_auth_type_none(monkeypatch):144 from pytest_selenium.drivers.saucelabs import SauceLabs, get_job_url145 monkeypatch.setenv("SAUCELABS_USERNAME", "foo")146 monkeypatch.setenv("SAUCELABS_API_KEY", "bar")147 session_id = "123456"148 expected = "https://api.us-west-1.saucelabs.com/v1/jobs/{}".format(session_id)149 actual = get_job_url(Config("none"), SauceLabs(), session_id)150 assert actual == expected151@pytest.mark.parametrize("auth_type", ["token", "day", "hour"])152def test_auth_type_expiration(monkeypatch, auth_type):153 import re154 from pytest_selenium.drivers.saucelabs import SauceLabs, get_job_url155 monkeypatch.setenv("SAUCELABS_USERNAME", "foo")156 monkeypatch.setenv("SAUCELABS_API_KEY", "bar")157 session_id = "123456"158 expected_pattern = (159 r"https://api.us-west-1.saucelabs\.com/v1/jobs/"160 r"{}\?auth=[a-f0-9]{{32}}$".format(session_id)161 )162 actual = get_job_url(Config(auth_type), SauceLabs(), session_id)163 assert re.match(expected_pattern, actual)164def test_data_center_option(testdir, monkeypatch):165 monkeypatch.setenv("SAUCELABS_USERNAME", "foo")166 monkeypatch.setenv("SAUCELABS_API_KEY", "bar")167 expected_data_center = "us-east-1"168 testdir.makeini(169 f"""170 [pytest]171 saucelabs_data_center = {expected_data_center}172 """173 )174 file_test = testdir.makepyfile(175 f"""176 import pytest177 @pytest.mark.nondestructive178 def test_pass(driver_kwargs):179 assert "{expected_data_center}" in driver_kwargs['command_executor']180 """181 )182 testdir.quick_qa("--driver", "SauceLabs", file_test, passed=1)183def test_data_center_option_file(testdir, monkeypatch, tmpdir):184 monkeypatch.setattr(os.path, "expanduser", lambda p: str(tmpdir))185 monkeypatch.setenv("SAUCELABS_USERNAME", "foo")186 monkeypatch.setenv("SAUCELABS_API_KEY", "bar")187 expected_data_center = "us-east-1"188 tmpdir.join(".saucelabs").write(f"[options]\ndata_center={expected_data_center}")189 file_test = testdir.makepyfile(190 f"""191 import pytest192 @pytest.mark.nondestructive193 def test_pass(driver_kwargs):194 assert "{expected_data_center}" in driver_kwargs['command_executor']195 """196 )197 testdir.quick_qa("--driver", "SauceLabs", file_test, passed=1)198def test_data_center_option_precedence(testdir, monkeypatch, tmpdir):199 monkeypatch.setattr(os.path, "expanduser", lambda p: str(tmpdir))200 monkeypatch.setenv("SAUCELABS_USERNAME", "foo")201 monkeypatch.setenv("SAUCELABS_API_KEY", "bar")202 expected_data_center = "us-east-1"203 tmpdir.join(".saucelabs").write(f"[options]\ndata_center={expected_data_center}")204 testdir.makeini(205 f"""206 [pytest]207 saucelabs_data_center = "ap-east-1"208 """209 )210 file_test = testdir.makepyfile(211 f"""212 import pytest213 @pytest.mark.nondestructive214 def test_pass(driver_kwargs):215 assert "{expected_data_center}" in driver_kwargs['command_executor']216 """217 )218 testdir.quick_qa("--driver", "SauceLabs", file_test, passed=1)219class Config(object):220 def __init__(self, value):221 self._value = value222 def getini(self, key):223 if key == "saucelabs_job_auth":224 return self._value225 else:...

Full Screen

Full Screen

test_xdg.py

Source:test_xdg.py Github

copy

Full Screen

1"""Test suite for xdg."""2import os3from pathlib import Path4from _pytest.monkeypatch import MonkeyPatch5import xdg6HOME_DIR = Path("/homedir")7def test_xdg_cache_home_unset(monkeypatch: MonkeyPatch) -> None:8 """Test xdg_cache_home when XDG_CACHE_HOME is unset."""9 monkeypatch.delenv("XDG_CACHE_HOME", raising=False)10 monkeypatch.setenv("HOME", os.fspath(HOME_DIR))11 assert xdg.xdg_cache_home() == HOME_DIR / ".cache"12def test_xdg_cache_home_empty(monkeypatch: MonkeyPatch) -> None:13 """Test xdg_cache_home when XDG_CACHE_HOME is empty."""14 monkeypatch.setenv("HOME", os.fspath(HOME_DIR))15 monkeypatch.setenv("XDG_CACHE_HOME", "")16 assert xdg.xdg_cache_home() == HOME_DIR / ".cache"17def test_xdg_cache_home_relative(monkeypatch: MonkeyPatch) -> None:18 """Test xdg_cache_home when XDG_CACHE_HOME is relative path."""19 monkeypatch.setenv("HOME", os.fspath(HOME_DIR))20 monkeypatch.setenv("XDG_CACHE_HOME", "rela/tive")21 assert xdg.xdg_cache_home() == HOME_DIR / ".cache"22def test_xdg_cache_home_absolute(monkeypatch: MonkeyPatch) -> None:23 """Test xdg_cache_home when XDG_CACHE_HOME is absolute path."""24 monkeypatch.setenv("XDG_CACHE_HOME", "/xdg_cache_home")25 assert xdg.xdg_cache_home() == Path("/xdg_cache_home")26def test_xdg_config_dirs_unset(monkeypatch: MonkeyPatch) -> None:27 """Test xdg_config_dirs when XDG_CONFIG_DIRS is unset."""28 monkeypatch.delenv("XDG_CONFIG_DIRS", raising=False)29 assert xdg.xdg_config_dirs() == [Path("/etc/xdg")]30def test_xdg_config_dirs_empty(monkeypatch: MonkeyPatch) -> None:31 """Test xdg_config_dirs when XDG_CONFIG_DIRS is empty."""32 monkeypatch.setenv("XDG_CONFIG_DIRS", "")33 assert xdg.xdg_config_dirs() == [Path("/etc/xdg")]34def test_xdg_config_dirs_relative(monkeypatch: MonkeyPatch) -> None:35 """Test xdg_config_dirs when XDG_CONFIG_DIRS is relative paths."""36 monkeypatch.setenv("XDG_CONFIG_DIRS", "rela/tive:ano/ther")37 assert xdg.xdg_config_dirs() == [Path("/etc/xdg")]38def test_xdg_config_dirs_set(monkeypatch: MonkeyPatch) -> None:39 """Test xdg_config_dirs when XDG_CONFIG_DIRS is set."""40 monkeypatch.setenv("XDG_CONFIG_DIRS", "/first:rela/tive:/sec/ond")41 assert xdg.xdg_config_dirs() == [Path("/first"), Path("/sec/ond")]42def test_xdg_config_home_unset(monkeypatch: MonkeyPatch) -> None:43 """Test xdg_config_home when XDG_CONFIG_HOME is unset."""44 monkeypatch.delenv("XDG_CONFIG_HOME", raising=False)45 monkeypatch.setenv("HOME", os.fspath(HOME_DIR))46 assert xdg.xdg_config_home() == HOME_DIR / ".config"47def test_xdg_config_home_empty(monkeypatch: MonkeyPatch) -> None:48 """Test xdg_config_home when XDG_CONFIG_HOME is empty."""49 monkeypatch.setenv("HOME", os.fspath(HOME_DIR))50 monkeypatch.setenv("XDG_CONFIG_HOME", "")51 assert xdg.xdg_config_home() == HOME_DIR / ".config"52def test_xdg_config_home_relative(monkeypatch: MonkeyPatch) -> None:53 """Test xdg_config_home when XDG_CONFIG_HOME is relative path."""54 monkeypatch.setenv("HOME", os.fspath(HOME_DIR))55 monkeypatch.setenv("XDG_CONFIG_HOME", "rela/tive")56 assert xdg.xdg_config_home() == HOME_DIR / ".config"57def test_xdg_config_home_absolute(monkeypatch: MonkeyPatch) -> None:58 """Test xdg_config_home when XDG_CONFIG_HOME is absolute path."""59 monkeypatch.setenv("XDG_CONFIG_HOME", "/xdg_config_home")60 assert xdg.xdg_config_home() == Path("/xdg_config_home")61def test_xdg_data_dirs_unset(monkeypatch: MonkeyPatch) -> None:62 """Test xdg_data_dirs when XDG_DATA_DIRS is unset."""63 monkeypatch.delenv("XDG_DATA_DIRS", raising=False)64 assert xdg.xdg_data_dirs() == [65 Path("/usr/local/share/"),66 Path("/usr/share/"),67 ]68def test_xdg_data_dirs_empty(monkeypatch: MonkeyPatch) -> None:69 """Test xdg_data_dirs when XDG_DATA_DIRS is empty."""70 monkeypatch.setenv("XDG_DATA_DIRS", "")71 assert xdg.xdg_data_dirs() == [72 Path("/usr/local/share/"),73 Path("/usr/share/"),74 ]75def test_xdg_data_dirs_relative(monkeypatch: MonkeyPatch) -> None:76 """Test xdg_data_dirs when XDG_DATA_DIRS is relative paths."""77 monkeypatch.setenv("XDG_DATA_DIRS", "rela/tive:ano/ther")78 assert xdg.xdg_data_dirs() == [79 Path("/usr/local/share/"),80 Path("/usr/share/"),81 ]82def test_xdg_data_dirs_set(monkeypatch: MonkeyPatch) -> None:83 """Test xdg_data_dirs when XDG_DATA_DIRS is set."""84 monkeypatch.setenv("XDG_DATA_DIRS", "/first/:rela/tive:/sec/ond/")85 assert xdg.xdg_data_dirs() == [Path("/first/"), Path("/sec/ond/")]86def test_xdg_data_home_unset(monkeypatch: MonkeyPatch) -> None:87 """Test xdg_data_home when XDG_DATA_HOME is unset."""88 monkeypatch.delenv("XDG_DATA_HOME", raising=False)89 monkeypatch.setenv("HOME", os.fspath(HOME_DIR))90 assert xdg.xdg_data_home() == HOME_DIR / ".local" / "share"91def test_xdg_data_home_empty(monkeypatch: MonkeyPatch) -> None:92 """Test xdg_data_home when XDG_DATA_HOME is empty."""93 monkeypatch.setenv("HOME", os.fspath(HOME_DIR))94 monkeypatch.setenv("XDG_DATA_HOME", "")95 assert xdg.xdg_data_home() == HOME_DIR / ".local" / "share"96def test_xdg_data_home_relative(monkeypatch: MonkeyPatch) -> None:97 """Test xdg_data_home when XDG_DATA_HOME is relative path."""98 monkeypatch.setenv("HOME", os.fspath(HOME_DIR))99 monkeypatch.setenv("XDG_DATA_HOME", "rela/tive")100 assert xdg.xdg_data_home() == HOME_DIR / ".local" / "share"101def test_xdg_data_home_absolute(monkeypatch: MonkeyPatch) -> None:102 """Test xdg_data_home when XDG_DATA_HOME is absolute path."""103 monkeypatch.setenv("XDG_DATA_HOME", "/xdg_data_home")104 assert xdg.xdg_data_home() == Path("/xdg_data_home")105def test_xdg_runtime_dir_unset(monkeypatch: MonkeyPatch) -> None:106 """Test xdg_runtime_dir when XDG_RUNTIME_DIR is unset."""107 monkeypatch.delenv("XDG_RUNTIME_DIR", raising=False)108 assert xdg.xdg_runtime_dir() is None109def test_xdg_runtime_dir_empty(monkeypatch: MonkeyPatch) -> None:110 """Test xdg_runtime_dir when XDG_RUNTIME_DIR is empty."""111 monkeypatch.setenv("XDG_RUNTIME_DIR", "")112 assert xdg.xdg_runtime_dir() is None113def test_xdg_runtime_dir_relative(monkeypatch: MonkeyPatch) -> None:114 """Test xdg_runtime_dir when XDG_RUNTIME_DIR is relative path."""115 monkeypatch.setenv("XDG_RUNTIME_DIR", "rela/tive")116 assert xdg.xdg_runtime_dir() is None117def test_xdg_runtime_dir_absolute(monkeypatch: MonkeyPatch) -> None:118 """Test xdg_runtime_dir when XDG_RUNTIME_DIR is absolute path."""119 monkeypatch.setenv("XDG_RUNTIME_DIR", "/xdg_runtime_dir")120 assert xdg.xdg_runtime_dir() == Path("/xdg_runtime_dir")121def test_xdg_state_home_unset(monkeypatch: MonkeyPatch) -> None:122 """Test xdg_state_home when XDG_STATE_HOME is unset."""123 monkeypatch.delenv("XDG_STATE_HOME", raising=False)124 monkeypatch.setenv("HOME", os.fspath(HOME_DIR))125 assert xdg.xdg_state_home() == HOME_DIR / ".local" / "state"126def test_xdg_state_home_empty(monkeypatch: MonkeyPatch) -> None:127 """Test xdg_state_home when XDG_STATE_HOME is empty."""128 monkeypatch.setenv("HOME", os.fspath(HOME_DIR))129 monkeypatch.setenv("XDG_STATE_HOME", "")130 assert xdg.xdg_state_home() == HOME_DIR / ".local" / "state"131def test_xdg_state_home_relative(monkeypatch: MonkeyPatch) -> None:132 """Test xdg_state_home when XDG_STATE_HOME is relative path."""133 monkeypatch.setenv("HOME", os.fspath(HOME_DIR))134 monkeypatch.setenv("XDG_STATE_HOME", "rela/tive")135 assert xdg.xdg_state_home() == HOME_DIR / ".local" / "state"136def test_xdg_state_home_absolute(monkeypatch: MonkeyPatch) -> None:137 """Test xdg_state_home when XDG_STATE_HOME is absolute path."""138 monkeypatch.setenv("XDG_STATE_HOME", "/xdg_state_home")...

Full Screen

Full Screen

Pytest Tutorial

Looking for an in-depth tutorial around pytest? LambdaTest covers the detailed pytest tutorial that has everything related to the pytest, from setting up the pytest framework to automation testing. Delve deeper into pytest testing by exploring advanced use cases like parallel testing, pytest fixtures, parameterization, executing multiple test cases from a single file, and more.

Chapters

  1. What is pytest
  2. Pytest installation: Want to start pytest from scratch? See how to install and configure pytest for Python automation testing.
  3. Run first test with pytest framework: Follow this step-by-step tutorial to write and run your first pytest script.
  4. Parallel testing with pytest: A hands-on guide to parallel testing with pytest to improve the scalability of your test automation.
  5. Generate pytest reports: Reports make it easier to understand the results of pytest-based test runs. Learn how to generate pytest reports.
  6. Pytest Parameterized tests: Create and run your pytest scripts while avoiding code duplication and increasing test coverage with parameterization.
  7. Pytest Fixtures: Check out how to implement pytest fixtures for your end-to-end testing needs.
  8. Execute Multiple Test Cases: Explore different scenarios for running multiple test cases in pytest from a single file.
  9. Stop Test Suite after N Test Failures: See how to stop your test suite after n test failures in pytest using the @pytest.mark.incremental decorator and maxfail command-line option.

YouTube

Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.

https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP

Run Pytest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful