使用资源锁进行并行测试?

背景:现在使用java JUnit4,愿意迁移到JUnit5或TestNG。

当前状态:拥有 100 多个 Selenium 测试。其中大部分通过 Junit4 中的 @RunWith(Parameterized.class) 重复。(即根据提供的参数集创建测试类的多个实例,通常是浏览器类型 + 用户身份的组合。)共享大约 12 个用户的有限集合。

限制:被测试的应用程序阻止同一用户同时在多个地方登录。因此,如果用户在一个线程中运行的某个测试中登录应用程序,则会导致同一用户在同一时刻在另一个线程中运行的另一个测试中立即注销。

问题:当并行执行的测试无法共享某些资源时,是否有任何推荐的方法来管理线程安全?或者如何强制使用相同资源的那些测试在同一个线程中执行?

感谢您的想法。


这是到目前为止我用 TestNG 找到的一些解决方案的简化示例......:

public abstract class BaseTestCase {

    protected static ThreadLocal<WebDriver> threadLocalDriver = new ThreadLocal<>();

    protected String testUserName;


    private static final Set<String> inUse = new HashSet<>();


    public BaseTestCase(WebDriver driver, String testUserName) {

        threadLocalDriver.set(driver);

        this.testUserName = testUserName;

    }


    private boolean syncedAddUse(@NotNull String key){

        synchronized (inUse){

            return inUse.add(key);

        }

    }


    private boolean syncedRemoveUse(@NotNull String key){

        synchronized (inUse) {

            return inUse.remove(key);

        }

    }


    @DataProvider(parallel = true)

    public static Object[][] provideTestData() {

        //load pairs WebDriver+user from config file. E.g.:

        //Chrome + chromeUser

        //Chrome + chromeAdmin

        //Firefox + firefoxUser

        //etc...

    }


    @BeforeMethod

    public void syncPoint() throws InterruptedException {

        while( !syncedAddUse(testUserName) ){

            //Waiting due the testUserName is already in use at the moment.

            Thread.sleep(1000);

        }

    }


    @AfterMethod

    public void leaveSyncPoint(){

        syncedRemoveUse(testUserName);

    }

}


慕姐4208626
浏览 135回答 1
1回答

守着一只汪

我不知道有什么方法可以在每个组都在一个线程中运行的组中组织测试。但是您可以用“尝试锁定用户”替换“用户忙时睡眠”。一旦对用户完成另一个测试(即解锁锁),后者就会继续执行。下面的可运行示例应该让您开始了解“尝试锁定用户”的想法。请记住,如果您获得了锁(在您的情况下为“beforeTest”),您必须确保在“finally”块(在您的情况下为“afterTest”)中释放锁。否则执行可能会挂起并且永远不会完成。import java.util.Map;import java.util.Random;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.locks.ReentrantLock;import java.util.concurrent.TimeUnit;import java.util.stream.IntStream;// https://stackoverflow.com/questions/56474713/parallel-tests-with-resource-lockpublic class NamedResourceLocks {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Starting");&nbsp; &nbsp; &nbsp; &nbsp; ExecutorService executor = Executors.newCachedThreadPool();&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new NamedResourceLocks().run(executor);&nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; } finally {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; executor.shutdownNow();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Done");&nbsp; &nbsp; }&nbsp; &nbsp; final static String userPrefix = "user";&nbsp; &nbsp; final static int maxUsers = 3;&nbsp; &nbsp; final static long maxWait = 10_000; // 10 seconds&nbsp; &nbsp; final static long startTime = System.currentTimeMillis();&nbsp; &nbsp; final Map<String, ReentrantLock> userLocks = new ConcurrentHashMap<>();&nbsp; &nbsp; final int maxTests = maxUsers * 10;&nbsp; &nbsp; final CountDownLatch allTestsDone = new CountDownLatch(maxTests);&nbsp; &nbsp; void run(ExecutorService executor) throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; IntStream.range(0,&nbsp; maxUsers).forEach(u ->&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; userLocks.put(userPrefix + u, new ReentrantLock(true)));&nbsp; &nbsp; &nbsp; &nbsp; IntStream.range(0,&nbsp; maxTests).forEach(t ->&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; executor.execute(new Test(this, random.nextInt(maxUsers), t)));&nbsp; &nbsp; &nbsp; &nbsp; if (allTestsDone.await(maxWait, TimeUnit.MILLISECONDS)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("All tests finished");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; void lock(String user) throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; ReentrantLock lock = userLocks.get(user);&nbsp; &nbsp; &nbsp; &nbsp; if (!lock.tryLock(maxWait, TimeUnit.MILLISECONDS)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new RuntimeException("Waited too long.");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; void unlock(String user) {&nbsp; &nbsp; &nbsp; &nbsp; userLocks.get(user).unlock();&nbsp; &nbsp; }&nbsp; &nbsp; void oneTestDone() {&nbsp; &nbsp; &nbsp; &nbsp; allTestsDone.countDown();&nbsp; &nbsp; }&nbsp; &nbsp; final static Random random = new Random();&nbsp; &nbsp; static class Test implements Runnable {&nbsp; &nbsp; &nbsp; &nbsp; final NamedResourceLocks locks;&nbsp; &nbsp; &nbsp; &nbsp; final String user;&nbsp; &nbsp; &nbsp; &nbsp; final int testNumber;&nbsp; &nbsp; &nbsp; &nbsp; public Test(NamedResourceLocks locks, int userNumber, int testNumber) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.locks = locks;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.user = userPrefix + userNumber;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.testNumber = testNumber;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public void run() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; boolean haveLock = false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log(this, "acquiring lock");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; locks.lock(user);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; haveLock = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int sleepTime = random.nextInt(maxUsers) + 1;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log(this, "sleeping for " + sleepTime + " ms.");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Thread.sleep(sleepTime);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } finally {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (haveLock) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log(this, "releasing lock");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; locks.unlock(user);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; locks.oneTestDone();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; static void log(Test test, String msg) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println((System.currentTimeMillis() - startTime) + " - " +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; test.testNumber + " / " + test.user + " - " + msg);&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java