-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy pathtest_views.py
More file actions
863 lines (732 loc) · 29.9 KB
/
Copy pathtest_views.py
File metadata and controls
863 lines (732 loc) · 29.9 KB
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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
import unittest
from unittest.mock import patch, MagicMock
import flask
import requests
import datetime
import tempfile
from pathlib import Path
from webapp.views import (
json_asset_query,
build_events_index,
build_canonical_days_index,
append_utms_cookie_to_ubuntu_links,
get_knowledge_sections,
)
class TestViews(unittest.TestCase):
def setUp(self):
self.app = flask.Flask(__name__)
self.app_context = self.app.app_context()
self.app_context.push()
def tearDown(self):
self.app_context.pop()
@patch("webapp.views.requests.get")
def test_json_asset_query_success(self, mock_get):
"""Test successful JSON asset retrieval"""
# Mock successful response
mock_response = MagicMock()
mock_response.json.return_value = {"key": "value"}
mock_get.return_value = mock_response
with self.app.test_request_context():
result = json_asset_query("test.json")
self.assertEqual(result.get_json(), {"key": "value"})
mock_get.assert_called_once_with(
url="https://assets.ubuntu.com/v1/test.json"
)
@patch("webapp.views.requests.get")
@patch("webapp.views.flask.current_app")
def test_json_asset_query_http_error(self, mock_app, mock_get):
"""Test HTTP error handling"""
# Mock HTTPError
mock_get.side_effect = requests.HTTPError("404 Not Found")
mock_sentry = MagicMock()
mock_app.extensions = {"sentry": mock_sentry}
with self.app.test_request_context():
result = json_asset_query("nonexistent.json")
self.assertEqual(result[1], 404)
self.assertEqual(
result[0].get_json(), {"error": "Asset not found"}
)
mock_sentry.captureException.assert_called_once()
# Events Index Tests
@patch("webapp.views.flask.render_template")
def test_events_index_success(self, mock_render_template):
"""Test successful events index retrieval"""
mock_engage_docs = MagicMock()
# Mock event data
events_data = [
{
"topic_name": "Ubuntu 24.04 Release",
"event_location": "San Francisco",
"event_date": "15/02/2027",
"path": "/engage/event-1",
},
{
"topic_name": "Cloud Native Conference",
"event_location": "New York",
"event_date": "20/03/2027",
"path": "/engage/event-2",
},
]
mock_engage_docs.get_index.return_value = (events_data, 2, 2, 2)
mock_render_template.return_value = "Rendered template"
events_index = build_events_index(mock_engage_docs)
with self.app.test_request_context():
events_index()
mock_render_template.assert_called_once()
call_kwargs = mock_render_template.call_args[1]
self.assertIn("metadata", call_kwargs)
metadata = call_kwargs["metadata"]
self.assertEqual(len(metadata), 2)
@patch("webapp.views.flask.render_template")
def test_events_index_filters_without_topic_name(
self, mock_render_template
):
"""Test that events without topic_name are filtered out"""
mock_engage_docs = MagicMock()
events_data = [
{
"topic_name": "Valid Event",
"event_location": "San Francisco",
"event_date": "15/02/2027",
},
{"event_location": "New York", "event_date": "20/03/2027"},
]
mock_engage_docs.get_index.return_value = (events_data, 2, 2, 2)
mock_render_template.return_value = "Rendered template"
events_index = build_events_index(mock_engage_docs)
with self.app.test_request_context():
events_index()
call_kwargs = mock_render_template.call_args[1]
metadata = call_kwargs["metadata"]
self.assertEqual(len(metadata), 1)
self.assertEqual(metadata[0]["topic_name"], "Valid Event")
@patch("webapp.views.flask.render_template")
@patch("webapp.views.geocode_location")
def test_events_index_location_search(
self, mock_geocode, mock_render_template
):
"""Test events index with location-based search"""
mock_engage_docs = MagicMock()
events_data = [
{
"topic_name": "Event 1",
"event_location": "San Francisco",
"event_date": "15/02/2027",
},
{
"topic_name": "Event 2",
"event_location": "New York",
"event_date": "20/03/2027",
},
]
mock_engage_docs.get_index.return_value = (events_data, 2, 2, 2)
# Mock geocode location results
mock_location = MagicMock()
mock_location.latitude = 37.7749
mock_location.longitude = -122.4194
mock_geocode.return_value = mock_location
mock_render_template.return_value = "Rendered template"
events_index = build_events_index(mock_engage_docs)
with self.app.test_request_context("/?q=San%20Francisco"):
events_index()
call_kwargs = mock_render_template.call_args[1]
self.assertIn("metadata", call_kwargs)
@patch("webapp.views.flask.render_template")
@patch("webapp.views.geocode_location")
def test_events_index_keyword_search(
self, mock_geocode, mock_render_template
):
"""Test events index with keyword-based search"""
mock_engage_docs = MagicMock()
events_data = [
{
"topic_name": "Ubuntu Release Event",
"event_location": "San Francisco",
"event_date": "15/02/2027",
},
{
"topic_name": "Kubernetes Workshop",
"event_location": "New York",
"event_date": "20/03/2027",
},
]
mock_engage_docs.get_index.return_value = (events_data, 2, 2, 2)
mock_render_template.return_value = "Rendered template"
# Return None to trigger keyword search instead of geolocation search
mock_geocode.return_value = None
events_index = build_events_index(mock_engage_docs)
with self.app.test_request_context("/?q=Ubuntu"):
events_index()
call_kwargs = mock_render_template.call_args[1]
metadata = call_kwargs["metadata"]
self.assertEqual(len(metadata), 1)
self.assertEqual(metadata[0]["topic_name"], "Ubuntu Release Event")
@patch("webapp.views.flask.render_template")
def test_events_index_filters_past_events(self, mock_render_template):
"""Test that past events are filtered out"""
mock_engage_docs = MagicMock()
# Create dates: one in past, one in future
past_date = (
datetime.datetime.now() - datetime.timedelta(days=10)
).strftime("%d/%m/%Y")
future_date = (
datetime.datetime.now() + datetime.timedelta(days=10)
).strftime("%d/%m/%Y")
events_data = [
{
"topic_name": "Past Event",
"event_location": "San Francisco",
"event_date": past_date,
},
{
"topic_name": "Future Event",
"event_location": "New York",
"event_date": future_date,
},
]
mock_engage_docs.get_index.return_value = (events_data, 2, 2, 2)
mock_render_template.return_value = "Rendered template"
events_index = build_events_index(mock_engage_docs)
with self.app.test_request_context():
events_index()
call_kwargs = mock_render_template.call_args[1]
metadata = call_kwargs["metadata"]
self.assertEqual(len(metadata), 1)
self.assertEqual(metadata[0]["topic_name"], "Future Event")
# Canonical Days Tests
@patch("webapp.views.flask.render_template")
def test_canonical_days_index_success(self, mock_render_template):
"""Test successful canonical days index retrieval"""
mock_engage_docs = MagicMock()
future_date = (
datetime.datetime.now() + datetime.timedelta(days=30)
).strftime("%d/%m/%Y")
roadshow_data = [
{
"topic_name": "Canonical Days - London",
"event_location": "London",
"event_region": "EMEA",
"event_date": future_date,
"path": "/engage/roadshow-london",
},
{
"topic_name": "Canonical Days - Sydney",
"event_location": "Sydney",
"event_region": "APAC",
"event_date": future_date,
"path": "/engage/roadshow-sydney",
},
]
mock_engage_docs.get_index.return_value = (roadshow_data, 2, 2, 2)
mock_render_template.return_value = "Rendered template"
canonical_days_index = build_canonical_days_index(mock_engage_docs)
with self.app.test_request_context():
canonical_days_index()
call_kwargs = mock_render_template.call_args[1]
self.assertIn("metadata", call_kwargs)
metadata = call_kwargs["metadata"]
self.assertEqual(len(metadata), 2)
# Verify get_index was called with correct parameters
mock_engage_docs.get_index.assert_called_once()
call_args = mock_engage_docs.get_index.call_args
self.assertEqual(call_args[1]["tag_value"], "roadshow")
self.assertEqual(call_args[1]["key"], "type")
self.assertEqual(call_args[1]["value"], "roadshow")
@patch("webapp.views.flask.render_template")
def test_canonical_days_filters_incomplete_events(
self, mock_render_template
):
"""Test that events without required metadata are filtered"""
mock_engage_docs = MagicMock()
future_date = (
datetime.datetime.now() + datetime.timedelta(days=30)
).strftime("%d/%m/%Y")
roadshow_data = [
{
"topic_name": "Complete Event",
"event_location": "London",
"event_region": "EMEA",
"event_date": future_date,
},
{
"topic_name": "Incomplete Event",
"event_location": "Sydney",
# Missing event_region
"event_date": future_date,
},
{
"topic_name": "Another Incomplete",
"event_location": "Tokyo",
"event_region": "APAC",
# Missing event_date
},
]
mock_engage_docs.get_index.return_value = (roadshow_data, 3, 3, 3)
mock_render_template.return_value = "Rendered template"
canonical_days_index = build_canonical_days_index(mock_engage_docs)
with self.app.test_request_context():
canonical_days_index()
call_kwargs = mock_render_template.call_args[1]
metadata = call_kwargs["metadata"]
self.assertEqual(len(metadata), 1)
self.assertEqual(metadata[0]["topic_name"], "Complete Event")
@patch("webapp.views.flask.render_template")
def test_canonical_days_filters_past_events(self, mock_render_template):
"""Test that past roadshow events are filtered out"""
mock_engage_docs = MagicMock()
past_date = (
datetime.datetime.now() - datetime.timedelta(days=30)
).strftime("%d/%m/%Y")
future_date = (
datetime.datetime.now() + datetime.timedelta(days=30)
).strftime("%d/%m/%Y")
roadshow_data = [
{
"topic_name": "Past Roadshow",
"event_location": "London",
"event_region": "EMEA",
"event_date": past_date,
},
{
"topic_name": "Future Roadshow",
"event_location": "Sydney",
"event_region": "APAC",
"event_date": future_date,
},
]
mock_engage_docs.get_index.return_value = (roadshow_data, 2, 2, 2)
mock_render_template.return_value = "Rendered template"
canonical_days_index = build_canonical_days_index(mock_engage_docs)
with self.app.test_request_context():
canonical_days_index()
call_kwargs = mock_render_template.call_args[1]
metadata = call_kwargs["metadata"]
self.assertEqual(len(metadata), 1)
self.assertEqual(metadata[0]["topic_name"], "Future Roadshow")
@patch("webapp.views.flask.render_template")
def test_canonical_days_sorts_by_earliest_event(
self, mock_render_template
):
"""Test that roadshow events are sorted by earliest date"""
mock_engage_docs = MagicMock()
date1 = (
datetime.datetime.now() + datetime.timedelta(days=10)
).strftime("%d/%m/%Y")
date2 = (
datetime.datetime.now() + datetime.timedelta(days=30)
).strftime("%d/%m/%Y")
roadshow_data = [
{
"topic_name": "Earlier Event",
"event_location": "London",
"event_region": "EMEA",
"event_date": date1,
},
{
"topic_name": "Later Event",
"event_location": "Sydney",
"event_region": "APAC",
"event_date": date2,
},
]
mock_engage_docs.get_index.return_value = (roadshow_data, 2, 2, 2)
mock_render_template.return_value = "Rendered template"
canonical_days_index = build_canonical_days_index(mock_engage_docs)
with self.app.test_request_context():
canonical_days_index()
call_kwargs = mock_render_template.call_args[1]
metadata = call_kwargs["metadata"]
self.assertEqual(metadata[0]["topic_name"], "Earlier Event")
self.assertEqual(metadata[1]["topic_name"], "Later Event")
@patch("webapp.views.flask.render_template")
def test_canonical_days_prefixes_engage_paths_with_full_url(
self, mock_render_template
):
"""Test that engage paths are prefixed with full URL"""
mock_engage_docs = MagicMock()
future_date = (
datetime.datetime.now() + datetime.timedelta(days=30)
).strftime("%d/%m/%Y")
roadshow_data = [
{
"topic_name": "Roadshow",
"event_location": "London",
"event_region": "EMEA",
"event_date": future_date,
"path": "/engage/roadshow",
}
]
mock_engage_docs.get_index.return_value = (roadshow_data, 1, 1, 1)
mock_render_template.return_value = "Rendered template"
canonical_days_index = build_canonical_days_index(mock_engage_docs)
with self.app.test_request_context():
canonical_days_index()
call_kwargs = mock_render_template.call_args[1]
metadata = call_kwargs["metadata"]
self.assertEqual(
metadata[0]["path"], "https://ubuntu.com/engage/roadshow"
)
# append_utms_cookie_to_ubuntu_links Tests
def test_append_utms_cookie_no_cookie(self):
"""
Test that function returns unchanged response
when no cookie exists
"""
with self.app.test_request_context():
response = MagicMock()
response.mimetype = "text/html"
response.is_sequence = True
response.get_data.return_value = (
'<a href="https://ubuntu.com/test">Link</a>'
)
result = append_utms_cookie_to_ubuntu_links(response)
self.assertEqual(result, response)
response.set_data.assert_not_called()
def test_append_utms_cookie_non_html_response(self):
"""
Test that function returns unchanged response for non-HTML content
"""
with self.app.test_request_context():
response = MagicMock()
response.mimetype = "application/json"
response.is_sequence = True
result = append_utms_cookie_to_ubuntu_links(response)
self.assertEqual(result, response)
def test_append_utms_cookie_simple_append_with_question_mark(self):
"""
Test appending cookie to URL without existing parameters
"""
with self.app.test_request_context(
"/", headers={"Cookie": "utms=utm_source:test1&utm_medium:test2"}
):
response = MagicMock()
response.mimetype = "text/html"
response.is_sequence = True
html = '<a href="https://ubuntu.com/test">Link</a>'
response.get_data.return_value = html
append_utms_cookie_to_ubuntu_links(response)
# Verify set_data was called
response.set_data.assert_called_once()
updated_html = response.set_data.call_args[0][0]
self.assertIn("utm_source:test1&utm_medium:test2", updated_html)
self.assertIn("?", updated_html)
def test_append_utms_cookie_simple_append_with_ampersand(self):
"""
Test appending cookie to URL with existing parameters
"""
with self.app.test_request_context(
"/", headers={"Cookie": "utms=utm_source:test1"}
):
response = MagicMock()
response.mimetype = "text/html"
response.is_sequence = True
html = '<a href="https://ubuntu.com/test?existing=param">Link</a>'
response.get_data.return_value = html
append_utms_cookie_to_ubuntu_links(response)
updated_html = response.set_data.call_args[0][0]
self.assertIn("existing=param&utm_source:test1", updated_html)
def test_append_utms_cookie_multiple_links(self):
"""
Test appending cookie to multiple ubuntu.com links
"""
with self.app.test_request_context(
"/", headers={"Cookie": "utms=utm_source:test1"}
):
response = MagicMock()
response.mimetype = "text/html"
response.is_sequence = True
html = """
<a href="https://ubuntu.com/test1">Link 1</a>
<a href="https://ubuntu.com/test2">Link 2</a>
<a href="https://other.com/test">Other Link</a>
"""
response.get_data.return_value = html
append_utms_cookie_to_ubuntu_links(response)
updated_html = response.set_data.call_args[0][0]
# Count occurrences of utm_source
utm_count = updated_html.count("utm_source:test1")
self.assertEqual(utm_count, 2)
# Verify non-ubuntu.com link is unchanged
self.assertIn('href="https://other.com/test"', updated_html)
def test_append_utms_cookie_ignores_non_ubuntu_links(self):
"""
Test that non-ubuntu.com links are not modified
"""
with self.app.test_request_context(
"/", headers={"Cookie": "utms=utm_source:test1"}
):
response = MagicMock()
response.mimetype = "text/html"
response.is_sequence = True
html = '<a href="https://google.com/test">Link</a>'
response.get_data.return_value = html
append_utms_cookie_to_ubuntu_links(response)
updated_html = response.set_data.call_args[0][0]
self.assertEqual(updated_html, html)
def test_append_utms_cookie_with_duplicate_values(self):
"""
Test handling of cookie with duplicate parameter values
"""
with self.app.test_request_context(
"/",
headers={
"Cookie": "utms=utm_content:test1,test2&utm_medium:test2"
},
):
response = MagicMock()
response.mimetype = "text/html"
response.is_sequence = True
html = '<a href="https://ubuntu.com/test">Link</a>'
response.get_data.return_value = html
append_utms_cookie_to_ubuntu_links(response)
updated_html = response.set_data.call_args[0][0]
self.assertIn("utm_content:test1,test2", updated_html)
self.assertIn("utm_medium:test2", updated_html)
class TestKnowledgeSections(unittest.TestCase):
"""Test suite for get_knowledge_sections function using real files"""
def setUp(self):
self.app = flask.Flask(__name__)
# Create a temporary directory for testing
self.temp_dir = tempfile.mkdtemp()
self.webapp_dir = Path(self.temp_dir) / "webapp"
self.webapp_dir.mkdir(parents=True, exist_ok=True)
# Override the app's root_path to our webapp directory
self.app.root_path = str(self.webapp_dir)
self.app_context = self.app.app_context()
self.app_context.push()
def tearDown(self):
self.app_context.pop()
import shutil
shutil.rmtree(self.temp_dir)
def _create_knowledge_category(
self, slug, title, description, articles=None
):
"""Helper to create a knowledge category with real files"""
# Create templates/knowledge/{slug}/ directory
category_dir = Path(self.temp_dir) / "templates" / "knowledge" / slug
category_dir.mkdir(parents=True, exist_ok=True)
# Create index.html with title and description
index_html = f"""
{{% set title = "{title}" %}}
{{% set description = "{description}" %}}
<html>
<body>
<h1>{{ title }}</h1>
<p>{{ description }}</p>
</body>
</html>
"""
index_file = category_dir / "index.html"
index_file.write_text(index_html.strip())
# Create markdown articles if provided
if articles:
for article in articles:
article_slug = article["slug"]
article_content = f"""---
context:
hero_title: {article["title"]}
description: {article["description"]}
tag: {article["tag"]}
---
# {article["title"]}
{article["description"]}
"""
md_file = category_dir / f"{article_slug}.md"
md_file.write_text(article_content.strip())
def test_slug_extraction_from_directory_name(self):
"""Test that slug is correctly extracted from directory name"""
self._create_knowledge_category(
slug="ubuntu-and-linux",
title="Ubuntu and Linux",
description="Learn about Ubuntu",
articles=[],
)
with self.app.test_request_context():
sections = get_knowledge_sections()
self.assertEqual(len(sections), 1)
self.assertEqual(sections[0]["slug"], "ubuntu-and-linux")
def test_title_extraction_from_html(self):
"""Test that title is correctly extracted from HTML"""
self._create_knowledge_category(
slug="linux",
title="Getting Started with Linux",
description="Learn Linux basics",
articles=[],
)
with self.app.test_request_context():
sections = get_knowledge_sections()
self.assertEqual(
sections[0]["title"], "Getting Started with Linux"
)
def test_description_extraction_from_html(self):
"""Test that description is correctly extracted from HTML"""
self._create_knowledge_category(
slug="devops",
title="DevOps",
description="Learn DevOps best practices and methodologies",
articles=[],
)
with self.app.test_request_context():
sections = get_knowledge_sections()
self.assertEqual(
sections[0]["description"],
"Learn DevOps best practices and methodologies",
)
def test_articles_extraction_and_population(self):
"""Test that articles are correctly extracted and populated"""
articles = [
{
"slug": "aws-basics",
"title": "AWS Basics",
"description": "Introduction to AWS",
"tag": "cloud",
},
{
"slug": "azure-intro",
"title": "Azure Intro",
"description": "Introduction to Azure",
"tag": "cloud",
},
{
"slug": "gcp-guide",
"title": "GCP Guide",
"description": "Introduction to GCP",
"tag": "cloud",
},
]
self._create_knowledge_category(
slug="cloud-and-infrastructure",
title="Cloud and infrastructure",
description="Cloud and infrastructure description",
articles=articles,
)
with self.app.test_request_context():
sections = get_knowledge_sections()
self.assertEqual(len(sections), 1)
self.assertEqual(len(sections[0]["articles"]), 3)
self.assertEqual(
sections[0]["articles"][0]["hero_title"], "AWS Basics"
)
self.assertEqual(
sections[0]["articles"][1]["hero_title"], "Azure Intro"
)
self.assertEqual(
sections[0]["articles"][2]["hero_title"], "GCP Guide"
)
def test_all_four_fields_together(self):
"""
Test that slug, title, description, and articles
are all correctly populated
"""
articles = [
{
"slug": "fundamentals",
"title": "K8s Fundamentals",
"description": "Core concepts",
"tag": "kubernetes",
},
{
"slug": "deployments",
"title": "Advanced Deployments",
"description": "Advanced patterns",
"tag": "kubernetes",
},
]
self._create_knowledge_category(
slug="kubernetes-guide",
title="Kubernetes Complete Guide",
description="Guide to Kubernetes orchestration",
articles=articles,
)
with self.app.test_request_context():
sections = get_knowledge_sections()
# Verify all four fields
self.assertEqual(sections[0]["slug"], "kubernetes-guide")
self.assertEqual(sections[0]["title"], "Kubernetes Complete Guide")
self.assertEqual(
sections[0]["description"], "Guide to Kubernetes orchestration"
)
self.assertEqual(len(sections[0]["articles"]), 2)
# Verify structure of returned dict
expected_keys = {
"slug",
"title",
"description",
"articles",
"last_modified",
}
self.assertEqual(set(sections[0].keys()), expected_keys)
def test_multiple_sections(self):
"""Test retrieval of multiple sections"""
self._create_knowledge_category(
slug="linux",
title="Linux Guide",
description="Learn Linux",
articles=[],
)
self._create_knowledge_category(
slug="containers",
title="Container Guide",
description="Learn Containers",
articles=[],
)
with self.app.test_request_context():
sections = get_knowledge_sections()
self.assertEqual(len(sections), 2)
slugs = [s["slug"] for s in sections]
self.assertIn("linux", slugs)
self.assertIn("containers", slugs)
def test_filters_underscore_directories(self):
"""Test that directories starting with underscore are filtered out"""
self._create_knowledge_category(
slug="valid-section",
title="Valid Section",
description="This should be included",
articles=[],
)
# Create a directory with underscore (should be ignored)
underscore_dir = (
Path(self.temp_dir) / "templates" / "knowledge" / "_invalid"
)
underscore_dir.mkdir(parents=True, exist_ok=True)
(underscore_dir / "index.html").write_text(
'{% set title = "Invalid" %}'
)
with self.app.test_request_context():
sections = get_knowledge_sections()
self.assertEqual(len(sections), 1)
self.assertEqual(sections[0]["slug"], "valid-section")
def test_empty_knowledge_directory(self):
"""Test when knowledge directory is empty"""
# Create the knowledge dir but leave it empty
knowledge_dir = Path(self.temp_dir) / "templates" / "knowledge"
knowledge_dir.mkdir(parents=True, exist_ok=True)
with self.app.test_request_context():
sections = get_knowledge_sections()
self.assertEqual(sections, [])
def test_missing_knowledge_directory(self):
"""Test when knowledge directory doesn't exist"""
# Don't create any knowledge directory
with self.app.test_request_context():
sections = get_knowledge_sections()
self.assertEqual(sections, [])
def test_category_without_index_html(self):
"""Test that categories without index.html are skipped"""
self._create_knowledge_category(
slug="valid-section",
title="Valid Section",
description="This should be included",
articles=[],
)
# Create a category without index.html
no_index_dir = (
Path(self.temp_dir) / "templates" / "knowledge" / "no-index"
)
no_index_dir.mkdir(parents=True, exist_ok=True)
with self.app.test_request_context():
sections = get_knowledge_sections()
# Should only have the valid section
self.assertEqual(len(sections), 1)
self.assertEqual(sections[0]["slug"], "valid-section")
if __name__ == "__main__":
unittest.main()