Operating Systems TestAndSet instruction
You are right, TestAndSet doesn't test the value of the flag, it merely sets it, but returns the previous value, which must be tested elsewhere.

The trick is that as the assignment is atomic, only one process can cause a transition from 0 to 1 (others only cause a "transition" from 1 to 1), and only it can pass the while.