def test_read_and_update_resource(self):
        with self.assertRaises(BadRequest):
            self.sms.read_service_definition()

        service_definition = Mock()
        service_definition.name = "name"

        service_definition.definition = self.yaml_definition
        service_definition.description = "This is just a test, don't panic"
        self.mock_clients.resource_registry.read.return_value = service_definition

        sd = self.sms.read_service_definition("123")
        self.assertTrue(sd is service_definition)
        self.mock_clients.resource_registry.read.assert_called_once_with("123", "")

        sd.name = "new    name"
        with self.assertRaises(BadRequest):
            self.sms.update_service_definition(sd)

        sd.definition = self.bad_yaml
        with self.assertRaises(BadRequest):
            self.sms.update_service_definition(service_definition)

        sd.name = "new_name"
        sd.definition = self.yaml_definition
        self.mock_clients.resource_registry.update.return_value = ["123", 2]
        sd_id = self.sms.update_service_definition(sd)
        self.assertEqual(sd_id, "123")
        self.mock_clients.resource_registry.update.assert_called_once_with(sd)
    def test_read_and_update_object(self):
        with self.assertRaises(BadRequest):
            self.oms.read_object_type(None)

        ot = Mock()
        ot.definition = self.yaml_definition
        ot.name = "name"
        ot.description = "This is just a test, don't panic"
        self.oms.clients.resource_registry.read.return_value = ot

        ot_return = self.oms.read_object_type("123")
        self.assertTrue(ot_return is ot)
        self.oms.clients.resource_registry.read.assert_called_once_with("123", "")

        ot_return.name = "new    name"
        with self.assertRaises(BadRequest):
            self.oms.update_object_type(ot_return)

        ot_return.name = "new_name"
        ot_return.definition = self.bad_yaml
        with self.assertRaises(BadRequest):
            self.oms.update_object_type(ot_return)

        ot.definition = self.yaml_definition
        self.oms.clients.resource_registry.update.return_value = ["123", 2]
        ot_id = self.oms.update_object_type(ot_return)
        self.assertEqual(ot_id, "123")
        self.oms.clients.resource_registry.update.assert_called_once_with(ot_return)
Example #3
0
    def test_files(self):
        gist = Mock()
        gist.description = "Dale Name #notebook #hello"
        gist.files = object()

        tg = TaggedGist.from_gist(gist)
        nt.assert_is(tg.files, gist.files)
    def test_create_resource(self):
        # Create ResourceType
        rt = Mock()
        rt.name = "bad name"
        with self.assertRaises(BadRequest):
            self.rms.create_resource_type(rt, "123")

        rt.name = "good_name"
        bad_object_id = None
        with self.assertRaises(BadRequest):
            self.rms.create_resource_type(rt, bad_object_id)

        # Create ObjectType
        ot = Mock()
        ot.definition = self.object_definition
        ot.name = "good_name"
        ot.description = "This is just a test. No need to panic"

        self.rms.clients.resource_registry.read.return_value = ot
        resource_id_return_value = "123"
        version_return_value = 1
        self.rms.clients.resource_registry.create.return_value = [resource_id_return_value, version_return_value]
        self.rms.clients.resource_registry.create_association.return_value = "999"

        object_id = "444"
        resource_id = self.rms.create_resource_type(rt, object_id)
        self.assertEqual(resource_id, "123")

        self.rms.clients.resource_registry.read.assert_called_once_with(object_id, "")
        self.rms.clients.resource_registry.create.assert_called_once_with(rt)
        self.rms.clients.resource_registry.create_association.assert_called_once_with(
            resource_id_return_value, PRED.hasObjectType, object_id, "H2H"
        )
Example #5
0
 def test_fetchone_nt(self):
     cursor = Mock()
     cursor.description = (("id", 3, 2, 11, 11, 0, 0), ("status", 253, 7, 80, 80, 0, 0))
     cursor.fetchone = Mock(return_value=(34, "info"))
     r = fetchone_nt(cursor)
     self.assertEqual(r.__class__.__name__, "Results")
     self.assertEqual(r.id, 34)
     self.assertEqual(r.status, "info")
Example #6
0
    def test_fetchiter_nt(self):
        cursor = Mock()
        cursor.description = (("id", 3, 2, 11, 11, 0, 0), ("status", 253, 7, 80, 80, 0, 0))

        # Standard
        cursor.fetchmany = Mock(return_value=((34, "info"), (99, "warning")))
        num_it = 0
        for row in fetchiter_nt(cursor):
            self.assertEqual(row.__class__.__name__, "Results")
            if num_it == 0:
                self.assertEqual(row.id, 34)
                self.assertEqual(row.status, "info")
            if num_it == 1:
                self.assertEqual(row.id, 99)
                self.assertEqual(row.status, "warning")
            if num_it == 2:
                raise StopIteration
            num_it += 1
            if num_it == 2:
                cursor.fetchmany = Mock(return_value=[])
        self.assertEqual(num_it, 2)

        # Batch
        cursor.fetchmany = Mock(return_value=((34, "info"), (99, "warning")))
        num_it = 0
        for row in fetchiter_nt(cursor, batch=True):
            self.assertEqual(row.__class__.__name__, "list")
            self.assertEqual(row[0].__class__.__name__, "Results")
            self.assertEqual(row[0].id, 34)
            self.assertEqual(row[0].status, "info")
            self.assertEqual(row[1].__class__.__name__, "Results")
            self.assertEqual(row[1].id, 99)
            self.assertEqual(row[1].status, "warning")
            if num_it == 1:
                raise StopIteration
            num_it += 1
            if num_it == 1:
                cursor.fetchmany = Mock(return_value=[])
        self.assertEqual(num_it, 1)

        # Server cursor
        cursor.fetchall = Mock(return_value=((34, "info"), (99, "warning")))
        num_it = 0
        for row in fetchiter_nt(cursor, server_cursor="C"):
            self.assertEqual(row.__class__.__name__, "Results")
            if num_it == 0:
                self.assertEqual(row.id, 34)
                self.assertEqual(row.status, "info")
            if num_it == 1:
                self.assertEqual(row.id, 99)
                self.assertEqual(row.status, "warning")
            if num_it == 2:
                raise StopIteration
            num_it += 1
            if num_it == 2:
                cursor.fetchall = Mock(return_value=[])
        self.assertEqual(num_it, 2)
Example #7
0
    def test_from_gist(self):
        gist = Mock()
        gist.description = "Dale Name #notebook #hello"

        tg = TaggedGist.from_gist(gist)
        nt.assert_equals(tg.name, "Dale Name")
        nt.assert_items_equal(tg.tags, ["#notebook", "#hello"])
        nt.assert_true(tg.active)

        gist = Mock()
        gist.description = "Dale Name #notebook #inactive"

        tg = TaggedGist.from_gist(gist)
        nt.assert_equals(tg.name, "Dale Name")
        nt.assert_items_equal(tg.tags, ["#notebook"])

        # explicitly test system tags
        nt.assert_in("#inactive", TaggedGist.system_tags)
        nt.assert_not_in("#inactive", tg.tags)
        nt.assert_false(tg.active)
Example #8
0
def generate_tagged_gists(names):
    mocks = []
    for id, name in enumerate(names, 1):
        mock = Mock()
        mock.description = name
        mock.id = id
        mocks.append(mock)

    tagged_gists = [(mock.id, TaggedGist.from_gist(mock)) for mock in mocks if mock.description]
    tagged_gists = dict(tagged_gists)
    return tagged_gists
Example #9
0
def get_contest():
    contest = Mock()
    contest.id = get_int()
    contest.name = get_string()
    start = get_int(2 ** 11)
    duration = get_int(2 ** 8)
    contest.start = make_datetime(start)
    contest.stop = make_datetime(start + duration)
    contest.score_precision = 2
    contest.description = get_string()
    return contest
Example #10
0
 def test_make_float64_meta(self):
     params = Mock()
     params.name = "me"
     params.description = "desc"
     params.default = 32.6
     name, meta, default = parameters.float64(params)
     self.assertEqual(default, 32.6)
     self.assertEqual(name, "me")
     self.assertEqual(meta.description, "desc")
     self.assertIsInstance(meta, NumberMeta)
     self.assertEqual(meta.dtype, "float64")
Example #11
0
 def test_fetchall_nt(self):
     cursor = Mock()
     cursor.description = (("id", 3, 2, 11, 11, 0, 0), ("status", 253, 7, 80, 80, 0, 0))
     cursor.fetchall = Mock(return_value=((34, "info"), (99, "warning")))
     r = fetchall_nt(cursor)
     self.assertEqual(r.__class__.__name__, "list")
     self.assertEqual(r[0].__class__.__name__, "Results")
     self.assertEqual(r[0].id, 34)
     self.assertEqual(r[0].status, "info")
     self.assertEqual(r[1].__class__.__name__, "Results")
     self.assertEqual(r[1].id, 99)
     self.assertEqual(r[1].status, "warning")
Example #12
0
 def test_make_string_meta(self):
     params = Mock()
     params.name = "me"
     params.description = "desc"
     del params.default
     self.assertEqual(list(parameters.string.MethodMeta.takes.elements), ["name", "description", "default"])
     default_meta = parameters.string.MethodMeta.takes.elements["default"]
     self.assertIsInstance(default_meta, StringMeta)
     name, meta, default = parameters.string(params)
     self.assertEqual(default, REQUIRED)
     self.assertEqual(name, "me")
     self.assertEqual(meta.description, "desc")
     self.assertIsInstance(meta, StringMeta)
 def _make_version(self, not_automatic):
     ver = Mock(_Version)
     ver.description = "not_automatic: %s" % not_automatic
     ver.summary = "summary not_automatic: %s" % not_automatic
     ver.version = "version not_automatic: %s" % not_automatic
     mock_origin = Mock()
     if not_automatic:
         mock_origin.archive = "precise-backports"
     else:
         mock_origin.archive = "precise"
     ver.origins = [mock_origin]
     ver.not_automatic = not_automatic
     return ver
Example #14
0
 def test_make_int32_meta(self):
     params = Mock()
     params.name = "me"
     params.description = "desc"
     params.default = 32
     default_meta = parameters.int32.MethodMeta.takes.elements["default"]
     self.assertIsInstance(default_meta, NumberMeta)
     self.assertEqual(default_meta.dtype, "int32")
     name, meta, default = parameters.int32(params)
     self.assertEqual(default, 32)
     self.assertEqual(name, "me")
     self.assertEqual(meta.description, "desc")
     self.assertIsInstance(meta, NumberMeta)
     self.assertEqual(meta.dtype, "int32")
Example #15
0
 def test_feed_entry_future_published_time(self):
     """Test with future entry published time"""
     parse_mock = self.parse_mock
     entry_attrs = {
         "link": "test_entry_link",
         "published_parsed": (2114, 01, 01, 12, 0, 0, 2, 1, 0),  # 2114-01-01 12:00:00
     }
     entry_mock = Mock(**entry_attrs)
     entry_mock.description_detail.type = "text/plain"
     entry_mock.description = "Test Feed Description"
     parse_mock.return_value.entries = [entry_mock]
     db_entry_mock = Mock()
     db_entry_mock.objects.get_or_create.return_value = (Mock(), True)
     with patch("feedreader.utils.feedparser.parse", parse_mock):
         with patch("feedreader.utils.Entry", db_entry_mock):
             with patch("sys.stdout", new=StringIO()):  # Suppress printed output from test
                 poll_feed(self.feed_mock, verbose=True)
Example #16
0
    def test_failing_blacklist_means_query_doesnt_execute(self, mocked_conn):
        # I should really learn to set up mocks correctly because this CANT be the most efficient way...
        cursor_result = Mock()
        cursor_result.fetchall.return_value = []
        cursor_result.description = [("foo", "bar")]

        conn = Mock()
        conn.cursor.return_value = cursor_result
        mocked_conn.return_value = conn

        query = SimpleQueryFactory(sql="select 1;")
        resp = self.client.post(
            reverse("query_detail", kwargs={"query_id": query.id}), data={"sql": "select 'delete';"}
        )
        self.assertTemplateUsed(resp, "explorer/query.html")
        self.assertContains(resp, MSG_FAILED_BLACKLIST % "")

        # Feels fragile, but nor sure how else to access the called-with params of .execute
        self.assertEqual(conn.cursor.mock_calls[1][1][0], "select 1;")
Example #17
0
    def test__get_or_create_node(self):
        file = Mock()
        src_node = Mock()
        file.get_node.return_value = sentinel.node

        node = publicdb._get_or_create_node(file, sentinel.group, src_node)
        file.get_node.assert_called_once_with(sentinel.group, src_node.name)
        self.assertEqual(node, sentinel.node)

        file.get_node.side_effect = tables.NoSuchNodeError("no such node!")
        # Raise exception because type of Mock src_node is not Table or VLArray
        self.assertRaises(Exception, publicdb._get_or_create_node, file, sentinel.group, src_node)

        src_node = Mock(spec=tables.Table)
        src_node.description = sentinel.description
        node = publicdb._get_or_create_node(file, sentinel.group, src_node)
        file.create_table.assert_called_once_with(sentinel.group, src_node.name, src_node.description, src_node.title)

        src_node = Mock(spec=tables.VLArray)
        src_node.atom = sentinel.atom
        node = publicdb._get_or_create_node(file, sentinel.group, src_node)
        file.create_vlarray.assert_called_once_with(sentinel.group, src_node.name, src_node.atom, src_node.title)
Example #18
0
File: common.py Project: pjc42/nbx
def makeFakeGist():
    gist = Mock()
    gist.description = "Test Gist #notebook #pandas #woo"
    gist.id = 123
    # fake files
    filenames = ["a.ipynb", "b.ipynb", "test.txt"]
    files = {}
    for fn in filenames:
        fo = Mock()
        fo.filename = fn
        fo.content = fn + " content"
        files[fn] = fo

    gist.files = files
    # fake history
    history = []
    dates = pd.date_range("2000", freq="D", periods=4).to_pydatetime()
    for i, date in enumerate(dates):
        state = Mock()
        state.version = i
        state.committed_at = date
        raw_data = {}
        files = {}
        for fn in filenames:
            fo = {"content": "{fn}_{i}_revision_content".format(fn=fn, i=i), "filename": fn}
            files[fn] = fo
        # after 2, don't include 'a.ipynb'
        if i >= 2:
            del files["a.ipynb"]

        raw_data["files"] = files
        state.raw_data = raw_data
        history.append(state)

    gist.history = history

    return gist
Example #19
0
 def test_areas(self):
     p1, p2, project = Mock(), Mock(), Mock()
     p1.description = "a"
     p2.description = "b"
     project.areas.all = Mock(return_value=[p1, p2])
     self.assertEquals(areas(project), "a, b")
Example #20
0
_gs_resource = Mock()
_gs_resource.native_bbox = [1, 2, 3, 4]

Layer.objects.geonetwork = Mock()
Layer.objects.gs_catalog = Mock()

Layer.objects.gs_catalog.get_resource.return_value = _gs_resource

geonode.maps.models.get_csw = Mock()
geonode.maps.models.get_csw.return_value.records.get.return_value.identification.keywords = []

_csw_resource = Mock()
_csw_resource.protocol = "WWW:LINK-1.0-http--link"
_csw_resource.url = "http://example.com/"
_csw_resource.description = "example link"
geonode.maps.models.get_csw.return_value.records.get.return_value.distribution.online = [_csw_resource]


class MapTest(TestCase):
    """Tests geonode.maps app/module
    """

    fixtures = ["test_data.json", "map_data.json"]
    GEOSERVER = False

    def setUp(self):
        # If Geoserver and GeoNetwork are not running
        # avoid running tests that call those views.
        if "GEOSERVER" in os.environ:
            self.GEOSERVER = True
Example #21
0
    def test_track_changes_inserted(self):
        xml = """<p>some text <name>Some Name</name></p>"""
        test_doc = etree.parse(StringIO(xml))
        name_node = list(test_doc.iter("name"))[0]
        rsrc = Mock(spec=spotlight.DBpediaResource)
        rsrc.uri = "http://dbpedia.org/resource/TestResource"

        initial_length = len(list(test_doc.iter()))

        # no label/description
        rsrc.description = None
        rsrc.label = None
        old_text = "Some Name"
        self.tei_annotater.track_changes_inserted(name_node, old_text, rsrc)
        # should have added 3 nodes: 1 deletion, 2 for start/end insertion
        self.assertEqual(initial_length + 3, len(list(test_doc.iter())))

        preceding_sibs = list(name_node.itersiblings(preceding=True))
        following_sib = list(name_node.itersiblings())

        # second (farthest away) preceding sibling should be deletion,
        # then insert start
        deletion = preceding_sibs[1]
        insert_start = preceding_sibs[0]
        # insert end should be immediately after the node
        insert_end = following_sib[0]
        # inspect deletion marker
        self.assertEqual("oxy_delete", deletion.target)
        self.assertEqual(self.tei_annotater.track_changes_author, deletion.get("author"))
        self.assertEqual(old_text, deletion.get("content"))

        # inspect insert start
        self.assertEqual("oxy_insert_start", insert_start.target)
        self.assertEqual(self.tei_annotater.track_changes_author, insert_start.get("author"))
        self.assertEqual("(label/description unavailable)", insert_start.get("comment"))
        # inspect insert end
        self.assertEqual("oxy_insert_end", insert_end.target)

        # reset to test dbpedia with label
        test_doc = etree.parse(StringIO(xml))
        name_node = list(test_doc.iter("name"))[0]

        # no description but a label
        rsrc.label = "Some person's name"
        old_text = "Some Name"
        self.tei_annotater.track_changes_inserted(name_node, old_text, rsrc)
        insert_start = list(name_node.itersiblings(preceding=True))[0]
        self.assertEqual(
            rsrc.label,
            insert_start.get("comment"),
            "dbpedia resource label should be used as insert comment " + " when no description is available",
        )

        # reset to test dbpedia with description
        test_doc = etree.parse(StringIO(xml))
        name_node = list(test_doc.iter("name"))[0]

        # description (with quotes)
        rsrc.description = 'This person was "born" and is famous for ...'
        escaped_desc = rsrc.description.replace('"', "'")

        old_text = "Some Name"
        self.tei_annotater.track_changes_inserted(name_node, old_text, rsrc)
        insert_start = list(name_node.itersiblings(preceding=True))[0]
        self.assertEqual(
            escaped_desc,
            insert_start.get("comment"),
            "dbpedia resource description should be used as " + "insertion comment when available",
        )
Example #22
0
 def test_technologies(self):
     p1, p2, project = Mock(), Mock(), Mock()
     p1.description = "a"
     p2.description = "b"
     project.technologies.all = Mock(return_value=[p1, p2])
     self.assertEquals(technologies(project), "a, b")