Why does python not have a mechanism for data hiding?

Ben Finney bignose+hates-spam at benfinney.id.au
Wed Jun 4 18:29:09 EDT 2008


Roy Smith <roy at panix.com> writes:

> The only externally visible interface is pushTheButton(), yet you
> don't really want to call that during testing. What you do want to
> do is test that a random city really does get picked.

Then what you're really testing is the interactions of the "push the
button" function with its external interface: you're asserting that
the "push the red button" function actually uses the result from "pick
a random city" as its target.

Thus, the "pick a random city" function is being defined by you as
*interface* for the "push the button" function. Interfaces do need to
be unit tested.

This is done by having the unit test substitute a test double for the
"pick a random city" function, rigging that double so that its
behaviour is deterministic, and asserting that the "push the button"
function uses that deterministically-generated result.

It's at this point, of course, that the "pick a random city" function
has come rather close to being public API. The designer needs to have
a fairly good reason not to simply expose the "pick a random city"
function in the API.

> You can do one of two things at this point. You can say, "But,
> that's not part of the externally visible interface" and refuse to
> test it, or you can figure out a way to test it. Up to you.

Note that the only thing I'm saying one shouldn't do is unit test the
private function *directly*, since the design decision has been made
that it's not part of the API. The *behaviour* of the function, as
exposed via the "push the button" piblic API, should certainly be unit
tested.

Any behaviour of that function that's *not* exhibited through the
behaviour of some public API should *not* be unit tested, and should
in fact be removed during refactoring -- which will not break the unit
test suite since no unit tests depend on it.

Alternatively, as above, the design decision can be made that, in
fact, this function *is* part of the public API since external things
are depending on it directly. Then it needs full direct unit test
coverage.

-- 
 \         "I got contacts, but I only need them when I read, so I got |
  `\                                      flip-ups."  -- Steven Wright |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list