summaryrefslogtreecommitdiff
path: root/servers/gitlab_glab/tests/test_server.py
blob: a7e74a4e543a06df719ca8c3aac7f1be1348a8b5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
#!/usr/bin/env python3
"""Tests for the GitLab CLI MCP server implementation."""

import json
from unittest.mock import MagicMock, patch

from mcp_server_gitlab_glab.server import GitLabServer


class TestGitLabServer:
    """Tests for the GitLabServer class."""

    def test_init(self) -> None:
        """Test initialization of GitLabServer."""
        server = GitLabServer()
        assert hasattr(server, "auth_message")
        assert "glab auth login" in server.auth_message

    @patch("subprocess.run")
    def test_execute_glab_command_success(self, mock_run: MagicMock) -> None:
        """Test successful execution of a glab command."""
        # Mock successful command execution
        mock_process = MagicMock()
        mock_process.returncode = 0
        mock_process.stdout = "command output"
        mock_process.stderr = ""
        mock_run.return_value = mock_process

        server = GitLabServer()
        working_dir = "/test/directory"
        success, result = server.execute_glab_command(["--version"], working_dir)

        assert success is True
        assert result == "command output"
        mock_run.assert_called_once_with(
            ["glab", "--version"],
            capture_output=True,
            text=True,
            check=False,
            cwd=working_dir,
        )

    @patch("subprocess.run")
    def test_execute_glab_command_failure(self, mock_run: MagicMock) -> None:
        """Test failed execution of a glab command."""
        # Mock failed command execution
        mock_process = MagicMock()
        mock_process.returncode = 1
        mock_process.stdout = ""
        mock_process.stderr = "command failed"
        mock_run.return_value = mock_process

        server = GitLabServer()
        working_dir = "/test/directory"
        success, result = server.execute_glab_command(["--version"], working_dir)

        assert success is False
        assert result == {"error": "command failed"}
        mock_run.assert_called_once_with(
            ["glab", "--version"],
            capture_output=True,
            text=True,
            check=False,
            cwd=working_dir,
        )

    @patch("subprocess.run")
    def test_execute_glab_command_auth_error(self, mock_run: MagicMock) -> None:
        """Test authentication error during glab command execution."""
        # Mock authentication error
        mock_process = MagicMock()
        mock_process.returncode = 1
        mock_process.stdout = ""
        mock_process.stderr = "authentication required"
        mock_run.return_value = mock_process

        server = GitLabServer()
        working_dir = "/test/directory"
        success, result = server.execute_glab_command(["api", "/projects"], working_dir)

        assert success is False
        assert "error" in result
        assert "auth login" in result["error"]
        mock_run.assert_called_once_with(
            ["glab", "api", "/projects"],
            capture_output=True,
            text=True,
            check=False,
            cwd=working_dir,
        )

    @patch("subprocess.run")
    def test_execute_glab_command_not_found(self, mock_run: MagicMock) -> None:
        """Test glab command not found error."""
        # Mock FileNotFoundError
        mock_run.side_effect = FileNotFoundError("No such file or directory: 'glab'")

        server = GitLabServer()
        working_dir = "/test/directory"
        success, result = server.execute_glab_command(["--version"], working_dir)

        assert success is False
        assert "error" in result
        assert "glab command not found" in result["error"]

    @patch("subprocess.run")
    def test_execute_glab_api_command_success(self, mock_run: MagicMock) -> None:
        """Test successful execution of a glab api command with JSON response."""
        # Mock successful API command execution with JSON response
        mock_process = MagicMock()
        mock_process.returncode = 0
        mock_process.stdout = json.dumps([{"id": 1, "name": "test-project"}])
        mock_process.stderr = ""
        mock_run.return_value = mock_process

        server = GitLabServer()
        working_dir = "/test/directory"
        success, result = server.execute_glab_command(["api", "/projects"], working_dir)

        assert success is True
        assert isinstance(result, list)
        assert len(result) == 1
        assert result[0]["id"] == 1
        assert result[0]["name"] == "test-project"
        mock_run.assert_called_once_with(
            ["glab", "api", "/projects"],
            capture_output=True,
            text=True,
            check=False,
            cwd=working_dir,
        )

    @patch("subprocess.run")
    def test_execute_glab_api_command_invalid_json(self, mock_run: MagicMock) -> None:
        """Test glab api command with invalid JSON response."""
        # Mock API command execution with invalid JSON response
        mock_process = MagicMock()
        mock_process.returncode = 0
        mock_process.stdout = "invalid json"
        mock_process.stderr = ""
        mock_run.return_value = mock_process

        server = GitLabServer()
        working_dir = "/test/directory"
        success, result = server.execute_glab_command(["api", "/projects"], working_dir)

        assert success is False
        assert "error" in result
        assert "Failed to parse JSON response" in result["error"]

    @patch.object(GitLabServer, "execute_glab_command")
    def test_check_availability_success(self, mock_execute: MagicMock) -> None:
        """Test successful check_availability."""
        # Mock successful command execution
        mock_execute.return_value = (True, "glab version 1.0.0")

        server = GitLabServer()
        working_dir = "/test/directory"
        result = server.check_availability(working_dir)

        assert result["available"] is True
        assert result["version"] == "glab version 1.0.0"
        mock_execute.assert_called_once_with(["--version"], working_dir)

    @patch.object(GitLabServer, "execute_glab_command")
    def test_check_availability_failure(self, mock_execute: MagicMock) -> None:
        """Test failed check_availability."""
        # Mock failed command execution
        mock_execute.return_value = (False, {"error": "glab command not found"})

        server = GitLabServer()
        working_dir = "/test/directory"
        result = server.check_availability(working_dir)

        assert result["available"] is False
        assert result["error"] == "glab command not found"
        mock_execute.assert_called_once_with(["--version"], working_dir)

    @patch.object(GitLabServer, "execute_glab_command")
    def test_find_project_success(self, mock_execute: MagicMock) -> None:
        """Test successful find_project with a single project."""
        # Mock successful API response with a project
        mock_execute.return_value = (
            True,
            [
                {
                    "id": 1,
                    "name": "test-project",
                    "path_with_namespace": "group/test-project",
                    "web_url": "https://gitlab.com/group/test-project",
                    "description": "A test project",
                }
            ],
        )

        server = GitLabServer()
        working_dir = "/test/directory"
        result = server.find_project("test-project", working_dir)

        assert isinstance(result, list)
        assert len(result) == 1
        assert result[0]["id"] == 1
        assert result[0]["name"] == "test-project"
        assert result[0]["path_with_namespace"] == "group/test-project"
        assert result[0]["web_url"] == "https://gitlab.com/group/test-project"
        assert result[0]["description"] == "A test project"
        mock_execute.assert_called_once_with(
            ["api", "/projects?search_namespaces=true&search=test-project"], working_dir
        )

    @patch.object(GitLabServer, "execute_glab_command")
    def test_find_project_multiple_results(self, mock_execute: MagicMock) -> None:
        """Test successful find_project with multiple projects."""
        # Mock successful API response with multiple projects
        mock_execute.return_value = (
            True,
            [
                {
                    "id": 1,
                    "name": "test-project",
                    "path_with_namespace": "group/test-project",
                    "web_url": "https://gitlab.com/group/test-project",
                    "description": "A test project",
                },
                {
                    "id": 2,
                    "name": "test-project-2",
                    "path_with_namespace": "group/test-project-2",
                    "web_url": "https://gitlab.com/group/test-project-2",
                    "description": "Another test project",
                },
                {
                    "id": 3,
                    "name": "test-project-3",
                    "path_with_namespace": "group/test-project-3",
                    "web_url": "https://gitlab.com/group/test-project-3",
                    "description": "Yet another test project",
                },
            ],
        )

        server = GitLabServer()
        working_dir = "/test/directory"
        result = server.find_project("test-project", working_dir)

        assert isinstance(result, list)
        assert len(result) == 3

        # Check first project
        assert result[0]["id"] == 1
        assert result[0]["name"] == "test-project"
        assert result[0]["path_with_namespace"] == "group/test-project"

        # Check second project
        assert result[1]["id"] == 2
        assert result[1]["name"] == "test-project-2"
        assert result[1]["path_with_namespace"] == "group/test-project-2"

        # Check third project
        assert result[2]["id"] == 3
        assert result[2]["name"] == "test-project-3"
        assert result[2]["path_with_namespace"] == "group/test-project-3"

        mock_execute.assert_called_once_with(
            ["api", "/projects?search_namespaces=true&search=test-project"], working_dir
        )

    @patch.object(GitLabServer, "execute_glab_command")
    def test_find_project_not_found(self, mock_execute: MagicMock) -> None:
        """Test find_project with no results."""
        # Mock API response with no projects
        mock_execute.return_value = (True, [])

        server = GitLabServer()
        working_dir = "/test/directory"
        result = server.find_project("nonexistent-project", working_dir)

        assert "error" in result
        assert "not found" in result["error"]
        mock_execute.assert_called_once_with(
            [
                "api",
                "/projects?search_namespaces=true&search=nonexistent-project",
            ],
            working_dir
        )

    @patch.object(GitLabServer, "execute_glab_command")
    def test_find_project_api_error(self, mock_execute: MagicMock) -> None:
        """Test find_project with API error."""
        # Mock API error
        mock_execute.return_value = (False, {"error": "API error"})

        server = GitLabServer()
        working_dir = "/test/directory"
        result = server.find_project("test-project", working_dir)

        assert "error" in result
        assert result["error"] == "API error"
        mock_execute.assert_called_once_with(
            ["api", "/projects?search_namespaces=true&search=test-project"], working_dir
        )

    @patch.object(GitLabServer, "execute_glab_command")
    def test_search_issues_success(self, mock_execute: MagicMock) -> None:
        """Test successful issue search with default parameters."""
        # Mock successful command execution with JSON output
        mock_execute.return_value = (
            True,
            [
                {
                    "id": 1,
                    "iid": 101,
                    "title": "Test Issue 1",
                    "web_url": "https://gitlab.com/group/project/issues/101",
                    "state": "opened",
                    "created_at": "2025-01-01T00:00:00Z",
                    "updated_at": "2025-01-02T00:00:00Z",
                },
                {
                    "id": 2,
                    "iid": 102,
                    "title": "Test Issue 2",
                    "web_url": "https://gitlab.com/group/project/issues/102",
                    "state": "closed",
                    "created_at": "2025-01-03T00:00:00Z",
                    "updated_at": "2025-01-04T00:00:00Z",
                },
            ],
        )

        server = GitLabServer()
        working_dir = "/test/directory"
        result = server.search_issues(working_directory=working_dir)

        assert "issues" in result
        assert len(result["issues"]) == 2
        assert result["issues"][0]["id"] == 1
        assert result["issues"][0]["title"] == "Test Issue 1"
        assert result["issues"][1]["id"] == 2
        assert result["issues"][1]["title"] == "Test Issue 2"
        
        # Verify command was called with correct arguments
        mock_execute.assert_called_once_with(
            ["issue", "list", "-O", "json"],
            working_dir,
        )

    @patch.object(GitLabServer, "execute_glab_command")
    def test_search_issues_with_filters(self, mock_execute: MagicMock) -> None:
        """Test issue search with various filters."""
        # Mock successful command execution with JSON output
        mock_execute.return_value = (
            True,
            [
                {
                    "id": 1,
                    "iid": 101,
                    "title": "Test Issue 1",
                    "web_url": "https://gitlab.com/group/project/issues/101",
                    "state": "opened",
                    "created_at": "2025-01-01T00:00:00Z",
                    "updated_at": "2025-01-02T00:00:00Z",
                },
            ],
        )

        server = GitLabServer()
        working_dir = "/test/directory"
        result = server.search_issues(
            working_directory=working_dir,
            author="user1",
            assignee="user2",
            closed=True,
            confidential=True,
            group="test-group",
            issue_type="incident",
            iteration=123,
            label=["bug", "critical"],
            milestone="v1.0",
            not_assignee="user3",
            not_author="user4",
            not_label=["wontfix"],
            page=2,
            per_page=10,
            project="group/project",
        )

        assert "issues" in result
        assert len(result["issues"]) == 1
        assert result["issues"][0]["id"] == 1
        assert result["issues"][0]["title"] == "Test Issue 1"

        # Verify command was called with correct arguments
        mock_execute.assert_called_once_with(
            [
                "issue", "list", "-O", "json",
                "--author", "user1",
                "-a", "user2",
                "-c",
                "-C",
                "-g", "test-group",
                "-t", "incident",
                "-i", "123",
                "-l", "bug",
                "-l", "critical",
                "-m", "v1.0",
                "--not-assignee", "user3",
                "--not-author", "user4",
                "--not-label", "wontfix",
                "-p", "2",
                "-P", "10",
                "-R", "group/project",
            ],
            working_dir,
        )

    @patch.object(GitLabServer, "execute_glab_command")
    def test_search_issues_failure(self, mock_execute: MagicMock) -> None:
        """Test failed issue search."""
        # Mock failed command execution
        mock_execute.return_value = (False, {"error": "Failed to list issues"})

        server = GitLabServer()
        working_dir = "/test/directory"
        result = server.search_issues(working_directory=working_dir)

        assert "error" in result
        assert result["error"] == "Failed to list issues"
        mock_execute.assert_called_once_with(
            ["issue", "list", "-O", "json"],
            working_dir,
        )

    @patch.object(GitLabServer, "execute_glab_command")
    def test_search_issues_invalid_json(self, mock_execute: MagicMock) -> None:
        """Test issue search with invalid JSON response."""
        # Mock successful command execution but with invalid JSON
        mock_execute.return_value = (True, "invalid json")

        server = GitLabServer()
        working_dir = "/test/directory"
        result = server.search_issues(working_directory=working_dir)

        assert "error" in result
        assert result["error"] == "Failed to parse issues list"
        mock_execute.assert_called_once_with(
            ["issue", "list", "-O", "json"],
            working_dir,
        )

    @patch.object(GitLabServer, "execute_glab_command")
    def test_create_issue_success(self, mock_execute: MagicMock) -> None:
        """Test successful issue creation with required parameters."""
        # Mock successful command execution with actual glab output format
        mock_execute.return_value = (True, """- Creating issue in group/project
#1 Test Issue (less than a minute ago)
 https://gitlab.com/group/project/issues/1""")

        server = GitLabServer()
        working_dir = "/test/directory"
        result = server.create_issue(
            title="Test Issue",
            description="Test Description",
            working_directory=working_dir,
        )

        assert "url" in result
        assert result["url"] == "https://gitlab.com/group/project/issues/1"
        mock_execute.assert_called_once_with(
            ["issue", "create", "-y", "-t", "Test Issue", "-d", "Test Description"],
            working_dir,
        )

    @patch.object(GitLabServer, "execute_glab_command")
    def test_create_issue_with_all_params(self, mock_execute: MagicMock) -> None:
        """Test issue creation with all optional parameters."""
        # Mock successful command execution with actual glab output format
        mock_execute.return_value = (True, """- Creating issue in group/project
#2 Test Issue (less than a minute ago)
 https://gitlab.com/group/project/issues/2""")

        server = GitLabServer()
        working_dir = "/test/directory"
        result = server.create_issue(
            title="Test Issue",
            description="Test Description",
            working_directory=working_dir,
            labels=["bug", "critical"],
            assignee=["user1", "user2"],
            milestone="v1.0",
            epic_id=123,
            project="group/project",
        )

        assert "url" in result
        assert result["url"] == "https://gitlab.com/group/project/issues/2"
        mock_execute.assert_called_once_with(
            [
                "issue", "create", "-y",
                "-t", "Test Issue",
                "-d", "Test Description",
                "-l", "bug,critical",
                "-a", "user1",
                "-a", "user2",
                "-m", "v1.0",
                "--epic", "123",
                "-R", "group/project",
            ],
            working_dir,
        )

    @patch.object(GitLabServer, "execute_glab_command")
    def test_create_issue_failure(self, mock_execute: MagicMock) -> None:
        """Test failed issue creation."""
        # Mock failed command execution
        mock_execute.return_value = (False, {"error": "Failed to create issue"})

        server = GitLabServer()
        working_dir = "/test/directory"
        result = server.create_issue(
            title="Test Issue",
            description="Test Description",
            working_directory=working_dir,
        )

        assert "error" in result
        assert result["error"] == "Failed to create issue"
        mock_execute.assert_called_once_with(
            ["issue", "create", "-y", "-t", "Test Issue", "-d", "Test Description"],
            working_dir,
        )

    @patch.object(GitLabServer, "execute_glab_command")
    def test_create_issue_invalid_output(self, mock_execute: MagicMock) -> None:
        """Test issue creation with invalid output format."""
        # Mock successful command execution but without a URL in the output
        mock_execute.return_value = (True, """- Creating issue in group/project
#3 Test Issue (less than a minute ago)
 Invalid URL format""")

        server = GitLabServer()
        working_dir = "/test/directory"
        result = server.create_issue(
            title="Test Issue",
            description="Test Description",
            working_directory=working_dir,
        )

        assert "error" in result
        assert result["error"] == "Failed to extract issue URL from command output"
        mock_execute.assert_called_once_with(
            ["issue", "create", "-y", "-t", "Test Issue", "-d", "Test Description"],
            working_dir,
        )

    @patch("subprocess.run")
    def test_working_directory_is_used(self, mock_run: MagicMock) -> None:
        """Test that the working directory is correctly passed to subprocess.run."""
        # Mock successful command execution
        mock_process = MagicMock()
        mock_process.returncode = 0
        mock_process.stdout = "command output"
        mock_process.stderr = ""
        mock_run.return_value = mock_process

        server = GitLabServer()

        # Test with different working directories
        working_dirs = [
            "/home/user/project",
            "/tmp/gitlab",
            "/var/www/html",
        ]

        for working_dir in working_dirs:
            server.execute_glab_command(["status"], working_dir)
            mock_run.assert_called_with(
                ["glab", "status"],
                capture_output=True,
                text=True,
                check=False,
                cwd=working_dir,
            )

        # Verify the number of calls
        assert mock_run.call_count == len(working_dirs)

    @patch.object(GitLabServer, "execute_glab_command")
    def test_get_mr_diff_success_small(self, mock_execute: MagicMock) -> None:
        """Test successful MR diff retrieval with small diff."""
        # Mock successful command execution with small diff
        diff_content = """diff --git a/file.txt b/file.txt
index 1234567..abcdefg 100644
--- a/file.txt
+++ b/file.txt
@@ -1,3 +1,4 @@
 line 1
 line 2
+new line
 line 3"""
        mock_execute.return_value = (True, diff_content)

        server = GitLabServer()
        working_dir = "/test/directory"
        result = server.get_mr_diff(
            working_directory=working_dir,
            mr_id="123",
            color="never",
            raw=False,
            repo="group/project",
        )

        assert "diff" in result
        assert result["diff"] == diff_content
        assert result["size_kb"] < 1
        assert result["temp_file_path"] is None

        # Verify command was called with correct arguments
        mock_execute.assert_called_once_with(
            ["mr", "diff", "123", "--color", "never", "-R", "group/project"],
            working_dir,
        )

    @patch.object(GitLabServer, "execute_glab_command")
    def test_get_mr_diff_success_current_branch(self, mock_execute: MagicMock) -> None:
        """Test successful MR diff retrieval for current branch."""
        diff_content = "diff content"
        mock_execute.return_value = (True, diff_content)

        server = GitLabServer()
        working_dir = "/test/directory"
        result = server.get_mr_diff(working_directory=working_dir)

        assert "diff" in result
        assert result["diff"] == diff_content
        assert result["temp_file_path"] is None

        # Verify command was called without MR ID
        mock_execute.assert_called_once_with(
            ["mr", "diff", "--color", "never"],
            working_dir,
        )

    @patch.object(GitLabServer, "execute_glab_command")
    def test_get_mr_diff_with_raw_option(self, mock_execute: MagicMock) -> None:
        """Test MR diff retrieval with raw option."""
        diff_content = "raw diff content"
        mock_execute.return_value = (True, diff_content)

        server = GitLabServer()
        working_dir = "/test/directory"
        result = server.get_mr_diff(
            working_directory=working_dir,
            mr_id="branch-name",
            color="auto",
            raw=True,
        )

        assert "diff" in result
        assert result["diff"] == diff_content

        # Verify command was called with raw option
        mock_execute.assert_called_once_with(
            ["mr", "diff", "branch-name", "--color", "auto", "--raw"],
            working_dir,
        )

    @patch("tempfile.NamedTemporaryFile")
    @patch.object(GitLabServer, "execute_glab_command")
    def test_get_mr_diff_large_diff_temp_file(
        self, mock_execute: MagicMock, mock_temp_file: MagicMock
    ) -> None:
        """Test MR diff retrieval with large diff that gets saved to temp file."""
        # Create a large diff content (over 100KB)
        large_diff = "x" * (101 * 1024)  # 101 KB
        mock_execute.return_value = (True, large_diff)

        # Mock temporary file
        mock_file = MagicMock()
        mock_file.name = "/tmp/mr_diff_12345.diff"
        mock_temp_file.return_value.__enter__.return_value = mock_file

        server = GitLabServer()
        working_dir = "/test/directory"
        result = server.get_mr_diff(
            working_directory=working_dir,
            mr_id="123",
            max_size_kb=100,
        )

        assert result["diff_too_large"] is True
        assert result["size_kb"] > 100
        assert result["max_size_kb"] == 100
        assert result["temp_file_path"] == "/tmp/mr_diff_12345.diff"
        assert "message" in result

        # Verify temp file was created with correct parameters
        mock_temp_file.assert_called_once_with(
            mode='w',
            suffix='.diff',
            prefix='mr_diff_',
            delete=False,
            encoding='utf-8'
        )
        mock_file.write.assert_called_once_with(large_diff)

    @patch("tempfile.NamedTemporaryFile")
    @patch.object(GitLabServer, "execute_glab_command")
    def test_get_mr_diff_large_diff_temp_file_error(
        self, mock_execute: MagicMock, mock_temp_file: MagicMock
    ) -> None:
        """Test MR diff retrieval with large diff and temp file creation error."""
        # Create a large diff content
        large_diff = "x" * (101 * 1024)  # 101 KB
        mock_execute.return_value = (True, large_diff)

        # Mock temporary file creation error
        mock_temp_file.side_effect = Exception("Permission denied")

        server = GitLabServer()
        working_dir = "/test/directory"
        result = server.get_mr_diff(
            working_directory=working_dir,
            mr_id="123",
            max_size_kb=100,
        )

        assert "error" in result
        assert "too large" in result["error"]
        assert "Permission denied" in result["error"]

    @patch.object(GitLabServer, "execute_glab_command")
    def test_get_mr_diff_command_failure(self, mock_execute: MagicMock) -> None:
        """Test MR diff retrieval with command failure."""
        mock_execute.return_value = (False, {"error": "MR not found"})

        server = GitLabServer()
        working_dir = "/test/directory"
        result = server.get_mr_diff(working_directory=working_dir, mr_id="999")

        assert "error" in result
        assert result["error"] == "MR not found"

    @patch.object(GitLabServer, "execute_glab_command")
    def test_get_mr_diff_invalid_color_option(self, mock_execute: MagicMock) -> None:
        """Test MR diff with invalid color option skips color parameter."""
        diff_content = "diff content"
        mock_execute.return_value = (True, diff_content)

        server = GitLabServer()
        working_dir = "/test/directory"
        result = server.get_mr_diff(
            working_directory=working_dir,
            mr_id="123",
            color="invalid",  # Invalid color option
        )

        assert "diff" in result
        # Invalid color options should be filtered out, only valid ones are added
        mock_execute.assert_called_once_with(
            ["mr", "diff", "123"],
            working_dir,
        )