def browse_json(request, slug, attribute):
    """Return a page with a JSON list representing a domain tree for added URLs."""
    if request.method == 'GET':
        #Root is the id of the expand link clicked
        if 'root' in request.GET:
            root = request.GET['root']
            #No id specified
            if root == 'source':
                root = ''
            json_string = create_json_browse(slug, attribute, root)
        else:
            json_string = create_json_browse(slug, attribute, '')
    else:
        json_string = create_json_browse(slug, attribute, '')

    return HttpResponse(json_string, content_type='application/json')
    def test_returns_expected_with_no_children(self):
        project = factories.ProjectFactory()
        factories.SURTFactory(
            url_project=project,
            entity='http://www.example.com',
            value='http://(com,example,www)'
        )
        root = 'com,example,'
        expected = [{
            'id': 'com,example,www,',
            'text': '<a href="surt/http://(com,example,www">com,example,www</a>'
        }]
        results = url_handler.create_json_browse(project.project_slug, None, root)

        assert json.loads(results) == expected
    def test_returns_expected(self, root, text, id_group):
        project = factories.ProjectFactory()
        factories.SURTFactory(
            url_project=project,
            entity='http://www.example.com',
            value='http://(com,example,www)'
        )
        expected = [{
            'hasChildren': True,
            'id': id_group,
            'text': text
        }]
        results = url_handler.create_json_browse(project.project_slug, None, root)

        assert json.loads(results) == expected
    def test_groups_by_prefix_when_many_urls_exist(self):
        project = factories.ProjectFactory()
        urls = factories.SURTFactory.create_batch(101, url_project=project)
        root = 'com,'
        results = url_handler.create_json_browse(project.project_slug, None, root)
        expected = [
            {
                'hasChildren': True,
                'id': root + url.value[url.value.find(root) + 4],
                'text': url.value[url.value.find(root) + 4]
            } for url in urls
        ]

        for result in json.loads(results):
            assert result in expected

        assert json.loads(results).sort() == expected.sort()
 def test_empty_root(self):
     project = factories.ProjectFactory()
     root = ''
     assert url_handler.create_json_browse(project.project_slug, None, root) == '[]'
 def test_cannot_find_matching_surts(self):
     project = factories.ProjectFactory()
     root = 'example'
     assert url_handler.create_json_browse(project.project_slug, None, root) == '[]'
 def test_cannot_find_project(self):
     slug = 'blah'
     with pytest.raises(http.Http404):
         url_handler.create_json_browse(slug, None, None)