def test_marshal_projects_all_users(self, user1, user2, projects_user1_group1, projects_user2_group1): """ Test marshalling all projects for a group regardless of owner and filtering by owner. """ projects = projects_user1_group1 + projects_user2_group1 projects.sort(key=lambda x: lower_or_none(unwrap(x.name))) conn = get_connection(user1) user_name = conn.getUser().getName() django_client = self.new_django_client(user_name, user_name) version = api_settings.API_VERSIONS[-1] request_url = reverse('api_projects', kwargs={'api_version': version}) # Both users rsp = get_json(django_client, request_url) assert_objects(conn, rsp['data'], projects) assert rsp['meta']['totalCount'] == len(projects) eid = user1[1].id.val rsp = get_json(django_client, request_url, {'owner': eid}) assert_objects(conn, rsp['data'], projects_user1_group1) assert rsp['meta']['totalCount'] == len(projects_user1_group1) eid = user2[1].id.val rsp = get_json(django_client, request_url, {'owner': eid}) assert_objects(conn, rsp['data'], projects_user2_group1) assert rsp['meta']['totalCount'] == len(projects_user2_group1)
def test_project_delete(self, user1): conn = get_connection(user1) user_name = conn.getUser().getName() django_client = self.new_django_client(user_name, user_name) project = ProjectI() project.name = rstring('test_project_delete') project.description = rstring('Test update') project = get_update_service(user1).saveAndReturnObject(project) version = api_settings.API_VERSIONS[-1] project_url = reverse('api_project', kwargs={'api_version': version, 'object_id': project.id.val}) # Before delete, we can read pr_json = get_json(django_client, project_url) assert pr_json['data']['Name'] == 'test_project_delete' # Delete delete_json(django_client, project_url, {}) # Get should now return 404 rsp = get_json(django_client, project_url, status_code=404) assert rsp['message'] == 'Project %s not found' % project.id.val # Delete (again) should return 404 rsp = delete_json(django_client, project_url, {}, status_code=404) assert rsp['message'] == 'Project %s not found' % project.id.val save_url = reverse('api_save', kwargs={'api_version': version}) # TODO: Try to save deleted object - should return ApiException # see https://trello.com/c/qWNt9vLN/178-save-deleted-object with pytest.raises(AssertionError): rsp = put_json(django_client, save_url, pr_json, status_code=400) assert rsp['message'] == 'Project %s not found' % project.id.val
def test_marshal_projects_all_groups(self, user1, group1, group2, projects_user1): """ Test marshalling all projects for a user regardless of group and filtering by group. """ conn = get_connection(user1) user_name = conn.getUser().getName() django_client = self.new_django_client(user_name, user_name) version = api_settings.API_VERSIONS[-1] request_url = reverse('api_projects', kwargs={'api_version': version}) # All groups rsp = get_json(django_client, request_url) assert_objects(conn, rsp['data'], projects_user1) assert rsp['meta']['totalCount'] == len(projects_user1) # Filter by group A... gid = group1.id.val rsp = get_json(django_client, request_url, {'group': gid}) assert_objects(conn, rsp['data'], projects_user1, group=gid) assert rsp['meta']['totalCount'] == len(rsp['data']) # ...and group B gid = group2.id.val rsp = get_json(django_client, request_url, {'group': gid}) assert_objects(conn, rsp['data'], projects_user1, group=gid) assert rsp['meta']['totalCount'] == len(rsp['data'])
def test_filter_groups(self, user1): """ Test filtering groups by experimenter """ conn = get_connection(user1) user_name = conn.getUser().getName() user_id = conn.getUserId() group_id = conn.getEventContext().groupId django_client = self.new_django_client(user_name, user_name) request_url = reverse( 'api_experimentergroups', kwargs={'api_version': api_settings.API_VERSIONS[-1]}) # Test /experimentergroups/?experimenter=1 data = {'experimenter': user_id} rsp = get_json(django_client, request_url, data) groups_json = rsp['data'] # user1 is in a single group AND the 'user' group assert len(groups_json) == 2 user_group_id = conn.getAdminService().getSecurityRoles().userGroupId user_group = [g for g in groups_json if g["@id"] == user_group_id] assert user_group[0]['Name'] == 'user' other_group = [g for g in groups_json if g["@id"] != user_group_id] assert other_group[0]['Name'] == conn.getGroupFromContext().name assert other_group[0]['@id'] == group_id # Test same result with experimenters/1/experimentergroups/ request_url = reverse('api_experimenter_experimentergroups', kwargs={ 'api_version': api_settings.API_VERSIONS[-1], 'experimenter_id': user_id }) rsp = get_json(django_client, request_url) groups_json2 = rsp['data'] assert groups_json == groups_json2
def test_filter_experimenters(self, user1): """ Test filtering experimenters by group """ conn = get_connection(user1) user_name = conn.getUser().getName() user_id = conn.getUserId() group_id = conn.getEventContext().groupId django_client = self.new_django_client(user_name, user_name) request_url = reverse( 'api_experimenters', kwargs={'api_version': api_settings.API_VERSIONS[-1]}) # Test /experimenters/?experimentergroup=1 data = {'experimentergroup': group_id} rsp = get_json(django_client, request_url, data) exps_json = rsp['data'] # user1 is in a single group AND the 'user' group assert len(exps_json) == 1 assert exps_json[0]['@id'] == user_id assert exps_json[0]['UserName'] == user_name # Test same result with experimentergroups/1/experimenters/ request_url = reverse('api_experimentergroup_experimenters', kwargs={ 'api_version': api_settings.API_VERSIONS[-1], 'group_id': group_id }) rsp = get_json(django_client, request_url) exps_json2 = rsp['data'] assert exps_json == exps_json2
def test_link_unlink_tagset_tags(self): """ Tests linking of tagset to tag, then unlinking """ tag = self.make_tag() tagset = self.make_tag(ns=omero.constants.metadata.NSINSIGHTTAGSET) tagId = tag.id.val tagsetId = tagset.id.val links_url = reverse("api_links") # Link tagset to tag data = {'tagset': {tagsetId: {'tag': [tagId]}}} rsp = post_json(self.django_client, links_url, data) assert rsp == {"success": True} # Check that tag is listed under tagset... tags_url = reverse("api_tags_and_tagged") r = get_json(self.django_client, tags_url, {'id': tagsetId}) assert len(r['tags']) == 1 assert r['tags'][0]['id'] == tagId # Unlink first Tag from Tagset # data {} is same as for creating link above response = delete_json(self.django_client, links_url, data) assert response["success"] # Since the Delete is ansync - need to check repeatedly for deletion for i in range(10): rsp = get_json(self.django_client, tags_url, {'id': tagsetId}) if len(rsp['tags']) == 0: break sleep(0.5) # Check that link has been deleted assert len(rsp['tags']) == 0
def test_shapes(self, user1, image_rois, shapes): """Test listing Shapes""" image, rois = image_rois conn = get_connection(user1) user_name = conn.getUser().getName() client = self.new_django_client(user_name, user_name) version = api_settings.API_VERSIONS[-1] # List ALL shapes shapes_url = reverse('api_shapes', kwargs={'api_version': version}) rsp = get_json(client, shapes_url) shapes_json = rsp['data'] shape_ids = [shape['@id'] for shape in shapes_json] assert len(shape_ids) == len(shapes) assert_objects(conn, shapes_json, shape_ids, dtype="Shape") for shape_id in shape_ids: # Get a single Shape url = reverse('api_shape', kwargs={ 'api_version': version, 'object_id': shape_id }) rsp = get_json(client, url, {'image': image.id.val}) assert_objects(conn, [rsp['data']], [shape_id], dtype="Shape")
def test_roi_delete(self, user1, image_rois): """Test GET and DELETE of a single ROI.""" image, rois = image_rois conn = get_connection(user1) user_name = conn.getUser().getName() client = self.new_django_client(user_name, user_name) version = api_settings.API_VERSIONS[-1] # Before delete, we can read roi_id = rois[0].id.val roi_url = reverse('api_roi', kwargs={ 'api_version': version, 'object_id': roi_id }) rsp = get_json(client, roi_url) assert_objects(conn, [rsp['data']], rois[:1], dtype="Roi", opts={'load_shapes': True}) shape_json = rsp['data']['shapes'][0] shape_id = shape_json['@id'] shape_class = shape_json['@type'].split('#')[1] # e.g. Ellipse shape = conn.getQueryService().get(shape_class, shape_id) assert shape.id.val == shape_id # Delete delete_json(client, roi_url, {}) # Get should now return 404 rsp = get_json(client, roi_url, status_code=404) assert rsp['message'] == 'Roi %s not found' % roi_id # Check that Shape has also been deleted with pytest.raises(ValidationException): shape = conn.getQueryService().get(shape_class, shape_id)
def test_marshal_projects_pagination(self, user1, user2, projects_user1_group1, projects_user2_group1): """ Test pagination of projects """ projects = projects_user1_group1 + projects_user2_group1 projects.sort(key=lambda x: lower_or_none(unwrap(x.name))) conn = get_connection(user1) user_name = conn.getUser().getName() django_client = self.new_django_client(user_name, user_name) version = api_settings.API_VERSIONS[-1] request_url = reverse('api_projects', kwargs={'api_version': version}) # Test a range of limits. offset = 0 by default for limit in range(-1, 4): rsp = get_json(django_client, request_url, {'limit': limit}) assert rsp['meta']['totalCount'] == len(projects) if limit == -1: # if we passed a negative number, expect the default to be used limit = api_settings.API_LIMIT else: assert len(rsp['data']) == limit assert rsp['meta']['limit'] == limit assert_objects(conn, rsp['data'], projects[0:limit]) # Check that page 2 gives next n projects payload = {'limit': limit, 'offset': limit} rsp = get_json(django_client, request_url, payload) assert_objects(conn, rsp['data'], projects[limit:limit * 2]) assert rsp['meta']['totalCount'] == len(projects)
def test_project_create_read(self): """ Tests creation by POST to /save and reading with GET of /project/:id/ """ django_client = self.django_root_client group = self.ctx.groupId version = api_settings.API_VERSIONS[-1] # Need to get the Schema url to create @type base_url = reverse('api_base', kwargs={'api_version': version}) rsp = get_json(django_client, base_url) schema_url = rsp['url:schema'] # specify group via query params save_url = "%s?group=%s" % (rsp['url:save'], group) projects_url = rsp['url:projects'] project_name = 'test_api_projects' payload = {'Name': project_name, '@type': schema_url + '#Project'} rsp = post_json(django_client, save_url, payload, status_code=201) new_proj = rsp['data'] # We get the complete new Project returned assert new_proj['Name'] == project_name project_id = new_proj['@id'] # Read Project project_url = "%s%s/" % (projects_url, project_id) rsp = get_json(django_client, project_url) new_proj = rsp['data'] assert new_proj['@id'] == project_id conn = BlitzGateway(client_obj=self.root) assert_objects(conn, [new_proj], [project_id])
def test_batch_add_fileannotations(self, link_count): """Test adding file annotation to Project(s).""" client, user = self.new_client_and_user(perms='rwrw--') omeName = client.sf.getAdminService().getEventContext().userName django_client1 = self.new_django_client(omeName, omeName) # User creates 2 Projects pr1 = self.make_project("test_batch_file_ann1", client=client) pr2 = self.make_project("test_batch_file_ann2", client=client) pr_ids = [pr1.id.val, pr2.id.val] # Create File and FileAnnotation fname = "fname_%s" % client.getSessionId() update = client.sf.getUpdateService() f = omero.model.OriginalFileI() f.name = omero.rtypes.rstring(fname) f.path = omero.rtypes.rstring("") f = update.saveAndReturnObject(f) fa = omero.model.FileAnnotationI() fa.setFile(f) fa = update.saveAndReturnObject(fa) # get form for annotating both Projects request_url = reverse('annotate_file') data = {"project": pr_ids} rsp = get(django_client1, request_url, data) html = rsp.content.decode('utf-8') assert fname in html # Link File Annotation to 1 or 2 Projects post_data = {"project": pr_ids[0:link_count], "files": [fa.id.val]} post(django_client1, request_url, post_data) # Check for link to first Project api_ann_url = reverse('api_annotations') rsp = get_json(django_client1, api_ann_url, {"project": pr1.id.val}) assert fa.id.val in [a['id'] for a in rsp['annotations']] # Annotation Form should NOT show file if linked to BOTH projects show_file = link_count == 1 rsp = get(django_client1, request_url, data) html = rsp.content.decode('utf-8') assert (fname in html) == show_file # Remove file from both Projects remove_url = reverse('manage_action_containers', kwargs={ 'action': 'remove', 'o_type': 'file', 'o_id': fa.id.val }) remove_data = { 'parent': 'project-%s|project-%s' % (pr1.id.val, pr2.id.val) } post(django_client1, remove_url, remove_data) # Check for NO link rsp = get_json(django_client1, api_ann_url, {"project": pr1.id.val}) assert fa.id.val not in [a['id'] for a in rsp['annotations']]
def test_add_edit_and_remove_tag(self): # Add tag img = self.make_image() tag = self.new_tag() request_url = reverse('annotate_tags') data = { 'image': img.id.val, 'filter_mode': 'any', 'filter_owner_mode': 'all', 'index': 0, 'newtags-0-description': '', 'newtags-0-tag': 'foobar', 'newtags-0-tagset': '', 'newtags-INITIAL_FORMS': 0, 'newtags-MAX_NUM_FORMS': 1000, 'newtags-TOTAL_FORMS': 1, 'tags': tag.id.val } rsp = post(self.django_client, request_url, data) rspJson = json.loads(rsp.content) assert len(rspJson['new']) == 1 newTagId = rspJson['new'][0] assert rspJson['added'] == [tag.id.val] # Check that image is tagged with both tags request_url = reverse("api_annotations") data = {'image': img.id.val, 'type': 'tag'} data = get_json(self.django_client, request_url, data) assert len(data['annotations']) == 2 # Remove tag request_url = reverse("manage_action_containers", args=["remove", "tag", tag.id.val]) data = {'index': 0, 'parent': "image-%i" % img.id.val} post(self.django_client, request_url, data) # Check that tag is removed request_url = reverse("api_annotations") data = {'image': img.id.val, 'type': 'tag'} data = get_json(self.django_client, request_url, data) assert len(data['annotations']) == 1 # Delete other tag request_url = reverse("manage_action_containers", args=["delete", "tag", newTagId]) post(self.django_client, request_url, {}) # Check that tag is deleted from image request_url = reverse("api_annotations") data = {'image': img.id.val, 'type': 'tag'} completed = False # Async delete - Keep checking until done for t in range(20): rsp = get_json(self.django_client, request_url, data) if len(rsp['annotations']) == 0: completed = True break sleep(0.1) assert completed
def test_annotate_map(self): """Test we can create and retrieve map annotations, filter by ns.""" # Create User in a Read-Annotate group client1, user1 = self.new_client_and_user(perms='rwrw--') omeName = client1.sf.getAdminService().getEventContext().userName django_client = self.new_django_client(omeName, omeName) # User1 creates Dataset ds = self.make_dataset("user1_Dataset", client=client1) # Add 2 map annotations, one with ns specfied (default is 'client' ns) ns = 'test.annotate.map.ns' map_data_ns = [['testKey', 'someValue'], ['ns', ns]] self.annotate_dataset(django_client, map_data_ns, ds.id.val, ns) client_map_data = [['expect', 'client'], ['ns', 'to be used']] self.annotate_dataset(django_client, client_map_data, ds.id.val) # check maps got added request_url = reverse('api_annotations') data = { "dataset": ds.id.val, "type": "map", } # get both map annotations rsp = get_json(django_client, request_url, data) assert len(rsp['annotations']) == 2 # now filter by custom ns data['ns'] = ns rsp = get_json(django_client, request_url, data) assert len(rsp['annotations']) == 1 # check essential values ann = rsp['annotations'][0] ann_id = ann['id'] assert ann["values"] == map_data_ns assert ann["ns"] == ns assert ann["link"]["parent"]["id"] == ds.id.val # update map annotation new_data = [['new', 'data']] self.annotate_dataset(django_client, new_data, None, None, ann_id) rsp = get_json(django_client, request_url, data) assert rsp['annotations'][0]['values'] == new_data # delete map annotation (set data as empty list) self.annotate_dataset(django_client, [], None, None, ann_id) # only one left client_ns = omero.constants.metadata.NSCLIENTMAPANNOTATION del data['ns'] rsp = get_json(django_client, request_url, data) assert len(rsp['annotations']) == 1 ann = rsp['annotations'][0] assert ann["values"] == client_map_data assert ann["ns"] == client_ns
def test_project_update(self, user1): conn = get_connection(user1) group = conn.getEventContext().groupId user_name = conn.getUser().getName() django_client = self.new_django_client(user_name, user_name) project = ProjectI() project.name = rstring('test_project_update') project.description = rstring('Test update') project = get_update_service(user1).saveAndReturnObject(project) # Update Project in 2 ways... version = api_settings.API_VERSIONS[-1] project_url = reverse('api_project', kwargs={ 'api_version': version, 'object_id': project.id.val }) save_url = reverse('api_save', kwargs={'api_version': version}) # 1) Get Project, update and save back rsp = get_json(django_client, project_url) project_json = rsp['data'] assert project_json['Name'] == 'test_project_update' project_json['Name'] = 'new name' rsp = put_json(django_client, save_url, project_json) project_json = rsp['data'] assert project_json['@id'] == project.id.val assert project_json['Name'] == 'new name' # Name has changed assert project_json['Description'] == 'Test update' # No change # 2) Put from scratch (will delete empty fields, E.g. Description) save_url += '?group=' + str(group) payload = {'Name': 'updated name', '@id': project.id.val} # Test error message if we don't pass @type: rsp = put_json(django_client, save_url, payload, status_code=400) assert rsp['message'] == 'Need to specify @type attribute' # Add @type and try again payload['@type'] = project_json['@type'] rsp = put_json(django_client, save_url, payload) project_json = rsp['data'] assert project_json['@id'] == project.id.val assert project_json['Name'] == 'updated name' assert 'Description' not in project_json # Get project again to check update rsp = get_json(django_client, project_url) pr_json = rsp['data'] assert pr_json['Name'] == 'updated name' assert 'Description' not in pr_json # Now add description and save again pr_json['Description'] = 'New test description update' put_json(django_client, save_url, pr_json) # Read to check rsp = get_json(django_client, project_url) assert rsp['data']['Description'] == 'New test description update'
def test_login_example(self): """ Example of successful login as user would do for real, starting at base url and getting all other urls and info from there. """ # Create test user and get username & password for use below user = self.new_user() username = password = user.getOmeName().val # Django client, not logged in yet django_client = Client() # Start at the /api/ url to list versions... request_url = reverse('api_versions') rsp = get_json(django_client, request_url) # Pick the last version version = rsp['data'][-1] base_url = version['url:base'] # Base url will give a bunch of other urls base_rsp = get_json(django_client, base_url) login_url = base_rsp['url:login'] servers_url = base_rsp['url:servers'] login_url = base_rsp['url:login'] token_url = base_rsp['url:token'] # See what servers we can log in to servers_rsp = get_json(django_client, servers_url) server_id = servers_rsp['data'][0]['id'] # Need a CSRF token token_rsp = get_json(django_client, token_url) token = token_rsp['data'] # Can also get this from our session cookies csrf_token = django_client.cookies['csrftoken'].value assert csrf._compare_salted_tokens(token, csrf_token) is True # Now we have all info we need for login. # Set the header, so we don't need to do this for every POST/PUT/DELETE # OR we could add it to each POST as 'csrfmiddlewaretoken' django_client = Client(HTTP_X_CSRFTOKEN=token) data = { 'username': username, 'password': password, 'server': server_id, # 'csrfmiddlewaretoken': token, } login_rsp = django_client.post(login_url, data) login_json = json.loads(login_rsp.content) assert login_json['success'] event_context = login_json['eventContext'] # eventContext gives a bunch of info member_of_groups = event_context['memberOfGroups'] current_group = event_context['groupId'] user_id = event_context['userId'] assert len(member_of_groups) == 2 # includes 'user' group assert current_group in member_of_groups assert user_id > 0
def doDryRun(data): request_url = reverse("chownDryRun") rsp = post(django_client, request_url, data) jobId = rsp.content # Keep polling activities until dry-run job completed activities_url = reverse("activities_json") data = {"jobId": jobId} rsp = get_json(django_client, activities_url, data) while rsp["finished"] is not True: time.sleep(0.5) rsp = get_json(django_client, activities_url, data) return rsp
def doDryRun(data): request_url = reverse('chgrpDryRun') rsp = post(django_client, request_url, data) jobId = rsp.content # Keep polling activities until dry-run job completed activities_url = reverse('activities_json') data = {'jobId': jobId} rsp = get_json(django_client, activities_url, data) while rsp['finished'] is not True: time.sleep(0.5) rsp = get_json(django_client, activities_url, data) return rsp
def test_spw_parent_urls(self, user1, screen_plates): """Test browsing via urls in json /api/image -> well, plate, screen.""" conn = get_connection(user1) user_name = conn.getUser().getName() client = self.new_django_client(user_name, user_name) version = api_settings.API_VERSIONS[-1] screen, plate = screen_plates plates = screen.linkedPlateList() plates.sort(cmp_name_insensitive) # Listing wells - all have link to parents wells_url = reverse('api_wells', kwargs={'api_version': version}) rsp = get_json(client, wells_url) for w in rsp['data']: plates_url = build_url(client, 'api_well_plates', { 'api_version': version, 'well_id': w['@id'] }) assert w['url:plates'] == plates_url # Single Well has link to parents... well_id = rsp['data'][0]['@id'] well_url = wells_url + '%s/' % well_id rsp = get_json(client, well_url) well_json = rsp['data'] well_plates_url = build_url(client, 'api_well_plates', { 'api_version': version, 'well_id': well_id }) assert well_json['url:plates'] == well_plates_url # Get parent plate (Plates list, filtered by Well) print 'well_plates_url', well_plates_url rsp = get_json(client, well_plates_url) plates_json = rsp['data'] # check for link to Screen screens_url = build_url(client, 'api_plate_screens', { 'api_version': version, 'plate_id': plates_json[0]['@id'] }) assert plates_json[0]['url:screens'] == screens_url plate_url = plates_json[0]['url:plate'] assert_objects(conn, plates_json, [plates[0]], dtype='Plate') # Get the same Plate by ID rsp = get_json(client, plate_url) assert rsp['data']['url:screens'] == screens_url # Get Screen rsp = get_json(client, screens_url) assert_objects(conn, rsp['data'], [screen], dtype='Screen')
def test_marshal_projects_params(self, user1, user2, projects_user1_group1, projects_user2_group1): """ Tests normalize and childCount params of projects """ projects = projects_user1_group1 + projects_user2_group1 projects.sort(key=lambda x: lower_or_none(unwrap(x.name))) conn = get_connection(user1) user_name = conn.getUser().getName() django_client = self.new_django_client(user_name, user_name) version = api_settings.API_VERSIONS[-1] request_url = reverse('api_projects', kwargs={'api_version': version}) # Test 'childCount' parameter payload = {'childCount': 'true'} rsp = get_json(django_client, request_url, payload) childCounts = [p['omero:childCount'] for p in rsp['data']] assert childCounts == [0, 0, 0, 2, 1] # make dict of owners and groups to use in next test... owners = {} groups = {} for p in rsp['data']: details = p['omero:details'] owner = details['owner'] group = details['group'] owners[owner['@id']] = owner groups[group['@id']] = group # Test 'normalize' parameter. payload = {'normalize': 'true'} rsp = get_json(django_client, request_url, payload) assert rsp['meta']['totalCount'] == len(rsp['data']) for p in rsp['data']: details = p['omero:details'] owner = details['owner'] group = details['group'] # owner and group have @id only assert list(owner.keys()) == ['@id'] assert list(group.keys()) == ['@id'] # check normaliszed owners and groups are same as before rsp_owners = {} for o in rsp['experimenters']: rsp_owners[o['@id']] = o rsp_groups = {} for g in rsp['experimenterGroups']: rsp_groups[g['@id']] = g assert owners == rsp_owners assert groups == rsp_groups
def test_container_crud(self, dtype): """ Test create, read, update and delete of Containers. Create with POST to /save Read with GET of /m/dtype/:id/ Update with PUT to /m/dtype/:id/ Delete with DELETE to /m/dtype/:id/ """ django_client = self.django_root_client group = self.ctx.groupId version = api_settings.API_VERSIONS[-1] # Need to get the Schema url to create @type base_url = reverse('api_base', kwargs={'api_version': version}) rsp = get_json(django_client, base_url) schema_url = rsp['url:schema'] # specify group via query params save_url = "%s?group=%s" % (rsp['url:save'], group) project_name = 'test_container_create_read' payload = { 'Name': project_name, '@type': '%s#%s' % (schema_url, dtype) } rsp = post_json(django_client, save_url, payload, status_code=201) new_obj = rsp['data'] # We get the complete new Object returned assert new_obj['Name'] == project_name object_id = new_obj['@id'] # Read Object object_url = "%sm/%ss/%s/" % (base_url, dtype.lower(), object_id) rsp = get_json(django_client, object_url) object_json = rsp['data'] assert object_json['@id'] == object_id conn = BlitzGateway(client_obj=self.root) assert_objects(conn, [object_json], [object_id], dtype=dtype) # Update Object... object_json['Name'] = 'new name' rsp = put_json(django_client, save_url, object_json) # ...and read again to check rsp = get_json(django_client, object_url) updated_json = rsp['data'] assert updated_json['Name'] == 'new name' # Delete delete_json(django_client, object_url, {}) # Get should now return 404 rsp = get_json(django_client, object_url, status_code=404)
def test_screens(self, user1, user_screens): """Test listing of Screens.""" conn = get_connection(user1) user_name = conn.getUser().getName() client = self.new_django_client(user_name, user_name) version = api_settings.API_VERSIONS[-1] request_url = reverse('api_screens', kwargs={'api_version': version}) # List ALL Screens rsp = get_json(client, request_url) extra = [] for screen in user_screens: s_url = build_url(client, 'api_screen', { 'api_version': version, 'object_id': screen.id.val }) p_url = build_url(client, 'api_screen_plates', { 'api_version': version, 'screen_id': screen.id.val }) extra.append({'url:screen': s_url, 'url:plates': p_url}) assert_objects(conn, rsp['data'], user_screens, dtype="Screen", extra=extra)
def test_create_tag_and_tagset(self): """ Creates a Tagset then a Tag within the Tagset """ tsValue = 'testTagset' request_url = reverse("manage_action_containers", args=["addnewcontainer"]) data = {'folder_type': 'tagset', 'name': tsValue} response = post(self.django_client, request_url, data) tagsetId = json.loads(response.content).get("id") # check creation tagset = self.query.get('TagAnnotationI', tagsetId) assert tagset is not None assert tagset.ns.val == omero.constants.metadata.NSINSIGHTTAGSET assert tagset.textValue.val == tsValue # Add tag to the tagset request_url = reverse("manage_action_containers", args=["addnewcontainer", "tagset", tagsetId]) data = {'folder_type': 'tag', 'name': 'tagInTagset'} response2 = post(self.django_client, request_url, data) tagId = json.loads(response2.content).get("id") # Check that tag is listed under tagset... request_url = reverse("api_tags_and_tagged") data = {'id': tagsetId} data = get_json(self.django_client, request_url, data) assert len(data['tags']) == 1 assert data['tags'][0]['id'] == tagId
def test_histogram_bin_count(self, bins): """ Test that we get histogram json of the expected size. Default size is 256 bins. """ size_x = 125 size_y = 125 img_id = self.create_test_image(size_x=size_x, size_y=size_y, session=self.sf).id.val the_c = 0 args = [img_id, the_c] payload = {} if bins is not None: payload['bins'] = bins request_url = reverse('histogram_json', args=args) json = get_json(self.django_client, request_url, payload) data = json['data'] # Sum of all pixel counts should equal number of pixels in image assert sum(data) == size_x * size_y # Number of bins should equal the 'bins' parameter (256 by default) if bins is None: assert len(data) == 256 else: assert len(data) == bins
def test_create_tag(self): # Create User and Dataset in a Read-Annotate group client, user = self.new_client_and_user(perms='rwrw--') omeName = client.sf.getAdminService().getEventContext().userName django_client = self.new_django_client(omeName, omeName) ds = self.make_dataset("test_create_tag", client=client) tagname = "test_create_tag" desc = "The description of the new tag" request_url = reverse('annotate_tags') data = { 'dataset': ds.id.val, 'filter_mode': 'any', 'filter_owner_mode': 'all', 'index': 0, 'newtags-0-tag': tagname, 'newtags-0-description': desc, 'newtags-INITIAL_FORMS': 0, 'newtags-MAX_NUM_FORMS': 1000, 'newtags-TOTAL_FORMS': 1, 'tags': "", } post(django_client, request_url, data) # Check tag exists on Dataset request_url = reverse('api_annotations') data = {"dataset": ds.id.val} rsp = get_json(django_client, request_url, data) tagNames = [t['textValue'] for t in rsp['annotations']] assert tagNames == [tagname]
def test_api_experimenter_list_query_string(self, imaprtest, ac): def _expected(menu, extra, count, uid): _res = { "experimenter": { "omeName": menu.capitalize(), "firstName": menu.capitalize(), "extra": extra, "lastName": "", "id": uid, "childCount": count, } } _res['experimenter']['extra'] = extra if extra else {} return json.loads(json.dumps(_res)) request_url = reverse("mapannotations_api_experimenters", args=[ac['menu']]) data = { 'value': ac['value'], # 'experimenter_id': -1 by default } try: cs = ac['case_sensitive'] except KeyError: cs = False data['case_sensitive'] = cs ac['res_value']['case_sensitive'] = cs response = get_json( imaprtest.django_client, request_url, data) assert response == _expected( ac['menu'], ac['res_value'], ac['count'], -1)
def test_api_mapannotations_query_string(self, imaprtest, ac): request_url = reverse("mapannotations_api_mapannotations", args=[ac['menu']]) data = { 'value': ac['value'], 'orphaned': True, # 'experimenter_id': -1 by default } try: data['case_sensitive'] = ac['case_sensitive'] except KeyError: pass response = get_json( imaprtest.django_client, request_url, data) try: c = ac['count'] except KeyError: c = len(ac['res_value']) assert len(response['maps']) == c if len(ac['res_value']) > 0: names = ["%s (%d)" % (k, v) for k, v in ac['res_value'].items()] for r in response['maps']: assert r['name'] in names
def test_api_experimenter_list_query_string(self, imaprtest, ac): def _expected(menu, extra, count, uid): _res = { "experimenter": { "omeName": menu.capitalize(), "firstName": menu.capitalize(), "extra": extra, "lastName": "", "id": uid, "childCount": count, } } _res['experimenter']['extra'] = extra if extra else {} return json.loads(json.dumps(_res)) request_url = reverse("mapannotations_api_experimenters", args=[ac['menu']]) data = { 'value': ac['value'], # 'experimenter_id': -1 by default } try: cs = ac['case_sensitive'] except KeyError: cs = False data['case_sensitive'] = cs ac['res_value']['case_sensitive'] = cs response = get_json(imaprtest.django_client, request_url, data) assert response == _expected(ac['menu'], ac['res_value'], ac['count'], -1)
def test_api_mapannotations_query_string(self, imaprtest, ac): request_url = reverse("mapannotations_api_mapannotations", args=[ac['menu']]) data = { 'value': ac['value'], 'orphaned': True, # 'experimenter_id': -1 by default } try: data['case_sensitive'] = ac['case_sensitive'] except KeyError: pass response = get_json(imaprtest.django_client, request_url, data) try: c = ac['count'] except KeyError: c = len(ac['res_value']) assert len(response['maps']) == c if len(ac['res_value']) > 0: names = ["%s (%d)" % (k, v) for k, v in ac['res_value'].items()] for r in response['maps']: assert r['name'] in names
def test_container_tags_update(self, user1, dtype): """ Test updating a Object without losing linked Tags. If we load a Object without loading Annotations, then update and save the Object, we don't want to lose Annotation links """ conn = get_connection(user1) user_name = conn.getUser().getName() django_client = self.new_django_client(user_name, user_name) container = dtype[1]() container.name = rstring('test_container_tags_update') tag = TagAnnotationI() tag.textValue = rstring('tag') container.linkAnnotation(tag) container = get_update_service(user1).saveAndReturnObject(container) version = api_settings.API_VERSIONS[-1] object_url = reverse('api_%s' % dtype[0], kwargs={ 'api_version': version, 'object_id': container.id.val }) save_url = reverse('api_save', kwargs={'api_version': version}) # Get container, update and save back rsp = get_json(django_client, object_url) object_json = rsp['data'] object_json['Name'] = 'renamed container' put_json(django_client, save_url, object_json) # Check container has been updated and still has annotation links proj = conn.getObject(dtype[0], container.id.val) assert proj.getName() == 'renamed container' assert len(list(proj.listAnnotations())) == 1
def test_list_figures(self, user1): """Test create and update are rejected for unsupported types.""" conn = get_connection(user1) user_name = conn.getUser().getName() django_client = self.new_django_client(user_name, user_name) list_files_url = reverse('list_web_figures') rsp = get_json(django_client, list_files_url) assert len(rsp) == 0
def test_invalid_parameter(self): """Test that invalid query parameter gives suitable message.""" django_client = self.django_root_client version = api_settings.API_VERSIONS[-1] projects_url = reverse('api_projects', kwargs={'api_version': version}) payload = {'limit': 'foo'} rsp = get_json(django_client, projects_url, payload, status_code=400) assert (rsp['message'] == "invalid literal for int() with base 10: 'foo'")
def test_marshal_projects_not_logged_in(self): """ Test marshalling projects without log-in """ django_client = Client() version = api_settings.API_VERSIONS[-1] request_url = reverse('api_projects', kwargs={'api_version': version}) rsp = get_json(django_client, request_url, status_code=403) assert rsp['message'] == "Not logged in"
def test_autocomplete_case_sensitive(self, imaprtest, ac): request_url = reverse("mapannotations_autocomplete", args=[ac['menu']]) data = { 'value': ac['search_value'], 'case_sensitive': ac['case_sensitive'], 'query': 'true', } response = get_json( imaprtest.django_client, request_url, data) assert response == [{'value': ac['value']}]
def test_api_experimenter_list_wildcard(self, imaprtest, wildcard_settings, params): request_url = reverse("mapannotations_api_experimenters", args=[params['menu']]) response = get_json( imaprtest.django_client, request_url, {}) if params['childCount'] is not None: assert response['experimenter']['childCount'] == \ params['childCount'] else: with pytest.raises(KeyError) as excinfo: response['experimenter']['childCount'] assert excinfo.match("'childCount'")
def test_autocomplete_case_insensitive(self, imaprtest, ac): request_url = reverse("mapannotations_autocomplete", args=[ac['menu']]) data = { 'value': ac['search_value'], 'case_sensitive': ac['case_sensitive'], 'query': 'true', } response = get_json( imaprtest.django_client, request_url, data) res = [r['value'] for r in response] assert len(res) == len(ac['values']) assert sorted(res) == sorted(ac['values'])
def test_autocomplete_default(self, imaprtest, ac): request_url = reverse("mapannotations_autocomplete", args=[ac['menu']]) data = { 'value': ac['search_value'], 'query': 'true', } response = get_json( imaprtest.django_client, request_url, data) res = [] if ac['value'] is not None: res = [{'value': ac['value']}] assert response == res
def test_api_mapannotations_wildcard(self, imaprtest, wildcard_settings, params): request_url = reverse("mapannotations_api_mapannotations", args=[params['menu']]) response = get_json( imaprtest.django_client, request_url, {}) if params['count'] is not None: assert len(response['screens']) == params['count'] assert len(response['maps']) == 0 assert len(response['projects']) == 0 for r in response['screens']: assert r['name'].startswith("Screen001") assert r['childCount'] == 1 else: assert response == {u'screens': [], u'maps': [], u'projects': []}