|
79 | 79 | import com.vaadin.flow.server.VaadinResponse; |
80 | 80 | import com.vaadin.flow.server.VaadinService; |
81 | 81 | import com.vaadin.flow.server.VaadinServletRequest; |
| 82 | +import com.vaadin.flow.shared.Registration; |
82 | 83 | import com.vaadin.tests.util.AlwaysLockedVaadinSession; |
83 | 84 | import com.vaadin.tests.util.MockUI; |
84 | 85 |
|
@@ -408,6 +409,60 @@ public void removeComponent() { |
408 | 409 | ComponentTest.assertChildren(ui); |
409 | 410 | } |
410 | 411 |
|
| 412 | + @Test |
| 413 | + public void setLastHeartbeatTimestamp_heartbeatEventIsFired() { |
| 414 | + UI ui = new UI(); |
| 415 | + initUI(ui, "", null); |
| 416 | + |
| 417 | + long heartbeatTimestamp = System.currentTimeMillis(); |
| 418 | + List<HeartbeatEvent> events = new ArrayList<>(); |
| 419 | + ui.addHeartbeatListener(events::add); |
| 420 | + |
| 421 | + ui.getInternals().setLastHeartbeatTimestamp(heartbeatTimestamp); |
| 422 | + |
| 423 | + assertEquals(1, events.size()); |
| 424 | + assertEquals(ui, events.get(0).getSource()); |
| 425 | + assertEquals(heartbeatTimestamp, events.get(0).getHeartbeatTime()); |
| 426 | + } |
| 427 | + |
| 428 | + @Test |
| 429 | + public void setLastHeartbeatTimestamp_multipleHeartbeatListenerRegistered_eachHeartbeatListenerIsCalled() { |
| 430 | + UI ui = new UI(); |
| 431 | + initUI(ui, "", null); |
| 432 | + |
| 433 | + List<HeartbeatEvent> events = new ArrayList<>(); |
| 434 | + ui.addHeartbeatListener(events::add); |
| 435 | + ui.addHeartbeatListener(events::add); |
| 436 | + |
| 437 | + ui.getInternals().setLastHeartbeatTimestamp(System.currentTimeMillis()); |
| 438 | + |
| 439 | + assertEquals(2, events.size()); |
| 440 | + } |
| 441 | + |
| 442 | + @Test |
| 443 | + public void setLastHeartbeatTimestamp_heartbeatListenerRemoved_listenerNotRun() { |
| 444 | + UI ui = new UI(); |
| 445 | + initUI(ui, "", null); |
| 446 | + |
| 447 | + AtomicReference<Registration> reference = new AtomicReference<>(); |
| 448 | + AtomicInteger runCount = new AtomicInteger(); |
| 449 | + |
| 450 | + Registration registration = ui.addHeartbeatListener(event -> { |
| 451 | + runCount.incrementAndGet(); |
| 452 | + reference.get().remove(); // removes the listener on the first |
| 453 | + // invocation |
| 454 | + }); |
| 455 | + reference.set(registration); |
| 456 | + |
| 457 | + ui.getInternals().setLastHeartbeatTimestamp(System.currentTimeMillis()); |
| 458 | + assertEquals("Listener should have been run once", 1, runCount.get()); |
| 459 | + |
| 460 | + ui.getInternals().setLastHeartbeatTimestamp(System.currentTimeMillis()); |
| 461 | + assertEquals( |
| 462 | + "Listener should not have been run again since it was removed", |
| 463 | + 1, runCount.get()); |
| 464 | + } |
| 465 | + |
411 | 466 | @Test |
412 | 467 | public void setSession_attachEventIsFired() |
413 | 468 | throws InvalidRouteConfigurationException { |
|
0 commit comments