|
8 | 8 |
|
9 | 9 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
10 | 10 |
|
11 | | -from plutus_agent import db, metering, pricing, demo, reports |
| 11 | +from plutus_agent import db, metering, pricing, demo, reports, config as cfgmod |
12 | 12 | from plutus_agent.billing import handle_webhook_event |
| 13 | +from plutus_agent.utils import strict_int |
| 14 | +from plutus_agent.server import auth as authmod |
13 | 15 |
|
14 | 16 |
|
15 | 17 | _PATHS = {} # id(conn) -> file path, since sqlite3.Connection forbids attrs |
@@ -399,5 +401,178 @@ def test_hook_meters_payload(self): |
399 | 401 | os.environ.pop("PLUTUS_ORG", None) |
400 | 402 |
|
401 | 403 |
|
| 404 | +class TestPolishIssue37(unittest.TestCase): |
| 405 | + """Tests for the polish punch-list fixes (issue #37).""" |
| 406 | + |
| 407 | + def test_strict_int_accepts_integers(self): |
| 408 | + """strict_int accepts int and integer-valued strings.""" |
| 409 | + self.assertEqual(strict_int(5), 5) |
| 410 | + self.assertEqual(strict_int('5'), 5) |
| 411 | + self.assertEqual(strict_int(0), 0) |
| 412 | + self.assertEqual(strict_int('0'), 0) |
| 413 | + self.assertEqual(strict_int(-10), -10) |
| 414 | + self.assertEqual(strict_int('-10'), -10) |
| 415 | + |
| 416 | + def test_strict_int_rejects_floats(self): |
| 417 | + """strict_int rejects float values and float-bearing strings.""" |
| 418 | + with self.assertRaises(ValueError): |
| 419 | + strict_int(1.9) |
| 420 | + with self.assertRaises(ValueError): |
| 421 | + strict_int('1.9') |
| 422 | + with self.assertRaises(ValueError): |
| 423 | + strict_int(1.0) |
| 424 | + with self.assertRaises(ValueError): |
| 425 | + strict_int('1.0') |
| 426 | + |
| 427 | + def test_db_wiring_honors_env(self): |
| 428 | + """db_path() honors PLUTUS_DB environment variable.""" |
| 429 | + orig = os.environ.get('PLUTUS_DB') |
| 430 | + try: |
| 431 | + test_path = '/tmp/test_plutus_custom.db' |
| 432 | + os.environ['PLUTUS_DB'] = test_path |
| 433 | + self.assertEqual(str(cfgmod.db_path()), test_path) |
| 434 | + finally: |
| 435 | + if orig is None: |
| 436 | + os.environ.pop('PLUTUS_DB', None) |
| 437 | + else: |
| 438 | + os.environ['PLUTUS_DB'] = orig |
| 439 | + |
| 440 | + def test_config_save_creates_backup(self): |
| 441 | + """config.save() creates a timestamped backup when file exists.""" |
| 442 | + import tempfile |
| 443 | + import shutil |
| 444 | + from pathlib import Path |
| 445 | + |
| 446 | + home = tempfile.mkdtemp() |
| 447 | + orig_home = os.environ.get('PLUTUS_HOME') |
| 448 | + try: |
| 449 | + os.environ['PLUTUS_HOME'] = home |
| 450 | + cfg_path = cfgmod.config_path() |
| 451 | + |
| 452 | + # First save: no backup should be created |
| 453 | + initial_cfg = {'test': 'value1'} |
| 454 | + cfgmod.save(initial_cfg) |
| 455 | + self.assertTrue(cfg_path.exists()) |
| 456 | + backups = list(cfg_path.parent.glob('config.yaml.bak-*')) |
| 457 | + self.assertEqual(len(backups), 0, "No backup on first save") |
| 458 | + |
| 459 | + # Second save: backup should be created |
| 460 | + import time |
| 461 | + time.sleep(1.1) # Ensure different timestamp |
| 462 | + updated_cfg = {'test': 'value2'} |
| 463 | + cfgmod.save(updated_cfg) |
| 464 | + backups = list(cfg_path.parent.glob('config.yaml.bak-*')) |
| 465 | + self.assertGreaterEqual(len(backups), 1, "At least one backup after second save") |
| 466 | + |
| 467 | + # Third save: another backup |
| 468 | + time.sleep(1.1) |
| 469 | + cfgmod.save({'test': 'value3'}) |
| 470 | + backups = list(cfg_path.parent.glob('config.yaml.bak-*')) |
| 471 | + self.assertGreaterEqual(len(backups), 2, "At least two backups after third save") |
| 472 | + finally: |
| 473 | + if orig_home is None: |
| 474 | + os.environ.pop('PLUTUS_HOME', None) |
| 475 | + else: |
| 476 | + os.environ['PLUTUS_HOME'] = orig_home |
| 477 | + shutil.rmtree(home, ignore_errors=True) |
| 478 | + |
| 479 | + def test_email_verified_requires_truthy(self): |
| 480 | + """email_verified must be explicitly True or 'true', missing/False rejected.""" |
| 481 | + cfg = { |
| 482 | + 'auth': { |
| 483 | + 'google_client_id': 'test-client-id', |
| 484 | + 'google_client_secret': 'test-secret', |
| 485 | + 'base_url': 'http://localhost:8420' |
| 486 | + } |
| 487 | + } |
| 488 | + |
| 489 | + # Missing email_verified should raise |
| 490 | + claims_missing = { |
| 491 | + 'aud': 'test-client-id', |
| 492 | + 'iss': 'https://accounts.google.com', |
| 493 | + 'exp': time.time() + 3600, |
| 494 | + 'nonce': 'test-nonce', |
| 495 | + 'email': 'test@example.com' |
| 496 | + # email_verified missing |
| 497 | + } |
| 498 | + with self.assertRaises(authmod.AuthError) as ctx: |
| 499 | + authmod._claims_from_id_token.__wrapped__ = authmod._claims_from_id_token |
| 500 | + # We need to mock just the claims extraction part |
| 501 | + # Since _claims_from_id_token expects a JWT, let's test directly |
| 502 | + import base64 |
| 503 | + import json |
| 504 | + |
| 505 | + def make_fake_token(claims): |
| 506 | + # Create a fake JWT (we won't verify signature) |
| 507 | + header = base64.urlsafe_b64encode(json.dumps({'alg': 'RS256'}).encode()).decode().rstrip('=') |
| 508 | + payload = base64.urlsafe_b64encode(json.dumps(claims).encode()).decode().rstrip('=') |
| 509 | + return f"{header}.{payload}.fake_signature" |
| 510 | + |
| 511 | + fake_token = make_fake_token(claims_missing) |
| 512 | + authmod._claims_from_id_token(fake_token, cfg, 'test-nonce') |
| 513 | + self.assertIn('not verified', str(ctx.exception)) |
| 514 | + |
| 515 | + # False should raise |
| 516 | + claims_false = claims_missing.copy() |
| 517 | + claims_false['email_verified'] = False |
| 518 | + with self.assertRaises(authmod.AuthError) as ctx: |
| 519 | + fake_token = make_fake_token(claims_false) |
| 520 | + authmod._claims_from_id_token(fake_token, cfg, 'test-nonce') |
| 521 | + self.assertIn('not verified', str(ctx.exception)) |
| 522 | + |
| 523 | + # True should pass |
| 524 | + claims_true = claims_missing.copy() |
| 525 | + claims_true['email_verified'] = True |
| 526 | + fake_token = make_fake_token(claims_true) |
| 527 | + result = authmod._claims_from_id_token(fake_token, cfg, 'test-nonce') |
| 528 | + self.assertEqual(result['email'], 'test@example.com') |
| 529 | + |
| 530 | + # 'true' string should pass |
| 531 | + claims_str = claims_missing.copy() |
| 532 | + claims_str['email_verified'] = 'true' |
| 533 | + fake_token = make_fake_token(claims_str) |
| 534 | + result = authmod._claims_from_id_token(fake_token, cfg, 'test-nonce') |
| 535 | + self.assertEqual(result['email'], 'test@example.com') |
| 536 | + |
| 537 | + def test_minimal_yaml_read_roundtrip(self): |
| 538 | + """_minimal_yaml_read can parse simple YAML config.""" |
| 539 | + import tempfile |
| 540 | + from pathlib import Path |
| 541 | + |
| 542 | + fd, path_str = tempfile.mkstemp(suffix='.yaml') |
| 543 | + os.close(fd) |
| 544 | + path = Path(path_str) |
| 545 | + |
| 546 | + try: |
| 547 | + # Write a simple YAML config |
| 548 | + yaml_content = """server: |
| 549 | + host: 127.0.0.1 |
| 550 | + port: 8420 |
| 551 | +billing: |
| 552 | + currency: usd |
| 553 | + stripe_price_pro: price_123 |
| 554 | +alerts: |
| 555 | + enabled: false |
| 556 | + low_balance_usd: 10.0 |
| 557 | +""" |
| 558 | + path.write_text(yaml_content, encoding='utf-8') |
| 559 | + |
| 560 | + # Read it back with the minimal reader |
| 561 | + result = cfgmod._minimal_yaml_read(path) |
| 562 | + |
| 563 | + # Verify structure |
| 564 | + self.assertIn('server', result) |
| 565 | + self.assertIn('billing', result) |
| 566 | + self.assertIn('alerts', result) |
| 567 | + self.assertEqual(result['server']['host'], '127.0.0.1') |
| 568 | + self.assertEqual(result['server']['port'], 8420) |
| 569 | + self.assertEqual(result['billing']['currency'], 'usd') |
| 570 | + self.assertEqual(result['billing']['stripe_price_pro'], 'price_123') |
| 571 | + self.assertEqual(result['alerts']['enabled'], False) |
| 572 | + self.assertEqual(result['alerts']['low_balance_usd'], 10.0) |
| 573 | + finally: |
| 574 | + path.unlink() |
| 575 | + |
| 576 | + |
402 | 577 | if __name__ == "__main__": |
403 | 578 | unittest.main() |
0 commit comments