Adjust environment claim test to avoid race condition

This commit is contained in:
dandds
2019-09-23 14:53:18 -04:00
parent 46f8e07729
commit 0d45be68d5

View File

@@ -260,14 +260,16 @@ def test_claim_for_update(session):
environment = portfolio.applications[0].environments[0] environment = portfolio.applications[0].environments[0]
satisfied_claims = [] satisfied_claims = []
exceptions = []
# Two threads that race to acquire a claim on the same environment. # Two threads race to do work on environment and check out the lock
# SecondThread's claim will be rejected, resulting in a ClaimFailedException.
class FirstThread(Thread): class FirstThread(Thread):
def run(self): def run(self):
with claim_for_update(environment): try:
sleep(0.1) # doing some work with claim_for_update(environment):
satisfied_claims.append("FirstThread") satisfied_claims.append("FirstThread")
except ClaimFailedException:
exceptions.append("FirstThread")
class SecondThread(Thread): class SecondThread(Thread):
def run(self): def run(self):
@@ -275,7 +277,7 @@ def test_claim_for_update(session):
with claim_for_update(environment): with claim_for_update(environment):
satisfied_claims.append("SecondThread") satisfied_claims.append("SecondThread")
except ClaimFailedException: except ClaimFailedException:
pass exceptions.append("SecondThread")
t1 = FirstThread() t1 = FirstThread()
t2 = SecondThread() t2 = SecondThread()
@@ -286,8 +288,14 @@ def test_claim_for_update(session):
session.refresh(environment) session.refresh(environment)
# Only FirstThread acquired a claim and wrote to satisfied_claims assert len(satisfied_claims) == 1
assert satisfied_claims == ["FirstThread"] assert len(exceptions) == 1
if satisfied_claims == ["FirstThread"]:
assert exceptions == ["SecondThread"]
else:
assert satisfied_claims == ["SecondThread"]
assert exceptions == ["FirstThread"]
# The claim is released # The claim is released
assert environment.claimed_until is None assert environment.claimed_until is None