|
| 1 | +"""Tests for the mcpserver Context class.""" |
| 2 | + |
| 3 | +from mcp.server.auth.middleware.auth_context import auth_context_var |
| 4 | +from mcp.server.auth.middleware.bearer_auth import AuthenticatedUser |
| 5 | +from mcp.server.auth.provider import AccessToken |
| 6 | +from mcp.server.mcpserver import Context |
| 7 | + |
| 8 | + |
| 9 | +class TestContextSubject: |
| 10 | + """Tests for Context.subject property.""" |
| 11 | + |
| 12 | + def test_subject_returns_none_when_unauthenticated(self): |
| 13 | + ctx = Context() |
| 14 | + assert ctx.subject is None |
| 15 | + |
| 16 | + def test_subject_returns_none_when_token_has_no_subject(self): |
| 17 | + user = AuthenticatedUser(AccessToken(token="tok", client_id="client", scopes=["read"])) |
| 18 | + token = auth_context_var.set(user) |
| 19 | + try: |
| 20 | + ctx = Context() |
| 21 | + assert ctx.subject is None |
| 22 | + finally: |
| 23 | + auth_context_var.reset(token) |
| 24 | + |
| 25 | + def test_subject_returns_value_from_access_token(self): |
| 26 | + user = AuthenticatedUser(AccessToken(token="tok", client_id="client", scopes=["read"], subject="user-123")) |
| 27 | + token = auth_context_var.set(user) |
| 28 | + try: |
| 29 | + ctx = Context() |
| 30 | + assert ctx.subject == "user-123" |
| 31 | + finally: |
| 32 | + auth_context_var.reset(token) |
| 33 | + |
| 34 | + def test_subject_reflects_current_context(self): |
| 35 | + ctx = Context() |
| 36 | + assert ctx.subject is None |
| 37 | + |
| 38 | + user = AuthenticatedUser(AccessToken(token="a", client_id="c", scopes=[], subject="alice")) |
| 39 | + cv_token = auth_context_var.set(user) |
| 40 | + try: |
| 41 | + assert ctx.subject == "alice" |
| 42 | + finally: |
| 43 | + auth_context_var.reset(cv_token) |
| 44 | + |
| 45 | + assert ctx.subject is None |
0 commit comments