I'm not sure it's completely foolproof, but I use the fact that in a test, you will have probably started it from the command line with ./manage.py test, so 'test' is one of the command-line args. So this works:
import sys
if 'test' not in sys.argv:
mongodb.connect()