4

I stumbled upon this question that has no answer. The OP asks to unpack several variables (using pytest fixtures) and make them have their local name available to the testing function. I thought I had a clean solution, involving automatic unpacking of a dictionary:

import pytest

@pytest.fixture  
def my_fix():
    return {"A" : 4, "B": 6 }


def test_something(my_fix):
    locals().update(my_fix)

    assert A == 4
    assert B == 6

This is inspired by this answer in Quora. When I run this test using pytest, it fails, because there seems to be no local variables called A or B!

Anyone willing to shed some light on why this happens? Also, an answer to the original question would be greatly appreciated.

Community
  • 1
  • 1
Yair Daon
  • 1,043
  • 2
  • 15
  • 27
  • 3
    These links might help. The official docs say you cannot reliably modify locals(). https://stackoverflow.com/questions/8028708/dynamically-set-local-variable, https://docs.python.org/3/library/functions.html#locals – SteveJ Apr 13 '18 at 03:57
  • @TravisBlack I think not. From the docs it seems that pytest automatically calls my_fix. Also you can modify the code and see python returns an error - TypeError: 'dict' object is not callable. – Yair Daon Apr 13 '18 at 04:10
  • I actually do not get that error, but I never got an error with your code either. The only error I get is if I try to update with my_fix instead of my_fix: TypeError: 'function' object is not iterable. Probably has to do with python or pytest version. python 2.7 here. says pytest 1.4.29 i think? – Travis Black Apr 13 '18 at 04:13
  • @TravisBlack weird. Mine is Python 2.7.12, pytest-3.5.0 so that might be the reason... – Yair Daon Apr 13 '18 at 04:17

0 Answers0