How can I find the "real" difficulty on testnet? As is well known, testnet has a "20-minute rule": if no block is found within 20 minutes, the mining difficulty drops to 1 until a block is found.

From some experimentation, it appears that bitcoind's getdifficulty function reports the difficulty of the most recent block.  Thus, if the most recent block was mined under the 20-minute rule, getdifficulty returns 1.

In this case, how can I find the "real" difficulty level?  That is, the difficulty that would be required of a block submitted less than 20 minutes after the previous one?

The best approach I have found so far is to follow the blockchain back until I find a block with a difficulty other than 1 (or less than 20 minutes after the block preceding it).  But this will be prone to error if a difficulty adjustment has recently taken place.

bitcoind must know the real difficulty at all times; can I query it?
You can use the getblocktemplate RPC command and look at the target field.