Testando a API do aplicativo Reddit

Testando a API do aplicativo Reddit

1. Visão geral

Estamos construindo a API REST deour simple Reddit App há algum tempo - é hora de levar a sério estart testing it.

E agora que nósfinally switched para um mecanismo de autenticação mais simples, é mais fácil fazer isso também. Usaremosthe powerful rest-assured library para todos esses testes ao vivo.

2. Configuração inicial

Os testes de API precisam de um usuário para serem executados; para simplificar a execução de testes na API, teremos um usuário de teste criado antecipadamente - no bootstrap do aplicativo:

@Component
public class Setup {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PreferenceRepository preferenceRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostConstruct
    private void createTestUser() {
        User userJohn = userRepository.findByUsername("john");
        if (userJohn == null) {
            userJohn = new User();
            userJohn.setUsername("john");
            userJohn.setPassword(passwordEncoder.encode("123"));
            userJohn.setAccessToken("token");
            userRepository.save(userJohn);
            final Preference pref = new Preference();
            pref.setTimezone(TimeZone.getDefault().getID());
            pref.setEmail("[email protected]");
            preferenceRepository.save(pref);
            userJohn.setPreference(pref);
            userRepository.save(userJohn);
        }
    }
}

Observe comoSetup é um bean simples e estamos usando a anotação@PostConstruct para ligar a lógica de configuração real.

3. Suporte para testes ao vivo

Antes de começarmos a realmente escrever nossos testes,let’s first set up some basic supporting functionality podemos então alavancar.

Precisamos de coisas como autenticação, caminhos de URL e talvez alguns recursos de integração e exclusão de JSON:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
  classes = { TestConfig.class },
  loader = AnnotationConfigContextLoader.class)
public class AbstractLiveTest {
    public static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    @Autowired
    private CommonPaths commonPaths;

    protected String urlPrefix;

    protected ObjectMapper objectMapper = new ObjectMapper().setDateFormat(dateFormat);

    @Before
    public void setup() {
        urlPrefix = commonPaths.getServerRoot();
    }

    protected RequestSpecification givenAuth() {
        FormAuthConfig formConfig
          = new FormAuthConfig(urlPrefix + "/j_spring_security_check", "username", "password");
        return RestAssured.given().auth().form("john", "123", formConfig);
    }

    protected RequestSpecification withRequestBody(RequestSpecification req, Object obj)
      throws JsonProcessingException {
        return req.contentType(MediaType.APPLICATION_JSON_VALUE)
          .body(objectMapper.writeValueAsString(obj));
    }
}

Estamos apenas definindo alguns métodos e campos auxiliares simples para facilitar o teste real:

  • givenAuth(): para realizar a autenticação

  • withRequestBody(): para enviar a representação JSON de umObject como o corpo da solicitação HTTP

E aqui está nosso bean simples -CommonPaths - fornecendo uma abstração limpa para as URLs do sistema:

@Component
@PropertySource({ "classpath:web-${envTarget:local}.properties" })
public class CommonPaths {

    @Value("${http.protocol}")
    private String protocol;

    @Value("${http.port}")
    private String port;

    @Value("${http.host}")
    private String host;

    @Value("${http.address}")
    private String address;

    public String getServerRoot() {
        if (port.equals("80")) {
            return protocol + "://" + host + "/" + address;
        }
        return protocol + "://" + host + ":" + port + "/" + address;
    }
}

E a versão local do arquivo de propriedades:web-local.properties:

http.protocol=http
http.port=8080
http.host=localhost
http.address=reddit-scheduler

Por fim, a configuração muito simples do Spring de teste:

@Configuration
@ComponentScan({ "org.example.web.live" })
public class TestConfig {
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

4. Teste a / scheduledPosts API

A primeira API que vamos testar é a API/scheduledPosts:

public class ScheduledPostLiveTest extends AbstractLiveTest {
    private static final String date = "2016-01-01 00:00";

    private Post createPost() throws ParseException, IOException {
        Post post = new Post();
        post.setTitle("test");
        post.setUrl("test.com");
        post.setSubreddit("test");
        post.setSubmissionDate(dateFormat.parse(date));

        Response response = withRequestBody(givenAuth(), post)
          .post(urlPrefix + "/api/scheduledPosts?date=" + date);

        return objectMapper.reader().forType(Post.class).readValue(response.asString());
    }
}

Primeiro, vamos testarscheduling a new post:

@Test
public void whenScheduleANewPost_thenCreated()
  throws ParseException, IOException {
    Post post = new Post();
    post.setTitle("test");
    post.setUrl("test.com");
    post.setSubreddit("test");
    post.setSubmissionDate(dateFormat.parse(date));

    Response response = withRequestBody(givenAuth(), post)
      .post(urlPrefix + "/api/scheduledPosts?date=" + date);

    assertEquals(201, response.statusCode());
    Post result = objectMapper.reader().forType(Post.class).readValue(response.asString());
    assertEquals(result.getUrl(), post.getUrl());
}

A seguir, vamos testarretrieving all scheduled posts de um usuário:

@Test
public void whenGettingUserScheduledPosts_thenCorrect()
  throws ParseException, IOException {
    createPost();

    Response response = givenAuth().get(urlPrefix + "/api/scheduledPosts?page=0");

    assertEquals(201, response.statusCode());
    assertTrue(response.as(List.class).size() > 0);
}

A seguir, vamos testarediting a scheduled post:

@Test
public void whenUpdatingScheduledPost_thenUpdated()
  throws ParseException, IOException {
    Post post = createPost();

    post.setTitle("new title");
    Response response = withRequestBody(givenAuth(), post).
      put(urlPrefix + "/api/scheduledPosts/" + post.getId() + "?date=" + date);

    assertEquals(200, response.statusCode());
    response = givenAuth().get(urlPrefix + "/api/scheduledPosts/" + post.getId());
    assertTrue(response.asString().contains(post.getTitle()));
}

Por fim, vamos testarthe delete operation na API:

@Test
public void whenDeletingScheduledPost_thenDeleted()
  throws ParseException, IOException {
    Post post = createPost();
    Response response = givenAuth().delete(urlPrefix + "/api/scheduledPosts/" + post.getId());

    assertEquals(204, response.statusCode());
}

5. Teste a API /sites

A seguir - vamos testar a API de publicação dos recursos do Sites - os sites definidos por um usuário:

public class MySitesLiveTest extends AbstractLiveTest {

    private Site createSite() throws ParseException, IOException {
        Site site = new Site("/feed/");
        site.setName("example");

        Response response = withRequestBody(givenAuth(), site)
          .post(urlPrefix + "/sites");

        return objectMapper.reader().forType(Site.class).readValue(response.asString());
    }
}

Vamos testarretrieving all the sites do usuário:

@Test
public void whenGettingUserSites_thenCorrect()
  throws ParseException, IOException {
    createSite();
    Response response = givenAuth().get(urlPrefix + "/sites");

    assertEquals(200, response.statusCode());
    assertTrue(response.as(List.class).size() > 0);
}

E também recuperando os artigos de um site:

@Test
public void whenGettingSiteArticles_thenCorrect()
  throws ParseException, IOException {
    Site site = createSite();
    Response response = givenAuth().get(urlPrefix + "/sites/articles?id=" + site.getId());

    assertEquals(200, response.statusCode());
    assertTrue(response.as(List.class).size() > 0);
}

A seguir, vamos testaradding a new Site:

@Test
public void whenAddingNewSite_thenCorrect()
  throws ParseException, IOException {
    Site site = createSite();

    Response response = givenAuth().get(urlPrefix + "/sites");
    assertTrue(response.asString().contains(site.getUrl()));
}

Edeleting:

@Test
public void whenDeletingSite_thenDeleted() throws ParseException, IOException {
    Site site = createSite();
    Response response = givenAuth().delete(urlPrefix + "/sites/" + site.getId());

    assertEquals(204, response.statusCode());
}

6. Teste a API/user/preferences

Finalmente, vamos nos concentrar na API expondo as preferências do usuário.

Primeiro, vamos testargetting user’s preferences:

@Test
public void whenGettingPrefernce_thenCorrect() {
    Response response = givenAuth().get(urlPrefix + "/user/preference");

    assertEquals(200, response.statusCode());
    assertTrue(response.as(Preference.class).getEmail().contains("john"));
}

Eediting eles:

@Test
public void whenUpdattingPrefernce_thenCorrect()
  throws JsonProcessingException {
    Preference pref = givenAuth().get(urlPrefix + "/user/preference").as(Preference.class);
    pref.setEmail("[email protected]");
    Response response = withRequestBody(givenAuth(), pref).
      put(urlPrefix + "/user/preference/" + pref.getId());

    assertEquals(200, response.statusCode());
    response = givenAuth().get(urlPrefix + "/user/preference");
    assertEquals(response.as(Preference.class).getEmail(), pref.getEmail());
}

7. Conclusão

Neste artigo rápido, reunimos alguns testes básicos para nossa API REST.

Nada a imaginar - cenários mais avançados são necessários - masthis isn’t about perfection, it’s about progress and iterating in public.