Home > Mobile >  Is it safe to use Python's eval() in a unit-test for __repr__?
Is it safe to use Python's eval() in a unit-test for __repr__?

Time:02-16

eval() has been called evil, dangerous, bad practice, and so on an so forth.

Although I tend to avoid using eval(), I'm now tempted to use it in a unit-test for a custom implementation of __repr__ (as discussed e.g. here).

Based on the docs for __repr__:

... If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). ...

(although opinions differ as to whether this is very useful)

I would be tempted to test MyClass.__repr__ as follows:

assert eval(repr(my_class_instance)) == my_class_instance

Which brings me to my question:

Assuming we use "online" test runners, for CI/CD, would this usage of eval() introduce any security risks?

I don't think it would, seeing that the input to eval() is known and trusted, but I'm no security expert...

CodePudding user response:

eval is said to be evil because when you eval a string that has been provided by a user, you implicitely allow them to execute arbitrary code.

By here you are using a hard coded string. To be able to execute arbitrary code, an attacker would have to modify the test code or the __repr__ one. In either case that means that they would already have the possibility to execute arbitrary code, regardless of your use of eval.

So my opinion is that there is not security problem with using eval here. At most, you could add a comment for future readers explaining that you have examined that usage and decided that it added no security risk.

  • Related