Unix-style user accounts (passwd, groups, permissions) with a web-friendly Python API.

0 downloads

dbbasic-accounts/tests/test_passwd.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-accounts.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-accounts.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-accounts.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 Add comprehensive FAQ section 369661c 1 year ago History
test_passwd.py · 16.0 KB · 484 lines
1"""
2Tests for dbbasic-passwd
3"""
4
5import os
6import tempfile
7import shutil
8from pathlib import Path
9
10import pytest
11
12from dbbasic_passwd import PasswdDB, User
13
14
15@pytest.fixture
16def tmpdir():
17 """Create temporary directory for test databases"""
18 tmp = tempfile.mkdtemp()
19 yield tmp
20 shutil.rmtree(tmp)
21
22
23@pytest.fixture
24def passwd_db(tmpdir):
25 """Create PasswdDB instance in temp directory"""
26 return PasswdDB(etc_dir=tmpdir)
27
28
29class TestPasswdDB:
30 """Test PasswdDB initialization"""
31
32 def test_init_creates_files(self, tmpdir):
33 """Test that initialization creates passwd, shadow, group files"""
34 db = PasswdDB(etc_dir=tmpdir)
35
36 assert Path(tmpdir, "passwd.tsv").exists()
37 assert Path(tmpdir, "shadow.tsv").exists()
38 assert Path(tmpdir, "group.tsv").exists()
39
40 def test_shadow_permissions(self, tmpdir):
41 """Test that shadow.tsv has restricted permissions (Unix only)"""
42 db = PasswdDB(etc_dir=tmpdir)
43 shadow_path = Path(tmpdir, "shadow.tsv")
44
45 # Skip on Windows
46 if os.name != 'posix':
47 pytest.skip("Permission tests only on Unix")
48
49 stat_info = os.stat(shadow_path)
50 mode = stat_info.st_mode & 0o777
51 assert mode == 0o600, f"Expected 0o600, got {oct(mode)}"
52
53 def test_default_users_group(self, passwd_db):
54 """Test that default 'users' group is created"""
55 groups = passwd_db.list_groups()
56 assert len(groups) == 1
57 assert groups[0]['groupname'] == 'users'
58 assert groups[0]['gid'] == 100
59
60
61class TestUserAdd:
62 """Test useradd functionality"""
63
64 def test_useradd_basic(self, passwd_db):
65 """Test basic user creation"""
66 user = passwd_db.useradd('john', password='secret', fullname='John Doe')
67
68 assert user.username == 'john'
69 assert user.uid == 1000 # First user
70 assert user.gid == 100 # users group
71 assert user.fullname == 'John Doe'
72 assert user.homedir == '/home/john'
73 assert user.shell == '/bin/bash'
74
75 def test_useradd_custom_fields(self, passwd_db):
76 """Test user creation with custom fields"""
77 user = passwd_db.useradd(
78 'jane',
79 password='secret',
80 fullname='Jane Smith',
81 homedir='/var/www/jane',
82 shell='/bin/zsh'
83 )
84
85 assert user.username == 'jane'
86 assert user.homedir == '/var/www/jane'
87 assert user.shell == '/bin/zsh'
88
89 def test_useradd_duplicate_fails(self, passwd_db):
90 """Test that adding duplicate user fails"""
91 passwd_db.useradd('john', password='secret')
92
93 with pytest.raises(ValueError, match="already exists"):
94 passwd_db.useradd('john', password='other')
95
96 def test_useradd_increments_uid(self, passwd_db):
97 """Test that UIDs increment correctly"""
98 user1 = passwd_db.useradd('john', password='secret')
99 user2 = passwd_db.useradd('jane', password='secret')
100 user3 = passwd_db.useradd('bob', password='secret')
101
102 assert user1.uid == 1000
103 assert user2.uid == 1001
104 assert user3.uid == 1002
105
106 def test_useradd_with_groups(self, passwd_db):
107 """Test user creation with additional groups"""
108 passwd_db.groupadd('editors')
109 passwd_db.groupadd('admins')
110
111 user = passwd_db.useradd('john', password='secret', groups=['editors', 'admins'])
112
113 groups = passwd_db.groups('john')
114 assert 'users' in groups # Primary group
115 assert 'editors' in groups
116 assert 'admins' in groups
117
118
119class TestAuthentication:
120 """Test password hashing and authentication"""
121
122 def test_authenticate_success(self, passwd_db):
123 """Test successful authentication"""
124 passwd_db.useradd('john', password='secret123')
125
126 user = passwd_db.authenticate('john', 'secret123')
127 assert user is not None
128 assert user.username == 'john'
129
130 def test_authenticate_wrong_password(self, passwd_db):
131 """Test authentication with wrong password"""
132 passwd_db.useradd('john', password='secret123')
133
134 user = passwd_db.authenticate('john', 'wrongpassword')
135 assert user is None
136
137 def test_authenticate_nonexistent_user(self, passwd_db):
138 """Test authentication with nonexistent user"""
139 user = passwd_db.authenticate('nonexistent', 'password')
140 assert user is None
141
142 def test_passwd_changes_password(self, passwd_db):
143 """Test password change"""
144 passwd_db.useradd('john', password='oldpassword')
145
146 # Change password
147 result = passwd_db.passwd('john', 'newpassword')
148 assert result is True
149
150 # Old password fails
151 assert passwd_db.authenticate('john', 'oldpassword') is None
152
153 # New password works
154 user = passwd_db.authenticate('john', 'newpassword')
155 assert user is not None
156
157 def test_passwd_nonexistent_user(self, passwd_db):
158 """Test password change for nonexistent user"""
159 result = passwd_db.passwd('nonexistent', 'password')
160 assert result is False
161
162
163class TestUserManagement:
164 """Test user management (getuser, usermod, userdel)"""
165
166 def test_getuser_exists(self, passwd_db):
167 """Test getting existing user"""
168 passwd_db.useradd('john', password='secret', fullname='John Doe')
169
170 user = passwd_db.getuser('john')
171 assert user is not None
172 assert user.username == 'john'
173 assert user.fullname == 'John Doe'
174
175 def test_getuser_not_exists(self, passwd_db):
176 """Test getting nonexistent user"""
177 user = passwd_db.getuser('nonexistent')
178 assert user is None
179
180 def test_usermod_fullname(self, passwd_db):
181 """Test modifying user full name"""
182 passwd_db.useradd('john', password='secret', fullname='John Doe')
183
184 passwd_db.usermod('john', fullname='John Q. Doe')
185
186 user = passwd_db.getuser('john')
187 assert user.fullname == 'John Q. Doe'
188
189 def test_usermod_homedir_shell(self, passwd_db):
190 """Test modifying user homedir and shell"""
191 passwd_db.useradd('john', password='secret')
192
193 passwd_db.usermod('john', homedir='/var/www/john', shell='/bin/zsh')
194
195 user = passwd_db.getuser('john')
196 assert user.homedir == '/var/www/john'
197 assert user.shell == '/bin/zsh'
198
199 def test_usermod_add_groups(self, passwd_db):
200 """Test adding user to groups"""
201 passwd_db.groupadd('editors')
202 passwd_db.groupadd('admins')
203 passwd_db.useradd('john', password='secret')
204
205 passwd_db.usermod('john', add_groups=['editors', 'admins'])
206
207 groups = passwd_db.groups('john')
208 assert 'editors' in groups
209 assert 'admins' in groups
210
211 def test_usermod_remove_groups(self, passwd_db):
212 """Test removing user from groups"""
213 passwd_db.groupadd('editors')
214 passwd_db.useradd('john', password='secret', groups=['editors'])
215
216 assert 'editors' in passwd_db.groups('john')
217
218 passwd_db.usermod('john', remove_groups=['editors'])
219
220 assert 'editors' not in passwd_db.groups('john')
221
222 def test_usermod_nonexistent_user(self, passwd_db):
223 """Test modifying nonexistent user"""
224 result = passwd_db.usermod('nonexistent', fullname='New Name')
225 assert result is False
226
227 def test_userdel_success(self, passwd_db):
228 """Test deleting user"""
229 passwd_db.useradd('john', password='secret')
230 assert passwd_db.getuser('john') is not None
231
232 result = passwd_db.userdel('john')
233 assert result is True
234
235 assert passwd_db.getuser('john') is None
236 assert passwd_db.authenticate('john', 'secret') is None
237
238 def test_userdel_removes_from_groups(self, passwd_db):
239 """Test that deleting user removes from all groups"""
240 passwd_db.groupadd('editors')
241 passwd_db.useradd('john', password='secret', groups=['editors'])
242
243 # Verify user in group
244 groups = passwd_db.list_groups()
245 editors = [g for g in groups if g['groupname'] == 'editors'][0]
246 assert 'john' in editors['members']
247
248 # Delete user
249 passwd_db.userdel('john')
250
251 # Verify removed from group
252 groups = passwd_db.list_groups()
253 editors = [g for g in groups if g['groupname'] == 'editors'][0]
254 assert 'john' not in editors['members']
255
256 def test_userdel_nonexistent_user(self, passwd_db):
257 """Test deleting nonexistent user"""
258 result = passwd_db.userdel('nonexistent')
259 assert result is False
260
261
262class TestGroupManagement:
263 """Test group management"""
264
265 def test_groups_primary_group(self, passwd_db):
266 """Test that user is in primary group"""
267 passwd_db.useradd('john', password='secret')
268
269 groups = passwd_db.groups('john')
270 assert 'users' in groups # Default primary group
271
272 def test_groups_multiple(self, passwd_db):
273 """Test user with multiple groups"""
274 passwd_db.groupadd('editors')
275 passwd_db.groupadd('admins')
276 passwd_db.useradd('john', password='secret', groups=['editors', 'admins'])
277
278 groups = passwd_db.groups('john')
279 assert len(groups) == 3 # users, editors, admins
280 assert 'users' in groups
281 assert 'editors' in groups
282 assert 'admins' in groups
283
284 def test_groups_nonexistent_user(self, passwd_db):
285 """Test groups for nonexistent user"""
286 groups = passwd_db.groups('nonexistent')
287 assert groups == []
288
289 def test_groupadd_basic(self, passwd_db):
290 """Test basic group creation"""
291 group = passwd_db.groupadd('editors')
292
293 assert group['groupname'] == 'editors'
294 assert group['gid'] == 101 # After default 'users' group (100)
295 assert group['members'] == []
296
297 def test_groupadd_custom_gid(self, passwd_db):
298 """Test group creation with custom GID"""
299 group = passwd_db.groupadd('admins', gid=500)
300
301 assert group['groupname'] == 'admins'
302 assert group['gid'] == 500
303
304 def test_groupadd_duplicate_fails(self, passwd_db):
305 """Test that adding duplicate group fails"""
306 passwd_db.groupadd('editors')
307
308 with pytest.raises(ValueError, match="already exists"):
309 passwd_db.groupadd('editors')
310
311 def test_groupadd_increments_gid(self, passwd_db):
312 """Test that GIDs increment correctly"""
313 group1 = passwd_db.groupadd('editors')
314 group2 = passwd_db.groupadd('admins')
315 group3 = passwd_db.groupadd('moderators')
316
317 assert group1['gid'] == 101
318 assert group2['gid'] == 102
319 assert group3['gid'] == 103
320
321
322class TestListOperations:
323 """Test list_users and list_groups"""
324
325 def test_list_users_empty(self, passwd_db):
326 """Test listing users when empty"""
327 users = passwd_db.list_users()
328 assert users == []
329
330 def test_list_users_multiple(self, passwd_db):
331 """Test listing multiple users"""
332 passwd_db.useradd('john', password='secret')
333 passwd_db.useradd('jane', password='secret')
334 passwd_db.useradd('bob', password='secret')
335
336 users = passwd_db.list_users()
337 assert len(users) == 3
338
339 usernames = [u.username for u in users]
340 assert 'john' in usernames
341 assert 'jane' in usernames
342 assert 'bob' in usernames
343
344 def test_list_groups_default(self, passwd_db):
345 """Test listing groups includes default 'users' group"""
346 groups = passwd_db.list_groups()
347 assert len(groups) == 1
348 assert groups[0]['groupname'] == 'users'
349
350 def test_list_groups_multiple(self, passwd_db):
351 """Test listing multiple groups"""
352 passwd_db.groupadd('editors')
353 passwd_db.groupadd('admins')
354
355 groups = passwd_db.list_groups()
356 assert len(groups) == 3 # users, editors, admins
357
358 groupnames = [g['groupname'] for g in groups]
359 assert 'users' in groupnames
360 assert 'editors' in groupnames
361 assert 'admins' in groupnames
362
363 def test_list_groups_shows_members(self, passwd_db):
364 """Test that list_groups shows group members"""
365 passwd_db.groupadd('editors')
366 passwd_db.useradd('john', password='secret', groups=['editors'])
367 passwd_db.useradd('jane', password='secret', groups=['editors'])
368
369 groups = passwd_db.list_groups()
370 editors = [g for g in groups if g['groupname'] == 'editors'][0]
371
372 assert len(editors['members']) == 2
373 assert 'john' in editors['members']
374 assert 'jane' in editors['members']
375
376
377class TestPersistence:
378 """Test that data persists across instances"""
379
380 def test_user_persists(self, tmpdir):
381 """Test that user data persists"""
382 db1 = PasswdDB(etc_dir=tmpdir)
383 db1.useradd('john', password='secret', fullname='John Doe')
384
385 # Create new instance
386 db2 = PasswdDB(etc_dir=tmpdir)
387 user = db2.getuser('john')
388
389 assert user is not None
390 assert user.username == 'john'
391 assert user.fullname == 'John Doe'
392
393 def test_authentication_persists(self, tmpdir):
394 """Test that authentication works across instances"""
395 db1 = PasswdDB(etc_dir=tmpdir)
396 db1.useradd('john', password='secret123')
397
398 # Create new instance
399 db2 = PasswdDB(etc_dir=tmpdir)
400 user = db2.authenticate('john', 'secret123')
401
402 assert user is not None
403 assert user.username == 'john'
404
405 def test_groups_persist(self, tmpdir):
406 """Test that groups persist"""
407 db1 = PasswdDB(etc_dir=tmpdir)
408 db1.groupadd('editors')
409 db1.useradd('john', password='secret', groups=['editors'])
410
411 # Create new instance
412 db2 = PasswdDB(etc_dir=tmpdir)
413 groups = db2.groups('john')
414
415 assert 'editors' in groups
416
417
418class TestEdgeCases:
419 """Test edge cases and error conditions"""
420
421 def test_empty_username(self, passwd_db):
422 """Test handling of empty username"""
423 # dbbasic-tsv should handle this, but verify behavior
424 try:
425 passwd_db.useradd('', password='secret')
426 # If it doesn't raise, verify we can't authenticate
427 user = passwd_db.authenticate('', 'secret')
428 assert user is None or user.username == ''
429 except (ValueError, Exception):
430 pass # Expected behavior
431
432 def test_special_chars_in_username(self, passwd_db):
433 """Test usernames with special characters"""
434 user = passwd_db.useradd('john.doe', password='secret')
435 assert user.username == 'john.doe'
436
437 authenticated = passwd_db.authenticate('john.doe', 'secret')
438 assert authenticated is not None
439
440 def test_unicode_in_fullname(self, passwd_db):
441 """Test Unicode in full name"""
442 user = passwd_db.useradd('john', password='secret', fullname='Jöhn Döe 日本')
443 assert user.fullname == 'Jöhn Döe 日本'
444
445 retrieved = passwd_db.getuser('john')
446 assert retrieved.fullname == 'Jöhn Döe 日本'
447
448 def test_long_password(self, passwd_db):
449 """Test very long password"""
450 long_password = 'a' * 1000
451 passwd_db.useradd('john', password=long_password)
452
453 user = passwd_db.authenticate('john', long_password)
454 assert user is not None
455
456 def test_multiple_operations(self, passwd_db):
457 """Test complex sequence of operations"""
458 # Create groups
459 passwd_db.groupadd('editors')
460 passwd_db.groupadd('admins')
461
462 # Create users
463 passwd_db.useradd('john', password='secret1', groups=['editors'])
464 passwd_db.useradd('jane', password='secret2', groups=['editors', 'admins'])
465
466 # Modify users
467 passwd_db.usermod('john', fullname='John Doe', add_groups=['admins'])
468 passwd_db.passwd('jane', 'newsecret')
469
470 # Verify state
471 john = passwd_db.getuser('john')
472 assert john.fullname == 'John Doe'
473 assert 'admins' in passwd_db.groups('john')
474
475 jane_auth = passwd_db.authenticate('jane', 'newsecret')
476 assert jane_auth is not None
477
478 # Delete user
479 passwd_db.userdel('john')
480 assert passwd_db.getuser('john') is None
481
482 # Verify jane still works
483 jane = passwd_db.getuser('jane')
484 assert jane is not None