집계를 테스트하기 위한 시간 가속

솔루션에서 집계 결과를 더 잘 분석하기 위해 이벤트 제출 속도를 높일 수 있습니다. 테스트가 실행된 시간 보다 훨씬 긴 기간을 시뮬레이트하기 위해 JUnit 테스트를 작성할 수 있습니다.

시작하기 전에

JUnit 테스트 프로젝트를 작성하고, 테스트 드라이버 및 기타 Decision Server Insights 런타임 JAR 파일을 사용하는 데 필요한 패키지와 함께 java.time 및 java.util.concurrent.ScheduledExecutorService 패키지를 가져오십시오. 자세한 정보는 솔루션의 자동화된 테스트에 대한 클래스 경로 설정의 내용을 참조하십시오.

이 태스크 정보

ZonedDateTime 클래스를 사용하여 전송된 각 이벤트의 시간을 앞당기거나, 테스트 실행 중에 백그라운드로 시간을 앞당기기 위한 별도의 스레드를 작성할 수 있습니다. 예를 들어, 다음 코드는 ZonedDateTime 오브젝트를 사용하여 10일 동안 매일 임의 생성된 구매 이벤트를 전송합니다.

private Random random = new Random();
private ZonedDateTime eventTime;

eventTime = ZonedDateTime.now();
...
for(int n=0; n < 10; n++) {
   eventTime = eventTime.plusDays(1);
   Purchase purchase = MyEventFactory.createEvent(Purchase.class);
   purchase.setTimeStamp(eventTime);
   purchase.setCustomer(MyEventFactory.createRelationship(Customer.class, "John"));
   OrderItem item = MyEventFactory.createConcept(OrderItem.class));
   item.setAmount(Math.random() * 50 + 10);
   item.SetSku("Product" + n);
   purchase.addTo_orderItems(item);
   testDriver.submitEvent(purchase);
}
testDriver.endTest(); // end the test

JUnit 프로젝트의 각 테스트가 시작되는 시간을 가속하려면 스케줄된 실행기 서비스를 Java 클래스에 추가하십시오.

경고: 테스트를 가속한 후 서버를 다시 시작하지 않으면 이벤트가 순서에 맞지 않게 처리될 수 있습니다. 예를 들어, 엔진이 미래(시간 가속으로 인해)에 event1을 처리한 후 새 테스트가 시간소인이 event1보다 더 이전인 event2를 전송하면 이벤트가 순서에 맞지 않게 처리됩니다.
중요사항: 글로벌 엔티티 집계는 시간을 앞당기는 테스트 기술의 영향을 받지 않습니다. 예를 들어, 일 년 전에 TestEpoch 특성을 설정한 다음 일년 전에 이벤트를 전송하고 또 다른 이벤트 시간 소인이 오늘인 경우, 이 연도에 발생하도록 스케줄된 작업이 실행되지 않습니다. 글로벌 엔티티 집계가 now 키워드를 사용하는 Java 에이전트 또는 규칙에서 조회되는 경우에도 해당됩니다. now의 값은 실제 시간이며 시간이 TestEpoch 특성에 의해 조정되지 않습니다.

프로시저

  1. 시간 관련 변수, 테스트 드라이버 및 실행기 서비스에 대한 필드를 추가하십시오.
    private static final int MINUTES_PER_SEC = 30;
    private TestDriver driver;
    private Random random = new Random();
    private ZonedDateTime eventTime;
    private ZonedDateTime firstEventTime;
    private ScheduledExecutorService execSvc = Executors.newScheduledThreadPool(1);
  2. 테스트 드라이버와 실행기 서비스를 설정하기 위한 @Before 메소드를 작성하십시오.
    @Before
    public void initTestDriver() {
       try {
          driver = new TestDriver();
          driver.connect();
       } 
       catch (Exception exc) {
          exc.printStackTrace();
       }
    }
    
    @Before
    public void startUpdatingTime() {
       eventTime = ZonedDateTime.now();
       final ZonedDateTime start = eventTime;
       execSvc.schedule(new Runnable() {
          long elapsedMinutes = 0;
          long elapsedDays = 0;
          
          @Override
          public void run() {
             // move 1 hour every 2 seconds
             // 24 hours takes 48 seconds
             eventTime = eventTime.plusMinutes(MINUTES_PER_SEC);
             elapsedMinutes += MINUTES_PER_SEC;
             double d = (double) elapsedMinutes/60;
             if (d == 24) {
                elapsedDays++;
                System.out.println("######################################");
                System.out.println("# Event Time: "+eventTime);
                System.out.println("# Start time: "+start);
                System.out.println("# First event: "+firstEventTime);
                System.out.println("# Elapsed days (since test started): "+elapsedDays);
                System.out.println("# Elapsed mins (since test started): "+elapsedMinutes);
                System.out.println("######################################");
             }
             execSvc.schedule(this, 1, TimeUnit.SECONDS);
          }
       }, 1, TimeUnit.SECONDS);
    }
  3. 서비스를 종료하기 위한 @After 메소드를 작성하십시오.
    @After
    public void stopUpdatingTime() {
       execSvc.shutdown();
    }
  4. @Test 메소드를 작성하여 첫 번째 이벤트의 시간을 설정하고 새 이벤트를 제출하십시오.

    예를 들어, 다음 테스트는 글로벌 이벤트 집계에 영향을 미치는 임의 생성 트랜잭션 이벤트를 전송합니다.

    @Test
    public void testAvgTransactionLastPeriodExtended() throws Exception {
       int iterations = 10;
       int entityCount = 100;
       int txCount = 0;
       long start = System.currentTimeMillis();
       for (int i=0;i<iterations;i++) {
          for (int j=0;j<entityCount;j++) {
             // Submit transactions with random amounts up to 50,000
             double amount = getRandomAmount();
             submitTransaction("account_"+j, "customer_"+j+"@fmail.com", amount);
             txCount++;
             Thread.sleep(200);
          }
       }
       long duration = System.currentTimeMillis() - start;
       System.out.println(String.format("Submitted [%s] events in [%s] ms", txCount, duration));
    }
    	
    private double getRandomAmount() {
       double val = 50000 * random.nextDouble();
       BigDecimal bd = new BigDecimal(val);
       bd = bd.setScale(2, RoundingMode.HALF_UP);
       return bd.doubleValue();
    }
    
    private void submitTransaction(String accountId, String customerId, double amount) throws Exception {
       submitTransaction(accountId, customerId, amount, null);
    }
    
    private void submitTransaction(String accountId, String customerId, double amount, ZonedDateTime time) throws Exception {
       Transaction transaction = createTransaction(accountId, customerId, amount, time);
       if (null == firstEventTime) {
          firstEventTime = transaction.get$Timestamp();
       }
       RoutingStatus status = driver.getSolutionGateway().submit(transaction);
       Assert.assertEquals(RoutingStatus.STATUS_OK, status);
    
    private Transaction createTransaction(String accountId, String customerId, double amount, ZonedDateTime time) throws Exception {
       ConceptFactory factory = driver.getConceptFactory(ConceptFactory.class);
       if (null == time) {
          time = this.eventTime;
       }
       Transaction transaction = factory.createTransaction(time);
       transaction.setCountryCode("US");
       transaction.setAmount(amount);
       Relationship<Account> account = driver.getEventFactory().createRelationship(Account.class, accountId);
       transaction.setAccount(account);
       Relationship<Customer> customer = driver.getEventFactory().createRelationship(Customer.class, customerId);
       transaction.setCustomer(customer);
       return transaction;
    }

결과

테스트 실행 후 REST API를 호출하여 솔루션에 대한 정보를 검색할 수 있습니다. 자세한 정보는 REST API를 사용하여 엔티티 및 집계 값 가져오기를 참조하십시오.

다음에 수행할 작업

테스트 중에 글로벌 이벤트 집계 값을 캡처하고 이 값을 사용하여 새 이벤트를 생성할 수도 있습니다. 자세한 정보는 디버그 정보 수신 및 저장을 참조하십시오.