Ignore:
Timestamp:
12/10/13 15:18:42 (10 years ago)
Author:
olhsha
Message:

lintegrity unit test reconstructed so it does not mock any more. getAnnotation works (the others are "ignored"). Needs refactoring (the subdirectory with beans and DummySecurityFilter? class.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/test/java/eu/dasish/annotation/backend/rest/AnnotationsTest.java

    r4146 r4173  
    1818package eu.dasish.annotation.backend.rest;
    1919
    20 import eu.dasish.annotation.backend.dao.DBIntegrityService;
    2120import com.sun.jersey.api.client.ClientResponse;
    22 import eu.dasish.annotation.backend.Helpers;
     21import com.sun.jersey.api.client.WebResource;
     22import com.sun.jersey.api.client.WebResource.Builder;
     23import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
     24import com.sun.jersey.core.util.Base64;
     25import com.sun.jersey.spi.spring.container.servlet.SpringServlet;
     26import com.sun.jersey.test.framework.JerseyTest;
     27import com.sun.jersey.test.framework.WebAppDescriptor;
    2328import eu.dasish.annotation.backend.TestBackendConstants;
     29import eu.dasish.annotation.backend.TestInstances;
     30import eu.dasish.annotation.backend.dao.impl.JdbcResourceDaoTest;
    2431import eu.dasish.annotation.schema.Annotation;
    2532import eu.dasish.annotation.schema.ObjectFactory;
     
    2734import eu.dasish.annotation.schema.TargetInfo;
    2835import eu.dasish.annotation.schema.TargetInfoList;
     36import java.io.File;
     37import java.io.FileNotFoundException;
     38import java.net.URISyntaxException;
     39import java.net.URL;
    2940import java.sql.SQLException;
    30 import java.sql.Timestamp;
    3141import java.util.ArrayList;
    3242import java.util.List;
     43import java.util.Scanner;
    3344import java.util.UUID;
     45import javax.servlet.http.HttpServletRequest;
     46import javax.ws.rs.core.Context;
     47import javax.ws.rs.core.HttpHeaders;
    3448import javax.ws.rs.core.MediaType;
    35 import javax.ws.rs.core.UriInfo;
    3649import javax.xml.bind.JAXBElement;
    3750import javax.xml.datatype.DatatypeConfigurationException;
    3851import javax.xml.datatype.DatatypeFactory;
    39 import org.jmock.Expectations;
    4052import org.junit.Test;
    4153import static org.junit.Assert.*;
     54import org.junit.Before;
    4255import org.junit.Ignore;
     56import org.junit.runner.RunWith;
     57import org.springframework.beans.factory.annotation.Autowired;
     58import org.springframework.dao.DataAccessException;
     59import org.springframework.jdbc.core.JdbcTemplate;
     60import org.springframework.mock.web.MockHttpServletRequest;
     61import org.springframework.test.context.ContextConfiguration;
     62import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
     63import org.springframework.web.context.ContextLoaderListener;
     64import org.springframework.web.context.request.RequestContextListener;
     65
    4366/**
    4467 *
    4568 * @author olhsha
    4669 */
    47 public class AnnotationsTest extends ResourcesTest{
    48    
    49     private DBIntegrityService daoDispatcher;
    50    
    51     private UriInfo uriInfo;
     70@RunWith(value = SpringJUnit4ClassRunner.class)
     71@ContextConfiguration({"/spring-integrity-test-config/dataSource.xml"})
     72public class AnnotationsTest extends JerseyTest {   
     73   
     74    @Autowired
     75    private JdbcTemplate jdbcTemplate;
    5276   
    5377    public AnnotationsTest() {
    54         super(AnnotationResource.class.getPackage().getName());       
    55         daoDispatcher = webAppContext.getBean(DBIntegrityService.class);
    56         uriInfo = webAppContext.getBean(UriInfo.class);
    57     }
    58    
    59 
    60      /**
    61      * Test of getAnnotation method, of class annotationResource. Get <aid>.
    62      * GET api/annotations/<aid>
     78        super(new WebAppDescriptor.Builder(AnnotationResource.class.getPackage().getName())
     79                .servletClass(SpringServlet.class)
     80                .contextParam("contextConfigLocation", "classpath*:spring-integrity-test-config/*.xml")
     81                .addFilter(DummySecurityFilter.class, "DummySecurityFilter")
     82                .requestListenerClass(RequestContextListener.class)
     83                .contextListenerClass(ContextLoaderListener.class)
     84                .build());
     85       
     86    }
     87   
     88    private String getNormalisedSql() throws FileNotFoundException, URISyntaxException {
     89        // remove the unsupported sql for the test
     90        final URL sqlUrl = JdbcResourceDaoTest.class.getResource("/sql/DashishAnnotatorCreate.sql");
     91        String sqlString = new Scanner(new File(sqlUrl.toURI()), "UTF8").useDelimiter("\\Z").next();
     92        for (String unknownToken : new String[]{
     93                    "SET client_encoding",
     94                    "CREATE DATABASE",
     95                    "\\\\connect",
     96                    "SET default_with_oids",
     97                    "ALTER SEQUENCE",
     98                    "ALTER TABLE ONLY",
     99                    "ADD CONSTRAINT",
     100                    "CREATE INDEX", // "ALTER TABLE ONLY [a-z]* ALTER COLUMN",
     101                // "ALTER TABLE ONLY [^A]* ADD CONSTRAINT"
     102                }) {
     103            sqlString = sqlString.replaceAll(unknownToken, "-- " + unknownToken);
     104        }
     105        // obsolete(?) Peter's stuff, before body has been decided to be a text with its mimetype: sqlString = sqlString.replaceAll("body_xml xml", "body_xml text");
     106        sqlString = sqlString.replaceAll("CACHE 1;", "; -- CACHE 1;");
     107        //sqlString = sqlString.replaceAll("UUID", "text");
     108        sqlString = sqlString.replaceAll("SERIAL NOT NULL", "INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY");
     109        return sqlString;
     110    }
     111   
     112    private String getTestDataInsertSql() throws FileNotFoundException, URISyntaxException {
     113        final URL sqlUrl = AnnotationsTest.class.getResource("/test-data/InsertTestData.sql");
     114        String sqlString = new Scanner(new File(sqlUrl.toURI()), "UTF8").useDelimiter("\\Z").next();
     115        return sqlString;
     116    }
     117   
     118   
     119   
     120    @Override
     121    @Before
     122    public void setUp() throws DataAccessException, FileNotFoundException, URISyntaxException, Exception {
     123        super.setUp();
     124        jdbcTemplate.execute("DROP SCHEMA PUBLIC CASCADE");
     125        // consume the DashishAnnotatorCreate sql script to create the database
     126        jdbcTemplate.execute(getNormalisedSql());
     127        jdbcTemplate.execute(getTestDataInsertSql());
     128    }
     129
     130   
     131    @Override
     132    public void tearDown() throws Exception {
     133        super.tearDown();
     134    }
     135    /**
     136     * Test of getAnnotation method, of class annotationResource. Get <aid>. GET
     137     * api/annotations/<aid>
     138     */
     139    @Test
     140    public void testGetAnnotation() throws SQLException, DatatypeConfigurationException {
     141        System.out.println("testGetAnnotation");
     142        final String externalIDstring = TestBackendConstants._TEST_ANNOT_2_EXT;
     143        final Annotation testAnnotation = (new TestInstances(resource().getURI().toString())).getAnnotationOne();       
     144       
     145        final String requestUrl = "annotations/" + externalIDstring;
     146        System.out.println("requestUrl: " + requestUrl);
     147       
     148        Builder responseBuilder = getAuthenticatedResource(resource().path(requestUrl)).accept(MediaType.TEXT_XML);
     149       
     150        ClientResponse response = responseBuilder.get(ClientResponse.class);       
     151       
     152        assertEquals(200, response.getStatus());
     153        Annotation entity = response.getEntity(Annotation.class);
     154        assertEquals(testAnnotation.getBody().getTextBody().getValue(), entity.getBody().getTextBody().getValue());
     155        assertEquals(testAnnotation.getHeadline(), entity.getHeadline());
     156        assertEquals(testAnnotation.getOwnerRef(), entity.getOwnerRef());
     157        assertEquals(3, entity.getPermissions().getUserWithPermission().size());
     158        assertEquals("owner", entity.getPermissions().getUserWithPermission().get(0).getPermission().value());       
     159        assertEquals(resource().getURI()+"users/"+TestBackendConstants._TEST_USER_3_EXT_ID, entity.getPermissions().getUserWithPermission().get(0).getRef());
     160        assertEquals("writer", entity.getPermissions().getUserWithPermission().get(1).getPermission().value());
     161        assertEquals(resource().getURI()+"users/"+TestBackendConstants._TEST_USER_4_EXT_ID, entity.getPermissions().getUserWithPermission().get(1).getRef());
     162        assertEquals("reader", entity.getPermissions().getUserWithPermission().get(2).getPermission().value());
     163        assertEquals(resource().getURI()+"users/"+TestBackendConstants._TEST_USER_5_EXT_ID, entity.getPermissions().getUserWithPermission().get(2).getRef());
     164        assertEquals(2, entity.getTargets().getTargetInfo().size());
     165        assertEquals(resource().getURI().toString()+"targets/"+TestBackendConstants._TEST_Target_1_EXT_ID, entity.getTargets().getTargetInfo().get(0).getRef());
     166        assertEquals(resource().getURI().toString()+"targets/"+TestBackendConstants._TEST_Target_2_EXT_ID, entity.getTargets().getTargetInfo().get(1).getRef());
     167        assertEquals(testAnnotation.getLastModified(), entity.getLastModified());
     168        assertEquals(resource().getURI()+requestUrl, entity.getURI());
     169    }
     170
     171    /**
     172     * Test of deleteAnnotation method, of class AnnotationResource. Delete
     173     * <nid>. DELETE api/annotations/<aid>
    63174     */
    64175    @Test
    65176    @Ignore
    66     public void testGetAnnotation() throws SQLException, DatatypeConfigurationException{
    67         System.out.println("testGetAnnotation");
    68         final String externalIDstring= TestBackendConstants._TEST_ANNOT_2_EXT;
    69         final int annotationID = 2;
    70         final Annotation testAnnotation = new Annotation();
    71         testAnnotation.setOwnerRef("5");
    72         testAnnotation.setURI(externalIDstring);
    73         testAnnotation.setLastModified(DatatypeFactory.newInstance().newXMLGregorianCalendar(TestBackendConstants._TEST_ANNOT_2_TIME_STAMP));
    74        
     177    public void testDeleteAnnotation() throws SQLException {
     178        System.out.println("testDeleteAnnotation");
    75179        //final Number annotationID = daoDispatcher.getAnnotationInternalIdentifier(UUID.fromString(UUID));
    76         //final Annotation annotation = daoDispatcher.getAnnotation(annotationID);
    77         mockeryRest.checking(new Expectations() {
    78             {
    79                  
    80                 oneOf(uriInfo).getBaseUri();
    81                 will(returnValue("http://localhost:8080/annotator-backend/api/"));
    82                
    83                
    84                 oneOf(daoDispatcher).setServiceURI(with(any(String.class)));
    85                 will(doAll());
    86                
    87                 oneOf(daoDispatcher).getAnnotationInternalIdentifier(with(aNonNull(UUID.class)));               
    88                 will(returnValue(annotationID));               
    89                
    90                 oneOf(daoDispatcher).getAnnotation(annotationID);               
    91                 will(returnValue(testAnnotation));
    92             }
    93         });
    94        
    95         final String requestUrl = "annotations/" + externalIDstring;
    96         System.out.println("requestUrl: " + requestUrl);
    97         ClientResponse response = resource().path(requestUrl).accept(MediaType.TEXT_XML).get(ClientResponse.class);
    98         assertEquals(200, response.getStatus());
    99         Annotation entity = response.getEntity(Annotation.class);
    100         assertEquals(testAnnotation.getBody(), entity.getBody());
    101         assertEquals(testAnnotation.getHeadline(), entity.getHeadline());
    102         assertEquals(testAnnotation.getOwnerRef(), entity.getOwnerRef());
    103         assertEquals(testAnnotation.getPermissions(), entity.getPermissions());
    104         assertEquals(testAnnotation.getTargets(), entity.getTargets());
    105         assertEquals(testAnnotation.getLastModified(), entity.getLastModified());
    106         assertEquals(testAnnotation.getURI(), entity.getURI());
    107     } 
    108    
    109      /**
    110      * Test of deleteAnnotation method, of class AnnotationResource. Delete <nid>.
    111      * DELETE api/annotations/<aid>
    112      */
    113     @Test
    114     @Ignore
    115     public void testDeleteAnnotation() throws SQLException{
    116         System.out.println("testDeleteAnnotation");
    117          //final Number annotationID = daoDispatcher.getAnnotationInternalIdentifier(UUID.fromString(UUID));
    118180        //int[] resultDelete = daoDispatcher.deleteAnnotation(annotationID);
    119        
     181        
    120182        final int[] mockDelete = new int[4];
    121         mockDelete[0]=1; // # deleted annotations
    122         mockDelete[3]=1; // # deleted annotation_prinipal_permissions
    123         mockDelete[2]=2; // # deleted  annotations_target_Targets, (5,3), (5,4)
    124         mockDelete[3]=1; // # deletd Targets, 4
    125         mockeryRest.checking(new Expectations() {
    126             { 
    127                  
    128                 oneOf(uriInfo).getBaseUri();
    129                 will(returnValue("http://localhost:8080/annotator-backend/api/"));
    130                
    131                
    132                 oneOf(daoDispatcher).setServiceURI(with(any(String.class)));
    133                 will(doAll());
    134                
    135                 oneOf(daoDispatcher).getAnnotationInternalIdentifier(with(aNonNull(UUID.class)));             
    136                 will(returnValue(5));     
    137                
    138                 oneOf(daoDispatcher).deleteAnnotation(5);
    139                 will(returnValue(mockDelete));
    140             }
    141         });
     183        mockDelete[0] = 1; // # deleted annotations
     184        mockDelete[3] = 1; // # deleted annotation_prinipal_permissions
     185        mockDelete[2] = 2; // # deleted  annotations_target_Targets, (5,3), (5,4)
     186        mockDelete[3] = 1; // # deletd Targets, 4
     187       
     188        final String baseURI = this.getBaseURI().toString();
     189       
    142190        final String requestUrl = "annotations/" + TestBackendConstants._TEST_ANNOT_5_EXT;
    143191        System.out.println("requestUrl: " + requestUrl);
     
    146194        assertEquals("1 annotation(s) deleted.", response.getEntity(String.class));
    147195       
    148      
    149     }
     196       
     197    }
     198
    150199    /**
    151      * Test of createAnnotation method, of class AnnotationResource.
    152      * POST api/annotations/
     200     * Test of createAnnotation method, of class AnnotationResource. POST
     201     * api/annotations/
    153202     */
    154203    @Test
    155204    @Ignore
    156     public void testCreateAnnotation() throws SQLException, InstantiationException, IllegalAccessException, DatatypeConfigurationException, Exception{
     205    public void testCreateAnnotation() throws SQLException, InstantiationException, IllegalAccessException, DatatypeConfigurationException, Exception {
    157206        System.out.println("test createAnnotation");
    158207        // Peter's workaround on absence of "ObjectFactory.create... for annotations       
     
    160209       
    161210        final String ownerString = "5";
    162         final Number ownerID =  5;
     211        final Number ownerID = 5;
    163212        final Number newAnnotationID = 6;
    164213       
     
    173222        addedAnnotation.setTargets(TargetInfoList);
    174223        addedAnnotation.setOwnerRef(ownerString);
    175         addedAnnotation.setURI(TestBackendConstants._TEST_SERVLET_URI_annotations+UUID.randomUUID().toString());       
     224        addedAnnotation.setURI(TestBackendConstants._TEST_SERVLET_URI_annotations + UUID.randomUUID().toString());       
    176225        addedAnnotation.setLastModified(DatatypeFactory.newInstance().newXMLGregorianCalendar(TestBackendConstants._TEST_ANNOT_2_TIME_STAMP));       
    177226        TargetInfo TargetInfo = new TargetInfo();
     
    179228        TargetInfo.setRef(UUID.randomUUID().toString());
    180229        TargetInfo.setVersion("vandaag");
    181         TargetInfoList.getTargetInfo().add(TargetInfo);
     230        TargetInfoList.getTargetInfo().add(TargetInfo);        
    182231       
    183232        final List<Number> Targets = new ArrayList<Number>();
    184233        Targets.add(6);
    185234       
    186         mockeryRest.checking(new Expectations() {
    187             {
    188                  
    189                 oneOf(uriInfo).getBaseUri();
    190                 will(returnValue("http://localhost:8080/annotator-backend/api/"));
    191                
    192                
    193                 oneOf(daoDispatcher).setServiceURI(with(any(String.class)));
    194                 will(doAll());
    195                
    196                 oneOf(daoDispatcher).getUserInternalIdentifier(with(any(UUID.class)));
    197                 will(returnValue(ownerID));
    198                
    199                 //oneOf(daoDispatcher).addUsersAnnotation(annotToAddJB, ownerID);
    200                 oneOf(daoDispatcher).addUsersAnnotation(with(aNonNull(Number.class)), with(aNonNull(Annotation.class)));
    201                 will(returnValue(newAnnotationID));
    202                
    203                 oneOf(daoDispatcher).getAnnotation(newAnnotationID);
    204                 will(returnValue(addedAnnotation));
    205                
    206                 oneOf(daoDispatcher).getTargetsWithNoCachedRepresentation(newAnnotationID);
    207                 will(returnValue(Targets));
    208             }
    209         });
    210        
    211              
     235        final String baseURI = this.getBaseURI().toString();
    212236       
    213237        final String requestUrl = "annotations";
     
    216240        assertEquals(200, response.getStatus());
    217241       
    218         ResponseBody entity = response.getEntity(ResponseBody.class);
     242        ResponseBody entity = response.getEntity(ResponseBody.class);        
    219243        Annotation entityA = entity.getAnnotation();
    220244        assertEquals(addedAnnotation.getBody(), entityA.getBody());
     
    227251        assertEquals(addedAnnotation.getOwnerRef(), entityA.getOwnerRef());
    228252    }
     253   
     254   
     255   
     256    protected Builder getAuthenticatedResource(WebResource resource) {
     257        return resource.header(HttpHeaders.AUTHORIZATION, "Basic "  + new String(Base64.encode(DummyPrincipal.DUMMY_PRINCIPAL.getName()+":olhapassword")));
     258    }
    229259}
Note: See TracChangeset for help on using the changeset viewer.