test_sync.py 18.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#!/usr/bin/env python

# Copyright 2020 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

P
popcor255 已提交
17 18
import ntpath
import os
19 20 21 22
import shutil
import tempfile
import unittest
from unittest import mock
23
from urllib.parse import urlparse
P
popcor255 已提交
24

25 26 27
import git
import sync

28
from sync import (
29 30
    doc_config, docs_from_tree, get_links, is_absolute_url,
    is_fragment, get_tags, load_config, save_config,
31 32
    get_files_in_path, transform_link, transform_links_doc,
    transform_doc, transform_docs, read_front_matter)
P
popcor255 已提交
33 34


35 36
BASE_FOLDER = os.path.dirname(os.path.abspath(__file__))

P
popcor255 已提交
37 38
class TestSync(unittest.TestCase):

39 40
    def setUp(self):
        self._tempdir = tempfile.TemporaryDirectory()
41
        self._tempdir2 = tempfile.TemporaryDirectory()
42
        # Create a test repo in a tmp dir
43
        gitrepo = git.Repo.init(self._tempdir.name)
44 45 46 47
        # Copy test content in it
        docs_folder = os.path.join(self._tempdir.name, 'test-content')
        shutil.copytree(os.path.join(BASE_FOLDER, 'test-content'), docs_folder)
        # Commit the new content
48 49
        gitrepo.index.add(docs_folder)
        gitrepo.index.commit("Added test content")
50 51
        # Create a tag
        self.tagname = "test_version"
52 53
        gitrepo.create_tag(self.tagname)
        self.doc = gitrepo.tree().join('test-content/content.md')
54
        self.png = gitrepo.tree().join('test-content/tekton.png')
55 56 57 58
        # Create a branch
        self.branchname = "test_branch"
        gitrepo.create_head(self.branchname)
        self.gitrepo = gitrepo.clone(self._tempdir2)
59 60 61

    def tearDown(self):
        self._tempdir.cleanup()
62
        self._tempdir2.cleanup()
P
popcor255 已提交
63

64
    # Utils
P
popcor255 已提交
65 66 67 68 69 70 71 72 73 74 75 76
    def path_leaf(self, path):
        head, tail = ntpath.split(path)
        return tail or ntpath.basename(head)

    def read_and_delete_file(self, name):
        file = open(name, "r")
        text = file.read()
        file.close()
        os.remove(name)
        return text

    # Tests
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
    def test_doc_config(self):
        folder_config = dict(index='foo.md')

        expected = ('content.md', '', None)
        actual = doc_config(self.doc, folder_config)
        self.assertEqual(actual, expected)

    def test_doc_config_header(self):
        folder_config = dict(
            index='foo.md',
            header={'title': 'test'})

        header = folder_config['header']
        header['weight'] = 10
        expected = ('content.md', '', header)
        actual = doc_config(self.doc, folder_config, 10)
        self.assertEqual(actual, expected)

    def test_doc_config_index_target(self):
        folder_config = dict(
            index='content.md',
            header={'title': 'test'},
            target='foobar')

        header = folder_config['header']
        header['weight'] = 10
        expected = ('_index.md', 'foobar', header)
        actual = doc_config(self.doc, folder_config, 10)
        self.assertEqual(actual, expected)

    def test_docs_from_tree(self):
        tree = self.gitrepo.tree().join('test-content')
109
        expected = ['content.md', 'tekton.png', 'test.txt', 'unwanted.txt']
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
        actual = [x.name for x in docs_from_tree(tree)]
        self.assertEqual(actual, expected)

    def test_docs_from_tree_include(self):
        tree = self.gitrepo.tree().join('test-content')
        expected = ['content.md']
        actual = [x.name for x in
            docs_from_tree(tree, include=['*.md'])]
        self.assertEqual(actual, expected)

    def test_docs_from_tree_include_specific(self):
        tree = self.gitrepo.tree().join('test-content')
        expected = ['content.md', 'test.txt']
        actual = [x.name for x in
            docs_from_tree(tree, include=['content.md', 'test.txt'])]
        self.assertEqual(actual, expected)

    def test_docs_from_tree_include_subfolder(self):
        tree = self.gitrepo.tree().join('test-content/nested')
        expected = ['content.md']
        actual = [x.name for x in
            docs_from_tree(tree, include=['content.md'])]
        self.assertEqual(actual, expected)

    def test_docs_from_tree_exclude(self):
        tree = self.gitrepo.tree().join('test-content')
136
        expected = ['content.md', 'tekton.png']
137 138 139 140
        actual = [x.name for x in
            docs_from_tree(tree, exclude=['*.txt'])]
        self.assertEqual(actual, expected)

141
    def test_is_fragment(self):
P
popcor255 已提交
142 143
        """ Verify if a string is a reference. A reference is
        defined as  a string where its first character is a hashtag """
144 145 146
        self.assertFalse(is_fragment(urlparse("")))
        self.assertTrue(is_fragment(urlparse("#footer")))
        self.assertFalse(is_fragment(urlparse("www.google.com")))
P
popcor255 已提交
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161

    def test_get_tags(self):
        """ map a list of dictionaries to only
        have name, displayName feilds """
        expected = [{'name': 'test_tag', 'displayName': 'test_display'}]
        tags = {'tags': [
            {
                'name': 'test_tag',
                'displayName': 'test_display',
                'files': []
            },
        ]}

        self.assertEqual(get_tags(tags), expected)

162
    def test_load_save_config(self):
P
popcor255 已提交
163 164
        """ convert a list of files into a list of dictionaries """
        # create a tmp file with yaml txt
165
        text = "{repository: foo}"
P
popcor255 已提交
166

A
Andrea Frittoli 已提交
167
        with tempfile.NamedTemporaryFile(dir='/tmp', delete=False) as tmp:
P
popcor255 已提交
168 169 170
            tmp_name = tmp.name
            tmp.write(text.strip().encode())

171
        expected = [{'content': {'repository': "foo"},
172 173
                     'filename': tmp_name}]
        actual = load_config([tmp_name])
P
popcor255 已提交
174 175
        self.assertEqual(actual, expected)

176
        mod_config = actual
177 178
        mod_config[0]['content']['repository'] = "bar"
        expected = [{'content': {'repository': "bar"},
179 180 181 182 183 184
                     'filename': tmp_name}]
        save_config(mod_config)
        actual = load_config([tmp_name])
        self.assertEqual(actual, expected)
        self.read_and_delete_file(tmp_name)

185
    def test_get_files_in_path(self):
P
popcor255 已提交
186 187 188
        """ create a list of files within a
        directory that contain a valid extension"""

A
Andrea Frittoli 已提交
189
        with tempfile.NamedTemporaryFile(dir='/tmp', delete=True) as tmp:
P
popcor255 已提交
190
            expected = [tmp.name]
191
            actual = get_files_in_path("/tmp", self.path_leaf(tmp.name))
P
popcor255 已提交
192 193 194

        self.assertEqual(actual, expected)

A
Andrea Frittoli 已提交
195 196
        with tempfile.NamedTemporaryFile(dir='/tmp', delete=True) as tmp:
            expected = [tmp.name]
197
            actual = get_files_in_path("/tmp", self.path_leaf(tmp.name))
P
popcor255 已提交
198 199 200 201

        self.assertEqual(actual, expected)

    def test_get_links(self):
A
Andrea Frittoli 已提交
202
        """ return a list of links formatted in markdown in a given string"""
P
popcor255 已提交
203 204 205 206 207 208 209 210
        actual = "www.link.com"

        expected = get_links("")
        self.assertEqual([], expected)

        expected = get_links("[link](www.link.com) this is a link")
        self.assertEqual(actual, expected[0].get("href"))

211 212 213 214 215
    def test_multiple_get_links(self):
        """ This will ensure that get links will
        return a list of multiple md links """
        expected = ["www.link.com", "./link"]
        result = get_links("this is a [link](www.link.com) and [link](./link)")
P
popcor255 已提交
216

217 218
        for index, link in enumerate(result):
            self.assertEqual(link.get("href"), expected[index])
P
popcor255 已提交
219

220 221 222 223 224 225 226 227 228 229 230 231
    def test_is_absolute_url(self):
        """This will return a test to see if the link is a valid url format"""
        self.assertTrue(is_absolute_url(urlparse("http://www.fake.g00gl3.com")))
        self.assertTrue(is_absolute_url(urlparse("http://www.google.com")))
        self.assertFalse(is_absolute_url(urlparse("www.google.com")))
        self.assertFalse(is_absolute_url(urlparse(".sync.py")))
        self.assertFalse(is_absolute_url(urlparse("#fragment")))

    def test_transform_link(self):
        base_path = './test-content'
        rewrite_path = '/docs/foo'
        rewrite_url = 'https://foo.bar'
232 233
        local_files = {
            'test-content/content.md': ('_index.md', ''),
234
            'test-content/parallel.md': ('parallel.md', ''),
235
            'test-content/test.txt': ('test.txt', ''),
236 237 238
            'another-content/test.md': ('test.md', 'another'),
            'test-content/nested/content.md': ('content.md', 'nested'),
            'test-content/nested/example.yaml': ('example.yaml', 'nested')
239 240 241 242 243 244 245 246
        }

        cases = [
            "",
            "http://test.com",
            "test.txt",
            "content.md",
            "notthere.txt",
247 248
            "../another-content/test.md",
            "./nested/content.md",
249 250 251
            "./nested/example.yaml",
            "./parallel.md",
            "./parallel.md#with-fragment"
252 253 254 255 256 257 258 259
        ]

        expected_results = [
            "",
            "http://test.com",
            "/docs/foo/test.txt",
            "/docs/foo/",
            "https://foo.bar/test-content/notthere.txt",
260 261
            "/docs/foo/another/test/",
            "/docs/foo/nested/content/",
262 263 264
            "/docs/foo/nested/example.yaml",
            "/docs/foo/parallel/",
            "/docs/foo/parallel/#with-fragment"
265 266 267 268 269 270 271
        ]

        for case, expected in zip(cases, expected_results):
            self.assertEqual(
                transform_link(case, base_path, local_files, rewrite_path, rewrite_url),
                expected)

272
    def test_transform_links_doc(self):
273
        self.maxDiff = None
P
popcor255 已提交
274

275 276 277 278 279 280 281 282 283 284 285 286 287
        # Links are in a page stored undrer base_path
        base_path = 'test-content'

        # The following pages are synced
        local_files = {
            f'{base_path}/content.md': '_index.md',
            f'{base_path}/else.md': 'else.md',
            f'{base_path}/test.txt': 'test.txt',
            'some_other_folder/with_contend.md': 'with_contend.md'
        }

        cases = [
            "[exists-relative-link](./test.txt)",
288 289
            "[exists-relative-link-index](./content.md)\nand\n[exists-relative-link-index](./content.md#with-fragment)",
            "[else](else.md) and [else2](else.md)\nand\n[else-frag](./else.md#with-fragment) and [again](./else.md#with-another-fragment)",
290 291 292 293 294 295 296
            "[exists-relative-link-other-path](../some_other_folder/with_content.md)",
            "[exists-relative-link-fragment](test.txt#Fragment)",
            "[notfound-relative-link](./this/is/not/found.txt#FraGment)",
            "[notfound-relative-link-fragment](./this/is/not/found.md#fraGmenT)",
            "[notfound-relative-link-dotdot](../examples/notfound.txt)",
            "[invalid-absolute-link](www.github.com)",
            ("[valid-absolute-link](https://website-random321.net#FRagment) "
297 298 299
             "[valid-ref-link](#fooTEr)"),
            ("Valid link broken on two lines [exists-link-in-list]("
            "./test.txt)")
300 301 302
        ]
        expected_results = [
            "[exists-relative-link](/docs/test/test.txt)",
303 304
            "[exists-relative-link-index](/docs/test/)\nand\n[exists-relative-link-index](/docs/test/#with-fragment)",
            "[else](/docs/test/else) and [else](/docs/test/else/)\nand\n[else-frag](/docs/test/else/#with-fragment) and [again](/docs/test/else/#with-another-fragment)",
305 306 307 308 309 310 311
            "[exists-relative-link-other-path](/docs/test/else/)",
            "[exists-relative-link-fragment](/docs/test/test.txt#Fragment)",
            "[notfound-relative-link](http://test.com/tree/docs/test/this/is/not/found.txt#FraGment)",
            "[notfound-relative-link-fragment](http://test.com/tree/docs/test/this/is/not/found.md#fraGmenT)",
            "[notfound-relative-link-dotdot](http://test.com/tree/docs/examples/notfound.txt)",
            "[invalid-absolute-link](http://test.com/tree/docs/www.github.com)",
            ("[valid-absolute-link](https://website-random321.net#FRagment) "
312 313 314
             "[valid-ref-link](#footer)"),
            ("Valid link broken on two lines [exists-link-in-list]("
            "/docs/test/test.txt)")
315 316 317
        ]

        for case, expected in zip(cases, expected_results):
318 319
            actual = transform_links_doc(
                text=case, base_path=base_path, local_files=local_files,
320 321 322
                rewrite_path='/docs/test', rewrite_url='http://test.com/tree/docs/test'
            )

323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
    def test_read_front_matter(self):
        cases = [
            'abc',
            '---\ntest1',
            '---\ntest1: abc\ntest2: 1\n---\nabc',
            '<!--\n---\ntest1: abc\ntest2: 1\n---\n-->\nabc'
        ]
        expected = [
            ('abc', None),
            ('---\ntest1', None),
            ('abc', {"test1": "abc", "test2": 1}),
            ('abc', {"test1": "abc", "test2": 1})
        ]
        for case, exp in zip(cases, expected):
            actual = read_front_matter(case)
            self.assertEqual(actual, exp)

340 341 342 343 344
    def test_transform_doc(self):
        header = dict(test1='abc', test2=1, test3=True)
        with tempfile.TemporaryDirectory() as site_dir:
            expected_result = os.path.join(site_dir, 'target', 'target.md')
            expected_content = (
345
                "<!--\n"
346 347 348 349 350
                "---\n"
                "test1: abc\n"
                "test2: 1\n"
                "test3: true\n"
                "---\n"
351
                "-->\n"
352 353 354 355 356 357 358 359 360 361
            )
            actual_result = transform_doc(
                self.doc, 'test-content', 'target.md', 'target', header, {},
                '/doc/test', 'http://test.com/test/tree', site_dir)
            self.assertEqual(actual_result, expected_result)

            with open(expected_result, 'r') as result:
                actual_content = result.read()
                self.assertEqual(actual_content, expected_content)

362 363 364 365 366 367 368 369 370 371 372 373 374 375
    def test_transform_doc_png(self):
        with tempfile.TemporaryDirectory() as site_dir:
            expected_result = os.path.join(site_dir, 'target', 'tekton.png')
            expected_content = self.png.data_stream.read()

            actual_result = transform_doc(
                self.png, 'test-content', 'tekton.png', 'target', {}, {},
                '/doc/test', 'http://test.com/test/tree', site_dir)
            self.assertEqual(actual_result, expected_result)

            with open(expected_result, 'rb') as result:
                actual_content = result.read()
                self.assertEqual(actual_content, expected_content)

376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
    def test_transform_docs(self):
        folders_config = {
            'test-content': {
                'index': 'content.md',
                'target': 'target',
                'include': ['*.md', '*.txt'],
                'exclude': ['unwanted.txt'],
                'header': {
                    'test1': 'abc'
                }
            }
        }
        with tempfile.TemporaryDirectory() as site_dir:
            expected_results = [
                os.path.join(site_dir, 'target', '_index.md'),
                os.path.join(site_dir, 'target', 'test.txt')]

            template = (
394
                "<!--\n"
395 396 397 398
                "---\n"
                "test1: abc\n"
                "weight: {weight}\n"
                "---\n"
399
                "-->\n"
400 401 402 403 404 405 406 407 408 409 410 411
            )
            expected_contents = [template.format(weight=idx) for idx in range(2)]
            actual_results = transform_docs(
                self.gitrepo, self.tagname, folders_config, site_dir,
                '/doc/test', 'http://test.com/test/tree')
            self.assertEqual(set(actual_results), set(expected_results))

            for result, content in zip(expected_results, expected_contents):
                with open(result, 'r') as result:
                    actual_content = result.read()
                    self.assertEqual(actual_content, content)

412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
    def test_transform_docs_with_branch(self):
        folders_config = {
            'test-content': {
                'index': 'content.md',
                'target': 'target',
                'include': ['*.md', '*.txt'],
                'exclude': ['unwanted.txt'],
                'header': {
                    'test1': 'abc'
                }
            }
        }
        with tempfile.TemporaryDirectory() as site_dir:
            expected_results = [
                os.path.join(site_dir, 'target', '_index.md'),
                os.path.join(site_dir, 'target', 'test.txt')]

            template = (
430
                "<!--\n"
431 432 433 434
                "---\n"
                "test1: abc\n"
                "weight: {weight}\n"
                "---\n"
435
                "-->\n"
436 437 438 439 440 441 442 443 444 445 446 447
            )
            expected_contents = [template.format(weight=idx) for idx in range(2)]
            actual_results = transform_docs(
                self.gitrepo, self.branchname, folders_config, site_dir,
                '/doc/test', 'http://test.com/test/tree')
            self.assertEqual(set(actual_results), set(expected_results))

            for result, content in zip(expected_results, expected_contents):
                with open(result, 'r') as result:
                    actual_content = result.read()
                    self.assertEqual(actual_content, content)

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
    @mock.patch('sync.transform_docs')
    def test_download_resources_to_project(self, transform_docs_mock):
        folders_config = {
            'test-content': {
                'index': 'content.md',
                'target': 'target',
                'include': ['*.md', '*.txt'],
                'exclude': ['unwanted.txt'],
                'header': {
                    'test1': 'abc'
                }
            }
        }
        test_component = {
            'component': 'test',
            'repository': 'http://test.com/test',
            'tags': [{
                'name': self.tagname,
                'displayName': self.tagname,
                'folders': folders_config
            }]
        }
        clones = {'http://test.com/test': self.gitrepo}
        sync.download_resources_to_project([test_component], clones)
        transform_docs_mock.assert_called_once_with(
            git_repo=self.gitrepo,
            tag=self.tagname,
            folders=folders_config,
            site_folder=f'{sync.CONTENT_DIR}/test',
            base_path='/docs/test',
            base_url=f'http://test.com/test/tree/{self.tagname}/')
P
popcor255 已提交
479

480

P
popcor255 已提交
481 482
if __name__ == '__main__':
    unittest.main()