Completed
Push — master ( 953027...3b6ea8 )
by
unknown
21:16 queued 15s
created
apps/encryption/tests/SessionTest.php 1 patch
Indentation   +186 added lines, -186 removed lines patch added patch discarded remove patch
@@ -16,190 +16,190 @@
 block discarded – undo
16 16
 use Test\TestCase;
17 17
 
18 18
 class SessionTest extends TestCase {
19
-	private static $tempStorage = [];
20
-
21
-	protected Session $instance;
22
-	protected ISession&MockObject $sessionMock;
23
-
24
-	public function testThatGetPrivateKeyThrowsExceptionWhenNotSet(): void {
25
-		$this->expectException(PrivateKeyMissingException::class);
26
-		$this->expectExceptionMessage('Private Key missing for user: please try to log-out and log-in again');
27
-
28
-		$this->instance->getPrivateKey();
29
-	}
30
-
31
-	/**
32
-	 * @depends testThatGetPrivateKeyThrowsExceptionWhenNotSet
33
-	 */
34
-	public function testSetAndGetPrivateKey(): void {
35
-		$this->instance->setPrivateKey('dummyPrivateKey');
36
-		$this->assertEquals('dummyPrivateKey', $this->instance->getPrivateKey());
37
-	}
38
-
39
-	/**
40
-	 * @depends testSetAndGetPrivateKey
41
-	 */
42
-	public function testIsPrivateKeySet(): void {
43
-		$this->instance->setPrivateKey('dummyPrivateKey');
44
-		$this->assertTrue($this->instance->isPrivateKeySet());
45
-
46
-		unset(self::$tempStorage['privateKey']);
47
-		$this->assertFalse($this->instance->isPrivateKeySet());
48
-
49
-		// Set private key back so we can test clear method
50
-		self::$tempStorage['privateKey'] = 'dummyPrivateKey';
51
-	}
52
-
53
-	public function testDecryptAllModeActivated(): void {
54
-		$this->instance->prepareDecryptAll('user1', 'usersKey');
55
-		$this->assertTrue($this->instance->decryptAllModeActivated());
56
-		$this->assertSame('user1', $this->instance->getDecryptAllUid());
57
-		$this->assertSame('usersKey', $this->instance->getDecryptAllKey());
58
-	}
59
-
60
-	public function testDecryptAllModeDeactivated(): void {
61
-		$this->assertFalse($this->instance->decryptAllModeActivated());
62
-	}
63
-
64
-	/**
65
-	 * @expectExceptionMessage 'Please activate decrypt all mode first'
66
-	 */
67
-	public function testGetDecryptAllUidException(): void {
68
-		$this->expectException(\Exception::class);
69
-
70
-		$this->instance->getDecryptAllUid();
71
-	}
72
-
73
-	/**
74
-	 * @expectExceptionMessage 'No uid found while in decrypt all mode'
75
-	 */
76
-	public function testGetDecryptAllUidException2(): void {
77
-		$this->expectException(\Exception::class);
78
-
79
-		$this->instance->prepareDecryptAll(null, 'key');
80
-		$this->instance->getDecryptAllUid();
81
-	}
82
-
83
-	/**
84
-	 * @expectExceptionMessage 'Please activate decrypt all mode first'
85
-	 */
86
-	public function testGetDecryptAllKeyException(): void {
87
-		$this->expectException(PrivateKeyMissingException::class);
88
-
89
-		$this->instance->getDecryptAllKey();
90
-	}
91
-
92
-	/**
93
-	 * @expectExceptionMessage 'No key found while in decrypt all mode'
94
-	 */
95
-	public function testGetDecryptAllKeyException2(): void {
96
-		$this->expectException(PrivateKeyMissingException::class);
97
-
98
-		$this->instance->prepareDecryptAll('user', null);
99
-		$this->instance->getDecryptAllKey();
100
-	}
101
-
102
-
103
-	public function testSetAndGetStatusWillSetAndReturn(): void {
104
-		// Check if get status will return 0 if it has not been set before
105
-		$this->assertEquals(0, $this->instance->getStatus());
106
-
107
-		$this->instance->setStatus(Session::NOT_INITIALIZED);
108
-		$this->assertEquals(0, $this->instance->getStatus());
109
-
110
-		$this->instance->setStatus(Session::INIT_EXECUTED);
111
-		$this->assertEquals(1, $this->instance->getStatus());
112
-
113
-		$this->instance->setStatus(Session::INIT_SUCCESSFUL);
114
-		$this->assertEquals(2, $this->instance->getStatus());
115
-	}
116
-
117
-	/**
118
-	 * @dataProvider dataTestIsReady
119
-	 *
120
-	 * @param int $status
121
-	 * @param bool $expected
122
-	 */
123
-	public function testIsReady($status, $expected): void {
124
-		/** @var Session&MockObject $instance */
125
-		$instance = $this->getMockBuilder(Session::class)
126
-			->setConstructorArgs([$this->sessionMock])
127
-			->onlyMethods(['getStatus'])
128
-			->getMock();
129
-
130
-		$instance->expects($this->once())->method('getStatus')
131
-			->willReturn($status);
132
-
133
-		$this->assertSame($expected, $instance->isReady());
134
-	}
135
-
136
-	public static function dataTestIsReady(): array {
137
-		return [
138
-			[Session::INIT_SUCCESSFUL, true],
139
-			[Session::INIT_EXECUTED, false],
140
-			[Session::NOT_INITIALIZED, false],
141
-		];
142
-	}
143
-
144
-	/**
145
-	 * @param $key
146
-	 * @param $value
147
-	 */
148
-	public function setValueTester($key, $value) {
149
-		self::$tempStorage[$key] = $value;
150
-	}
151
-
152
-	/**
153
-	 * @param $key
154
-	 */
155
-	public function removeValueTester($key) {
156
-		unset(self::$tempStorage[$key]);
157
-	}
158
-
159
-	/**
160
-	 * @param $key
161
-	 * @return mixed
162
-	 */
163
-	public function getValueTester($key) {
164
-		if (!empty(self::$tempStorage[$key])) {
165
-			return self::$tempStorage[$key];
166
-		}
167
-		return null;
168
-	}
169
-
170
-
171
-	public function testClearWillRemoveValues(): void {
172
-		$this->instance->setPrivateKey('privateKey');
173
-		$this->instance->setStatus('initStatus');
174
-		$this->instance->prepareDecryptAll('user', 'key');
175
-		$this->assertNotEmpty(self::$tempStorage);
176
-		$this->instance->clear();
177
-		$this->assertEmpty(self::$tempStorage);
178
-	}
179
-
180
-
181
-	protected function setUp(): void {
182
-		parent::setUp();
183
-		$this->sessionMock = $this->createMock(ISession::class);
184
-
185
-		$this->sessionMock->expects($this->any())
186
-			->method('set')
187
-			->willReturnCallback([$this, 'setValueTester']);
188
-
189
-		$this->sessionMock->expects($this->any())
190
-			->method('get')
191
-			->willReturnCallback([$this, 'getValueTester']);
192
-
193
-		$this->sessionMock->expects($this->any())
194
-			->method('remove')
195
-			->willReturnCallback([$this, 'removeValueTester']);
196
-
197
-
198
-		$this->instance = new Session($this->sessionMock);
199
-	}
200
-
201
-	protected function tearDown(): void {
202
-		self::$tempStorage = [];
203
-		parent::tearDown();
204
-	}
19
+    private static $tempStorage = [];
20
+
21
+    protected Session $instance;
22
+    protected ISession&MockObject $sessionMock;
23
+
24
+    public function testThatGetPrivateKeyThrowsExceptionWhenNotSet(): void {
25
+        $this->expectException(PrivateKeyMissingException::class);
26
+        $this->expectExceptionMessage('Private Key missing for user: please try to log-out and log-in again');
27
+
28
+        $this->instance->getPrivateKey();
29
+    }
30
+
31
+    /**
32
+     * @depends testThatGetPrivateKeyThrowsExceptionWhenNotSet
33
+     */
34
+    public function testSetAndGetPrivateKey(): void {
35
+        $this->instance->setPrivateKey('dummyPrivateKey');
36
+        $this->assertEquals('dummyPrivateKey', $this->instance->getPrivateKey());
37
+    }
38
+
39
+    /**
40
+     * @depends testSetAndGetPrivateKey
41
+     */
42
+    public function testIsPrivateKeySet(): void {
43
+        $this->instance->setPrivateKey('dummyPrivateKey');
44
+        $this->assertTrue($this->instance->isPrivateKeySet());
45
+
46
+        unset(self::$tempStorage['privateKey']);
47
+        $this->assertFalse($this->instance->isPrivateKeySet());
48
+
49
+        // Set private key back so we can test clear method
50
+        self::$tempStorage['privateKey'] = 'dummyPrivateKey';
51
+    }
52
+
53
+    public function testDecryptAllModeActivated(): void {
54
+        $this->instance->prepareDecryptAll('user1', 'usersKey');
55
+        $this->assertTrue($this->instance->decryptAllModeActivated());
56
+        $this->assertSame('user1', $this->instance->getDecryptAllUid());
57
+        $this->assertSame('usersKey', $this->instance->getDecryptAllKey());
58
+    }
59
+
60
+    public function testDecryptAllModeDeactivated(): void {
61
+        $this->assertFalse($this->instance->decryptAllModeActivated());
62
+    }
63
+
64
+    /**
65
+     * @expectExceptionMessage 'Please activate decrypt all mode first'
66
+     */
67
+    public function testGetDecryptAllUidException(): void {
68
+        $this->expectException(\Exception::class);
69
+
70
+        $this->instance->getDecryptAllUid();
71
+    }
72
+
73
+    /**
74
+     * @expectExceptionMessage 'No uid found while in decrypt all mode'
75
+     */
76
+    public function testGetDecryptAllUidException2(): void {
77
+        $this->expectException(\Exception::class);
78
+
79
+        $this->instance->prepareDecryptAll(null, 'key');
80
+        $this->instance->getDecryptAllUid();
81
+    }
82
+
83
+    /**
84
+     * @expectExceptionMessage 'Please activate decrypt all mode first'
85
+     */
86
+    public function testGetDecryptAllKeyException(): void {
87
+        $this->expectException(PrivateKeyMissingException::class);
88
+
89
+        $this->instance->getDecryptAllKey();
90
+    }
91
+
92
+    /**
93
+     * @expectExceptionMessage 'No key found while in decrypt all mode'
94
+     */
95
+    public function testGetDecryptAllKeyException2(): void {
96
+        $this->expectException(PrivateKeyMissingException::class);
97
+
98
+        $this->instance->prepareDecryptAll('user', null);
99
+        $this->instance->getDecryptAllKey();
100
+    }
101
+
102
+
103
+    public function testSetAndGetStatusWillSetAndReturn(): void {
104
+        // Check if get status will return 0 if it has not been set before
105
+        $this->assertEquals(0, $this->instance->getStatus());
106
+
107
+        $this->instance->setStatus(Session::NOT_INITIALIZED);
108
+        $this->assertEquals(0, $this->instance->getStatus());
109
+
110
+        $this->instance->setStatus(Session::INIT_EXECUTED);
111
+        $this->assertEquals(1, $this->instance->getStatus());
112
+
113
+        $this->instance->setStatus(Session::INIT_SUCCESSFUL);
114
+        $this->assertEquals(2, $this->instance->getStatus());
115
+    }
116
+
117
+    /**
118
+     * @dataProvider dataTestIsReady
119
+     *
120
+     * @param int $status
121
+     * @param bool $expected
122
+     */
123
+    public function testIsReady($status, $expected): void {
124
+        /** @var Session&MockObject $instance */
125
+        $instance = $this->getMockBuilder(Session::class)
126
+            ->setConstructorArgs([$this->sessionMock])
127
+            ->onlyMethods(['getStatus'])
128
+            ->getMock();
129
+
130
+        $instance->expects($this->once())->method('getStatus')
131
+            ->willReturn($status);
132
+
133
+        $this->assertSame($expected, $instance->isReady());
134
+    }
135
+
136
+    public static function dataTestIsReady(): array {
137
+        return [
138
+            [Session::INIT_SUCCESSFUL, true],
139
+            [Session::INIT_EXECUTED, false],
140
+            [Session::NOT_INITIALIZED, false],
141
+        ];
142
+    }
143
+
144
+    /**
145
+     * @param $key
146
+     * @param $value
147
+     */
148
+    public function setValueTester($key, $value) {
149
+        self::$tempStorage[$key] = $value;
150
+    }
151
+
152
+    /**
153
+     * @param $key
154
+     */
155
+    public function removeValueTester($key) {
156
+        unset(self::$tempStorage[$key]);
157
+    }
158
+
159
+    /**
160
+     * @param $key
161
+     * @return mixed
162
+     */
163
+    public function getValueTester($key) {
164
+        if (!empty(self::$tempStorage[$key])) {
165
+            return self::$tempStorage[$key];
166
+        }
167
+        return null;
168
+    }
169
+
170
+
171
+    public function testClearWillRemoveValues(): void {
172
+        $this->instance->setPrivateKey('privateKey');
173
+        $this->instance->setStatus('initStatus');
174
+        $this->instance->prepareDecryptAll('user', 'key');
175
+        $this->assertNotEmpty(self::$tempStorage);
176
+        $this->instance->clear();
177
+        $this->assertEmpty(self::$tempStorage);
178
+    }
179
+
180
+
181
+    protected function setUp(): void {
182
+        parent::setUp();
183
+        $this->sessionMock = $this->createMock(ISession::class);
184
+
185
+        $this->sessionMock->expects($this->any())
186
+            ->method('set')
187
+            ->willReturnCallback([$this, 'setValueTester']);
188
+
189
+        $this->sessionMock->expects($this->any())
190
+            ->method('get')
191
+            ->willReturnCallback([$this, 'getValueTester']);
192
+
193
+        $this->sessionMock->expects($this->any())
194
+            ->method('remove')
195
+            ->willReturnCallback([$this, 'removeValueTester']);
196
+
197
+
198
+        $this->instance = new Session($this->sessionMock);
199
+    }
200
+
201
+    protected function tearDown(): void {
202
+        self::$tempStorage = [];
203
+        parent::tearDown();
204
+    }
205 205
 }
Please login to merge, or discard this patch.
apps/encryption/tests/UtilTest.php 1 patch
Indentation   +163 added lines, -163 removed lines patch added patch discarded remove patch
@@ -23,167 +23,167 @@
 block discarded – undo
23 23
 
24 24
 class UtilTest extends TestCase {
25 25
 
26
-	protected Util $instance;
27
-	protected static $tempStorage = [];
28
-
29
-	protected IConfig&MockObject $configMock;
30
-	protected View&MockObject $filesMock;
31
-	protected IUserManager&MockObject $userManagerMock;
32
-	protected IMountPoint&MockObject $mountMock;
33
-
34
-	public function testSetRecoveryForUser(): void {
35
-		$this->instance->setRecoveryForUser('1');
36
-		$this->assertArrayHasKey('recoveryEnabled', self::$tempStorage);
37
-	}
38
-
39
-	public function testIsRecoveryEnabledForUser(): void {
40
-		$this->assertTrue($this->instance->isRecoveryEnabledForUser('admin'));
41
-
42
-		// Assert recovery will return default value if not set
43
-		unset(self::$tempStorage['recoveryEnabled']);
44
-		$this->assertEquals(0, $this->instance->isRecoveryEnabledForUser('admin'));
45
-	}
46
-
47
-	public function testUserHasFiles(): void {
48
-		$this->filesMock->expects($this->once())
49
-			->method('file_exists')
50
-			->willReturn(true);
51
-
52
-		$this->assertTrue($this->instance->userHasFiles('admin'));
53
-	}
54
-
55
-	protected function setUp(): void {
56
-		parent::setUp();
57
-		$this->mountMock = $this->createMock(IMountPoint::class);
58
-		$this->filesMock = $this->createMock(View::class);
59
-		$this->userManagerMock = $this->createMock(IUserManager::class);
60
-
61
-		/** @var Crypt $cryptMock */
62
-		$cryptMock = $this->getMockBuilder(Crypt::class)
63
-			->disableOriginalConstructor()
64
-			->getMock();
65
-
66
-		$user = $this->createMock(IUser::class);
67
-		$user->expects($this->any())
68
-			->method('getUID')
69
-			->willReturn('admin');
70
-
71
-		/** @var IUserSession|MockObject $userSessionMock */
72
-		$userSessionMock = $this->createMock(IUserSession::class);
73
-		$userSessionMock->expects($this->any())
74
-			->method('getUser')
75
-			->willReturn($user);
76
-		$userSessionMock->expects($this->any())
77
-			->method('isLoggedIn')
78
-			->willReturn(true);
79
-
80
-		$this->configMock = $this->createMock(IConfig::class);
81
-
82
-		$this->configMock->expects($this->any())
83
-			->method('getUserValue')
84
-			->willReturnCallback([$this, 'getValueTester']);
85
-
86
-		$this->configMock->expects($this->any())
87
-			->method('setUserValue')
88
-			->willReturnCallback([$this, 'setValueTester']);
89
-
90
-		$this->instance = new Util($this->filesMock, $cryptMock, $userSessionMock, $this->configMock, $this->userManagerMock);
91
-	}
92
-
93
-	/**
94
-	 * @param $userId
95
-	 * @param $app
96
-	 * @param $key
97
-	 * @param $value
98
-	 */
99
-	public function setValueTester($userId, $app, $key, $value) {
100
-		self::$tempStorage[$key] = $value;
101
-	}
102
-
103
-	/**
104
-	 * @param $userId
105
-	 * @param $app
106
-	 * @param $key
107
-	 * @param $default
108
-	 * @return mixed
109
-	 */
110
-	public function getValueTester($userId, $app, $key, $default) {
111
-		if (!empty(self::$tempStorage[$key])) {
112
-			return self::$tempStorage[$key];
113
-		}
114
-		return $default ?: null;
115
-	}
116
-
117
-	/**
118
-	 * @dataProvider dataTestIsMasterKeyEnabled
119
-	 *
120
-	 * @param string $value
121
-	 * @param bool $expect
122
-	 */
123
-	public function testIsMasterKeyEnabled($value, $expect): void {
124
-		$this->configMock->expects($this->once())->method('getAppValue')
125
-			->with('encryption', 'useMasterKey', '1')->willReturn($value);
126
-		$this->assertSame($expect,
127
-			$this->instance->isMasterKeyEnabled()
128
-		);
129
-	}
130
-
131
-	public static function dataTestIsMasterKeyEnabled(): array {
132
-		return [
133
-			['0', false],
134
-			['1', true]
135
-		];
136
-	}
137
-
138
-	/**
139
-	 * @dataProvider dataTestShouldEncryptHomeStorage
140
-	 * @param string $returnValue return value from getAppValue()
141
-	 * @param bool $expected
142
-	 */
143
-	public function testShouldEncryptHomeStorage($returnValue, $expected): void {
144
-		$this->configMock->expects($this->once())->method('getAppValue')
145
-			->with('encryption', 'encryptHomeStorage', '1')
146
-			->willReturn($returnValue);
147
-
148
-		$this->assertSame($expected,
149
-			$this->instance->shouldEncryptHomeStorage());
150
-	}
151
-
152
-	public static function dataTestShouldEncryptHomeStorage(): array {
153
-		return [
154
-			['1', true],
155
-			['0', false]
156
-		];
157
-	}
158
-
159
-	/**
160
-	 * @dataProvider dataTestSetEncryptHomeStorage
161
-	 * @param $value
162
-	 * @param $expected
163
-	 */
164
-	public function testSetEncryptHomeStorage($value, $expected): void {
165
-		$this->configMock->expects($this->once())->method('setAppValue')
166
-			->with('encryption', 'encryptHomeStorage', $expected);
167
-		$this->instance->setEncryptHomeStorage($value);
168
-	}
169
-
170
-	public static function dataTestSetEncryptHomeStorage(): array {
171
-		return [
172
-			[true, '1'],
173
-			[false, '0']
174
-		];
175
-	}
176
-
177
-	public function testGetStorage(): void {
178
-		$return = $this->getMockBuilder(IStorage::class)
179
-			->disableOriginalConstructor()
180
-			->getMock();
181
-
182
-		$path = '/foo/bar.txt';
183
-		$this->filesMock->expects($this->once())->method('getMount')->with($path)
184
-			->willReturn($this->mountMock);
185
-		$this->mountMock->expects($this->once())->method('getStorage')->willReturn($return);
186
-
187
-		$this->assertEquals($return, $this->instance->getStorage($path));
188
-	}
26
+    protected Util $instance;
27
+    protected static $tempStorage = [];
28
+
29
+    protected IConfig&MockObject $configMock;
30
+    protected View&MockObject $filesMock;
31
+    protected IUserManager&MockObject $userManagerMock;
32
+    protected IMountPoint&MockObject $mountMock;
33
+
34
+    public function testSetRecoveryForUser(): void {
35
+        $this->instance->setRecoveryForUser('1');
36
+        $this->assertArrayHasKey('recoveryEnabled', self::$tempStorage);
37
+    }
38
+
39
+    public function testIsRecoveryEnabledForUser(): void {
40
+        $this->assertTrue($this->instance->isRecoveryEnabledForUser('admin'));
41
+
42
+        // Assert recovery will return default value if not set
43
+        unset(self::$tempStorage['recoveryEnabled']);
44
+        $this->assertEquals(0, $this->instance->isRecoveryEnabledForUser('admin'));
45
+    }
46
+
47
+    public function testUserHasFiles(): void {
48
+        $this->filesMock->expects($this->once())
49
+            ->method('file_exists')
50
+            ->willReturn(true);
51
+
52
+        $this->assertTrue($this->instance->userHasFiles('admin'));
53
+    }
54
+
55
+    protected function setUp(): void {
56
+        parent::setUp();
57
+        $this->mountMock = $this->createMock(IMountPoint::class);
58
+        $this->filesMock = $this->createMock(View::class);
59
+        $this->userManagerMock = $this->createMock(IUserManager::class);
60
+
61
+        /** @var Crypt $cryptMock */
62
+        $cryptMock = $this->getMockBuilder(Crypt::class)
63
+            ->disableOriginalConstructor()
64
+            ->getMock();
65
+
66
+        $user = $this->createMock(IUser::class);
67
+        $user->expects($this->any())
68
+            ->method('getUID')
69
+            ->willReturn('admin');
70
+
71
+        /** @var IUserSession|MockObject $userSessionMock */
72
+        $userSessionMock = $this->createMock(IUserSession::class);
73
+        $userSessionMock->expects($this->any())
74
+            ->method('getUser')
75
+            ->willReturn($user);
76
+        $userSessionMock->expects($this->any())
77
+            ->method('isLoggedIn')
78
+            ->willReturn(true);
79
+
80
+        $this->configMock = $this->createMock(IConfig::class);
81
+
82
+        $this->configMock->expects($this->any())
83
+            ->method('getUserValue')
84
+            ->willReturnCallback([$this, 'getValueTester']);
85
+
86
+        $this->configMock->expects($this->any())
87
+            ->method('setUserValue')
88
+            ->willReturnCallback([$this, 'setValueTester']);
89
+
90
+        $this->instance = new Util($this->filesMock, $cryptMock, $userSessionMock, $this->configMock, $this->userManagerMock);
91
+    }
92
+
93
+    /**
94
+     * @param $userId
95
+     * @param $app
96
+     * @param $key
97
+     * @param $value
98
+     */
99
+    public function setValueTester($userId, $app, $key, $value) {
100
+        self::$tempStorage[$key] = $value;
101
+    }
102
+
103
+    /**
104
+     * @param $userId
105
+     * @param $app
106
+     * @param $key
107
+     * @param $default
108
+     * @return mixed
109
+     */
110
+    public function getValueTester($userId, $app, $key, $default) {
111
+        if (!empty(self::$tempStorage[$key])) {
112
+            return self::$tempStorage[$key];
113
+        }
114
+        return $default ?: null;
115
+    }
116
+
117
+    /**
118
+     * @dataProvider dataTestIsMasterKeyEnabled
119
+     *
120
+     * @param string $value
121
+     * @param bool $expect
122
+     */
123
+    public function testIsMasterKeyEnabled($value, $expect): void {
124
+        $this->configMock->expects($this->once())->method('getAppValue')
125
+            ->with('encryption', 'useMasterKey', '1')->willReturn($value);
126
+        $this->assertSame($expect,
127
+            $this->instance->isMasterKeyEnabled()
128
+        );
129
+    }
130
+
131
+    public static function dataTestIsMasterKeyEnabled(): array {
132
+        return [
133
+            ['0', false],
134
+            ['1', true]
135
+        ];
136
+    }
137
+
138
+    /**
139
+     * @dataProvider dataTestShouldEncryptHomeStorage
140
+     * @param string $returnValue return value from getAppValue()
141
+     * @param bool $expected
142
+     */
143
+    public function testShouldEncryptHomeStorage($returnValue, $expected): void {
144
+        $this->configMock->expects($this->once())->method('getAppValue')
145
+            ->with('encryption', 'encryptHomeStorage', '1')
146
+            ->willReturn($returnValue);
147
+
148
+        $this->assertSame($expected,
149
+            $this->instance->shouldEncryptHomeStorage());
150
+    }
151
+
152
+    public static function dataTestShouldEncryptHomeStorage(): array {
153
+        return [
154
+            ['1', true],
155
+            ['0', false]
156
+        ];
157
+    }
158
+
159
+    /**
160
+     * @dataProvider dataTestSetEncryptHomeStorage
161
+     * @param $value
162
+     * @param $expected
163
+     */
164
+    public function testSetEncryptHomeStorage($value, $expected): void {
165
+        $this->configMock->expects($this->once())->method('setAppValue')
166
+            ->with('encryption', 'encryptHomeStorage', $expected);
167
+        $this->instance->setEncryptHomeStorage($value);
168
+    }
169
+
170
+    public static function dataTestSetEncryptHomeStorage(): array {
171
+        return [
172
+            [true, '1'],
173
+            [false, '0']
174
+        ];
175
+    }
176
+
177
+    public function testGetStorage(): void {
178
+        $return = $this->getMockBuilder(IStorage::class)
179
+            ->disableOriginalConstructor()
180
+            ->getMock();
181
+
182
+        $path = '/foo/bar.txt';
183
+        $this->filesMock->expects($this->once())->method('getMount')->with($path)
184
+            ->willReturn($this->mountMock);
185
+        $this->mountMock->expects($this->once())->method('getStorage')->willReturn($return);
186
+
187
+        $this->assertEquals($return, $this->instance->getStorage($path));
188
+    }
189 189
 }
Please login to merge, or discard this patch.
apps/encryption/tests/Command/FixEncryptedVersionTest.php 1 patch
Indentation   +274 added lines, -274 removed lines patch added patch discarded remove patch
@@ -33,101 +33,101 @@  discard block
 block discarded – undo
33 33
  * @package OCA\Encryption\Tests\Command
34 34
  */
35 35
 class FixEncryptedVersionTest extends TestCase {
36
-	use MountProviderTrait;
37
-	use EncryptionTrait;
38
-	use UserTrait;
39
-
40
-	private string $userId;
41
-
42
-	private FixEncryptedVersion $fixEncryptedVersion;
43
-
44
-	private CommandTester $commandTester;
45
-
46
-	protected Util&MockObject $util;
47
-
48
-	public function setUp(): void {
49
-		parent::setUp();
50
-
51
-		Server::get(IConfig::class)->setAppValue('encryption', 'useMasterKey', '1');
52
-
53
-		$this->util = $this->getMockBuilder(Util::class)
54
-			->disableOriginalConstructor()->getMock();
55
-
56
-		$this->userId = $this->getUniqueId('user_');
57
-
58
-		$this->createUser($this->userId, 'foo12345678');
59
-		$tmpFolder = Server::get(ITempManager::class)->getTemporaryFolder();
60
-		$this->registerMount($this->userId, '\OC\Files\Storage\Local', '/' . $this->userId, ['datadir' => $tmpFolder]);
61
-		$this->setupForUser($this->userId, 'foo12345678');
62
-		$this->loginWithEncryption($this->userId);
63
-
64
-		$this->fixEncryptedVersion = new FixEncryptedVersion(
65
-			Server::get(IConfig::class),
66
-			Server::get(LoggerInterface::class),
67
-			Server::get(IRootFolder::class),
68
-			Server::get(IUserManager::class),
69
-			$this->util,
70
-			new View('/')
71
-		);
72
-		$this->commandTester = new CommandTester($this->fixEncryptedVersion);
73
-
74
-		$this->assertTrue(Server::get(\OCP\Encryption\IManager::class)->isEnabled());
75
-		$this->assertTrue(Server::get(\OCP\Encryption\IManager::class)->isReady());
76
-		$this->assertTrue(Server::get(\OCP\Encryption\IManager::class)->isReadyForUser($this->userId));
77
-	}
78
-
79
-	/**
80
-	 * In this test the encrypted version of the file is less than the original value
81
-	 * but greater than zero
82
-	 */
83
-	public function testEncryptedVersionLessThanOriginalValue(): void {
84
-		$this->util->expects($this->once())->method('isMasterKeyEnabled')
85
-			->willReturn(true);
86
-
87
-		$view = new View('/' . $this->userId . '/files');
88
-
89
-		$view->touch('hello.txt');
90
-		$view->touch('world.txt');
91
-		$view->touch('foo.txt');
92
-		$view->file_put_contents('hello.txt', 'a test string for hello');
93
-		$view->file_put_contents('hello.txt', 'Yet another value');
94
-		$view->file_put_contents('hello.txt', 'Lets modify again1');
95
-		$view->file_put_contents('hello.txt', 'Lets modify again2');
96
-		$view->file_put_contents('hello.txt', 'Lets modify again3');
97
-		$view->file_put_contents('world.txt', 'a test string for world');
98
-		$view->file_put_contents('world.txt', 'a test string for world');
99
-		$view->file_put_contents('world.txt', 'a test string for world');
100
-		$view->file_put_contents('world.txt', 'a test string for world');
101
-		$view->file_put_contents('foo.txt', 'a foo test');
102
-
103
-		$fileInfo1 = $view->getFileInfo('hello.txt');
104
-
105
-		$storage1 = $fileInfo1->getStorage();
106
-		$cache1 = $storage1->getCache();
107
-		$fileCache1 = $cache1->get($fileInfo1->getId());
108
-
109
-		//Now change the encrypted version to two
110
-		$cacheInfo = ['encryptedVersion' => 2, 'encrypted' => 2];
111
-		$cache1->put($fileCache1->getPath(), $cacheInfo);
112
-
113
-		$fileInfo2 = $view->getFileInfo('world.txt');
114
-		$storage2 = $fileInfo2->getStorage();
115
-		$cache2 = $storage2->getCache();
116
-		$filecache2 = $cache2->get($fileInfo2->getId());
117
-
118
-		//Now change the encrypted version to 1
119
-		$cacheInfo = ['encryptedVersion' => 1, 'encrypted' => 1];
120
-		$cache2->put($filecache2->getPath(), $cacheInfo);
121
-
122
-		$this->commandTester->execute([
123
-			'user' => $this->userId
124
-		]);
125
-
126
-		$output = $this->commandTester->getDisplay();
127
-
128
-		$this->assertStringContainsString("Verifying the content of file \"/$this->userId/files/foo.txt\"
36
+    use MountProviderTrait;
37
+    use EncryptionTrait;
38
+    use UserTrait;
39
+
40
+    private string $userId;
41
+
42
+    private FixEncryptedVersion $fixEncryptedVersion;
43
+
44
+    private CommandTester $commandTester;
45
+
46
+    protected Util&MockObject $util;
47
+
48
+    public function setUp(): void {
49
+        parent::setUp();
50
+
51
+        Server::get(IConfig::class)->setAppValue('encryption', 'useMasterKey', '1');
52
+
53
+        $this->util = $this->getMockBuilder(Util::class)
54
+            ->disableOriginalConstructor()->getMock();
55
+
56
+        $this->userId = $this->getUniqueId('user_');
57
+
58
+        $this->createUser($this->userId, 'foo12345678');
59
+        $tmpFolder = Server::get(ITempManager::class)->getTemporaryFolder();
60
+        $this->registerMount($this->userId, '\OC\Files\Storage\Local', '/' . $this->userId, ['datadir' => $tmpFolder]);
61
+        $this->setupForUser($this->userId, 'foo12345678');
62
+        $this->loginWithEncryption($this->userId);
63
+
64
+        $this->fixEncryptedVersion = new FixEncryptedVersion(
65
+            Server::get(IConfig::class),
66
+            Server::get(LoggerInterface::class),
67
+            Server::get(IRootFolder::class),
68
+            Server::get(IUserManager::class),
69
+            $this->util,
70
+            new View('/')
71
+        );
72
+        $this->commandTester = new CommandTester($this->fixEncryptedVersion);
73
+
74
+        $this->assertTrue(Server::get(\OCP\Encryption\IManager::class)->isEnabled());
75
+        $this->assertTrue(Server::get(\OCP\Encryption\IManager::class)->isReady());
76
+        $this->assertTrue(Server::get(\OCP\Encryption\IManager::class)->isReadyForUser($this->userId));
77
+    }
78
+
79
+    /**
80
+     * In this test the encrypted version of the file is less than the original value
81
+     * but greater than zero
82
+     */
83
+    public function testEncryptedVersionLessThanOriginalValue(): void {
84
+        $this->util->expects($this->once())->method('isMasterKeyEnabled')
85
+            ->willReturn(true);
86
+
87
+        $view = new View('/' . $this->userId . '/files');
88
+
89
+        $view->touch('hello.txt');
90
+        $view->touch('world.txt');
91
+        $view->touch('foo.txt');
92
+        $view->file_put_contents('hello.txt', 'a test string for hello');
93
+        $view->file_put_contents('hello.txt', 'Yet another value');
94
+        $view->file_put_contents('hello.txt', 'Lets modify again1');
95
+        $view->file_put_contents('hello.txt', 'Lets modify again2');
96
+        $view->file_put_contents('hello.txt', 'Lets modify again3');
97
+        $view->file_put_contents('world.txt', 'a test string for world');
98
+        $view->file_put_contents('world.txt', 'a test string for world');
99
+        $view->file_put_contents('world.txt', 'a test string for world');
100
+        $view->file_put_contents('world.txt', 'a test string for world');
101
+        $view->file_put_contents('foo.txt', 'a foo test');
102
+
103
+        $fileInfo1 = $view->getFileInfo('hello.txt');
104
+
105
+        $storage1 = $fileInfo1->getStorage();
106
+        $cache1 = $storage1->getCache();
107
+        $fileCache1 = $cache1->get($fileInfo1->getId());
108
+
109
+        //Now change the encrypted version to two
110
+        $cacheInfo = ['encryptedVersion' => 2, 'encrypted' => 2];
111
+        $cache1->put($fileCache1->getPath(), $cacheInfo);
112
+
113
+        $fileInfo2 = $view->getFileInfo('world.txt');
114
+        $storage2 = $fileInfo2->getStorage();
115
+        $cache2 = $storage2->getCache();
116
+        $filecache2 = $cache2->get($fileInfo2->getId());
117
+
118
+        //Now change the encrypted version to 1
119
+        $cacheInfo = ['encryptedVersion' => 1, 'encrypted' => 1];
120
+        $cache2->put($filecache2->getPath(), $cacheInfo);
121
+
122
+        $this->commandTester->execute([
123
+            'user' => $this->userId
124
+        ]);
125
+
126
+        $output = $this->commandTester->getDisplay();
127
+
128
+        $this->assertStringContainsString("Verifying the content of file \"/$this->userId/files/foo.txt\"
129 129
 The file \"/$this->userId/files/foo.txt\" is: OK", $output);
130
-		$this->assertStringContainsString("Verifying the content of file \"/$this->userId/files/hello.txt\"
130
+        $this->assertStringContainsString("Verifying the content of file \"/$this->userId/files/hello.txt\"
131 131
 Attempting to fix the path: \"/$this->userId/files/hello.txt\"
132 132
 Decrement the encrypted version to 1
133 133
 Increment the encrypted version to 3
@@ -135,256 +135,256 @@  discard block
 block discarded – undo
135 135
 Increment the encrypted version to 5
136 136
 The file \"/$this->userId/files/hello.txt\" is: OK
137 137
 Fixed the file: \"/$this->userId/files/hello.txt\" with version 5", $output);
138
-		$this->assertStringContainsString("Verifying the content of file \"/$this->userId/files/world.txt\"
138
+        $this->assertStringContainsString("Verifying the content of file \"/$this->userId/files/world.txt\"
139 139
 Attempting to fix the path: \"/$this->userId/files/world.txt\"
140 140
 Increment the encrypted version to 2
141 141
 Increment the encrypted version to 3
142 142
 Increment the encrypted version to 4
143 143
 The file \"/$this->userId/files/world.txt\" is: OK
144 144
 Fixed the file: \"/$this->userId/files/world.txt\" with version 4", $output);
145
-	}
146
-
147
-	/**
148
-	 * In this test the encrypted version of the file is greater than the original value
149
-	 * but greater than zero
150
-	 */
151
-	public function testEncryptedVersionGreaterThanOriginalValue(): void {
152
-		$this->util->expects($this->once())->method('isMasterKeyEnabled')
153
-			->willReturn(true);
154
-
155
-		$view = new View('/' . $this->userId . '/files');
156
-
157
-		$view->touch('hello.txt');
158
-		$view->touch('world.txt');
159
-		$view->touch('foo.txt');
160
-		$view->file_put_contents('hello.txt', 'a test string for hello');
161
-		$view->file_put_contents('hello.txt', 'Lets modify again2');
162
-		$view->file_put_contents('hello.txt', 'Lets modify again3');
163
-		$view->file_put_contents('world.txt', 'a test string for world');
164
-		$view->file_put_contents('world.txt', 'a test string for world');
165
-		$view->file_put_contents('world.txt', 'a test string for world');
166
-		$view->file_put_contents('world.txt', 'a test string for world');
167
-		$view->file_put_contents('foo.txt', 'a foo test');
168
-
169
-		$fileInfo1 = $view->getFileInfo('hello.txt');
170
-
171
-		$storage1 = $fileInfo1->getStorage();
172
-		$cache1 = $storage1->getCache();
173
-		$fileCache1 = $cache1->get($fileInfo1->getId());
174
-
175
-		//Now change the encrypted version to fifteen
176
-		$cacheInfo = ['encryptedVersion' => 5, 'encrypted' => 5];
177
-		$cache1->put($fileCache1->getPath(), $cacheInfo);
178
-
179
-		$fileInfo2 = $view->getFileInfo('world.txt');
180
-		$storage2 = $fileInfo2->getStorage();
181
-		$cache2 = $storage2->getCache();
182
-		$filecache2 = $cache2->get($fileInfo2->getId());
183
-
184
-		//Now change the encrypted version to 1
185
-		$cacheInfo = ['encryptedVersion' => 6, 'encrypted' => 6];
186
-		$cache2->put($filecache2->getPath(), $cacheInfo);
187
-
188
-		$this->commandTester->execute([
189
-			'user' => $this->userId
190
-		]);
191
-
192
-		$output = $this->commandTester->getDisplay();
193
-
194
-		$this->assertStringContainsString("Verifying the content of file \"/$this->userId/files/foo.txt\"
145
+    }
146
+
147
+    /**
148
+     * In this test the encrypted version of the file is greater than the original value
149
+     * but greater than zero
150
+     */
151
+    public function testEncryptedVersionGreaterThanOriginalValue(): void {
152
+        $this->util->expects($this->once())->method('isMasterKeyEnabled')
153
+            ->willReturn(true);
154
+
155
+        $view = new View('/' . $this->userId . '/files');
156
+
157
+        $view->touch('hello.txt');
158
+        $view->touch('world.txt');
159
+        $view->touch('foo.txt');
160
+        $view->file_put_contents('hello.txt', 'a test string for hello');
161
+        $view->file_put_contents('hello.txt', 'Lets modify again2');
162
+        $view->file_put_contents('hello.txt', 'Lets modify again3');
163
+        $view->file_put_contents('world.txt', 'a test string for world');
164
+        $view->file_put_contents('world.txt', 'a test string for world');
165
+        $view->file_put_contents('world.txt', 'a test string for world');
166
+        $view->file_put_contents('world.txt', 'a test string for world');
167
+        $view->file_put_contents('foo.txt', 'a foo test');
168
+
169
+        $fileInfo1 = $view->getFileInfo('hello.txt');
170
+
171
+        $storage1 = $fileInfo1->getStorage();
172
+        $cache1 = $storage1->getCache();
173
+        $fileCache1 = $cache1->get($fileInfo1->getId());
174
+
175
+        //Now change the encrypted version to fifteen
176
+        $cacheInfo = ['encryptedVersion' => 5, 'encrypted' => 5];
177
+        $cache1->put($fileCache1->getPath(), $cacheInfo);
178
+
179
+        $fileInfo2 = $view->getFileInfo('world.txt');
180
+        $storage2 = $fileInfo2->getStorage();
181
+        $cache2 = $storage2->getCache();
182
+        $filecache2 = $cache2->get($fileInfo2->getId());
183
+
184
+        //Now change the encrypted version to 1
185
+        $cacheInfo = ['encryptedVersion' => 6, 'encrypted' => 6];
186
+        $cache2->put($filecache2->getPath(), $cacheInfo);
187
+
188
+        $this->commandTester->execute([
189
+            'user' => $this->userId
190
+        ]);
191
+
192
+        $output = $this->commandTester->getDisplay();
193
+
194
+        $this->assertStringContainsString("Verifying the content of file \"/$this->userId/files/foo.txt\"
195 195
 The file \"/$this->userId/files/foo.txt\" is: OK", $output);
196
-		$this->assertStringContainsString("Verifying the content of file \"/$this->userId/files/hello.txt\"
196
+        $this->assertStringContainsString("Verifying the content of file \"/$this->userId/files/hello.txt\"
197 197
 Attempting to fix the path: \"/$this->userId/files/hello.txt\"
198 198
 Decrement the encrypted version to 4
199 199
 Decrement the encrypted version to 3
200 200
 The file \"/$this->userId/files/hello.txt\" is: OK
201 201
 Fixed the file: \"/$this->userId/files/hello.txt\" with version 3", $output);
202
-		$this->assertStringContainsString("Verifying the content of file \"/$this->userId/files/world.txt\"
202
+        $this->assertStringContainsString("Verifying the content of file \"/$this->userId/files/world.txt\"
203 203
 Attempting to fix the path: \"/$this->userId/files/world.txt\"
204 204
 Decrement the encrypted version to 5
205 205
 Decrement the encrypted version to 4
206 206
 The file \"/$this->userId/files/world.txt\" is: OK
207 207
 Fixed the file: \"/$this->userId/files/world.txt\" with version 4", $output);
208
-	}
208
+    }
209 209
 
210
-	public function testVersionIsRestoredToOriginalIfNoFixIsFound(): void {
211
-		$this->util->expects($this->once())->method('isMasterKeyEnabled')
212
-			->willReturn(true);
210
+    public function testVersionIsRestoredToOriginalIfNoFixIsFound(): void {
211
+        $this->util->expects($this->once())->method('isMasterKeyEnabled')
212
+            ->willReturn(true);
213 213
 
214
-		$view = new View('/' . $this->userId . '/files');
214
+        $view = new View('/' . $this->userId . '/files');
215 215
 
216
-		$view->touch('bar.txt');
217
-		for ($i = 0; $i < 40; $i++) {
218
-			$view->file_put_contents('bar.txt', 'a test string for hello ' . $i);
219
-		}
216
+        $view->touch('bar.txt');
217
+        for ($i = 0; $i < 40; $i++) {
218
+            $view->file_put_contents('bar.txt', 'a test string for hello ' . $i);
219
+        }
220 220
 
221
-		$fileInfo = $view->getFileInfo('bar.txt');
221
+        $fileInfo = $view->getFileInfo('bar.txt');
222 222
 
223
-		$storage = $fileInfo->getStorage();
224
-		$cache = $storage->getCache();
225
-		$fileCache = $cache->get($fileInfo->getId());
223
+        $storage = $fileInfo->getStorage();
224
+        $cache = $storage->getCache();
225
+        $fileCache = $cache->get($fileInfo->getId());
226 226
 
227
-		$cacheInfo = ['encryptedVersion' => 15, 'encrypted' => 15];
228
-		$cache->put($fileCache->getPath(), $cacheInfo);
227
+        $cacheInfo = ['encryptedVersion' => 15, 'encrypted' => 15];
228
+        $cache->put($fileCache->getPath(), $cacheInfo);
229 229
 
230
-		$this->commandTester->execute([
231
-			'user' => $this->userId
232
-		]);
230
+        $this->commandTester->execute([
231
+            'user' => $this->userId
232
+        ]);
233 233
 
234
-		$cacheInfo = $cache->get($fileInfo->getId());
235
-		$encryptedVersion = $cacheInfo['encryptedVersion'];
234
+        $cacheInfo = $cache->get($fileInfo->getId());
235
+        $encryptedVersion = $cacheInfo['encryptedVersion'];
236 236
 
237
-		$this->assertEquals(15, $encryptedVersion);
238
-	}
237
+        $this->assertEquals(15, $encryptedVersion);
238
+    }
239 239
 
240
-	public function testRepairUnencryptedFileWhenVersionIsSet(): void {
241
-		$this->util->expects($this->once())->method('isMasterKeyEnabled')
242
-			->willReturn(true);
240
+    public function testRepairUnencryptedFileWhenVersionIsSet(): void {
241
+        $this->util->expects($this->once())->method('isMasterKeyEnabled')
242
+            ->willReturn(true);
243 243
 
244
-		$view = new View('/' . $this->userId . '/files');
244
+        $view = new View('/' . $this->userId . '/files');
245 245
 
246
-		// create a file, it's encrypted and also the version is set in the database
247
-		$view->touch('hello.txt');
246
+        // create a file, it's encrypted and also the version is set in the database
247
+        $view->touch('hello.txt');
248 248
 
249
-		$fileInfo1 = $view->getFileInfo('hello.txt');
249
+        $fileInfo1 = $view->getFileInfo('hello.txt');
250 250
 
251
-		$storage1 = $fileInfo1->getStorage();
252
-		$cache1 = $storage1->getCache();
253
-		$fileCache1 = $cache1->get($fileInfo1->getId());
251
+        $storage1 = $fileInfo1->getStorage();
252
+        $cache1 = $storage1->getCache();
253
+        $fileCache1 = $cache1->get($fileInfo1->getId());
254 254
 
255
-		// Now change the encrypted version
256
-		$cacheInfo = ['encryptedVersion' => 1, 'encrypted' => 1];
257
-		$cache1->put($fileCache1->getPath(), $cacheInfo);
255
+        // Now change the encrypted version
256
+        $cacheInfo = ['encryptedVersion' => 1, 'encrypted' => 1];
257
+        $cache1->put($fileCache1->getPath(), $cacheInfo);
258 258
 
259
-		$absPath = $storage1->getSourcePath('') . $fileInfo1->getInternalPath();
259
+        $absPath = $storage1->getSourcePath('') . $fileInfo1->getInternalPath();
260 260
 
261
-		// create unencrypted file on disk, the version stays
262
-		file_put_contents($absPath, 'hello contents');
261
+        // create unencrypted file on disk, the version stays
262
+        file_put_contents($absPath, 'hello contents');
263 263
 
264
-		$this->commandTester->execute([
265
-			'user' => $this->userId
266
-		]);
264
+        $this->commandTester->execute([
265
+            'user' => $this->userId
266
+        ]);
267 267
 
268
-		$output = $this->commandTester->getDisplay();
268
+        $output = $this->commandTester->getDisplay();
269 269
 
270
-		$this->assertStringContainsString("Verifying the content of file \"/$this->userId/files/hello.txt\"
270
+        $this->assertStringContainsString("Verifying the content of file \"/$this->userId/files/hello.txt\"
271 271
 Attempting to fix the path: \"/$this->userId/files/hello.txt\"
272 272
 Set the encrypted version to 0 (unencrypted)
273 273
 The file \"/$this->userId/files/hello.txt\" is: OK
274 274
 Fixed the file: \"/$this->userId/files/hello.txt\" with version 0 (unencrypted)", $output);
275 275
 
276
-		// the file can be decrypted
277
-		$this->assertEquals('hello contents', $view->file_get_contents('hello.txt'));
278
-	}
276
+        // the file can be decrypted
277
+        $this->assertEquals('hello contents', $view->file_get_contents('hello.txt'));
278
+    }
279 279
 
280
-	/**
281
-	 * Test commands with a file path
282
-	 */
283
-	public function testExecuteWithFilePathOption(): void {
284
-		$this->util->expects($this->once())->method('isMasterKeyEnabled')
285
-			->willReturn(true);
280
+    /**
281
+     * Test commands with a file path
282
+     */
283
+    public function testExecuteWithFilePathOption(): void {
284
+        $this->util->expects($this->once())->method('isMasterKeyEnabled')
285
+            ->willReturn(true);
286 286
 
287
-		$view = new View('/' . $this->userId . '/files');
287
+        $view = new View('/' . $this->userId . '/files');
288 288
 
289
-		$view->touch('hello.txt');
290
-		$view->touch('world.txt');
289
+        $view->touch('hello.txt');
290
+        $view->touch('world.txt');
291 291
 
292
-		$this->commandTester->execute([
293
-			'user' => $this->userId,
294
-			'--path' => '/hello.txt'
295
-		]);
292
+        $this->commandTester->execute([
293
+            'user' => $this->userId,
294
+            '--path' => '/hello.txt'
295
+        ]);
296 296
 
297
-		$output = $this->commandTester->getDisplay();
297
+        $output = $this->commandTester->getDisplay();
298 298
 
299
-		$this->assertStringContainsString("Verifying the content of file \"/$this->userId/files/hello.txt\"
299
+        $this->assertStringContainsString("Verifying the content of file \"/$this->userId/files/hello.txt\"
300 300
 The file \"/$this->userId/files/hello.txt\" is: OK", $output);
301
-		$this->assertStringNotContainsString('world.txt', $output);
302
-	}
301
+        $this->assertStringNotContainsString('world.txt', $output);
302
+    }
303 303
 
304
-	/**
305
-	 * Test commands with a directory path
306
-	 */
307
-	public function testExecuteWithDirectoryPathOption(): void {
308
-		$this->util->expects($this->once())->method('isMasterKeyEnabled')
309
-			->willReturn(true);
304
+    /**
305
+     * Test commands with a directory path
306
+     */
307
+    public function testExecuteWithDirectoryPathOption(): void {
308
+        $this->util->expects($this->once())->method('isMasterKeyEnabled')
309
+            ->willReturn(true);
310 310
 
311
-		$view = new View('/' . $this->userId . '/files');
311
+        $view = new View('/' . $this->userId . '/files');
312 312
 
313
-		$view->mkdir('sub');
314
-		$view->touch('sub/hello.txt');
315
-		$view->touch('world.txt');
313
+        $view->mkdir('sub');
314
+        $view->touch('sub/hello.txt');
315
+        $view->touch('world.txt');
316 316
 
317
-		$this->commandTester->execute([
318
-			'user' => $this->userId,
319
-			'--path' => '/sub'
320
-		]);
317
+        $this->commandTester->execute([
318
+            'user' => $this->userId,
319
+            '--path' => '/sub'
320
+        ]);
321 321
 
322
-		$output = $this->commandTester->getDisplay();
322
+        $output = $this->commandTester->getDisplay();
323 323
 
324
-		$this->assertStringContainsString("Verifying the content of file \"/$this->userId/files/sub/hello.txt\"
324
+        $this->assertStringContainsString("Verifying the content of file \"/$this->userId/files/sub/hello.txt\"
325 325
 The file \"/$this->userId/files/sub/hello.txt\" is: OK", $output);
326
-		$this->assertStringNotContainsString('world.txt', $output);
327
-	}
326
+        $this->assertStringNotContainsString('world.txt', $output);
327
+    }
328 328
 
329
-	public function testExecuteWithNoUser(): void {
330
-		$this->util->expects($this->once())->method('isMasterKeyEnabled')
331
-			->willReturn(true);
329
+    public function testExecuteWithNoUser(): void {
330
+        $this->util->expects($this->once())->method('isMasterKeyEnabled')
331
+            ->willReturn(true);
332 332
 
333
-		$this->commandTester->execute([
334
-			'user' => null,
335
-			'--path' => '/'
336
-		]);
333
+        $this->commandTester->execute([
334
+            'user' => null,
335
+            '--path' => '/'
336
+        ]);
337 337
 
338
-		$output = $this->commandTester->getDisplay();
338
+        $output = $this->commandTester->getDisplay();
339 339
 
340
-		$this->assertStringContainsString('Either a user id or --all needs to be provided', $output);
341
-	}
340
+        $this->assertStringContainsString('Either a user id or --all needs to be provided', $output);
341
+    }
342 342
 
343
-	public function testExecuteWithBadUser(): void {
344
-		$this->util->expects($this->once())->method('isMasterKeyEnabled')
345
-			->willReturn(true);
343
+    public function testExecuteWithBadUser(): void {
344
+        $this->util->expects($this->once())->method('isMasterKeyEnabled')
345
+            ->willReturn(true);
346 346
 
347
-		$this->commandTester->execute([
348
-			'user' => 'nonexisting',
349
-			'--path' => '/'
350
-		]);
347
+        $this->commandTester->execute([
348
+            'user' => 'nonexisting',
349
+            '--path' => '/'
350
+        ]);
351 351
 
352
-		$output = $this->commandTester->getDisplay();
352
+        $output = $this->commandTester->getDisplay();
353 353
 
354
-		$this->assertStringContainsString('does not exist', $output);
355
-	}
354
+        $this->assertStringContainsString('does not exist', $output);
355
+    }
356 356
 
357
-	/**
358
-	 * Test commands with a directory path
359
-	 */
360
-	public function testExecuteWithNonExistentPath(): void {
361
-		$this->util->expects($this->once())->method('isMasterKeyEnabled')
362
-			->willReturn(true);
357
+    /**
358
+     * Test commands with a directory path
359
+     */
360
+    public function testExecuteWithNonExistentPath(): void {
361
+        $this->util->expects($this->once())->method('isMasterKeyEnabled')
362
+            ->willReturn(true);
363 363
 
364
-		$this->commandTester->execute([
365
-			'user' => $this->userId,
366
-			'--path' => '/non-exist'
367
-		]);
364
+        $this->commandTester->execute([
365
+            'user' => $this->userId,
366
+            '--path' => '/non-exist'
367
+        ]);
368 368
 
369
-		$output = $this->commandTester->getDisplay();
369
+        $output = $this->commandTester->getDisplay();
370 370
 
371
-		$this->assertStringContainsString('Please provide a valid path.', $output);
372
-	}
371
+        $this->assertStringContainsString('Please provide a valid path.', $output);
372
+    }
373 373
 
374
-	/**
375
-	 * Test commands without master key
376
-	 */
377
-	public function testExecuteWithNoMasterKey(): void {
378
-		Server::get(IConfig::class)->setAppValue('encryption', 'useMasterKey', '0');
379
-		$this->util->expects($this->once())->method('isMasterKeyEnabled')
380
-			->willReturn(false);
374
+    /**
375
+     * Test commands without master key
376
+     */
377
+    public function testExecuteWithNoMasterKey(): void {
378
+        Server::get(IConfig::class)->setAppValue('encryption', 'useMasterKey', '0');
379
+        $this->util->expects($this->once())->method('isMasterKeyEnabled')
380
+            ->willReturn(false);
381 381
 
382
-		$this->commandTester->execute([
383
-			'user' => $this->userId,
384
-		]);
382
+        $this->commandTester->execute([
383
+            'user' => $this->userId,
384
+        ]);
385 385
 
386
-		$output = $this->commandTester->getDisplay();
386
+        $output = $this->commandTester->getDisplay();
387 387
 
388
-		$this->assertStringContainsString('only works with master key', $output);
389
-	}
388
+        $this->assertStringContainsString('only works with master key', $output);
389
+    }
390 390
 }
Please login to merge, or discard this patch.
apps/encryption/tests/Controller/SettingsControllerTest.php 1 patch
Indentation   +185 added lines, -185 removed lines patch added patch discarded remove patch
@@ -26,189 +26,189 @@
 block discarded – undo
26 26
 
27 27
 class SettingsControllerTest extends TestCase {
28 28
 
29
-	protected SettingsController $controller;
30
-
31
-	protected IRequest&MockObject $requestMock;
32
-	protected IL10N&MockObject $l10nMock;
33
-	protected IUserManager&MockObject $userManagerMock;
34
-	protected IUserSession&MockObject $userSessionMock;
35
-	protected KeyManager&MockObject $keyManagerMock;
36
-	protected Crypt&MockObject $cryptMock;
37
-	protected Session&MockObject $sessionMock;
38
-	protected IUser&MockObject $user;
39
-	protected ISession&MockObject $ocSessionMock;
40
-	protected Util&MockObject $utilMock;
41
-
42
-	protected function setUp(): void {
43
-		parent::setUp();
44
-
45
-		$this->requestMock = $this->createMock(IRequest::class);
46
-
47
-		$this->l10nMock = $this->getMockBuilder(IL10N::class)
48
-			->disableOriginalConstructor()->getMock();
49
-
50
-		$this->l10nMock->expects($this->any())
51
-			->method('t')
52
-			->willReturnCallback(function ($message) {
53
-				return $message;
54
-			});
55
-
56
-		$this->userManagerMock = $this->getMockBuilder(IUserManager::class)
57
-			->disableOriginalConstructor()->getMock();
58
-
59
-		$this->keyManagerMock = $this->getMockBuilder(KeyManager::class)
60
-			->disableOriginalConstructor()->getMock();
61
-
62
-		$this->cryptMock = $this->getMockBuilder(Crypt::class)
63
-			->disableOriginalConstructor()->getMock();
64
-
65
-		$this->ocSessionMock = $this->getMockBuilder(ISession::class)->disableOriginalConstructor()->getMock();
66
-
67
-		$this->user = $this->createMock(IUser::class);
68
-		$this->user->expects($this->any())
69
-			->method('getUID')
70
-			->willReturn('testUserUid');
71
-
72
-		$this->userSessionMock = $this->createMock(IUserSession::class);
73
-		$this->userSessionMock->expects($this->any())
74
-			->method('getUser')
75
-			->willReturn($this->user);
76
-
77
-		$this->sessionMock = $this->getMockBuilder(Session::class)
78
-			->disableOriginalConstructor()->getMock();
79
-
80
-		$this->utilMock = $this->getMockBuilder(Util::class)
81
-			->disableOriginalConstructor()
82
-			->getMock();
83
-
84
-		$this->controller = new SettingsController(
85
-			'encryption',
86
-			$this->requestMock,
87
-			$this->l10nMock,
88
-			$this->userManagerMock,
89
-			$this->userSessionMock,
90
-			$this->keyManagerMock,
91
-			$this->cryptMock,
92
-			$this->sessionMock,
93
-			$this->ocSessionMock,
94
-			$this->utilMock
95
-		);
96
-	}
97
-
98
-	/**
99
-	 * test updatePrivateKeyPassword() if wrong new password was entered
100
-	 */
101
-	public function testUpdatePrivateKeyPasswordWrongNewPassword(): void {
102
-		$oldPassword = 'old';
103
-		$newPassword = 'new';
104
-
105
-		$this->user->expects($this->any())
106
-			->method('getUID')
107
-			->willReturn('uid');
108
-
109
-		$this->userManagerMock
110
-			->expects($this->exactly(2))
111
-			->method('checkPassword')
112
-			->willReturn(false);
113
-
114
-		$result = $this->controller->updatePrivateKeyPassword($oldPassword, $newPassword);
115
-
116
-		$data = $result->getData();
117
-
118
-		$this->assertSame(Http::STATUS_BAD_REQUEST, $result->getStatus());
119
-		$this->assertSame('The current log-in password was not correct, please try again.',
120
-			$data['message']);
121
-	}
122
-
123
-	/**
124
-	 * test updatePrivateKeyPassword() if wrong old password was entered
125
-	 */
126
-	public function testUpdatePrivateKeyPasswordWrongOldPassword(): void {
127
-		$oldPassword = 'old';
128
-		$newPassword = 'new';
129
-
130
-		$this->userManagerMock
131
-			->expects($this->once())
132
-			->method('checkPassword')
133
-			->willReturn(true);
134
-
135
-		$this->cryptMock
136
-			->expects($this->once())
137
-			->method('decryptPrivateKey')
138
-			->willReturn(false);
139
-
140
-		$result = $this->controller->updatePrivateKeyPassword($oldPassword, $newPassword);
141
-
142
-		$data = $result->getData();
143
-
144
-		$this->assertSame(Http::STATUS_BAD_REQUEST, $result->getStatus());
145
-		$this->assertSame('The old password was not correct, please try again.',
146
-			$data['message']);
147
-	}
148
-
149
-	/**
150
-	 * test updatePrivateKeyPassword() with the correct old and new password
151
-	 */
152
-	public function testUpdatePrivateKeyPassword(): void {
153
-		$oldPassword = 'old';
154
-		$newPassword = 'new';
155
-
156
-		$this->ocSessionMock->expects($this->once())
157
-			->method('get')
158
-			->with('loginname')
159
-			->willReturn('testUser');
160
-
161
-		$this->userManagerMock
162
-			->expects($this->exactly(2))
163
-			->method('checkPassword')
164
-			->willReturnMap([
165
-				['testUserUid', 'new', false],
166
-				['testUser', 'new', true],
167
-			]);
168
-
169
-		$this->cryptMock
170
-			->expects($this->once())
171
-			->method('decryptPrivateKey')
172
-			->willReturn('decryptedKey');
173
-
174
-		$this->cryptMock
175
-			->expects($this->once())
176
-			->method('encryptPrivateKey')
177
-			->willReturn('encryptedKey');
178
-
179
-		$this->cryptMock
180
-			->expects($this->once())
181
-			->method('generateHeader')
182
-			->willReturn('header.');
183
-
184
-		// methods which must be called after successful changing the key password
185
-		$this->keyManagerMock
186
-			->expects($this->once())
187
-			->method('setPrivateKey')
188
-			->with($this->equalTo('testUserUid'), $this->equalTo('header.encryptedKey'));
189
-
190
-		$this->sessionMock
191
-			->expects($this->once())
192
-			->method('setPrivateKey')
193
-			->with($this->equalTo('decryptedKey'));
194
-
195
-		$this->sessionMock
196
-			->expects($this->once())
197
-			->method('setStatus')
198
-			->with($this->equalTo(Session::INIT_SUCCESSFUL));
199
-
200
-		$result = $this->controller->updatePrivateKeyPassword($oldPassword, $newPassword);
201
-
202
-		$data = $result->getData();
203
-
204
-		$this->assertSame(Http::STATUS_OK, $result->getStatus());
205
-		$this->assertSame('Private key password successfully updated.',
206
-			$data['message']);
207
-	}
208
-
209
-	public function testSetEncryptHomeStorage(): void {
210
-		$value = true;
211
-		$this->utilMock->expects($this->once())->method('setEncryptHomeStorage')->with($value);
212
-		$this->controller->setEncryptHomeStorage($value);
213
-	}
29
+    protected SettingsController $controller;
30
+
31
+    protected IRequest&MockObject $requestMock;
32
+    protected IL10N&MockObject $l10nMock;
33
+    protected IUserManager&MockObject $userManagerMock;
34
+    protected IUserSession&MockObject $userSessionMock;
35
+    protected KeyManager&MockObject $keyManagerMock;
36
+    protected Crypt&MockObject $cryptMock;
37
+    protected Session&MockObject $sessionMock;
38
+    protected IUser&MockObject $user;
39
+    protected ISession&MockObject $ocSessionMock;
40
+    protected Util&MockObject $utilMock;
41
+
42
+    protected function setUp(): void {
43
+        parent::setUp();
44
+
45
+        $this->requestMock = $this->createMock(IRequest::class);
46
+
47
+        $this->l10nMock = $this->getMockBuilder(IL10N::class)
48
+            ->disableOriginalConstructor()->getMock();
49
+
50
+        $this->l10nMock->expects($this->any())
51
+            ->method('t')
52
+            ->willReturnCallback(function ($message) {
53
+                return $message;
54
+            });
55
+
56
+        $this->userManagerMock = $this->getMockBuilder(IUserManager::class)
57
+            ->disableOriginalConstructor()->getMock();
58
+
59
+        $this->keyManagerMock = $this->getMockBuilder(KeyManager::class)
60
+            ->disableOriginalConstructor()->getMock();
61
+
62
+        $this->cryptMock = $this->getMockBuilder(Crypt::class)
63
+            ->disableOriginalConstructor()->getMock();
64
+
65
+        $this->ocSessionMock = $this->getMockBuilder(ISession::class)->disableOriginalConstructor()->getMock();
66
+
67
+        $this->user = $this->createMock(IUser::class);
68
+        $this->user->expects($this->any())
69
+            ->method('getUID')
70
+            ->willReturn('testUserUid');
71
+
72
+        $this->userSessionMock = $this->createMock(IUserSession::class);
73
+        $this->userSessionMock->expects($this->any())
74
+            ->method('getUser')
75
+            ->willReturn($this->user);
76
+
77
+        $this->sessionMock = $this->getMockBuilder(Session::class)
78
+            ->disableOriginalConstructor()->getMock();
79
+
80
+        $this->utilMock = $this->getMockBuilder(Util::class)
81
+            ->disableOriginalConstructor()
82
+            ->getMock();
83
+
84
+        $this->controller = new SettingsController(
85
+            'encryption',
86
+            $this->requestMock,
87
+            $this->l10nMock,
88
+            $this->userManagerMock,
89
+            $this->userSessionMock,
90
+            $this->keyManagerMock,
91
+            $this->cryptMock,
92
+            $this->sessionMock,
93
+            $this->ocSessionMock,
94
+            $this->utilMock
95
+        );
96
+    }
97
+
98
+    /**
99
+     * test updatePrivateKeyPassword() if wrong new password was entered
100
+     */
101
+    public function testUpdatePrivateKeyPasswordWrongNewPassword(): void {
102
+        $oldPassword = 'old';
103
+        $newPassword = 'new';
104
+
105
+        $this->user->expects($this->any())
106
+            ->method('getUID')
107
+            ->willReturn('uid');
108
+
109
+        $this->userManagerMock
110
+            ->expects($this->exactly(2))
111
+            ->method('checkPassword')
112
+            ->willReturn(false);
113
+
114
+        $result = $this->controller->updatePrivateKeyPassword($oldPassword, $newPassword);
115
+
116
+        $data = $result->getData();
117
+
118
+        $this->assertSame(Http::STATUS_BAD_REQUEST, $result->getStatus());
119
+        $this->assertSame('The current log-in password was not correct, please try again.',
120
+            $data['message']);
121
+    }
122
+
123
+    /**
124
+     * test updatePrivateKeyPassword() if wrong old password was entered
125
+     */
126
+    public function testUpdatePrivateKeyPasswordWrongOldPassword(): void {
127
+        $oldPassword = 'old';
128
+        $newPassword = 'new';
129
+
130
+        $this->userManagerMock
131
+            ->expects($this->once())
132
+            ->method('checkPassword')
133
+            ->willReturn(true);
134
+
135
+        $this->cryptMock
136
+            ->expects($this->once())
137
+            ->method('decryptPrivateKey')
138
+            ->willReturn(false);
139
+
140
+        $result = $this->controller->updatePrivateKeyPassword($oldPassword, $newPassword);
141
+
142
+        $data = $result->getData();
143
+
144
+        $this->assertSame(Http::STATUS_BAD_REQUEST, $result->getStatus());
145
+        $this->assertSame('The old password was not correct, please try again.',
146
+            $data['message']);
147
+    }
148
+
149
+    /**
150
+     * test updatePrivateKeyPassword() with the correct old and new password
151
+     */
152
+    public function testUpdatePrivateKeyPassword(): void {
153
+        $oldPassword = 'old';
154
+        $newPassword = 'new';
155
+
156
+        $this->ocSessionMock->expects($this->once())
157
+            ->method('get')
158
+            ->with('loginname')
159
+            ->willReturn('testUser');
160
+
161
+        $this->userManagerMock
162
+            ->expects($this->exactly(2))
163
+            ->method('checkPassword')
164
+            ->willReturnMap([
165
+                ['testUserUid', 'new', false],
166
+                ['testUser', 'new', true],
167
+            ]);
168
+
169
+        $this->cryptMock
170
+            ->expects($this->once())
171
+            ->method('decryptPrivateKey')
172
+            ->willReturn('decryptedKey');
173
+
174
+        $this->cryptMock
175
+            ->expects($this->once())
176
+            ->method('encryptPrivateKey')
177
+            ->willReturn('encryptedKey');
178
+
179
+        $this->cryptMock
180
+            ->expects($this->once())
181
+            ->method('generateHeader')
182
+            ->willReturn('header.');
183
+
184
+        // methods which must be called after successful changing the key password
185
+        $this->keyManagerMock
186
+            ->expects($this->once())
187
+            ->method('setPrivateKey')
188
+            ->with($this->equalTo('testUserUid'), $this->equalTo('header.encryptedKey'));
189
+
190
+        $this->sessionMock
191
+            ->expects($this->once())
192
+            ->method('setPrivateKey')
193
+            ->with($this->equalTo('decryptedKey'));
194
+
195
+        $this->sessionMock
196
+            ->expects($this->once())
197
+            ->method('setStatus')
198
+            ->with($this->equalTo(Session::INIT_SUCCESSFUL));
199
+
200
+        $result = $this->controller->updatePrivateKeyPassword($oldPassword, $newPassword);
201
+
202
+        $data = $result->getData();
203
+
204
+        $this->assertSame(Http::STATUS_OK, $result->getStatus());
205
+        $this->assertSame('Private key password successfully updated.',
206
+            $data['message']);
207
+    }
208
+
209
+    public function testSetEncryptHomeStorage(): void {
210
+        $value = true;
211
+        $this->utilMock->expects($this->once())->method('setEncryptHomeStorage')->with($value);
212
+        $this->controller->setEncryptHomeStorage($value);
213
+    }
214 214
 }
Please login to merge, or discard this patch.
apps/encryption/tests/Controller/StatusControllerTest.php 1 patch
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -19,56 +19,56 @@
 block discarded – undo
19 19
 
20 20
 class StatusControllerTest extends TestCase {
21 21
 
22
-	protected IRequest&MockObject $requestMock;
23
-	protected IL10N&MockObject $l10nMock;
24
-	protected Session&MockObject $sessionMock;
25
-	protected IManager&MockObject $encryptionManagerMock;
22
+    protected IRequest&MockObject $requestMock;
23
+    protected IL10N&MockObject $l10nMock;
24
+    protected Session&MockObject $sessionMock;
25
+    protected IManager&MockObject $encryptionManagerMock;
26 26
 
27
-	protected StatusController $controller;
27
+    protected StatusController $controller;
28 28
 
29
-	protected function setUp(): void {
30
-		parent::setUp();
29
+    protected function setUp(): void {
30
+        parent::setUp();
31 31
 
32
-		$this->sessionMock = $this->getMockBuilder(Session::class)
33
-			->disableOriginalConstructor()->getMock();
34
-		$this->requestMock = $this->createMock(IRequest::class);
32
+        $this->sessionMock = $this->getMockBuilder(Session::class)
33
+            ->disableOriginalConstructor()->getMock();
34
+        $this->requestMock = $this->createMock(IRequest::class);
35 35
 
36
-		$this->l10nMock = $this->getMockBuilder(IL10N::class)
37
-			->disableOriginalConstructor()->getMock();
38
-		$this->l10nMock->expects($this->any())
39
-			->method('t')
40
-			->willReturnCallback(function ($message) {
41
-				return $message;
42
-			});
43
-		$this->encryptionManagerMock = $this->createMock(IManager::class);
36
+        $this->l10nMock = $this->getMockBuilder(IL10N::class)
37
+            ->disableOriginalConstructor()->getMock();
38
+        $this->l10nMock->expects($this->any())
39
+            ->method('t')
40
+            ->willReturnCallback(function ($message) {
41
+                return $message;
42
+            });
43
+        $this->encryptionManagerMock = $this->createMock(IManager::class);
44 44
 
45
-		$this->controller = new StatusController('encryptionTest',
46
-			$this->requestMock,
47
-			$this->l10nMock,
48
-			$this->sessionMock,
49
-			$this->encryptionManagerMock);
50
-	}
45
+        $this->controller = new StatusController('encryptionTest',
46
+            $this->requestMock,
47
+            $this->l10nMock,
48
+            $this->sessionMock,
49
+            $this->encryptionManagerMock);
50
+    }
51 51
 
52
-	/**
53
-	 * @dataProvider dataTestGetStatus
54
-	 *
55
-	 * @param string $status
56
-	 * @param string $expectedStatus
57
-	 */
58
-	public function testGetStatus($status, $expectedStatus): void {
59
-		$this->sessionMock->expects($this->once())
60
-			->method('getStatus')->willReturn($status);
61
-		$result = $this->controller->getStatus();
62
-		$data = $result->getData();
63
-		$this->assertSame($expectedStatus, $data['status']);
64
-	}
52
+    /**
53
+     * @dataProvider dataTestGetStatus
54
+     *
55
+     * @param string $status
56
+     * @param string $expectedStatus
57
+     */
58
+    public function testGetStatus($status, $expectedStatus): void {
59
+        $this->sessionMock->expects($this->once())
60
+            ->method('getStatus')->willReturn($status);
61
+        $result = $this->controller->getStatus();
62
+        $data = $result->getData();
63
+        $this->assertSame($expectedStatus, $data['status']);
64
+    }
65 65
 
66
-	public static function dataTestGetStatus(): array {
67
-		return [
68
-			[Session::INIT_EXECUTED, 'interactionNeeded'],
69
-			[Session::INIT_SUCCESSFUL, 'success'],
70
-			[Session::NOT_INITIALIZED, 'interactionNeeded'],
71
-			['unknown', 'error'],
72
-		];
73
-	}
66
+    public static function dataTestGetStatus(): array {
67
+        return [
68
+            [Session::INIT_EXECUTED, 'interactionNeeded'],
69
+            [Session::INIT_SUCCESSFUL, 'success'],
70
+            [Session::NOT_INITIALIZED, 'interactionNeeded'],
71
+            ['unknown', 'error'],
72
+        ];
73
+    }
74 74
 }
Please login to merge, or discard this patch.
apps/encryption/tests/Controller/RecoveryControllerTest.php 1 patch
Indentation   +137 added lines, -137 removed lines patch added patch discarded remove patch
@@ -19,141 +19,141 @@
 block discarded – undo
19 19
 use Test\TestCase;
20 20
 
21 21
 class RecoveryControllerTest extends TestCase {
22
-	protected RecoveryController $controller;
23
-
24
-	protected IRequest&MockObject $requestMock;
25
-	protected IConfig&MockObject $configMock;
26
-	protected IL10N&MockObject $l10nMock;
27
-	protected Recovery&MockObject $recoveryMock;
28
-
29
-	public static function adminRecoveryProvider(): array {
30
-		return [
31
-			['test', 'test', '1', 'Recovery key successfully enabled', Http::STATUS_OK],
32
-			['', 'test', '1', 'Missing recovery key password', Http::STATUS_BAD_REQUEST],
33
-			['test', '', '1', 'Please repeat the recovery key password', Http::STATUS_BAD_REQUEST],
34
-			['test', 'something that doesn\'t match', '1', 'Repeated recovery key password does not match the provided recovery key password', Http::STATUS_BAD_REQUEST],
35
-			['test', 'test', '0', 'Recovery key successfully disabled', Http::STATUS_OK],
36
-		];
37
-	}
38
-
39
-	/**
40
-	 * @dataProvider adminRecoveryProvider
41
-	 * @param $recoveryPassword
42
-	 * @param $passConfirm
43
-	 * @param $enableRecovery
44
-	 * @param $expectedMessage
45
-	 * @param $expectedStatus
46
-	 */
47
-	public function testAdminRecovery($recoveryPassword, $passConfirm, $enableRecovery, $expectedMessage, $expectedStatus): void {
48
-		$this->recoveryMock->expects($this->any())
49
-			->method('enableAdminRecovery')
50
-			->willReturn(true);
51
-
52
-		$this->recoveryMock->expects($this->any())
53
-			->method('disableAdminRecovery')
54
-			->willReturn(true);
55
-
56
-		$response = $this->controller->adminRecovery($recoveryPassword,
57
-			$passConfirm,
58
-			$enableRecovery);
59
-
60
-
61
-		$this->assertEquals($expectedMessage, $response->getData()['data']['message']);
62
-		$this->assertEquals($expectedStatus, $response->getStatus());
63
-	}
64
-
65
-	public static function changeRecoveryPasswordProvider(): array {
66
-		return [
67
-			['test', 'test', 'oldtestFail', 'Could not change the password. Maybe the old password was not correct.', Http::STATUS_BAD_REQUEST],
68
-			['test', 'test', 'oldtest', 'Password successfully changed.', Http::STATUS_OK],
69
-			['test', 'notmatch', 'oldtest', 'Repeated recovery key password does not match the provided recovery key password', Http::STATUS_BAD_REQUEST],
70
-			['', 'test', 'oldtest', 'Please provide a new recovery password', Http::STATUS_BAD_REQUEST],
71
-			['test', 'test', '', 'Please provide the old recovery password', Http::STATUS_BAD_REQUEST]
72
-		];
73
-	}
74
-
75
-	/**
76
-	 * @dataProvider changeRecoveryPasswordProvider
77
-	 * @param $password
78
-	 * @param $confirmPassword
79
-	 * @param $oldPassword
80
-	 * @param $expectedMessage
81
-	 * @param $expectedStatus
82
-	 */
83
-	public function testChangeRecoveryPassword($password, $confirmPassword, $oldPassword, $expectedMessage, $expectedStatus): void {
84
-		$this->recoveryMock->expects($this->any())
85
-			->method('changeRecoveryKeyPassword')
86
-			->with($password, $oldPassword)
87
-			->willReturnMap([
88
-				['test', 'oldTestFail', false],
89
-				['test', 'oldtest', true]
90
-			]);
91
-
92
-		$response = $this->controller->changeRecoveryPassword($password,
93
-			$oldPassword,
94
-			$confirmPassword);
95
-
96
-		$this->assertEquals($expectedMessage, $response->getData()['data']['message']);
97
-		$this->assertEquals($expectedStatus, $response->getStatus());
98
-	}
99
-
100
-	public static function userSetRecoveryProvider(): array {
101
-		return [
102
-			['1', 'Recovery Key enabled', Http::STATUS_OK],
103
-			['0', 'Could not enable the recovery key, please try again or contact your administrator', Http::STATUS_BAD_REQUEST]
104
-		];
105
-	}
106
-
107
-	/**
108
-	 * @dataProvider userSetRecoveryProvider
109
-	 * @param $enableRecovery
110
-	 * @param $expectedMessage
111
-	 * @param $expectedStatus
112
-	 */
113
-	public function testUserSetRecovery($enableRecovery, $expectedMessage, $expectedStatus): void {
114
-		$this->recoveryMock->expects($this->any())
115
-			->method('setRecoveryForUser')
116
-			->with($enableRecovery)
117
-			->willReturnMap([
118
-				['1', true],
119
-				['0', false]
120
-			]);
121
-
122
-
123
-		$response = $this->controller->userSetRecovery($enableRecovery);
124
-
125
-		$this->assertEquals($expectedMessage, $response->getData()['data']['message']);
126
-		$this->assertEquals($expectedStatus, $response->getStatus());
127
-	}
128
-
129
-	protected function setUp(): void {
130
-		parent::setUp();
131
-
132
-		$this->requestMock = $this->getMockBuilder(IRequest::class)
133
-			->disableOriginalConstructor()
134
-			->getMock();
135
-
136
-		$this->configMock = $this->getMockBuilder(IConfig::class)
137
-			->disableOriginalConstructor()
138
-			->getMock();
139
-
140
-		$this->l10nMock = $this->getMockBuilder(IL10N::class)
141
-			->disableOriginalConstructor()
142
-			->getMock();
143
-
144
-		// Make l10n work in our tests
145
-		$this->l10nMock->expects($this->any())
146
-			->method('t')
147
-			->willReturnArgument(0);
148
-
149
-		$this->recoveryMock = $this->getMockBuilder(Recovery::class)
150
-			->disableOriginalConstructor()
151
-			->getMock();
152
-
153
-		$this->controller = new RecoveryController('encryption',
154
-			$this->requestMock,
155
-			$this->configMock,
156
-			$this->l10nMock,
157
-			$this->recoveryMock);
158
-	}
22
+    protected RecoveryController $controller;
23
+
24
+    protected IRequest&MockObject $requestMock;
25
+    protected IConfig&MockObject $configMock;
26
+    protected IL10N&MockObject $l10nMock;
27
+    protected Recovery&MockObject $recoveryMock;
28
+
29
+    public static function adminRecoveryProvider(): array {
30
+        return [
31
+            ['test', 'test', '1', 'Recovery key successfully enabled', Http::STATUS_OK],
32
+            ['', 'test', '1', 'Missing recovery key password', Http::STATUS_BAD_REQUEST],
33
+            ['test', '', '1', 'Please repeat the recovery key password', Http::STATUS_BAD_REQUEST],
34
+            ['test', 'something that doesn\'t match', '1', 'Repeated recovery key password does not match the provided recovery key password', Http::STATUS_BAD_REQUEST],
35
+            ['test', 'test', '0', 'Recovery key successfully disabled', Http::STATUS_OK],
36
+        ];
37
+    }
38
+
39
+    /**
40
+     * @dataProvider adminRecoveryProvider
41
+     * @param $recoveryPassword
42
+     * @param $passConfirm
43
+     * @param $enableRecovery
44
+     * @param $expectedMessage
45
+     * @param $expectedStatus
46
+     */
47
+    public function testAdminRecovery($recoveryPassword, $passConfirm, $enableRecovery, $expectedMessage, $expectedStatus): void {
48
+        $this->recoveryMock->expects($this->any())
49
+            ->method('enableAdminRecovery')
50
+            ->willReturn(true);
51
+
52
+        $this->recoveryMock->expects($this->any())
53
+            ->method('disableAdminRecovery')
54
+            ->willReturn(true);
55
+
56
+        $response = $this->controller->adminRecovery($recoveryPassword,
57
+            $passConfirm,
58
+            $enableRecovery);
59
+
60
+
61
+        $this->assertEquals($expectedMessage, $response->getData()['data']['message']);
62
+        $this->assertEquals($expectedStatus, $response->getStatus());
63
+    }
64
+
65
+    public static function changeRecoveryPasswordProvider(): array {
66
+        return [
67
+            ['test', 'test', 'oldtestFail', 'Could not change the password. Maybe the old password was not correct.', Http::STATUS_BAD_REQUEST],
68
+            ['test', 'test', 'oldtest', 'Password successfully changed.', Http::STATUS_OK],
69
+            ['test', 'notmatch', 'oldtest', 'Repeated recovery key password does not match the provided recovery key password', Http::STATUS_BAD_REQUEST],
70
+            ['', 'test', 'oldtest', 'Please provide a new recovery password', Http::STATUS_BAD_REQUEST],
71
+            ['test', 'test', '', 'Please provide the old recovery password', Http::STATUS_BAD_REQUEST]
72
+        ];
73
+    }
74
+
75
+    /**
76
+     * @dataProvider changeRecoveryPasswordProvider
77
+     * @param $password
78
+     * @param $confirmPassword
79
+     * @param $oldPassword
80
+     * @param $expectedMessage
81
+     * @param $expectedStatus
82
+     */
83
+    public function testChangeRecoveryPassword($password, $confirmPassword, $oldPassword, $expectedMessage, $expectedStatus): void {
84
+        $this->recoveryMock->expects($this->any())
85
+            ->method('changeRecoveryKeyPassword')
86
+            ->with($password, $oldPassword)
87
+            ->willReturnMap([
88
+                ['test', 'oldTestFail', false],
89
+                ['test', 'oldtest', true]
90
+            ]);
91
+
92
+        $response = $this->controller->changeRecoveryPassword($password,
93
+            $oldPassword,
94
+            $confirmPassword);
95
+
96
+        $this->assertEquals($expectedMessage, $response->getData()['data']['message']);
97
+        $this->assertEquals($expectedStatus, $response->getStatus());
98
+    }
99
+
100
+    public static function userSetRecoveryProvider(): array {
101
+        return [
102
+            ['1', 'Recovery Key enabled', Http::STATUS_OK],
103
+            ['0', 'Could not enable the recovery key, please try again or contact your administrator', Http::STATUS_BAD_REQUEST]
104
+        ];
105
+    }
106
+
107
+    /**
108
+     * @dataProvider userSetRecoveryProvider
109
+     * @param $enableRecovery
110
+     * @param $expectedMessage
111
+     * @param $expectedStatus
112
+     */
113
+    public function testUserSetRecovery($enableRecovery, $expectedMessage, $expectedStatus): void {
114
+        $this->recoveryMock->expects($this->any())
115
+            ->method('setRecoveryForUser')
116
+            ->with($enableRecovery)
117
+            ->willReturnMap([
118
+                ['1', true],
119
+                ['0', false]
120
+            ]);
121
+
122
+
123
+        $response = $this->controller->userSetRecovery($enableRecovery);
124
+
125
+        $this->assertEquals($expectedMessage, $response->getData()['data']['message']);
126
+        $this->assertEquals($expectedStatus, $response->getStatus());
127
+    }
128
+
129
+    protected function setUp(): void {
130
+        parent::setUp();
131
+
132
+        $this->requestMock = $this->getMockBuilder(IRequest::class)
133
+            ->disableOriginalConstructor()
134
+            ->getMock();
135
+
136
+        $this->configMock = $this->getMockBuilder(IConfig::class)
137
+            ->disableOriginalConstructor()
138
+            ->getMock();
139
+
140
+        $this->l10nMock = $this->getMockBuilder(IL10N::class)
141
+            ->disableOriginalConstructor()
142
+            ->getMock();
143
+
144
+        // Make l10n work in our tests
145
+        $this->l10nMock->expects($this->any())
146
+            ->method('t')
147
+            ->willReturnArgument(0);
148
+
149
+        $this->recoveryMock = $this->getMockBuilder(Recovery::class)
150
+            ->disableOriginalConstructor()
151
+            ->getMock();
152
+
153
+        $this->controller = new RecoveryController('encryption',
154
+            $this->requestMock,
155
+            $this->configMock,
156
+            $this->l10nMock,
157
+            $this->recoveryMock);
158
+    }
159 159
 }
Please login to merge, or discard this patch.
apps/encryption/tests/Crypto/EncryptionTest.php 1 patch
Indentation   +379 added lines, -379 removed lines patch added patch discarded remove patch
@@ -29,383 +29,383 @@
 block discarded – undo
29 29
 
30 30
 class EncryptionTest extends TestCase {
31 31
 
32
-	protected Encryption $instance;
33
-
34
-	protected KeyManager&MockObject $keyManagerMock;
35
-	protected EncryptAll&MockObject $encryptAllMock;
36
-	protected DecryptAll&MockObject $decryptAllMock;
37
-	protected Session&MockObject $sessionMock;
38
-	protected Crypt&MockObject $cryptMock;
39
-	protected Util&MockObject $utilMock;
40
-	protected LoggerInterface&MockObject $loggerMock;
41
-	protected IL10N&MockObject $l10nMock;
42
-	protected IStorage&MockObject $storageMock;
43
-
44
-	protected function setUp(): void {
45
-		parent::setUp();
46
-
47
-		$this->storageMock = $this->getMockBuilder(IStorage::class)
48
-			->disableOriginalConstructor()->getMock();
49
-		$this->cryptMock = $this->getMockBuilder(Crypt::class)
50
-			->disableOriginalConstructor()
51
-			->getMock();
52
-		$this->utilMock = $this->getMockBuilder(Util::class)
53
-			->disableOriginalConstructor()
54
-			->getMock();
55
-		$this->keyManagerMock = $this->getMockBuilder(KeyManager::class)
56
-			->disableOriginalConstructor()
57
-			->getMock();
58
-		$this->sessionMock = $this->getMockBuilder(Session::class)
59
-			->disableOriginalConstructor()
60
-			->getMock();
61
-		$this->encryptAllMock = $this->getMockBuilder(EncryptAll::class)
62
-			->disableOriginalConstructor()
63
-			->getMock();
64
-		$this->decryptAllMock = $this->getMockBuilder(DecryptAll::class)
65
-			->disableOriginalConstructor()
66
-			->getMock();
67
-		$this->loggerMock = $this->getMockBuilder(LoggerInterface::class)
68
-			->disableOriginalConstructor()
69
-			->getMock();
70
-		$this->l10nMock = $this->getMockBuilder(IL10N::class)
71
-			->disableOriginalConstructor()
72
-			->getMock();
73
-		$this->l10nMock->expects($this->any())
74
-			->method('t')
75
-			->with($this->anything())
76
-			->willReturnArgument(0);
77
-
78
-		$this->instance = new Encryption(
79
-			$this->cryptMock,
80
-			$this->keyManagerMock,
81
-			$this->utilMock,
82
-			$this->sessionMock,
83
-			$this->encryptAllMock,
84
-			$this->decryptAllMock,
85
-			$this->loggerMock,
86
-			$this->l10nMock
87
-		);
88
-	}
89
-
90
-	/**
91
-	 * test if public key from one of the recipients is missing
92
-	 */
93
-	public function testEndUser1(): void {
94
-		$this->sessionMock->expects($this->once())
95
-			->method('decryptAllModeActivated')
96
-			->willReturn(false);
97
-
98
-		$this->instance->begin('/foo/bar', 'user1', 'r', [], ['users' => ['user1', 'user2', 'user3']]);
99
-		$this->endTest();
100
-	}
101
-
102
-	/**
103
-	 * test if public key from owner is missing
104
-	 *
105
-	 */
106
-	public function testEndUser2(): void {
107
-		$this->sessionMock->expects($this->once())
108
-			->method('decryptAllModeActivated')
109
-			->willReturn(false);
110
-
111
-		$this->expectException(PublicKeyMissingException::class);
112
-
113
-		$this->instance->begin('/foo/bar', 'user2', 'r', [], ['users' => ['user1', 'user2', 'user3']]);
114
-		$this->endTest();
115
-	}
116
-
117
-	/**
118
-	 * common part of testEndUser1 and testEndUser2
119
-	 *
120
-	 * @throws PublicKeyMissingException
121
-	 */
122
-	public function endTest() {
123
-		// prepare internal variables
124
-		self::invokePrivate($this->instance, 'isWriteOperation', [true]);
125
-		self::invokePrivate($this->instance, 'writeCache', ['']);
126
-
127
-		$this->keyManagerMock->expects($this->any())
128
-			->method('getPublicKey')
129
-			->willReturnCallback([$this, 'getPublicKeyCallback']);
130
-		$this->keyManagerMock->expects($this->any())
131
-			->method('addSystemKeys')
132
-			->willReturnCallback([$this, 'addSystemKeysCallback']);
133
-		$this->cryptMock->expects($this->any())
134
-			->method('multiKeyEncrypt')
135
-			->willReturn([]);
136
-
137
-		$this->instance->end('/foo/bar');
138
-	}
139
-
140
-
141
-	public function getPublicKeyCallback($uid) {
142
-		if ($uid === 'user2') {
143
-			throw new PublicKeyMissingException($uid);
144
-		}
145
-		return $uid;
146
-	}
147
-
148
-	public function addSystemKeysCallback($accessList, $publicKeys) {
149
-		$this->assertSame(2, count($publicKeys));
150
-		$this->assertArrayHasKey('user1', $publicKeys);
151
-		$this->assertArrayHasKey('user3', $publicKeys);
152
-		return $publicKeys;
153
-	}
154
-
155
-	/**
156
-	 * @dataProvider dataProviderForTestGetPathToRealFile
157
-	 */
158
-	public function testGetPathToRealFile($path, $expected): void {
159
-		$this->assertSame($expected,
160
-			self::invokePrivate($this->instance, 'getPathToRealFile', [$path])
161
-		);
162
-	}
163
-
164
-	public static function dataProviderForTestGetPathToRealFile(): array {
165
-		return [
166
-			['/user/files/foo/bar.txt', '/user/files/foo/bar.txt'],
167
-			['/user/files/foo.txt', '/user/files/foo.txt'],
168
-			['/user/files_versions/foo.txt.v543534', '/user/files/foo.txt'],
169
-			['/user/files_versions/foo/bar.txt.v5454', '/user/files/foo/bar.txt'],
170
-		];
171
-	}
172
-
173
-	/**
174
-	 * @dataProvider dataTestBegin
175
-	 */
176
-	public function testBegin($mode, $header, $legacyCipher, $defaultCipher, $fileKey, $expected): void {
177
-		$this->sessionMock->expects($this->once())
178
-			->method('decryptAllModeActivated')
179
-			->willReturn(false);
180
-
181
-		$this->sessionMock->expects($this->never())->method('getDecryptAllUid');
182
-		$this->sessionMock->expects($this->never())->method('getDecryptAllKey');
183
-		$this->keyManagerMock->expects($this->never())->method('getEncryptedFileKey');
184
-		$this->keyManagerMock->expects($this->never())->method('getShareKey');
185
-		$this->cryptMock->expects($this->never())->method('multiKeyDecrypt');
186
-
187
-		$this->cryptMock->expects($this->any())
188
-			->method('getCipher')
189
-			->willReturn($defaultCipher);
190
-		$this->cryptMock->expects($this->any())
191
-			->method('getLegacyCipher')
192
-			->willReturn($legacyCipher);
193
-		if (empty($fileKey)) {
194
-			$this->cryptMock->expects($this->once())
195
-				->method('generateFileKey')
196
-				->willReturn('fileKey');
197
-		} else {
198
-			$this->cryptMock->expects($this->never())
199
-				->method('generateFileKey');
200
-		}
201
-
202
-		$this->keyManagerMock->expects($this->once())
203
-			->method('getFileKey')
204
-			->willReturn($fileKey);
205
-
206
-		$result = $this->instance->begin('/user/files/foo.txt', 'user', $mode, $header, []);
207
-
208
-		$this->assertArrayHasKey('cipher', $result);
209
-		$this->assertSame($expected, $result['cipher']);
210
-		if ($mode === 'w') {
211
-			$this->assertTrue(self::invokePrivate($this->instance, 'isWriteOperation'));
212
-		} else {
213
-			$this->assertFalse(self::invokePrivate($this->instance, 'isWriteOperation'));
214
-		}
215
-	}
216
-
217
-	public static function dataTestBegin(): array {
218
-		return [
219
-			['w', ['cipher' => 'myCipher'], 'legacyCipher', 'defaultCipher', 'fileKey', 'defaultCipher'],
220
-			['r', ['cipher' => 'myCipher'], 'legacyCipher', 'defaultCipher', 'fileKey', 'myCipher'],
221
-			['w', [], 'legacyCipher', 'defaultCipher', '', 'defaultCipher'],
222
-			['r', [], 'legacyCipher', 'defaultCipher', 'file_key', 'legacyCipher'],
223
-		];
224
-	}
225
-
226
-
227
-	/**
228
-	 * test begin() if decryptAll mode was activated
229
-	 */
230
-	public function testBeginDecryptAll(): void {
231
-		$path = '/user/files/foo.txt';
232
-		$fileKey = 'fileKey';
233
-
234
-		$this->sessionMock->expects($this->once())
235
-			->method('decryptAllModeActivated')
236
-			->willReturn(true);
237
-		$this->keyManagerMock->expects($this->once())
238
-			->method('getFileKey')
239
-			->with($path, 'user', null, true)
240
-			->willReturn($fileKey);
241
-
242
-		$this->instance->begin($path, 'user', 'r', [], []);
243
-
244
-		$this->assertSame($fileKey,
245
-			$this->invokePrivate($this->instance, 'fileKey')
246
-		);
247
-	}
248
-
249
-	/**
250
-	 * test begin() if encryption is not initialized but the master key is enabled
251
-	 * in this case we can initialize the encryption without a username/password
252
-	 * and continue
253
-	 */
254
-	public function testBeginInitMasterKey(): void {
255
-		$this->sessionMock->expects($this->once())
256
-			->method('decryptAllModeActivated')
257
-			->willReturn(false);
258
-
259
-		$this->sessionMock->expects($this->once())->method('isReady')->willReturn(false);
260
-		$this->utilMock->expects($this->once())->method('isMasterKeyEnabled')
261
-			->willReturn(true);
262
-		$this->keyManagerMock->expects($this->once())->method('init')->with('', '');
263
-
264
-		$this->instance->begin('/user/files/welcome.txt', 'user', 'r', [], []);
265
-	}
266
-
267
-	/**
268
-	 * @dataProvider dataTestUpdate
269
-	 *
270
-	 * @param string $fileKey
271
-	 * @param boolean $expected
272
-	 */
273
-	public function testUpdate($fileKey, $expected): void {
274
-		$this->keyManagerMock->expects($this->once())
275
-			->method('getFileKey')->willReturn($fileKey);
276
-
277
-		$this->keyManagerMock->expects($this->any())
278
-			->method('getPublicKey')->willReturn('publicKey');
279
-
280
-		$this->keyManagerMock->expects($this->any())
281
-			->method('addSystemKeys')
282
-			->willReturnCallback(function ($accessList, $publicKeys) {
283
-				return $publicKeys;
284
-			});
285
-
286
-		$this->keyManagerMock->expects($this->never())->method('getVersion');
287
-		$this->keyManagerMock->expects($this->never())->method('setVersion');
288
-
289
-		$this->assertSame($expected,
290
-			$this->instance->update('path', 'user1', ['users' => ['user1']])
291
-		);
292
-	}
293
-
294
-	public static function dataTestUpdate(): array {
295
-		return [
296
-			['', false],
297
-			['fileKey', true]
298
-		];
299
-	}
300
-
301
-	public function testUpdateNoUsers(): void {
302
-		$this->invokePrivate($this->instance, 'rememberVersion', [['path' => 2]]);
303
-
304
-		$this->keyManagerMock->expects($this->never())->method('getFileKey');
305
-		$this->keyManagerMock->expects($this->never())->method('getPublicKey');
306
-		$this->keyManagerMock->expects($this->never())->method('addSystemKeys');
307
-		$this->keyManagerMock->expects($this->once())->method('setVersion')
308
-			->willReturnCallback(function ($path, $version, $view): void {
309
-				$this->assertSame('path', $path);
310
-				$this->assertSame(2, $version);
311
-				$this->assertTrue($view instanceof View);
312
-			});
313
-		$this->instance->update('path', 'user1', []);
314
-	}
315
-
316
-	/**
317
-	 * Test case if the public key is missing. Nextcloud should still encrypt
318
-	 * the file for the remaining users
319
-	 */
320
-	public function testUpdateMissingPublicKey(): void {
321
-		$this->keyManagerMock->expects($this->once())
322
-			->method('getFileKey')->willReturn('fileKey');
323
-
324
-		$this->keyManagerMock->expects($this->any())
325
-			->method('getPublicKey')->willReturnCallback(
326
-				function ($user): void {
327
-					throw new PublicKeyMissingException($user);
328
-				}
329
-			);
330
-
331
-		$this->keyManagerMock->expects($this->any())
332
-			->method('addSystemKeys')
333
-			->willReturnCallback(function ($accessList, $publicKeys) {
334
-				return $publicKeys;
335
-			});
336
-
337
-		$this->cryptMock->expects($this->once())->method('multiKeyEncrypt')
338
-			->willReturnCallback(
339
-				function ($fileKey, $publicKeys) {
340
-					$this->assertEmpty($publicKeys);
341
-					$this->assertSame('fileKey', $fileKey);
342
-					return [];
343
-				}
344
-			);
345
-
346
-		$this->keyManagerMock->expects($this->never())->method('getVersion');
347
-		$this->keyManagerMock->expects($this->never())->method('setVersion');
348
-
349
-		$this->assertTrue(
350
-			$this->instance->update('path', 'user1', ['users' => ['user1']])
351
-		);
352
-	}
353
-
354
-	/**
355
-	 * by default the encryption module should encrypt regular files, files in
356
-	 * files_versions and files in files_trashbin
357
-	 *
358
-	 * @dataProvider dataTestShouldEncrypt
359
-	 */
360
-	public function testShouldEncrypt($path, $shouldEncryptHomeStorage, $isHomeStorage, $expected): void {
361
-		$this->utilMock->expects($this->once())->method('shouldEncryptHomeStorage')
362
-			->willReturn($shouldEncryptHomeStorage);
363
-
364
-		if ($shouldEncryptHomeStorage === false) {
365
-			$this->storageMock->expects($this->once())->method('instanceOfStorage')
366
-				->with('\OCP\Files\IHomeStorage')->willReturn($isHomeStorage);
367
-			$this->utilMock->expects($this->once())->method('getStorage')->with($path)
368
-				->willReturn($this->storageMock);
369
-		}
370
-
371
-		$this->assertSame($expected,
372
-			$this->instance->shouldEncrypt($path)
373
-		);
374
-	}
375
-
376
-	public static function dataTestShouldEncrypt(): array {
377
-		return [
378
-			['/user1/files/foo.txt', true, true, true],
379
-			['/user1/files_versions/foo.txt', true, true, true],
380
-			['/user1/files_trashbin/foo.txt', true, true, true],
381
-			['/user1/some_folder/foo.txt', true, true, false],
382
-			['/user1/foo.txt', true, true, false],
383
-			['/user1/files', true, true, false],
384
-			['/user1/files_trashbin', true, true, false],
385
-			['/user1/files_versions', true, true, false],
386
-			// test if shouldEncryptHomeStorage is set to false
387
-			['/user1/files/foo.txt', false, true, false],
388
-			['/user1/files_versions/foo.txt', false, false, true],
389
-		];
390
-	}
391
-
392
-
393
-	public function testDecrypt(): void {
394
-		$this->expectException(DecryptionFailedException::class);
395
-		$this->expectExceptionMessage('Cannot decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
396
-
397
-		$this->instance->decrypt('abc');
398
-	}
399
-
400
-	public function testPrepareDecryptAll(): void {
401
-		/** @var \Symfony\Component\Console\Input\InputInterface $input */
402
-		$input = $this->createMock(InputInterface::class);
403
-		/** @var \Symfony\Component\Console\Output\OutputInterface $output */
404
-		$output = $this->createMock(OutputInterface::class);
405
-
406
-		$this->decryptAllMock->expects($this->once())->method('prepare')
407
-			->with($input, $output, 'user');
408
-
409
-		$this->instance->prepareDecryptAll($input, $output, 'user');
410
-	}
32
+    protected Encryption $instance;
33
+
34
+    protected KeyManager&MockObject $keyManagerMock;
35
+    protected EncryptAll&MockObject $encryptAllMock;
36
+    protected DecryptAll&MockObject $decryptAllMock;
37
+    protected Session&MockObject $sessionMock;
38
+    protected Crypt&MockObject $cryptMock;
39
+    protected Util&MockObject $utilMock;
40
+    protected LoggerInterface&MockObject $loggerMock;
41
+    protected IL10N&MockObject $l10nMock;
42
+    protected IStorage&MockObject $storageMock;
43
+
44
+    protected function setUp(): void {
45
+        parent::setUp();
46
+
47
+        $this->storageMock = $this->getMockBuilder(IStorage::class)
48
+            ->disableOriginalConstructor()->getMock();
49
+        $this->cryptMock = $this->getMockBuilder(Crypt::class)
50
+            ->disableOriginalConstructor()
51
+            ->getMock();
52
+        $this->utilMock = $this->getMockBuilder(Util::class)
53
+            ->disableOriginalConstructor()
54
+            ->getMock();
55
+        $this->keyManagerMock = $this->getMockBuilder(KeyManager::class)
56
+            ->disableOriginalConstructor()
57
+            ->getMock();
58
+        $this->sessionMock = $this->getMockBuilder(Session::class)
59
+            ->disableOriginalConstructor()
60
+            ->getMock();
61
+        $this->encryptAllMock = $this->getMockBuilder(EncryptAll::class)
62
+            ->disableOriginalConstructor()
63
+            ->getMock();
64
+        $this->decryptAllMock = $this->getMockBuilder(DecryptAll::class)
65
+            ->disableOriginalConstructor()
66
+            ->getMock();
67
+        $this->loggerMock = $this->getMockBuilder(LoggerInterface::class)
68
+            ->disableOriginalConstructor()
69
+            ->getMock();
70
+        $this->l10nMock = $this->getMockBuilder(IL10N::class)
71
+            ->disableOriginalConstructor()
72
+            ->getMock();
73
+        $this->l10nMock->expects($this->any())
74
+            ->method('t')
75
+            ->with($this->anything())
76
+            ->willReturnArgument(0);
77
+
78
+        $this->instance = new Encryption(
79
+            $this->cryptMock,
80
+            $this->keyManagerMock,
81
+            $this->utilMock,
82
+            $this->sessionMock,
83
+            $this->encryptAllMock,
84
+            $this->decryptAllMock,
85
+            $this->loggerMock,
86
+            $this->l10nMock
87
+        );
88
+    }
89
+
90
+    /**
91
+     * test if public key from one of the recipients is missing
92
+     */
93
+    public function testEndUser1(): void {
94
+        $this->sessionMock->expects($this->once())
95
+            ->method('decryptAllModeActivated')
96
+            ->willReturn(false);
97
+
98
+        $this->instance->begin('/foo/bar', 'user1', 'r', [], ['users' => ['user1', 'user2', 'user3']]);
99
+        $this->endTest();
100
+    }
101
+
102
+    /**
103
+     * test if public key from owner is missing
104
+     *
105
+     */
106
+    public function testEndUser2(): void {
107
+        $this->sessionMock->expects($this->once())
108
+            ->method('decryptAllModeActivated')
109
+            ->willReturn(false);
110
+
111
+        $this->expectException(PublicKeyMissingException::class);
112
+
113
+        $this->instance->begin('/foo/bar', 'user2', 'r', [], ['users' => ['user1', 'user2', 'user3']]);
114
+        $this->endTest();
115
+    }
116
+
117
+    /**
118
+     * common part of testEndUser1 and testEndUser2
119
+     *
120
+     * @throws PublicKeyMissingException
121
+     */
122
+    public function endTest() {
123
+        // prepare internal variables
124
+        self::invokePrivate($this->instance, 'isWriteOperation', [true]);
125
+        self::invokePrivate($this->instance, 'writeCache', ['']);
126
+
127
+        $this->keyManagerMock->expects($this->any())
128
+            ->method('getPublicKey')
129
+            ->willReturnCallback([$this, 'getPublicKeyCallback']);
130
+        $this->keyManagerMock->expects($this->any())
131
+            ->method('addSystemKeys')
132
+            ->willReturnCallback([$this, 'addSystemKeysCallback']);
133
+        $this->cryptMock->expects($this->any())
134
+            ->method('multiKeyEncrypt')
135
+            ->willReturn([]);
136
+
137
+        $this->instance->end('/foo/bar');
138
+    }
139
+
140
+
141
+    public function getPublicKeyCallback($uid) {
142
+        if ($uid === 'user2') {
143
+            throw new PublicKeyMissingException($uid);
144
+        }
145
+        return $uid;
146
+    }
147
+
148
+    public function addSystemKeysCallback($accessList, $publicKeys) {
149
+        $this->assertSame(2, count($publicKeys));
150
+        $this->assertArrayHasKey('user1', $publicKeys);
151
+        $this->assertArrayHasKey('user3', $publicKeys);
152
+        return $publicKeys;
153
+    }
154
+
155
+    /**
156
+     * @dataProvider dataProviderForTestGetPathToRealFile
157
+     */
158
+    public function testGetPathToRealFile($path, $expected): void {
159
+        $this->assertSame($expected,
160
+            self::invokePrivate($this->instance, 'getPathToRealFile', [$path])
161
+        );
162
+    }
163
+
164
+    public static function dataProviderForTestGetPathToRealFile(): array {
165
+        return [
166
+            ['/user/files/foo/bar.txt', '/user/files/foo/bar.txt'],
167
+            ['/user/files/foo.txt', '/user/files/foo.txt'],
168
+            ['/user/files_versions/foo.txt.v543534', '/user/files/foo.txt'],
169
+            ['/user/files_versions/foo/bar.txt.v5454', '/user/files/foo/bar.txt'],
170
+        ];
171
+    }
172
+
173
+    /**
174
+     * @dataProvider dataTestBegin
175
+     */
176
+    public function testBegin($mode, $header, $legacyCipher, $defaultCipher, $fileKey, $expected): void {
177
+        $this->sessionMock->expects($this->once())
178
+            ->method('decryptAllModeActivated')
179
+            ->willReturn(false);
180
+
181
+        $this->sessionMock->expects($this->never())->method('getDecryptAllUid');
182
+        $this->sessionMock->expects($this->never())->method('getDecryptAllKey');
183
+        $this->keyManagerMock->expects($this->never())->method('getEncryptedFileKey');
184
+        $this->keyManagerMock->expects($this->never())->method('getShareKey');
185
+        $this->cryptMock->expects($this->never())->method('multiKeyDecrypt');
186
+
187
+        $this->cryptMock->expects($this->any())
188
+            ->method('getCipher')
189
+            ->willReturn($defaultCipher);
190
+        $this->cryptMock->expects($this->any())
191
+            ->method('getLegacyCipher')
192
+            ->willReturn($legacyCipher);
193
+        if (empty($fileKey)) {
194
+            $this->cryptMock->expects($this->once())
195
+                ->method('generateFileKey')
196
+                ->willReturn('fileKey');
197
+        } else {
198
+            $this->cryptMock->expects($this->never())
199
+                ->method('generateFileKey');
200
+        }
201
+
202
+        $this->keyManagerMock->expects($this->once())
203
+            ->method('getFileKey')
204
+            ->willReturn($fileKey);
205
+
206
+        $result = $this->instance->begin('/user/files/foo.txt', 'user', $mode, $header, []);
207
+
208
+        $this->assertArrayHasKey('cipher', $result);
209
+        $this->assertSame($expected, $result['cipher']);
210
+        if ($mode === 'w') {
211
+            $this->assertTrue(self::invokePrivate($this->instance, 'isWriteOperation'));
212
+        } else {
213
+            $this->assertFalse(self::invokePrivate($this->instance, 'isWriteOperation'));
214
+        }
215
+    }
216
+
217
+    public static function dataTestBegin(): array {
218
+        return [
219
+            ['w', ['cipher' => 'myCipher'], 'legacyCipher', 'defaultCipher', 'fileKey', 'defaultCipher'],
220
+            ['r', ['cipher' => 'myCipher'], 'legacyCipher', 'defaultCipher', 'fileKey', 'myCipher'],
221
+            ['w', [], 'legacyCipher', 'defaultCipher', '', 'defaultCipher'],
222
+            ['r', [], 'legacyCipher', 'defaultCipher', 'file_key', 'legacyCipher'],
223
+        ];
224
+    }
225
+
226
+
227
+    /**
228
+     * test begin() if decryptAll mode was activated
229
+     */
230
+    public function testBeginDecryptAll(): void {
231
+        $path = '/user/files/foo.txt';
232
+        $fileKey = 'fileKey';
233
+
234
+        $this->sessionMock->expects($this->once())
235
+            ->method('decryptAllModeActivated')
236
+            ->willReturn(true);
237
+        $this->keyManagerMock->expects($this->once())
238
+            ->method('getFileKey')
239
+            ->with($path, 'user', null, true)
240
+            ->willReturn($fileKey);
241
+
242
+        $this->instance->begin($path, 'user', 'r', [], []);
243
+
244
+        $this->assertSame($fileKey,
245
+            $this->invokePrivate($this->instance, 'fileKey')
246
+        );
247
+    }
248
+
249
+    /**
250
+     * test begin() if encryption is not initialized but the master key is enabled
251
+     * in this case we can initialize the encryption without a username/password
252
+     * and continue
253
+     */
254
+    public function testBeginInitMasterKey(): void {
255
+        $this->sessionMock->expects($this->once())
256
+            ->method('decryptAllModeActivated')
257
+            ->willReturn(false);
258
+
259
+        $this->sessionMock->expects($this->once())->method('isReady')->willReturn(false);
260
+        $this->utilMock->expects($this->once())->method('isMasterKeyEnabled')
261
+            ->willReturn(true);
262
+        $this->keyManagerMock->expects($this->once())->method('init')->with('', '');
263
+
264
+        $this->instance->begin('/user/files/welcome.txt', 'user', 'r', [], []);
265
+    }
266
+
267
+    /**
268
+     * @dataProvider dataTestUpdate
269
+     *
270
+     * @param string $fileKey
271
+     * @param boolean $expected
272
+     */
273
+    public function testUpdate($fileKey, $expected): void {
274
+        $this->keyManagerMock->expects($this->once())
275
+            ->method('getFileKey')->willReturn($fileKey);
276
+
277
+        $this->keyManagerMock->expects($this->any())
278
+            ->method('getPublicKey')->willReturn('publicKey');
279
+
280
+        $this->keyManagerMock->expects($this->any())
281
+            ->method('addSystemKeys')
282
+            ->willReturnCallback(function ($accessList, $publicKeys) {
283
+                return $publicKeys;
284
+            });
285
+
286
+        $this->keyManagerMock->expects($this->never())->method('getVersion');
287
+        $this->keyManagerMock->expects($this->never())->method('setVersion');
288
+
289
+        $this->assertSame($expected,
290
+            $this->instance->update('path', 'user1', ['users' => ['user1']])
291
+        );
292
+    }
293
+
294
+    public static function dataTestUpdate(): array {
295
+        return [
296
+            ['', false],
297
+            ['fileKey', true]
298
+        ];
299
+    }
300
+
301
+    public function testUpdateNoUsers(): void {
302
+        $this->invokePrivate($this->instance, 'rememberVersion', [['path' => 2]]);
303
+
304
+        $this->keyManagerMock->expects($this->never())->method('getFileKey');
305
+        $this->keyManagerMock->expects($this->never())->method('getPublicKey');
306
+        $this->keyManagerMock->expects($this->never())->method('addSystemKeys');
307
+        $this->keyManagerMock->expects($this->once())->method('setVersion')
308
+            ->willReturnCallback(function ($path, $version, $view): void {
309
+                $this->assertSame('path', $path);
310
+                $this->assertSame(2, $version);
311
+                $this->assertTrue($view instanceof View);
312
+            });
313
+        $this->instance->update('path', 'user1', []);
314
+    }
315
+
316
+    /**
317
+     * Test case if the public key is missing. Nextcloud should still encrypt
318
+     * the file for the remaining users
319
+     */
320
+    public function testUpdateMissingPublicKey(): void {
321
+        $this->keyManagerMock->expects($this->once())
322
+            ->method('getFileKey')->willReturn('fileKey');
323
+
324
+        $this->keyManagerMock->expects($this->any())
325
+            ->method('getPublicKey')->willReturnCallback(
326
+                function ($user): void {
327
+                    throw new PublicKeyMissingException($user);
328
+                }
329
+            );
330
+
331
+        $this->keyManagerMock->expects($this->any())
332
+            ->method('addSystemKeys')
333
+            ->willReturnCallback(function ($accessList, $publicKeys) {
334
+                return $publicKeys;
335
+            });
336
+
337
+        $this->cryptMock->expects($this->once())->method('multiKeyEncrypt')
338
+            ->willReturnCallback(
339
+                function ($fileKey, $publicKeys) {
340
+                    $this->assertEmpty($publicKeys);
341
+                    $this->assertSame('fileKey', $fileKey);
342
+                    return [];
343
+                }
344
+            );
345
+
346
+        $this->keyManagerMock->expects($this->never())->method('getVersion');
347
+        $this->keyManagerMock->expects($this->never())->method('setVersion');
348
+
349
+        $this->assertTrue(
350
+            $this->instance->update('path', 'user1', ['users' => ['user1']])
351
+        );
352
+    }
353
+
354
+    /**
355
+     * by default the encryption module should encrypt regular files, files in
356
+     * files_versions and files in files_trashbin
357
+     *
358
+     * @dataProvider dataTestShouldEncrypt
359
+     */
360
+    public function testShouldEncrypt($path, $shouldEncryptHomeStorage, $isHomeStorage, $expected): void {
361
+        $this->utilMock->expects($this->once())->method('shouldEncryptHomeStorage')
362
+            ->willReturn($shouldEncryptHomeStorage);
363
+
364
+        if ($shouldEncryptHomeStorage === false) {
365
+            $this->storageMock->expects($this->once())->method('instanceOfStorage')
366
+                ->with('\OCP\Files\IHomeStorage')->willReturn($isHomeStorage);
367
+            $this->utilMock->expects($this->once())->method('getStorage')->with($path)
368
+                ->willReturn($this->storageMock);
369
+        }
370
+
371
+        $this->assertSame($expected,
372
+            $this->instance->shouldEncrypt($path)
373
+        );
374
+    }
375
+
376
+    public static function dataTestShouldEncrypt(): array {
377
+        return [
378
+            ['/user1/files/foo.txt', true, true, true],
379
+            ['/user1/files_versions/foo.txt', true, true, true],
380
+            ['/user1/files_trashbin/foo.txt', true, true, true],
381
+            ['/user1/some_folder/foo.txt', true, true, false],
382
+            ['/user1/foo.txt', true, true, false],
383
+            ['/user1/files', true, true, false],
384
+            ['/user1/files_trashbin', true, true, false],
385
+            ['/user1/files_versions', true, true, false],
386
+            // test if shouldEncryptHomeStorage is set to false
387
+            ['/user1/files/foo.txt', false, true, false],
388
+            ['/user1/files_versions/foo.txt', false, false, true],
389
+        ];
390
+    }
391
+
392
+
393
+    public function testDecrypt(): void {
394
+        $this->expectException(DecryptionFailedException::class);
395
+        $this->expectExceptionMessage('Cannot decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
396
+
397
+        $this->instance->decrypt('abc');
398
+    }
399
+
400
+    public function testPrepareDecryptAll(): void {
401
+        /** @var \Symfony\Component\Console\Input\InputInterface $input */
402
+        $input = $this->createMock(InputInterface::class);
403
+        /** @var \Symfony\Component\Console\Output\OutputInterface $output */
404
+        $output = $this->createMock(OutputInterface::class);
405
+
406
+        $this->decryptAllMock->expects($this->once())->method('prepare')
407
+            ->with($input, $output, 'user');
408
+
409
+        $this->instance->prepareDecryptAll($input, $output, 'user');
410
+    }
411 411
 }
Please login to merge, or discard this patch.
apps/encryption/tests/Crypto/EncryptAllTest.php 1 patch
Indentation   +344 added lines, -344 removed lines patch added patch discarded remove patch
@@ -32,348 +32,348 @@
 block discarded – undo
32 32
 
33 33
 class EncryptAllTest extends TestCase {
34 34
 
35
-	protected KeyManager&MockObject $keyManager;
36
-	protected Util&MockObject $util;
37
-	protected IUserManager&MockObject $userManager;
38
-	protected Setup&MockObject $setupUser;
39
-	protected View&MockObject $view;
40
-	protected IConfig&MockObject $config;
41
-	protected IMailer&MockObject $mailer;
42
-	protected IL10N&MockObject $l;
43
-	protected IFactory&MockObject $l10nFactory;
44
-	protected \Symfony\Component\Console\Helper\QuestionHelper&MockObject $questionHelper;
45
-	protected \Symfony\Component\Console\Input\InputInterface&MockObject $inputInterface;
46
-	protected \Symfony\Component\Console\Output\OutputInterface&MockObject $outputInterface;
47
-	protected UserInterface&MockObject $userInterface;
48
-	protected ISecureRandom&MockObject $secureRandom;
49
-
50
-	protected EncryptAll $encryptAll;
51
-
52
-	protected function setUp(): void {
53
-		parent::setUp();
54
-		$this->setupUser = $this->getMockBuilder(Setup::class)
55
-			->disableOriginalConstructor()->getMock();
56
-		$this->keyManager = $this->getMockBuilder(KeyManager::class)
57
-			->disableOriginalConstructor()->getMock();
58
-		$this->util = $this->getMockBuilder(Util::class)
59
-			->disableOriginalConstructor()->getMock();
60
-		$this->userManager = $this->getMockBuilder(IUserManager::class)
61
-			->disableOriginalConstructor()->getMock();
62
-		$this->view = $this->getMockBuilder(View::class)
63
-			->disableOriginalConstructor()->getMock();
64
-		$this->config = $this->getMockBuilder(IConfig::class)
65
-			->disableOriginalConstructor()->getMock();
66
-		$this->mailer = $this->getMockBuilder(IMailer::class)
67
-			->disableOriginalConstructor()->getMock();
68
-		$this->l10nFactory = $this->createMock(IFactory::class);
69
-		$this->l = $this->getMockBuilder(IL10N::class)
70
-			->disableOriginalConstructor()->getMock();
71
-		$this->questionHelper = $this->getMockBuilder(QuestionHelper::class)
72
-			->disableOriginalConstructor()->getMock();
73
-		$this->inputInterface = $this->getMockBuilder(InputInterface::class)
74
-			->disableOriginalConstructor()->getMock();
75
-		$this->outputInterface = $this->getMockBuilder(OutputInterface::class)
76
-			->disableOriginalConstructor()->getMock();
77
-		$this->userInterface = $this->getMockBuilder(UserInterface::class)
78
-			->disableOriginalConstructor()->getMock();
79
-
80
-		/**
81
-		 * We need format method to return a string
82
-		 * @var OutputFormatterInterface|\PHPUnit\Framework\MockObject\MockObject
83
-		 */
84
-		$outputFormatter = $this->createMock(OutputFormatterInterface::class);
85
-		$outputFormatter->method('isDecorated')->willReturn(false);
86
-		$outputFormatter->method('format')->willReturnArgument(0);
87
-
88
-		$this->outputInterface->expects($this->any())->method('getFormatter')
89
-			->willReturn($outputFormatter);
90
-
91
-		$this->userManager->expects($this->any())->method('getBackends')->willReturn([$this->userInterface]);
92
-		$this->userInterface->expects($this->any())->method('getUsers')->willReturn(['user1', 'user2']);
93
-
94
-		$this->secureRandom = $this->getMockBuilder(ISecureRandom::class)->disableOriginalConstructor()->getMock();
95
-		$this->secureRandom->expects($this->any())->method('generate')->willReturn('12345678');
96
-
97
-
98
-		$this->encryptAll = new EncryptAll(
99
-			$this->setupUser,
100
-			$this->userManager,
101
-			$this->view,
102
-			$this->keyManager,
103
-			$this->util,
104
-			$this->config,
105
-			$this->mailer,
106
-			$this->l,
107
-			$this->l10nFactory,
108
-			$this->questionHelper,
109
-			$this->secureRandom
110
-		);
111
-	}
112
-
113
-	public function testEncryptAll(): void {
114
-		/** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject  $encryptAll */
115
-		$encryptAll = $this->getMockBuilder(EncryptAll::class)
116
-			->setConstructorArgs(
117
-				[
118
-					$this->setupUser,
119
-					$this->userManager,
120
-					$this->view,
121
-					$this->keyManager,
122
-					$this->util,
123
-					$this->config,
124
-					$this->mailer,
125
-					$this->l,
126
-					$this->l10nFactory,
127
-					$this->questionHelper,
128
-					$this->secureRandom
129
-				]
130
-			)
131
-			->onlyMethods(['createKeyPairs', 'encryptAllUsersFiles', 'outputPasswords'])
132
-			->getMock();
133
-
134
-		$this->util->expects($this->any())->method('isMasterKeyEnabled')->willReturn(false);
135
-		$encryptAll->expects($this->once())->method('createKeyPairs')->with();
136
-		$encryptAll->expects($this->once())->method('outputPasswords')->with();
137
-		$encryptAll->expects($this->once())->method('encryptAllUsersFiles')->with();
138
-
139
-		$encryptAll->encryptAll($this->inputInterface, $this->outputInterface);
140
-	}
141
-
142
-	public function testEncryptAllWithMasterKey(): void {
143
-		/** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject  $encryptAll */
144
-		$encryptAll = $this->getMockBuilder(EncryptAll::class)
145
-			->setConstructorArgs(
146
-				[
147
-					$this->setupUser,
148
-					$this->userManager,
149
-					$this->view,
150
-					$this->keyManager,
151
-					$this->util,
152
-					$this->config,
153
-					$this->mailer,
154
-					$this->l,
155
-					$this->l10nFactory,
156
-					$this->questionHelper,
157
-					$this->secureRandom
158
-				]
159
-			)
160
-			->onlyMethods(['createKeyPairs', 'encryptAllUsersFiles', 'outputPasswords'])
161
-			->getMock();
162
-
163
-		$this->util->expects($this->any())->method('isMasterKeyEnabled')->willReturn(true);
164
-		$encryptAll->expects($this->never())->method('createKeyPairs');
165
-		$this->keyManager->expects($this->once())->method('validateMasterKey');
166
-		$encryptAll->expects($this->once())->method('encryptAllUsersFiles')->with();
167
-		$encryptAll->expects($this->never())->method('outputPasswords');
168
-
169
-		$encryptAll->encryptAll($this->inputInterface, $this->outputInterface);
170
-	}
171
-
172
-	public function testCreateKeyPairs(): void {
173
-		/** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject  $encryptAll */
174
-		$encryptAll = $this->getMockBuilder(EncryptAll::class)
175
-			->setConstructorArgs(
176
-				[
177
-					$this->setupUser,
178
-					$this->userManager,
179
-					$this->view,
180
-					$this->keyManager,
181
-					$this->util,
182
-					$this->config,
183
-					$this->mailer,
184
-					$this->l,
185
-					$this->l10nFactory,
186
-					$this->questionHelper,
187
-					$this->secureRandom
188
-				]
189
-			)
190
-			->onlyMethods(['setupUserFS', 'generateOneTimePassword'])
191
-			->getMock();
192
-
193
-
194
-		// set protected property $output
195
-		$this->invokePrivate($encryptAll, 'output', [$this->outputInterface]);
196
-
197
-		$this->keyManager->expects($this->exactly(2))->method('userHasKeys')
198
-			->willReturnCallback(
199
-				function ($user) {
200
-					if ($user === 'user1') {
201
-						return false;
202
-					}
203
-					return true;
204
-				}
205
-			);
206
-
207
-		$encryptAll->expects($this->once())->method('setupUserFS')->with('user1');
208
-		$encryptAll->expects($this->once())->method('generateOneTimePassword')->with('user1')->willReturn('password');
209
-		$this->setupUser->expects($this->once())->method('setupUser')->with('user1', 'password');
210
-
211
-		$this->invokePrivate($encryptAll, 'createKeyPairs');
212
-
213
-		$userPasswords = $this->invokePrivate($encryptAll, 'userPasswords');
214
-
215
-		// we only expect the skipped user, because generateOneTimePassword which
216
-		// would set the user with the new password was mocked.
217
-		// This method will be tested separately
218
-		$this->assertSame(1, count($userPasswords));
219
-		$this->assertSame('', $userPasswords['user2']);
220
-	}
221
-
222
-	public function testEncryptAllUsersFiles(): void {
223
-		/** @var EncryptAll&MockObject $encryptAll */
224
-		$encryptAll = $this->getMockBuilder(EncryptAll::class)
225
-			->setConstructorArgs(
226
-				[
227
-					$this->setupUser,
228
-					$this->userManager,
229
-					$this->view,
230
-					$this->keyManager,
231
-					$this->util,
232
-					$this->config,
233
-					$this->mailer,
234
-					$this->l,
235
-					$this->l10nFactory,
236
-					$this->questionHelper,
237
-					$this->secureRandom
238
-				]
239
-			)
240
-			->onlyMethods(['encryptUsersFiles'])
241
-			->getMock();
242
-
243
-		$this->util->expects($this->any())->method('isMasterKeyEnabled')->willReturn(false);
244
-
245
-		// set protected property $output
246
-		$this->invokePrivate($encryptAll, 'output', [$this->outputInterface]);
247
-		$this->invokePrivate($encryptAll, 'userPasswords', [['user1' => 'pwd1', 'user2' => 'pwd2']]);
248
-
249
-		$encryptAllCalls = [];
250
-		$encryptAll->expects($this->exactly(2))
251
-			->method('encryptUsersFiles')
252
-			->willReturnCallback(function ($uid) use (&$encryptAllCalls) {
253
-				$encryptAllCalls[] = $uid;
254
-			});
255
-
256
-		$this->invokePrivate($encryptAll, 'encryptAllUsersFiles');
257
-		self::assertEquals([
258
-			'user1',
259
-			'user2',
260
-		], $encryptAllCalls);
261
-	}
262
-
263
-	public function testEncryptUsersFiles(): void {
264
-		/** @var EncryptAll&MockObject $encryptAll */
265
-		$encryptAll = $this->getMockBuilder(EncryptAll::class)
266
-			->setConstructorArgs(
267
-				[
268
-					$this->setupUser,
269
-					$this->userManager,
270
-					$this->view,
271
-					$this->keyManager,
272
-					$this->util,
273
-					$this->config,
274
-					$this->mailer,
275
-					$this->l,
276
-					$this->l10nFactory,
277
-					$this->questionHelper,
278
-					$this->secureRandom
279
-				]
280
-			)
281
-			->onlyMethods(['encryptFile', 'setupUserFS'])
282
-			->getMock();
283
-
284
-		$this->util->expects($this->any())->method('isMasterKeyEnabled')->willReturn(false);
285
-
286
-		$this->view->expects($this->exactly(2))->method('getDirectoryContent')
287
-			->willReturnMap([
288
-				[
289
-					'/user1/files',
290
-					'',
291
-					null,
292
-					[
293
-						['name' => 'foo', 'type' => 'dir'],
294
-						['name' => 'bar', 'type' => 'file'],
295
-					],
296
-				],
297
-				[
298
-					'/user1/files/foo',
299
-					'',
300
-					null,
301
-					[
302
-						['name' => 'subfile', 'type' => 'file']
303
-					],
304
-				],
305
-			]);
306
-
307
-		$this->view->expects($this->any())->method('is_dir')
308
-			->willReturnCallback(
309
-				function ($path) {
310
-					if ($path === '/user1/files/foo') {
311
-						return true;
312
-					}
313
-					return false;
314
-				}
315
-			);
316
-
317
-		$encryptAllCalls = [];
318
-		$encryptAll->expects($this->exactly(2))
319
-			->method('encryptFile')
320
-			->willReturnCallback(function (string $path) use (&$encryptAllCalls) {
321
-				$encryptAllCalls[] = $path;
322
-			});
323
-
324
-		$outputFormatter = $this->createMock(OutputFormatterInterface::class);
325
-		$outputFormatter->method('isDecorated')->willReturn(false);
326
-		$this->outputInterface->expects($this->any())
327
-			->method('getFormatter')
328
-			->willReturn($outputFormatter);
329
-		$progressBar = new ProgressBar($this->outputInterface);
330
-
331
-		$this->invokePrivate($encryptAll, 'encryptUsersFiles', ['user1', $progressBar, '']);
332
-		self::assertEquals([
333
-			'/user1/files/bar',
334
-			'/user1/files/foo/subfile',
335
-		], $encryptAllCalls);
336
-	}
337
-
338
-	public function testGenerateOneTimePassword(): void {
339
-		$password = $this->invokePrivate($this->encryptAll, 'generateOneTimePassword', ['user1']);
340
-		$this->assertTrue(is_string($password));
341
-		$this->assertSame(8, strlen($password));
342
-
343
-		$userPasswords = $this->invokePrivate($this->encryptAll, 'userPasswords');
344
-		$this->assertSame(1, count($userPasswords));
345
-		$this->assertSame($password, $userPasswords['user1']);
346
-	}
347
-
348
-	/**
349
-	 * @dataProvider dataTestEncryptFile
350
-	 * @param $isEncrypted
351
-	 */
352
-	public function testEncryptFile($isEncrypted): void {
353
-		$fileInfo = $this->createMock(FileInfo::class);
354
-		$fileInfo->expects($this->any())->method('isEncrypted')
355
-			->willReturn($isEncrypted);
356
-		$this->view->expects($this->any())->method('getFileInfo')
357
-			->willReturn($fileInfo);
358
-
359
-
360
-		if ($isEncrypted) {
361
-			$this->view->expects($this->never())->method('copy');
362
-			$this->view->expects($this->never())->method('rename');
363
-		} else {
364
-			$this->view->expects($this->once())->method('copy');
365
-			$this->view->expects($this->once())->method('rename');
366
-		}
367
-
368
-		$this->assertTrue(
369
-			$this->invokePrivate($this->encryptAll, 'encryptFile', ['foo.txt'])
370
-		);
371
-	}
372
-
373
-	public static function dataTestEncryptFile(): array {
374
-		return [
375
-			[true],
376
-			[false],
377
-		];
378
-	}
35
+    protected KeyManager&MockObject $keyManager;
36
+    protected Util&MockObject $util;
37
+    protected IUserManager&MockObject $userManager;
38
+    protected Setup&MockObject $setupUser;
39
+    protected View&MockObject $view;
40
+    protected IConfig&MockObject $config;
41
+    protected IMailer&MockObject $mailer;
42
+    protected IL10N&MockObject $l;
43
+    protected IFactory&MockObject $l10nFactory;
44
+    protected \Symfony\Component\Console\Helper\QuestionHelper&MockObject $questionHelper;
45
+    protected \Symfony\Component\Console\Input\InputInterface&MockObject $inputInterface;
46
+    protected \Symfony\Component\Console\Output\OutputInterface&MockObject $outputInterface;
47
+    protected UserInterface&MockObject $userInterface;
48
+    protected ISecureRandom&MockObject $secureRandom;
49
+
50
+    protected EncryptAll $encryptAll;
51
+
52
+    protected function setUp(): void {
53
+        parent::setUp();
54
+        $this->setupUser = $this->getMockBuilder(Setup::class)
55
+            ->disableOriginalConstructor()->getMock();
56
+        $this->keyManager = $this->getMockBuilder(KeyManager::class)
57
+            ->disableOriginalConstructor()->getMock();
58
+        $this->util = $this->getMockBuilder(Util::class)
59
+            ->disableOriginalConstructor()->getMock();
60
+        $this->userManager = $this->getMockBuilder(IUserManager::class)
61
+            ->disableOriginalConstructor()->getMock();
62
+        $this->view = $this->getMockBuilder(View::class)
63
+            ->disableOriginalConstructor()->getMock();
64
+        $this->config = $this->getMockBuilder(IConfig::class)
65
+            ->disableOriginalConstructor()->getMock();
66
+        $this->mailer = $this->getMockBuilder(IMailer::class)
67
+            ->disableOriginalConstructor()->getMock();
68
+        $this->l10nFactory = $this->createMock(IFactory::class);
69
+        $this->l = $this->getMockBuilder(IL10N::class)
70
+            ->disableOriginalConstructor()->getMock();
71
+        $this->questionHelper = $this->getMockBuilder(QuestionHelper::class)
72
+            ->disableOriginalConstructor()->getMock();
73
+        $this->inputInterface = $this->getMockBuilder(InputInterface::class)
74
+            ->disableOriginalConstructor()->getMock();
75
+        $this->outputInterface = $this->getMockBuilder(OutputInterface::class)
76
+            ->disableOriginalConstructor()->getMock();
77
+        $this->userInterface = $this->getMockBuilder(UserInterface::class)
78
+            ->disableOriginalConstructor()->getMock();
79
+
80
+        /**
81
+         * We need format method to return a string
82
+         * @var OutputFormatterInterface|\PHPUnit\Framework\MockObject\MockObject
83
+         */
84
+        $outputFormatter = $this->createMock(OutputFormatterInterface::class);
85
+        $outputFormatter->method('isDecorated')->willReturn(false);
86
+        $outputFormatter->method('format')->willReturnArgument(0);
87
+
88
+        $this->outputInterface->expects($this->any())->method('getFormatter')
89
+            ->willReturn($outputFormatter);
90
+
91
+        $this->userManager->expects($this->any())->method('getBackends')->willReturn([$this->userInterface]);
92
+        $this->userInterface->expects($this->any())->method('getUsers')->willReturn(['user1', 'user2']);
93
+
94
+        $this->secureRandom = $this->getMockBuilder(ISecureRandom::class)->disableOriginalConstructor()->getMock();
95
+        $this->secureRandom->expects($this->any())->method('generate')->willReturn('12345678');
96
+
97
+
98
+        $this->encryptAll = new EncryptAll(
99
+            $this->setupUser,
100
+            $this->userManager,
101
+            $this->view,
102
+            $this->keyManager,
103
+            $this->util,
104
+            $this->config,
105
+            $this->mailer,
106
+            $this->l,
107
+            $this->l10nFactory,
108
+            $this->questionHelper,
109
+            $this->secureRandom
110
+        );
111
+    }
112
+
113
+    public function testEncryptAll(): void {
114
+        /** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject  $encryptAll */
115
+        $encryptAll = $this->getMockBuilder(EncryptAll::class)
116
+            ->setConstructorArgs(
117
+                [
118
+                    $this->setupUser,
119
+                    $this->userManager,
120
+                    $this->view,
121
+                    $this->keyManager,
122
+                    $this->util,
123
+                    $this->config,
124
+                    $this->mailer,
125
+                    $this->l,
126
+                    $this->l10nFactory,
127
+                    $this->questionHelper,
128
+                    $this->secureRandom
129
+                ]
130
+            )
131
+            ->onlyMethods(['createKeyPairs', 'encryptAllUsersFiles', 'outputPasswords'])
132
+            ->getMock();
133
+
134
+        $this->util->expects($this->any())->method('isMasterKeyEnabled')->willReturn(false);
135
+        $encryptAll->expects($this->once())->method('createKeyPairs')->with();
136
+        $encryptAll->expects($this->once())->method('outputPasswords')->with();
137
+        $encryptAll->expects($this->once())->method('encryptAllUsersFiles')->with();
138
+
139
+        $encryptAll->encryptAll($this->inputInterface, $this->outputInterface);
140
+    }
141
+
142
+    public function testEncryptAllWithMasterKey(): void {
143
+        /** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject  $encryptAll */
144
+        $encryptAll = $this->getMockBuilder(EncryptAll::class)
145
+            ->setConstructorArgs(
146
+                [
147
+                    $this->setupUser,
148
+                    $this->userManager,
149
+                    $this->view,
150
+                    $this->keyManager,
151
+                    $this->util,
152
+                    $this->config,
153
+                    $this->mailer,
154
+                    $this->l,
155
+                    $this->l10nFactory,
156
+                    $this->questionHelper,
157
+                    $this->secureRandom
158
+                ]
159
+            )
160
+            ->onlyMethods(['createKeyPairs', 'encryptAllUsersFiles', 'outputPasswords'])
161
+            ->getMock();
162
+
163
+        $this->util->expects($this->any())->method('isMasterKeyEnabled')->willReturn(true);
164
+        $encryptAll->expects($this->never())->method('createKeyPairs');
165
+        $this->keyManager->expects($this->once())->method('validateMasterKey');
166
+        $encryptAll->expects($this->once())->method('encryptAllUsersFiles')->with();
167
+        $encryptAll->expects($this->never())->method('outputPasswords');
168
+
169
+        $encryptAll->encryptAll($this->inputInterface, $this->outputInterface);
170
+    }
171
+
172
+    public function testCreateKeyPairs(): void {
173
+        /** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject  $encryptAll */
174
+        $encryptAll = $this->getMockBuilder(EncryptAll::class)
175
+            ->setConstructorArgs(
176
+                [
177
+                    $this->setupUser,
178
+                    $this->userManager,
179
+                    $this->view,
180
+                    $this->keyManager,
181
+                    $this->util,
182
+                    $this->config,
183
+                    $this->mailer,
184
+                    $this->l,
185
+                    $this->l10nFactory,
186
+                    $this->questionHelper,
187
+                    $this->secureRandom
188
+                ]
189
+            )
190
+            ->onlyMethods(['setupUserFS', 'generateOneTimePassword'])
191
+            ->getMock();
192
+
193
+
194
+        // set protected property $output
195
+        $this->invokePrivate($encryptAll, 'output', [$this->outputInterface]);
196
+
197
+        $this->keyManager->expects($this->exactly(2))->method('userHasKeys')
198
+            ->willReturnCallback(
199
+                function ($user) {
200
+                    if ($user === 'user1') {
201
+                        return false;
202
+                    }
203
+                    return true;
204
+                }
205
+            );
206
+
207
+        $encryptAll->expects($this->once())->method('setupUserFS')->with('user1');
208
+        $encryptAll->expects($this->once())->method('generateOneTimePassword')->with('user1')->willReturn('password');
209
+        $this->setupUser->expects($this->once())->method('setupUser')->with('user1', 'password');
210
+
211
+        $this->invokePrivate($encryptAll, 'createKeyPairs');
212
+
213
+        $userPasswords = $this->invokePrivate($encryptAll, 'userPasswords');
214
+
215
+        // we only expect the skipped user, because generateOneTimePassword which
216
+        // would set the user with the new password was mocked.
217
+        // This method will be tested separately
218
+        $this->assertSame(1, count($userPasswords));
219
+        $this->assertSame('', $userPasswords['user2']);
220
+    }
221
+
222
+    public function testEncryptAllUsersFiles(): void {
223
+        /** @var EncryptAll&MockObject $encryptAll */
224
+        $encryptAll = $this->getMockBuilder(EncryptAll::class)
225
+            ->setConstructorArgs(
226
+                [
227
+                    $this->setupUser,
228
+                    $this->userManager,
229
+                    $this->view,
230
+                    $this->keyManager,
231
+                    $this->util,
232
+                    $this->config,
233
+                    $this->mailer,
234
+                    $this->l,
235
+                    $this->l10nFactory,
236
+                    $this->questionHelper,
237
+                    $this->secureRandom
238
+                ]
239
+            )
240
+            ->onlyMethods(['encryptUsersFiles'])
241
+            ->getMock();
242
+
243
+        $this->util->expects($this->any())->method('isMasterKeyEnabled')->willReturn(false);
244
+
245
+        // set protected property $output
246
+        $this->invokePrivate($encryptAll, 'output', [$this->outputInterface]);
247
+        $this->invokePrivate($encryptAll, 'userPasswords', [['user1' => 'pwd1', 'user2' => 'pwd2']]);
248
+
249
+        $encryptAllCalls = [];
250
+        $encryptAll->expects($this->exactly(2))
251
+            ->method('encryptUsersFiles')
252
+            ->willReturnCallback(function ($uid) use (&$encryptAllCalls) {
253
+                $encryptAllCalls[] = $uid;
254
+            });
255
+
256
+        $this->invokePrivate($encryptAll, 'encryptAllUsersFiles');
257
+        self::assertEquals([
258
+            'user1',
259
+            'user2',
260
+        ], $encryptAllCalls);
261
+    }
262
+
263
+    public function testEncryptUsersFiles(): void {
264
+        /** @var EncryptAll&MockObject $encryptAll */
265
+        $encryptAll = $this->getMockBuilder(EncryptAll::class)
266
+            ->setConstructorArgs(
267
+                [
268
+                    $this->setupUser,
269
+                    $this->userManager,
270
+                    $this->view,
271
+                    $this->keyManager,
272
+                    $this->util,
273
+                    $this->config,
274
+                    $this->mailer,
275
+                    $this->l,
276
+                    $this->l10nFactory,
277
+                    $this->questionHelper,
278
+                    $this->secureRandom
279
+                ]
280
+            )
281
+            ->onlyMethods(['encryptFile', 'setupUserFS'])
282
+            ->getMock();
283
+
284
+        $this->util->expects($this->any())->method('isMasterKeyEnabled')->willReturn(false);
285
+
286
+        $this->view->expects($this->exactly(2))->method('getDirectoryContent')
287
+            ->willReturnMap([
288
+                [
289
+                    '/user1/files',
290
+                    '',
291
+                    null,
292
+                    [
293
+                        ['name' => 'foo', 'type' => 'dir'],
294
+                        ['name' => 'bar', 'type' => 'file'],
295
+                    ],
296
+                ],
297
+                [
298
+                    '/user1/files/foo',
299
+                    '',
300
+                    null,
301
+                    [
302
+                        ['name' => 'subfile', 'type' => 'file']
303
+                    ],
304
+                ],
305
+            ]);
306
+
307
+        $this->view->expects($this->any())->method('is_dir')
308
+            ->willReturnCallback(
309
+                function ($path) {
310
+                    if ($path === '/user1/files/foo') {
311
+                        return true;
312
+                    }
313
+                    return false;
314
+                }
315
+            );
316
+
317
+        $encryptAllCalls = [];
318
+        $encryptAll->expects($this->exactly(2))
319
+            ->method('encryptFile')
320
+            ->willReturnCallback(function (string $path) use (&$encryptAllCalls) {
321
+                $encryptAllCalls[] = $path;
322
+            });
323
+
324
+        $outputFormatter = $this->createMock(OutputFormatterInterface::class);
325
+        $outputFormatter->method('isDecorated')->willReturn(false);
326
+        $this->outputInterface->expects($this->any())
327
+            ->method('getFormatter')
328
+            ->willReturn($outputFormatter);
329
+        $progressBar = new ProgressBar($this->outputInterface);
330
+
331
+        $this->invokePrivate($encryptAll, 'encryptUsersFiles', ['user1', $progressBar, '']);
332
+        self::assertEquals([
333
+            '/user1/files/bar',
334
+            '/user1/files/foo/subfile',
335
+        ], $encryptAllCalls);
336
+    }
337
+
338
+    public function testGenerateOneTimePassword(): void {
339
+        $password = $this->invokePrivate($this->encryptAll, 'generateOneTimePassword', ['user1']);
340
+        $this->assertTrue(is_string($password));
341
+        $this->assertSame(8, strlen($password));
342
+
343
+        $userPasswords = $this->invokePrivate($this->encryptAll, 'userPasswords');
344
+        $this->assertSame(1, count($userPasswords));
345
+        $this->assertSame($password, $userPasswords['user1']);
346
+    }
347
+
348
+    /**
349
+     * @dataProvider dataTestEncryptFile
350
+     * @param $isEncrypted
351
+     */
352
+    public function testEncryptFile($isEncrypted): void {
353
+        $fileInfo = $this->createMock(FileInfo::class);
354
+        $fileInfo->expects($this->any())->method('isEncrypted')
355
+            ->willReturn($isEncrypted);
356
+        $this->view->expects($this->any())->method('getFileInfo')
357
+            ->willReturn($fileInfo);
358
+
359
+
360
+        if ($isEncrypted) {
361
+            $this->view->expects($this->never())->method('copy');
362
+            $this->view->expects($this->never())->method('rename');
363
+        } else {
364
+            $this->view->expects($this->once())->method('copy');
365
+            $this->view->expects($this->once())->method('rename');
366
+        }
367
+
368
+        $this->assertTrue(
369
+            $this->invokePrivate($this->encryptAll, 'encryptFile', ['foo.txt'])
370
+        );
371
+    }
372
+
373
+    public static function dataTestEncryptFile(): array {
374
+        return [
375
+            [true],
376
+            [false],
377
+        ];
378
+    }
379 379
 }
Please login to merge, or discard this patch.
apps/encryption/tests/Crypto/DecryptAllTest.php 1 patch
Indentation   +86 added lines, -86 removed lines patch added patch discarded remove patch
@@ -20,90 +20,90 @@
 block discarded – undo
20 20
 
21 21
 class DecryptAllTest extends TestCase {
22 22
 
23
-	protected DecryptAll $instance;
24
-
25
-	protected Util&MockObject $util;
26
-	protected KeyManager&MockObject $keyManager;
27
-	protected Crypt&MockObject $crypt;
28
-	protected Session&MockObject $session;
29
-	protected QuestionHelper&MockObject $questionHelper;
30
-
31
-	protected function setUp(): void {
32
-		parent::setUp();
33
-
34
-		$this->util = $this->getMockBuilder(Util::class)
35
-			->disableOriginalConstructor()->getMock();
36
-		$this->keyManager = $this->getMockBuilder(KeyManager::class)
37
-			->disableOriginalConstructor()->getMock();
38
-		$this->crypt = $this->getMockBuilder(Crypt::class)
39
-			->disableOriginalConstructor()->getMock();
40
-		$this->session = $this->getMockBuilder(Session::class)
41
-			->disableOriginalConstructor()->getMock();
42
-		$this->questionHelper = $this->getMockBuilder(QuestionHelper::class)
43
-			->disableOriginalConstructor()->getMock();
44
-
45
-		$this->instance = new DecryptAll(
46
-			$this->util,
47
-			$this->keyManager,
48
-			$this->crypt,
49
-			$this->session,
50
-			$this->questionHelper
51
-		);
52
-	}
53
-
54
-	public function testUpdateSession(): void {
55
-		$this->session->expects($this->once())->method('prepareDecryptAll')
56
-			->with('user1', 'key1');
57
-
58
-		$this->invokePrivate($this->instance, 'updateSession', ['user1', 'key1']);
59
-	}
60
-
61
-	/**
62
-	 * @dataProvider dataTestGetPrivateKey
63
-	 *
64
-	 * @param string $user
65
-	 * @param string $recoveryKeyId
66
-	 */
67
-	public function testGetPrivateKey($user, $recoveryKeyId, $masterKeyId): void {
68
-		$password = 'passwd';
69
-		$recoveryKey = 'recoveryKey';
70
-		$userKey = 'userKey';
71
-		$masterKey = 'userKey';
72
-		$unencryptedKey = 'unencryptedKey';
73
-
74
-		$this->keyManager->expects($this->any())->method('getRecoveryKeyId')
75
-			->willReturn($recoveryKeyId);
76
-
77
-		if ($user === $recoveryKeyId) {
78
-			$this->keyManager->expects($this->once())->method('getSystemPrivateKey')
79
-				->with($recoveryKeyId)->willReturn($recoveryKey);
80
-			$this->keyManager->expects($this->never())->method('getPrivateKey');
81
-			$this->crypt->expects($this->once())->method('decryptPrivateKey')
82
-				->with($recoveryKey, $password)->willReturn($unencryptedKey);
83
-		} elseif ($user === $masterKeyId) {
84
-			$this->keyManager->expects($this->once())->method('getSystemPrivateKey')
85
-				->with($masterKeyId)->willReturn($masterKey);
86
-			$this->keyManager->expects($this->never())->method('getPrivateKey');
87
-			$this->crypt->expects($this->once())->method('decryptPrivateKey')
88
-				->with($masterKey, $password, $masterKeyId)->willReturn($unencryptedKey);
89
-		} else {
90
-			$this->keyManager->expects($this->never())->method('getSystemPrivateKey');
91
-			$this->keyManager->expects($this->once())->method('getPrivateKey')
92
-				->with($user)->willReturn($userKey);
93
-			$this->crypt->expects($this->once())->method('decryptPrivateKey')
94
-				->with($userKey, $password, $user)->willReturn($unencryptedKey);
95
-		}
96
-
97
-		$this->assertSame($unencryptedKey,
98
-			$this->invokePrivate($this->instance, 'getPrivateKey', [$user, $password])
99
-		);
100
-	}
101
-
102
-	public static function dataTestGetPrivateKey() {
103
-		return [
104
-			['user1', 'recoveryKey', 'masterKeyId'],
105
-			['recoveryKeyId', 'recoveryKeyId', 'masterKeyId'],
106
-			['masterKeyId', 'masterKeyId', 'masterKeyId']
107
-		];
108
-	}
23
+    protected DecryptAll $instance;
24
+
25
+    protected Util&MockObject $util;
26
+    protected KeyManager&MockObject $keyManager;
27
+    protected Crypt&MockObject $crypt;
28
+    protected Session&MockObject $session;
29
+    protected QuestionHelper&MockObject $questionHelper;
30
+
31
+    protected function setUp(): void {
32
+        parent::setUp();
33
+
34
+        $this->util = $this->getMockBuilder(Util::class)
35
+            ->disableOriginalConstructor()->getMock();
36
+        $this->keyManager = $this->getMockBuilder(KeyManager::class)
37
+            ->disableOriginalConstructor()->getMock();
38
+        $this->crypt = $this->getMockBuilder(Crypt::class)
39
+            ->disableOriginalConstructor()->getMock();
40
+        $this->session = $this->getMockBuilder(Session::class)
41
+            ->disableOriginalConstructor()->getMock();
42
+        $this->questionHelper = $this->getMockBuilder(QuestionHelper::class)
43
+            ->disableOriginalConstructor()->getMock();
44
+
45
+        $this->instance = new DecryptAll(
46
+            $this->util,
47
+            $this->keyManager,
48
+            $this->crypt,
49
+            $this->session,
50
+            $this->questionHelper
51
+        );
52
+    }
53
+
54
+    public function testUpdateSession(): void {
55
+        $this->session->expects($this->once())->method('prepareDecryptAll')
56
+            ->with('user1', 'key1');
57
+
58
+        $this->invokePrivate($this->instance, 'updateSession', ['user1', 'key1']);
59
+    }
60
+
61
+    /**
62
+     * @dataProvider dataTestGetPrivateKey
63
+     *
64
+     * @param string $user
65
+     * @param string $recoveryKeyId
66
+     */
67
+    public function testGetPrivateKey($user, $recoveryKeyId, $masterKeyId): void {
68
+        $password = 'passwd';
69
+        $recoveryKey = 'recoveryKey';
70
+        $userKey = 'userKey';
71
+        $masterKey = 'userKey';
72
+        $unencryptedKey = 'unencryptedKey';
73
+
74
+        $this->keyManager->expects($this->any())->method('getRecoveryKeyId')
75
+            ->willReturn($recoveryKeyId);
76
+
77
+        if ($user === $recoveryKeyId) {
78
+            $this->keyManager->expects($this->once())->method('getSystemPrivateKey')
79
+                ->with($recoveryKeyId)->willReturn($recoveryKey);
80
+            $this->keyManager->expects($this->never())->method('getPrivateKey');
81
+            $this->crypt->expects($this->once())->method('decryptPrivateKey')
82
+                ->with($recoveryKey, $password)->willReturn($unencryptedKey);
83
+        } elseif ($user === $masterKeyId) {
84
+            $this->keyManager->expects($this->once())->method('getSystemPrivateKey')
85
+                ->with($masterKeyId)->willReturn($masterKey);
86
+            $this->keyManager->expects($this->never())->method('getPrivateKey');
87
+            $this->crypt->expects($this->once())->method('decryptPrivateKey')
88
+                ->with($masterKey, $password, $masterKeyId)->willReturn($unencryptedKey);
89
+        } else {
90
+            $this->keyManager->expects($this->never())->method('getSystemPrivateKey');
91
+            $this->keyManager->expects($this->once())->method('getPrivateKey')
92
+                ->with($user)->willReturn($userKey);
93
+            $this->crypt->expects($this->once())->method('decryptPrivateKey')
94
+                ->with($userKey, $password, $user)->willReturn($unencryptedKey);
95
+        }
96
+
97
+        $this->assertSame($unencryptedKey,
98
+            $this->invokePrivate($this->instance, 'getPrivateKey', [$user, $password])
99
+        );
100
+    }
101
+
102
+    public static function dataTestGetPrivateKey() {
103
+        return [
104
+            ['user1', 'recoveryKey', 'masterKeyId'],
105
+            ['recoveryKeyId', 'recoveryKeyId', 'masterKeyId'],
106
+            ['masterKeyId', 'masterKeyId', 'masterKeyId']
107
+        ];
108
+    }
109 109
 }
Please login to merge, or discard this patch.