1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/basictypes.h"
6 #include "base/run_loop.h"
7 #include "content/browser/message_port_service.h"
8 #include "content/browser/service_worker/embedded_worker_registry.h"
9 #include "content/browser/service_worker/embedded_worker_test_helper.h"
10 #include "content/browser/service_worker/service_worker_context_core.h"
11 #include "content/browser/service_worker/service_worker_registration.h"
12 #include "content/browser/service_worker/service_worker_test_utils.h"
13 #include "content/browser/service_worker/service_worker_version.h"
14 #include "content/common/service_worker/service_worker_utils.h"
15 #include "content/public/test/test_browser_thread_bundle.h"
16 #include "testing/gtest/include/gtest/gtest.h"
18 // IPC messages for testing ---------------------------------------------------
20 #define IPC_MESSAGE_IMPL
21 #include "ipc/ipc_message_macros.h"
23 #define IPC_MESSAGE_START TestMsgStart
25 IPC_MESSAGE_CONTROL0(TestMsg_Message
);
26 IPC_MESSAGE_ROUTED1(TestMsg_MessageFromWorker
, int);
28 // ---------------------------------------------------------------------------
34 static const int kRenderProcessId
= 1;
36 class MessageReceiver
: public EmbeddedWorkerTestHelper
{
39 : EmbeddedWorkerTestHelper(base::FilePath(), kRenderProcessId
),
40 current_embedded_worker_id_(0) {}
41 ~MessageReceiver() override
{}
43 bool OnMessageToWorker(int thread_id
,
44 int embedded_worker_id
,
45 const IPC::Message
& message
) override
{
46 if (EmbeddedWorkerTestHelper::OnMessageToWorker(
47 thread_id
, embedded_worker_id
, message
)) {
50 current_embedded_worker_id_
= embedded_worker_id
;
52 IPC_BEGIN_MESSAGE_MAP(MessageReceiver
, message
)
53 IPC_MESSAGE_HANDLER(TestMsg_Message
, OnMessage
)
54 IPC_MESSAGE_UNHANDLED(handled
= false)
59 void SimulateSendValueToBrowser(int embedded_worker_id
, int value
) {
60 SimulateSend(new TestMsg_MessageFromWorker(embedded_worker_id
, value
));
68 int current_embedded_worker_id_
;
69 DISALLOW_COPY_AND_ASSIGN(MessageReceiver
);
72 void VerifyCalled(bool* called
) {
76 void ObserveStatusChanges(ServiceWorkerVersion
* version
,
77 std::vector
<ServiceWorkerVersion::Status
>* statuses
) {
78 statuses
->push_back(version
->status());
79 version
->RegisterStatusChangeCallback(
80 base::Bind(&ObserveStatusChanges
, base::Unretained(version
), statuses
));
83 void ReceiveFetchResult(ServiceWorkerStatusCode
* status
,
84 ServiceWorkerStatusCode actual_status
,
85 ServiceWorkerFetchEventResult actual_result
,
86 const ServiceWorkerResponse
& response
) {
87 *status
= actual_status
;
90 // A specialized listener class to receive test messages from a worker.
91 class MessageReceiverFromWorker
: public EmbeddedWorkerInstance::Listener
{
93 explicit MessageReceiverFromWorker(EmbeddedWorkerInstance
* instance
)
94 : instance_(instance
) {
95 instance_
->AddListener(this);
97 ~MessageReceiverFromWorker() override
{ instance_
->RemoveListener(this); }
99 void OnStarted() override
{ NOTREACHED(); }
100 void OnStopped(EmbeddedWorkerInstance::Status old_status
) override
{
103 bool OnMessageReceived(const IPC::Message
& message
) override
{
105 IPC_BEGIN_MESSAGE_MAP(MessageReceiverFromWorker
, message
)
106 IPC_MESSAGE_HANDLER(TestMsg_MessageFromWorker
, OnMessageFromWorker
)
107 IPC_MESSAGE_UNHANDLED(handled
= false)
108 IPC_END_MESSAGE_MAP()
112 void OnMessageFromWorker(int value
) { received_values_
.push_back(value
); }
113 const std::vector
<int>& received_values() const { return received_values_
; }
116 EmbeddedWorkerInstance
* instance_
;
117 std::vector
<int> received_values_
;
118 DISALLOW_COPY_AND_ASSIGN(MessageReceiverFromWorker
);
121 void SetUpDummyMessagePort(std::vector
<TransferredMessagePort
>* ports
) {
123 MessagePortService::GetInstance()->Create(MSG_ROUTING_NONE
, nullptr,
125 TransferredMessagePort dummy_port
;
126 dummy_port
.id
= port_id
;
127 ports
->push_back(dummy_port
);
130 base::Time
GetYesterday() {
131 return base::Time::Now() - base::TimeDelta::FromDays(1) -
132 base::TimeDelta::FromSeconds(1);
137 class ServiceWorkerVersionTest
: public testing::Test
{
139 struct RunningStateListener
: public ServiceWorkerVersion::Listener
{
140 RunningStateListener() : last_status(ServiceWorkerVersion::STOPPED
) {}
141 ~RunningStateListener() override
{}
142 void OnRunningStateChanged(ServiceWorkerVersion
* version
) override
{
143 last_status
= version
->running_status();
145 ServiceWorkerVersion::RunningStatus last_status
;
148 ServiceWorkerVersionTest()
149 : thread_bundle_(TestBrowserThreadBundle::IO_MAINLOOP
) {}
151 void SetUp() override
{
152 helper_
= GetMessageReceiver();
154 pattern_
= GURL("http://www.example.com/");
155 registration_
= new ServiceWorkerRegistration(
158 helper_
->context()->AsWeakPtr());
159 version_
= new ServiceWorkerVersion(
161 GURL("http://www.example.com/service_worker.js"),
163 helper_
->context()->AsWeakPtr());
164 std::vector
<ServiceWorkerDatabase::ResourceRecord
> records
;
166 ServiceWorkerDatabase::ResourceRecord(10, version_
->script_url(), 100));
167 version_
->script_cache_map()->SetResources(records
);
169 // Make the registration findable via storage functions.
170 helper_
->context()->storage()->LazyInitialize(base::Bind(&base::DoNothing
));
171 base::RunLoop().RunUntilIdle();
172 ServiceWorkerStatusCode status
= SERVICE_WORKER_ERROR_FAILED
;
173 helper_
->context()->storage()->StoreRegistration(
176 CreateReceiverOnCurrentThread(&status
));
177 base::RunLoop().RunUntilIdle();
178 ASSERT_EQ(SERVICE_WORKER_OK
, status
);
180 // Simulate adding one process to the pattern.
181 helper_
->SimulateAddProcessToPattern(pattern_
, kRenderProcessId
);
182 ASSERT_TRUE(helper_
->context()->process_manager()
183 ->PatternHasProcessToRun(pattern_
));
186 virtual scoped_ptr
<MessageReceiver
> GetMessageReceiver() {
187 return make_scoped_ptr(new MessageReceiver());
190 void TearDown() override
{
196 TestBrowserThreadBundle thread_bundle_
;
197 scoped_ptr
<MessageReceiver
> helper_
;
198 scoped_refptr
<ServiceWorkerRegistration
> registration_
;
199 scoped_refptr
<ServiceWorkerVersion
> version_
;
203 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerVersionTest
);
206 class MessageReceiverDisallowStart
: public MessageReceiver
{
208 MessageReceiverDisallowStart()
209 : MessageReceiver() {}
210 ~MessageReceiverDisallowStart() override
{}
212 void OnStartWorker(int embedded_worker_id
,
213 int64 service_worker_version_id
,
215 const GURL
& script_url
) override
{
220 DISALLOW_COPY_AND_ASSIGN(MessageReceiverDisallowStart
);
223 class ServiceWorkerFailToStartTest
: public ServiceWorkerVersionTest
{
225 ServiceWorkerFailToStartTest()
226 : ServiceWorkerVersionTest() {}
228 scoped_ptr
<MessageReceiver
> GetMessageReceiver() override
{
229 return make_scoped_ptr(new MessageReceiverDisallowStart());
233 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerFailToStartTest
);
236 class MessageReceiverDisallowFetch
: public MessageReceiver
{
238 MessageReceiverDisallowFetch() : MessageReceiver() {}
239 ~MessageReceiverDisallowFetch() override
{}
241 void OnFetchEvent(int embedded_worker_id
,
243 const ServiceWorkerFetchRequest
& request
) override
{
248 DISALLOW_COPY_AND_ASSIGN(MessageReceiverDisallowFetch
);
251 class ServiceWorkerWaitForeverInFetchTest
: public ServiceWorkerVersionTest
{
253 ServiceWorkerWaitForeverInFetchTest() : ServiceWorkerVersionTest() {}
255 scoped_ptr
<MessageReceiver
> GetMessageReceiver() override
{
256 return make_scoped_ptr(new MessageReceiverDisallowFetch());
260 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerWaitForeverInFetchTest
);
263 TEST_F(ServiceWorkerVersionTest
, ConcurrentStartAndStop
) {
264 // Call StartWorker() multiple times.
265 ServiceWorkerStatusCode status1
= SERVICE_WORKER_ERROR_FAILED
;
266 ServiceWorkerStatusCode status2
= SERVICE_WORKER_ERROR_FAILED
;
267 ServiceWorkerStatusCode status3
= SERVICE_WORKER_ERROR_FAILED
;
268 version_
->StartWorker(CreateReceiverOnCurrentThread(&status1
));
269 version_
->StartWorker(CreateReceiverOnCurrentThread(&status2
));
271 EXPECT_EQ(ServiceWorkerVersion::STARTING
, version_
->running_status());
272 base::RunLoop().RunUntilIdle();
273 EXPECT_EQ(ServiceWorkerVersion::RUNNING
, version_
->running_status());
275 // Call StartWorker() after it's started.
276 version_
->StartWorker(CreateReceiverOnCurrentThread(&status3
));
277 base::RunLoop().RunUntilIdle();
279 // All should just succeed.
280 EXPECT_EQ(SERVICE_WORKER_OK
, status1
);
281 EXPECT_EQ(SERVICE_WORKER_OK
, status2
);
282 EXPECT_EQ(SERVICE_WORKER_OK
, status3
);
284 // Call StopWorker() multiple times.
285 status1
= SERVICE_WORKER_ERROR_FAILED
;
286 status2
= SERVICE_WORKER_ERROR_FAILED
;
287 version_
->StopWorker(CreateReceiverOnCurrentThread(&status1
));
288 version_
->StopWorker(CreateReceiverOnCurrentThread(&status2
));
290 EXPECT_EQ(ServiceWorkerVersion::STOPPING
, version_
->running_status());
291 base::RunLoop().RunUntilIdle();
292 EXPECT_EQ(ServiceWorkerVersion::STOPPED
, version_
->running_status());
294 // All StopWorker should just succeed.
295 EXPECT_EQ(SERVICE_WORKER_OK
, status1
);
296 EXPECT_EQ(SERVICE_WORKER_OK
, status2
);
298 // Start worker again.
299 status1
= SERVICE_WORKER_ERROR_FAILED
;
300 status2
= SERVICE_WORKER_ERROR_FAILED
;
301 status3
= SERVICE_WORKER_ERROR_FAILED
;
303 version_
->StartWorker(CreateReceiverOnCurrentThread(&status1
));
305 EXPECT_EQ(ServiceWorkerVersion::STARTING
, version_
->running_status());
306 base::RunLoop().RunUntilIdle();
307 EXPECT_EQ(ServiceWorkerVersion::RUNNING
, version_
->running_status());
310 status2
= SERVICE_WORKER_ERROR_FAILED
;
311 version_
->StopWorker(CreateReceiverOnCurrentThread(&status2
));
313 // And try calling StartWorker while StopWorker is in queue.
314 version_
->StartWorker(CreateReceiverOnCurrentThread(&status3
));
316 EXPECT_EQ(ServiceWorkerVersion::STOPPING
, version_
->running_status());
317 base::RunLoop().RunUntilIdle();
318 EXPECT_EQ(ServiceWorkerVersion::RUNNING
, version_
->running_status());
320 // All should just succeed.
321 EXPECT_EQ(SERVICE_WORKER_OK
, status1
);
322 EXPECT_EQ(SERVICE_WORKER_OK
, status2
);
323 EXPECT_EQ(SERVICE_WORKER_OK
, status3
);
326 TEST_F(ServiceWorkerVersionTest
, DispatchEventToStoppedWorker
) {
327 EXPECT_EQ(ServiceWorkerVersion::STOPPED
, version_
->running_status());
329 // Dispatch an event without starting the worker.
330 ServiceWorkerStatusCode status
= SERVICE_WORKER_ERROR_FAILED
;
331 version_
->SetStatus(ServiceWorkerVersion::INSTALLING
);
332 version_
->DispatchInstallEvent(CreateReceiverOnCurrentThread(&status
));
333 base::RunLoop().RunUntilIdle();
334 EXPECT_EQ(SERVICE_WORKER_OK
, status
);
336 // The worker should be now started.
337 EXPECT_EQ(ServiceWorkerVersion::RUNNING
, version_
->running_status());
339 // Stop the worker, and then dispatch an event immediately after that.
340 status
= SERVICE_WORKER_ERROR_FAILED
;
341 ServiceWorkerStatusCode stop_status
= SERVICE_WORKER_ERROR_FAILED
;
342 version_
->StopWorker(CreateReceiverOnCurrentThread(&stop_status
));
343 version_
->DispatchInstallEvent(CreateReceiverOnCurrentThread(&status
));
344 base::RunLoop().RunUntilIdle();
345 EXPECT_EQ(SERVICE_WORKER_OK
, stop_status
);
347 // Dispatch an event should return SERVICE_WORKER_OK since the worker
348 // should have been restarted to dispatch the event.
349 EXPECT_EQ(SERVICE_WORKER_OK
, status
);
351 // The worker should be now started again.
352 EXPECT_EQ(ServiceWorkerVersion::RUNNING
, version_
->running_status());
355 TEST_F(ServiceWorkerVersionTest
, ReceiveMessageFromWorker
) {
357 ServiceWorkerStatusCode status
= SERVICE_WORKER_ERROR_FAILED
;
358 version_
->StartWorker(CreateReceiverOnCurrentThread(&status
));
359 EXPECT_EQ(ServiceWorkerVersion::STARTING
, version_
->running_status());
360 base::RunLoop().RunUntilIdle();
361 EXPECT_EQ(SERVICE_WORKER_OK
, status
);
362 EXPECT_EQ(ServiceWorkerVersion::RUNNING
, version_
->running_status());
364 MessageReceiverFromWorker
receiver(version_
->embedded_worker());
366 // Simulate sending some dummy values from the worker.
367 helper_
->SimulateSendValueToBrowser(
368 version_
->embedded_worker()->embedded_worker_id(), 555);
369 helper_
->SimulateSendValueToBrowser(
370 version_
->embedded_worker()->embedded_worker_id(), 777);
372 // Verify the receiver received the values.
373 ASSERT_EQ(2U, receiver
.received_values().size());
374 EXPECT_EQ(555, receiver
.received_values()[0]);
375 EXPECT_EQ(777, receiver
.received_values()[1]);
378 TEST_F(ServiceWorkerVersionTest
, InstallAndWaitCompletion
) {
379 version_
->SetStatus(ServiceWorkerVersion::INSTALLING
);
381 // Dispatch an install event.
382 ServiceWorkerStatusCode status
= SERVICE_WORKER_ERROR_FAILED
;
383 version_
->DispatchInstallEvent(CreateReceiverOnCurrentThread(&status
));
385 // Wait for the completion.
386 bool status_change_called
= false;
387 version_
->RegisterStatusChangeCallback(
388 base::Bind(&VerifyCalled
, &status_change_called
));
390 base::RunLoop().RunUntilIdle();
392 // Version's status must not have changed during installation.
393 EXPECT_EQ(SERVICE_WORKER_OK
, status
);
394 EXPECT_FALSE(status_change_called
);
395 EXPECT_EQ(ServiceWorkerVersion::INSTALLING
, version_
->status());
398 TEST_F(ServiceWorkerVersionTest
, ActivateAndWaitCompletion
) {
399 version_
->SetStatus(ServiceWorkerVersion::ACTIVATING
);
401 // Dispatch an activate event.
402 ServiceWorkerStatusCode status
= SERVICE_WORKER_ERROR_FAILED
;
403 version_
->DispatchActivateEvent(CreateReceiverOnCurrentThread(&status
));
405 // Wait for the completion.
406 bool status_change_called
= false;
407 version_
->RegisterStatusChangeCallback(
408 base::Bind(&VerifyCalled
, &status_change_called
));
410 base::RunLoop().RunUntilIdle();
412 // Version's status must not have changed during activation.
413 EXPECT_EQ(SERVICE_WORKER_OK
, status
);
414 EXPECT_FALSE(status_change_called
);
415 EXPECT_EQ(ServiceWorkerVersion::ACTIVATING
, version_
->status());
418 TEST_F(ServiceWorkerVersionTest
, RepeatedlyObserveStatusChanges
) {
419 EXPECT_EQ(ServiceWorkerVersion::NEW
, version_
->status());
421 // Repeatedly observe status changes (the callback re-registers itself).
422 std::vector
<ServiceWorkerVersion::Status
> statuses
;
423 version_
->RegisterStatusChangeCallback(
424 base::Bind(&ObserveStatusChanges
, version_
, &statuses
));
426 version_
->SetStatus(ServiceWorkerVersion::INSTALLING
);
427 version_
->SetStatus(ServiceWorkerVersion::INSTALLED
);
428 version_
->SetStatus(ServiceWorkerVersion::ACTIVATING
);
429 version_
->SetStatus(ServiceWorkerVersion::ACTIVATED
);
430 version_
->SetStatus(ServiceWorkerVersion::REDUNDANT
);
432 // Verify that we could successfully observe repeated status changes.
433 ASSERT_EQ(5U, statuses
.size());
434 ASSERT_EQ(ServiceWorkerVersion::INSTALLING
, statuses
[0]);
435 ASSERT_EQ(ServiceWorkerVersion::INSTALLED
, statuses
[1]);
436 ASSERT_EQ(ServiceWorkerVersion::ACTIVATING
, statuses
[2]);
437 ASSERT_EQ(ServiceWorkerVersion::ACTIVATED
, statuses
[3]);
438 ASSERT_EQ(ServiceWorkerVersion::REDUNDANT
, statuses
[4]);
441 TEST_F(ServiceWorkerVersionTest
, IdleTimeout
) {
442 // Used to reliably test when the idle time gets reset regardless of clock
444 const base::TimeDelta kOneSecond
= base::TimeDelta::FromSeconds(1);
446 // Verify the timer is not running when version initializes its status.
447 version_
->SetStatus(ServiceWorkerVersion::ACTIVATED
);
448 EXPECT_FALSE(version_
->timeout_timer_
.IsRunning());
450 // Verify the timer is running after the worker is started.
451 ServiceWorkerStatusCode status
= SERVICE_WORKER_ERROR_FAILED
;
452 version_
->StartWorker(CreateReceiverOnCurrentThread(&status
));
453 base::RunLoop().RunUntilIdle();
454 EXPECT_EQ(SERVICE_WORKER_OK
, status
);
455 EXPECT_TRUE(version_
->timeout_timer_
.IsRunning());
456 EXPECT_FALSE(version_
->idle_time_
.is_null());
458 // The idle time should be reset if the worker is restarted without
460 status
= SERVICE_WORKER_ERROR_FAILED
;
461 version_
->idle_time_
-= kOneSecond
;
462 base::TimeTicks idle_time
= version_
->idle_time_
;
463 version_
->StopWorker(CreateReceiverOnCurrentThread(&status
));
464 base::RunLoop().RunUntilIdle();
465 EXPECT_EQ(SERVICE_WORKER_OK
, status
);
466 status
= SERVICE_WORKER_ERROR_FAILED
;
467 version_
->StartWorker(CreateReceiverOnCurrentThread(&status
));
468 base::RunLoop().RunUntilIdle();
469 EXPECT_EQ(SERVICE_WORKER_OK
, status
);
470 EXPECT_TRUE(version_
->timeout_timer_
.IsRunning());
471 EXPECT_LT(idle_time
, version_
->idle_time_
);
473 // Adding a controllee resets the idle time.
474 version_
->idle_time_
-= kOneSecond
;
475 idle_time
= version_
->idle_time_
;
476 scoped_ptr
<ServiceWorkerProviderHost
> host(new ServiceWorkerProviderHost(
477 33 /* dummy render process id */, MSG_ROUTING_NONE
/* render_frame_id */,
478 1 /* dummy provider_id */, SERVICE_WORKER_PROVIDER_FOR_WINDOW
,
479 helper_
->context()->AsWeakPtr(), NULL
));
480 version_
->AddControllee(host
.get());
481 EXPECT_TRUE(version_
->timeout_timer_
.IsRunning());
482 EXPECT_LT(idle_time
, version_
->idle_time_
);
484 // Completing an event resets the idle time.
485 status
= SERVICE_WORKER_ERROR_FAILED
;
486 version_
->idle_time_
-= kOneSecond
;
487 idle_time
= version_
->idle_time_
;
488 version_
->DispatchFetchEvent(ServiceWorkerFetchRequest(),
489 base::Bind(&base::DoNothing
),
490 base::Bind(&ReceiveFetchResult
, &status
));
491 base::RunLoop().RunUntilIdle();
493 EXPECT_EQ(SERVICE_WORKER_OK
, status
);
494 EXPECT_LT(idle_time
, version_
->idle_time_
);
496 // Dispatching a message event resets the idle time.
497 std::vector
<TransferredMessagePort
> ports
;
498 SetUpDummyMessagePort(&ports
);
499 status
= SERVICE_WORKER_ERROR_FAILED
;
500 version_
->idle_time_
-= kOneSecond
;
501 idle_time
= version_
->idle_time_
;
502 version_
->DispatchMessageEvent(base::string16(), ports
,
503 CreateReceiverOnCurrentThread(&status
));
504 base::RunLoop().RunUntilIdle();
505 MessagePortService::GetInstance()->Destroy(ports
[0].id
);
507 EXPECT_EQ(SERVICE_WORKER_OK
, status
);
508 EXPECT_LT(idle_time
, version_
->idle_time_
);
511 // Test that the worker stays alive for some time after
512 // receiving a push event.
513 // TODO(falken): Remove this test once Facebook doesn't rely on the behavior:
515 TEST_F(ServiceWorkerVersionTest
, StayAliveAfterPush
) {
516 const base::TimeDelta kTenSeconds
= base::TimeDelta::FromSeconds(10);
517 ServiceWorkerStatusCode status
= SERVICE_WORKER_ERROR_FAILED
;
518 version_
->SetStatus(ServiceWorkerVersion::ACTIVATED
);
519 version_
->DispatchPushEvent(CreateReceiverOnCurrentThread(&status
),
521 base::RunLoop().RunUntilIdle();
523 // Pretend we've been idle for 10 seconds and fire the timeout code.
524 version_
->idle_time_
= base::TimeTicks::Now() - kTenSeconds
;
525 version_
->OnTimeoutTimer();
526 EXPECT_EQ(ServiceWorkerVersion::RUNNING
, version_
->running_status());
529 TEST_F(ServiceWorkerVersionTest
, SetDevToolsAttached
) {
530 ServiceWorkerStatusCode status
= SERVICE_WORKER_ERROR_FAILED
;
531 version_
->StartWorker(CreateReceiverOnCurrentThread(&status
));
533 ASSERT_EQ(ServiceWorkerVersion::STARTING
, version_
->running_status());
535 ASSERT_TRUE(version_
->timeout_timer_
.IsRunning());
536 ASSERT_FALSE(version_
->start_time_
.is_null());
537 ASSERT_FALSE(version_
->skip_recording_startup_time_
);
539 // Simulate DevTools is attached. This should deactivate the timer for start
540 // timeout, but not stop the timer itself.
541 version_
->SetDevToolsAttached(true);
542 EXPECT_TRUE(version_
->timeout_timer_
.IsRunning());
543 EXPECT_TRUE(version_
->start_time_
.is_null());
544 EXPECT_TRUE(version_
->skip_recording_startup_time_
);
546 // Simulate DevTools is detached. This should reactivate the timer for start
548 version_
->SetDevToolsAttached(false);
549 EXPECT_TRUE(version_
->timeout_timer_
.IsRunning());
550 EXPECT_FALSE(version_
->start_time_
.is_null());
551 EXPECT_TRUE(version_
->skip_recording_startup_time_
);
553 base::RunLoop().RunUntilIdle();
554 EXPECT_EQ(SERVICE_WORKER_OK
, status
);
555 EXPECT_EQ(ServiceWorkerVersion::RUNNING
, version_
->running_status());
558 TEST_F(ServiceWorkerVersionTest
, StoppingBeforeDestruct
) {
559 RunningStateListener listener
;
560 version_
->AddListener(&listener
);
562 ServiceWorkerStatusCode status
= SERVICE_WORKER_ERROR_FAILED
;
563 version_
->StartWorker(CreateReceiverOnCurrentThread(&status
));
564 base::RunLoop().RunUntilIdle();
565 EXPECT_EQ(SERVICE_WORKER_OK
, status
);
566 EXPECT_EQ(ServiceWorkerVersion::RUNNING
, version_
->running_status());
567 EXPECT_EQ(ServiceWorkerVersion::RUNNING
, listener
.last_status
);
570 EXPECT_EQ(ServiceWorkerVersion::STOPPING
, listener
.last_status
);
573 // Test that update isn't triggered for a non-stale worker.
574 TEST_F(ServiceWorkerVersionTest
, StaleUpdate_FreshWorker
) {
575 ServiceWorkerStatusCode status
= SERVICE_WORKER_ERROR_FAILED
;
577 version_
->SetStatus(ServiceWorkerVersion::ACTIVATED
);
578 registration_
->SetActiveVersion(version_
);
579 registration_
->set_last_update_check(base::Time::Now());
580 version_
->DispatchPushEvent(CreateReceiverOnCurrentThread(&status
),
582 base::RunLoop().RunUntilIdle();
584 EXPECT_EQ(SERVICE_WORKER_OK
, status
);
585 EXPECT_TRUE(version_
->stale_time_
.is_null());
586 EXPECT_FALSE(version_
->update_timer_
.IsRunning());
589 // Test that update isn't triggered for a non-active worker.
590 TEST_F(ServiceWorkerVersionTest
, StaleUpdate_NonActiveWorker
) {
591 ServiceWorkerStatusCode status
= SERVICE_WORKER_ERROR_FAILED
;
593 version_
->SetStatus(ServiceWorkerVersion::INSTALLING
);
594 registration_
->SetInstallingVersion(version_
);
595 registration_
->set_last_update_check(GetYesterday());
596 version_
->DispatchInstallEvent(CreateReceiverOnCurrentThread(&status
));
597 base::RunLoop().RunUntilIdle();
599 EXPECT_EQ(SERVICE_WORKER_OK
, status
);
600 EXPECT_TRUE(version_
->stale_time_
.is_null());
601 EXPECT_FALSE(version_
->update_timer_
.IsRunning());
604 // Test that staleness is detected when starting a worker.
605 TEST_F(ServiceWorkerVersionTest
, StaleUpdate_StartWorker
) {
606 ServiceWorkerStatusCode status
= SERVICE_WORKER_ERROR_FAILED
;
608 // Starting the worker marks it as stale.
609 version_
->SetStatus(ServiceWorkerVersion::ACTIVATED
);
610 registration_
->SetActiveVersion(version_
);
611 registration_
->set_last_update_check(GetYesterday());
612 version_
->DispatchPushEvent(CreateReceiverOnCurrentThread(&status
),
614 base::RunLoop().RunUntilIdle();
615 EXPECT_EQ(SERVICE_WORKER_OK
, status
);
616 EXPECT_FALSE(version_
->stale_time_
.is_null());
617 EXPECT_FALSE(version_
->update_timer_
.IsRunning());
619 // Update is actually scheduled after the worker stops.
620 version_
->StopWorker(CreateReceiverOnCurrentThread(&status
));
621 base::RunLoop().RunUntilIdle();
622 EXPECT_EQ(SERVICE_WORKER_OK
, status
);
623 EXPECT_TRUE(version_
->stale_time_
.is_null());
624 EXPECT_TRUE(version_
->update_timer_
.IsRunning());
627 // Test that staleness is detected on a running worker.
628 TEST_F(ServiceWorkerVersionTest
, StaleUpdate_RunningWorker
) {
629 ServiceWorkerStatusCode status
= SERVICE_WORKER_ERROR_FAILED
;
631 // Start a fresh worker.
632 version_
->SetStatus(ServiceWorkerVersion::ACTIVATED
);
633 registration_
->SetActiveVersion(version_
);
634 registration_
->set_last_update_check(base::Time::Now());
635 version_
->DispatchPushEvent(CreateReceiverOnCurrentThread(&status
),
637 base::RunLoop().RunUntilIdle();
638 EXPECT_EQ(SERVICE_WORKER_OK
, status
);
639 EXPECT_TRUE(version_
->stale_time_
.is_null());
641 // Simulate it running for a day. It will be marked stale.
642 registration_
->set_last_update_check(GetYesterday());
643 version_
->OnTimeoutTimer();
644 EXPECT_FALSE(version_
->stale_time_
.is_null());
645 EXPECT_FALSE(version_
->update_timer_
.IsRunning());
647 // Simulate it running for past the wait threshold. The update will be
649 version_
->stale_time_
=
650 base::TimeTicks::Now() -
651 base::TimeDelta::FromMinutes(
652 ServiceWorkerVersion::kStartWorkerTimeoutMinutes
+ 1);
653 version_
->OnTimeoutTimer();
654 EXPECT_TRUE(version_
->stale_time_
.is_null());
655 EXPECT_TRUE(version_
->update_timer_
.IsRunning());
658 // Test that a stream of events doesn't restart the timer.
659 TEST_F(ServiceWorkerVersionTest
, StaleUpdate_DoNotDeferTimer
) {
660 // Make a stale worker.
661 version_
->SetStatus(ServiceWorkerVersion::ACTIVATED
);
662 registration_
->SetActiveVersion(version_
);
663 registration_
->set_last_update_check(GetYesterday());
664 base::TimeTicks stale_time
=
665 base::TimeTicks::Now() -
666 base::TimeDelta::FromMinutes(
667 ServiceWorkerVersion::kStartWorkerTimeoutMinutes
+ 1);
668 version_
->stale_time_
= stale_time
;
670 // Stale time is not deferred.
671 version_
->DispatchPushEvent(
672 base::Bind(&ServiceWorkerUtils::NoOpStatusCallback
), std::string());
673 version_
->DispatchPushEvent(
674 base::Bind(&ServiceWorkerUtils::NoOpStatusCallback
), std::string());
675 EXPECT_EQ(stale_time
, version_
->stale_time_
);
677 // Timeout triggers the update.
678 version_
->OnTimeoutTimer();
679 EXPECT_TRUE(version_
->stale_time_
.is_null());
680 EXPECT_TRUE(version_
->update_timer_
.IsRunning());
682 // Update timer is not deferred.
683 base::TimeTicks run_time
= version_
->update_timer_
.desired_run_time();
684 version_
->DispatchPushEvent(
685 base::Bind(&ServiceWorkerUtils::NoOpStatusCallback
), std::string());
686 version_
->DispatchPushEvent(
687 base::Bind(&ServiceWorkerUtils::NoOpStatusCallback
), std::string());
688 version_
->DispatchPushEvent(
689 base::Bind(&ServiceWorkerUtils::NoOpStatusCallback
), std::string());
690 base::RunLoop().RunUntilIdle();
691 EXPECT_TRUE(version_
->stale_time_
.is_null());
692 EXPECT_EQ(run_time
, version_
->update_timer_
.desired_run_time());
695 TEST_F(ServiceWorkerWaitForeverInFetchTest
, RequestTimeout
) {
696 ServiceWorkerStatusCode status
= SERVICE_WORKER_ERROR_NETWORK
; // dummy value
698 version_
->SetStatus(ServiceWorkerVersion::ACTIVATED
);
699 version_
->DispatchFetchEvent(ServiceWorkerFetchRequest(),
700 base::Bind(&base::DoNothing
),
701 base::Bind(&ReceiveFetchResult
, &status
));
702 base::RunLoop().RunUntilIdle();
704 // Callback has not completed yet.
705 EXPECT_EQ(SERVICE_WORKER_ERROR_NETWORK
, status
);
706 EXPECT_EQ(ServiceWorkerVersion::RUNNING
, version_
->running_status());
709 EXPECT_TRUE(version_
->timeout_timer_
.IsRunning());
710 version_
->SetAllRequestTimes(
711 base::TimeTicks::Now() -
712 base::TimeDelta::FromMinutes(
713 ServiceWorkerVersion::kRequestTimeoutMinutes
+ 1));
714 version_
->timeout_timer_
.user_task().Run();
715 base::RunLoop().RunUntilIdle();
716 EXPECT_EQ(SERVICE_WORKER_ERROR_TIMEOUT
, status
);
717 EXPECT_EQ(ServiceWorkerVersion::STOPPED
, version_
->running_status());
720 TEST_F(ServiceWorkerFailToStartTest
, RendererCrash
) {
721 ServiceWorkerStatusCode status
= SERVICE_WORKER_ERROR_NETWORK
; // dummy value
722 version_
->StartWorker(
723 CreateReceiverOnCurrentThread(&status
));
724 base::RunLoop().RunUntilIdle();
726 // Callback has not completed yet.
727 EXPECT_EQ(SERVICE_WORKER_ERROR_NETWORK
, status
);
728 EXPECT_EQ(ServiceWorkerVersion::STARTING
, version_
->running_status());
730 // Simulate renderer crash: do what
731 // ServiceWorkerDispatcherHost::OnFilterRemoved does.
732 int process_id
= helper_
->mock_render_process_id();
733 helper_
->context()->RemoveAllProviderHostsForProcess(process_id
);
734 helper_
->context()->embedded_worker_registry()->RemoveChildProcessSender(
736 base::RunLoop().RunUntilIdle();
738 // Callback completed.
739 EXPECT_EQ(SERVICE_WORKER_ERROR_START_WORKER_FAILED
, status
);
740 EXPECT_EQ(ServiceWorkerVersion::STOPPED
, version_
->running_status());
743 TEST_F(ServiceWorkerFailToStartTest
, Timeout
) {
744 ServiceWorkerStatusCode status
= SERVICE_WORKER_ERROR_NETWORK
; // dummy value
746 // We could just call StartWorker but make it interesting and test
747 // starting the worker as part of dispatching an event.
748 version_
->SetStatus(ServiceWorkerVersion::ACTIVATING
);
749 version_
->DispatchActivateEvent(CreateReceiverOnCurrentThread(&status
));
750 base::RunLoop().RunUntilIdle();
752 // Callback has not completed yet.
753 EXPECT_EQ(SERVICE_WORKER_ERROR_NETWORK
, status
);
754 EXPECT_EQ(ServiceWorkerVersion::STARTING
, version_
->running_status());
757 EXPECT_TRUE(version_
->timeout_timer_
.IsRunning());
758 version_
->start_time_
=
759 base::TimeTicks::Now() -
760 base::TimeDelta::FromMinutes(
761 ServiceWorkerVersion::kStartWorkerTimeoutMinutes
+ 1);
762 version_
->timeout_timer_
.user_task().Run();
763 base::RunLoop().RunUntilIdle();
764 EXPECT_EQ(SERVICE_WORKER_ERROR_TIMEOUT
, status
);
765 EXPECT_EQ(ServiceWorkerVersion::STOPPED
, version_
->running_status());
768 } // namespace content