Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
MaintenanceModeEnablerTest.php
Go to the documentation of this file.
1 <?php
7 
10 use PHPUnit\Framework\TestCase;
11 use Symfony\Component\Console\Output\OutputInterface;
12 
13 class MaintenanceModeEnablerTest extends TestCase
14 {
18  public function testSuccessfulTask(bool $maintenanceModeEnabledInitially)
19  {
20  $maintenanceMode = $this->createMaintenanceMode($maintenanceModeEnabledInitially);
21  $enabler = new MaintenanceModeEnabler($maintenanceMode);
22  $successTask = function () {
23  // do nothing
24  };
25 
26  $enabler->executeInMaintenanceMode(
27  $successTask,
28  $this->createOutput(),
29  true
30  );
31 
32  $this->assertEquals(
33  $maintenanceModeEnabledInitially,
34  $maintenanceMode->isOn(),
35  'Initial state is not restored'
36  );
37  }
38 
42  public function testFailedTaskWithMaintenanceModeOnFailure(bool $maintenanceModeEnabledInitially)
43  {
44  $maintenanceMode = $this->createMaintenanceMode($maintenanceModeEnabledInitially);
45  $enabler = new MaintenanceModeEnabler($maintenanceMode);
46  $failedTask = function () {
47  throw new \Exception('Woops!');
48  };
49 
50  try {
51  $enabler->executeInMaintenanceMode(
52  $failedTask,
53  $this->createOutput(),
54  true
55  );
56  } catch (\Exception $e) {
57  $this->assertEquals(
58  true,
59  $maintenanceMode->isOn(),
60  'Maintenance mode is not active after failure'
61  );
62  }
63  }
64 
68  public function testFailedTaskWithRestoredModeOnFailure(bool $maintenanceModeEnabledInitially)
69  {
70  $maintenanceMode = $this->createMaintenanceMode($maintenanceModeEnabledInitially);
71  $enabler = new MaintenanceModeEnabler($maintenanceMode);
72  $failedTask = function () {
73  throw new \Exception('Woops!');
74  };
75 
76  try {
77  $enabler->executeInMaintenanceMode(
78  $failedTask,
79  $this->createOutput(),
80  false
81  );
82  } catch (\Exception $e) {
83  $this->assertEquals(
84  $maintenanceModeEnabledInitially,
85  $maintenanceMode->isOn(),
86  'Initial state is not restored'
87  );
88  }
89  }
90 
94  public function initialAppStateProvider()
95  {
96  return [
97  'Maintenance mode disabled initially' => [false],
98  'Maintenance mode enabled initially' => [true],
99  ];
100  }
101 
106  private function createMaintenanceMode(bool $isOn): MaintenanceMode
107  {
108  $maintenanceMode = $this->getMockBuilder(MaintenanceMode::class)
109  ->disableOriginalConstructor()
110  ->getMock();
111 
112  $maintenanceMode->method('isOn')->willReturnCallback(function () use (&$isOn) {
113  return $isOn;
114  });
115  $maintenanceMode->method('set')->willReturnCallback(function ($newValue) use (&$isOn) {
116  $isOn = (bool)$newValue;
117  return true;
118  });
119 
120  return $maintenanceMode;
121  }
122 
126  private function createOutput(): OutputInterface
127  {
128  $output = $this->getMockBuilder(OutputInterface::class)
129  ->getMockForAbstractClass();
130  return $output;
131  }
132 }