Optimal tests of quantum nonlocality