Unverified Commit 18f52fe7 authored by Lukas Wiest's avatar Lukas Wiest 🚂
Browse files

test: add unittests for first library state

parent b841acdd
package de.hft.unifiedticketing.core;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.util.*;
public class FilterTest
{
public Filter instance;
@BeforeEach
public void initBeforeEach()
{
instance = mock(Filter.class, withSettings().useConstructor().defaultAnswer(CALLS_REAL_METHODS));
}
@Test
public void testWithSingleAssigneeId()
{
String value = "testId";
Set<String> expected = new HashSet<>();
expected.add(value);
instance.withAssigneeId(value);
assertEquals(expected, instance.setFilters.get(Filter.FilterNames.ASSIGNEEID.name()));
}
@Test
public void testWithMultipleAssigneeId()
{
String[] values = new String[]{"testId", "anotherone", "thirdId"};
Set<String> expected = new HashSet<>(Arrays.asList(values));
Object valueBeforeFirstAdd = instance.setFilters.get(Filter.FilterNames.ASSIGNEEID.name());
instance.withAssigneeId(values[0]);
Object valueAfterFirstAdd = instance.setFilters.get(Filter.FilterNames.ASSIGNEEID.name());
Arrays.stream(values).forEach(instance::withAssigneeId);
Arrays.stream(values).forEach(instance::withAssigneeId);
Object valueAfterAllAdds = instance.setFilters.get(Filter.FilterNames.ASSIGNEEID.name());
assertAll(
() -> assertNull(valueBeforeFirstAdd), // no initial instance present
() -> assertNotNull(valueAfterFirstAdd), // after first add there has to be one
() -> assertSame(valueAfterFirstAdd, valueAfterAllAdds), // check the collection stayed the same
() -> assertEquals(expected, valueAfterAllAdds) // check the content is only in there once and complete
);
}
@Test
public void testWithSingleAssigneeName()
{
String value = "testName";
Set<String> expected = new HashSet<>();
expected.add(value);
instance.withAssigneeName(value);
assertEquals(expected, instance.setFilters.get(Filter.FilterNames.ASSIGNEENAME.name()));
}
@Test
public void testWithMultipleAssigneeName()
{
String[] values = new String[]{"testName", "anotherone", "thirdName"};
Set<String> expected = new HashSet<>(Arrays.asList(values));
Object valueBeforeFirstAdd = instance.setFilters.get(Filter.FilterNames.ASSIGNEENAME.name());
instance.withAssigneeName(values[0]);
Object valueAfterFirstAdd = instance.setFilters.get(Filter.FilterNames.ASSIGNEENAME.name());
Arrays.stream(values).forEach(instance::withAssigneeName);
Arrays.stream(values).forEach(instance::withAssigneeName);
Object valueAfterAllAdds = instance.setFilters.get(Filter.FilterNames.ASSIGNEENAME.name());
assertAll(
() -> assertNull(valueBeforeFirstAdd), // no initial instance present
() -> assertNotNull(valueAfterFirstAdd), // after first add there has to be one
() -> assertSame(valueAfterFirstAdd, valueAfterAllAdds), // check the collection stayed the same
() -> assertEquals(expected, valueAfterAllAdds) // check the content is only in there once and complete
);
}
@Test
public void testWithDescriptionContain()
{
String expected = "test description";
Object valueBeforeFirstAdd = instance.setFilters.get(Filter.FilterNames.DESCRIPTION_CONTAIN.name());
instance.withDescriptionContain(expected);
Object valueAfterAdd = instance.setFilters.get(Filter.FilterNames.DESCRIPTION_CONTAIN.name());
assertAll(
() -> assertNull(valueBeforeFirstAdd), // no initial instance present
() -> assertEquals(expected, valueAfterAdd) // after add there has to be the set one
);
}
@Test
public void testWithDescriptionMatch()
{
String expected = "^some stupid regex number [0-9]+";
Object valueBeforeFirstAdd = instance.setFilters.get(Filter.FilterNames.DESCRIPTION_MATCH.name());
instance.withDescriptionMatch(expected);
Object valueAfterAdd = instance.setFilters.get(Filter.FilterNames.DESCRIPTION_MATCH.name());
assertAll(
() -> assertNull(valueBeforeFirstAdd), // no initial instance present
() -> assertEquals(expected, valueAfterAdd) // after add there has to be the set one
);
}
@Test
public void testWithSingleTicketId()
{
String value = "testId";
Set<String> expected = new HashSet<>();
expected.add(value);
instance.withId(value);
assertEquals(expected, instance.setFilters.get(Filter.FilterNames.IDS.name()));
}
@Test
public void testWithMultipleTicketIds()
{
String[] values = new String[]{"testId", "anotherone", "thirdId"};
Set<String> expected = new HashSet<>(Arrays.asList(values));
Object valueBeforeFirstAdd = instance.setFilters.get(Filter.FilterNames.IDS.name());
instance.withId(values[0]);
Object valueAfterFirstAdd = instance.setFilters.get(Filter.FilterNames.IDS.name());
Arrays.stream(values).forEach(instance::withId);
Arrays.stream(values).forEach(instance::withId);
Object valueAfterAllAdds = instance.setFilters.get(Filter.FilterNames.IDS.name());
assertAll(
() -> assertNull(valueBeforeFirstAdd), // no initial instance present
() -> assertNotNull(valueAfterFirstAdd), // after first add there has to be one
() -> assertSame(valueAfterFirstAdd, valueAfterAllAdds), // check the collection stayed the same
() -> assertEquals(expected, valueAfterAllAdds) // check the content is only in there once and complete
);
}
@Test
public void testIsOpen()
{
instance
.isOpen()
.isClosed()
.isOpen();
assertEquals(Boolean.TRUE, instance.setFilters.get(Filter.FilterNames.OPEN.name()));
}
@Test
public void testIsClosed()
{
instance
.isClosed()
.isOpen()
.isClosed();
assertEquals(Boolean.FALSE, instance.setFilters.get(Filter.FilterNames.OPEN.name()));
}
@Test
public void testWithSingleLabel()
{
String value = "test";
Set<String> expected = new HashSet<>();
expected.add(value);
instance.withLabel(value);
assertEquals(expected, instance.setFilters.get(Filter.FilterNames.LABELS.name()));
}
@Test
public void testWithMultipleLabels()
{
String[] values = new String[]{"test", "To Do", "Bug", "Feature", "review"};
Set<String> expected = new HashSet<>(Arrays.asList(values));
Object valueBeforeFirstAdd = instance.setFilters.get(Filter.FilterNames.LABELS.name());
instance.withLabel(values[0]);
Object valueAfterFirstAdd = instance.setFilters.get(Filter.FilterNames.LABELS.name());
Arrays.stream(values).forEach(instance::withLabel);
Arrays.stream(values).forEach(instance::withLabel);
Object valueAfterAllAdds = instance.setFilters.get(Filter.FilterNames.LABELS.name());
assertAll(
() -> assertNull(valueBeforeFirstAdd), // no initial instance present
() -> assertNotNull(valueAfterFirstAdd), // after first add there has to be one
() -> assertSame(valueAfterFirstAdd, valueAfterAllAdds), // check the collection stayed the same
() -> assertEquals(expected, valueAfterAllAdds) // check the content is only in there once and complete
);
}
@Test
public void testSetPage()
{
int value = 2;
instance.setPage(value);
assertEquals(value, instance.setFilters.get(Filter.FilterNames.PAGE.name()));
}
@Test
public void testSetPageSize()
{
int value = 2;
instance.setPageSize(value);
assertEquals(value, instance.setFilters.get(Filter.FilterNames.PAGINATION.name()));
}
@Test
public void testWithTitleContain()
{
String expected = "test title";
instance.withTitleContain(expected);
assertEquals(expected, instance.setFilters.get(Filter.FilterNames.TITLE_CONTAINS.name()));
}
@Test
public void testWithTitleMatch()
{
String expected = "^some stupid regex number [0-9]+";
instance.withTitleMatch(expected);
assertEquals(expected, instance.setFilters.get(Filter.FilterNames.TITLE_MATCH.name()));
}
@Test
public void testAddToSet()
{
Set<String> expected = new HashSet<>(Arrays.asList("test", "another", "something"));
Map<String, Object> store = new HashMap<>();
expected.forEach(s -> Filter.addToSet(Filter.FilterNames.LABELS, store, s));
assertEquals(expected, store.get(Filter.FilterNames.LABELS.name()));
}
@Test
public void testInitialValues()
{
assertAll(
() -> assertNotNull(instance.setFilters),
() -> assertEquals(0, instance.setFilters.size())
);
}
@Test
public void testFluentApi()
{
Filter before = instance;
Filter after = instance.setPage(1)
.setPageSize(1)
.withAssigneeId("1")
.withAssigneeName("Max")
.withDescriptionContain("Muster")
.withDescriptionMatch("Mann")
.withId("ID")
.withLabel("blabber")
.withTitleContain("hell no")
.withTitleMatch("finally")
.isOpen()
.isClosed();
assertSame(before, after);
}
}
package de.hft.unifiedticketing.core;
import de.hft.unifiedticketing.systems.gitlab.GitlabTicketSystemBuilder;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class RegisteredSystemsTest
{
@Test
public void testGitlab()
{
Class expected = new RegisteredSystems().gitlab().getClass();
Class actual = GitlabTicketSystemBuilder.class;
assertEquals(expected, actual);
}
}
package de.hft.unifiedticketing.core;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class TicketAssigneeTest
{
@Test
public void testEquals()
{
TicketAssignee a1 = new TicketAssignee(null, "1", null, null);
TicketAssignee a2 = new TicketAssignee(null, "1", null, null);
TicketAssignee a3 = new TicketAssignee(null, "2", null, null);
assertEquals(a1, a2);
assertNotEquals(a1, a3);
}
}
package de.hft.unifiedticketing.core;
import de.hft.unifiedticketing.exceptions.AssertionException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
public class TicketBuilderTest
{
public TicketBuilder instance;
@BeforeEach
public void initBeforeEach()
{
instance = mock(TicketBuilder.class,
withSettings().useConstructor(mock(TicketSystem.class)).defaultAnswer(CALLS_REAL_METHODS));
}
@Test
public void testInit()
{
TicketSystem ts = mock(TicketSystem.class);
instance = mock(TicketBuilder.class, withSettings().useConstructor(ts));
assertAll(
() -> assertSame(ts, instance.parent),
() -> assertNull(instance.description),
() -> assertNull(instance.labels),
() -> assertNull(instance.title)
// seems not possible with mock
// () -> assertThrows(AssertionException.class, () -> new TicketBuilderTestImpl(null))
);
}
@Test
public void testDescription()
{
String expected = "some descriptive stuff";
instance.description(expected);
assertEquals(expected, instance.description);
}
@Test
public void testLabelsBySet()
{
Set<String> expected = new HashSet<>(Arrays.asList("unifiedticketing", "bug", "To Do"));
instance.labels(expected);
assertEquals(expected, instance.labels);
}
@Test
public void testLabelsByArray()
{
String[] input = new String[]{"unifiedticketing", "feature", "review"};
instance.labels(input);
verify(instance, times(1)).labels(new HashSet<>(Arrays.asList(input)));
}
@Test
public void testTitle()
{
String expected = "outstanding title: yolo";
instance.title(expected);
assertEquals(expected, instance.title);
}
@Test
public void testFluentApi()
{
TicketBuilder before = instance;
TicketBuilder after = instance
.description("some")
.labels(new String[]{"random"})
.labels(new HashSet<>(Collections.singleton("values")))
.title("here");
assertSame(before, after);
}
}
package de.hft.unifiedticketing.core;
import de.hft.unifiedticketing.exceptions.AssertionException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
public class TicketSystemBuilderTest
{
public TicketSystemBuilder instance;
@BeforeEach
public void initBeforeEach()
{
instance = mock(TicketSystemBuilder.class, withSettings().useConstructor().defaultAnswer(CALLS_REAL_METHODS));
}
@Test
public void testWithBaseUrl()
{
String expected = "some.url.tld";
instance.withBaseUrl(expected);
assertEquals(expected, instance.baseUrl);
assertAll(
() -> assertThrows(AssertionException.class, () -> instance.withBaseUrl("http://urlwithprefix.com")),
() -> assertThrows(AssertionException.class, () -> instance.withBaseUrl("https://urlwithprefix.com"))
);
}
@Test
public void testFluentApi()
{
TicketSystemBuilder before = instance;
TicketSystemBuilder after = instance
.withBaseUrl("teststring");
assertSame(before, after);
}
}
package de.hft.unifiedticketing.core;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
public class TicketSystemTest
{
public TicketSystem instance;
@BeforeEach
public void initBeforeEach()
{
instance = mock(TicketSystem.class,
withSettings().useConstructor().defaultAnswer(CALLS_REAL_METHODS));
}
@Test
public void testInit()
{
assertAll(
() -> assertNull(instance.apiKey),
() -> assertNull(instance.baseUrl),
() -> assertNull(instance.password),
() -> assertNull(instance.username)
);
}
@Test
public void testConfigBoolean()
{
assertFalse(instance.getConfigTrue(TicketSystem.ConfigurationOptions.RETURN_NULL_ON_ERROR));
instance.config(TicketSystem.ConfigurationOptions.RETURN_NULL_ON_ERROR, true);
assertTrue(instance.getConfigTrue(TicketSystem.ConfigurationOptions.RETURN_NULL_ON_ERROR));
instance.config(TicketSystem.ConfigurationOptions.RETURN_NULL_ON_ERROR, false);
assertFalse(instance.getConfigTrue(TicketSystem.ConfigurationOptions.RETURN_NULL_ON_ERROR));
}
@Test
public void testConfigValue()
{
assertNull(instance.getConfigValue(TicketSystem.ConfigurationOptions.RETURN_NULL_ON_ERROR));
String expected = "some string value";
instance.config(TicketSystem.ConfigurationOptions.RETURN_NULL_ON_ERROR, expected);
assertFalse(instance.getConfigTrue(TicketSystem.ConfigurationOptions.RETURN_NULL_ON_ERROR));
assertEquals(expected, instance.getConfigValue(TicketSystem.ConfigurationOptions.RETURN_NULL_ON_ERROR));
expected = "TRUE";
instance.config(TicketSystem.ConfigurationOptions.RETURN_NULL_ON_ERROR, expected);
assertTrue(instance.getConfigTrue(TicketSystem.ConfigurationOptions.RETURN_NULL_ON_ERROR));
instance.config(TicketSystem.ConfigurationOptions.RETURN_NULL_ON_ERROR, null);
assertFalse(instance.getConfigTrue(TicketSystem.ConfigurationOptions.RETURN_NULL_ON_ERROR));
assertEquals(null, instance.getConfigValue(TicketSystem.ConfigurationOptions.RETURN_NULL_ON_ERROR));
}
@Test
public void testGetTicketByIdByInt()
{
int input = 5;
instance.getTicketById(input);
verify(instance, times(1)).getTicketById(String.valueOf(input));
}
@Test
public void testFluentApi()
{
TicketSystem before = instance;
TicketSystem after = instance
.config(TicketSystem.ConfigurationOptions.RETURN_NULL_ON_ERROR, true)
.config(TicketSystem.ConfigurationOptions.RETURN_NULL_ON_ERROR, "something");
assertSame(before, after);
}
}
package de.hft.unifiedticketing.core;
import de.hft.unifiedticketing.exceptions.AssertionException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.mockito.Mockito.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
@ExtendWith(MockitoExtension.class)
public class TicketTest
{
private Ticket instance;
@BeforeEach
public void initBeforeEach()
{
instance = mock(Ticket.class,
withSettings().useConstructor(mock(TicketSystem.class)).defaultAnswer(CALLS_REAL_METHODS));
}
@Test
public void testInitialValues()
{
TicketSystem parent = mock(TicketSystem.class);
instance = mock(Ticket.class,
withSettings().useConstructor(parent).defaultAnswer(CALLS_REAL_METHODS));
assertAll(
() -> assertNotNull(instance.assignees),
() -> assertEquals(HashSet.class, instance.assignees.getClass()),
() -> assertNull(instance.description),
() -> assertNull(instance.description),
() -> assertNull(instance.id),
() -> assertNotNull(instance.labels),
() -> assertEquals(HashSet.class, instance.labels.getClass()),
() -> assertTrue(instance.open),
() -> assertNull(instance.title),
() -> assertNotNull(instance.updatedFields),
() -> assertEquals(HashSet.class, instance.updatedFields.getClass()),
() -> assertSame(parent, instance.parent)
// constructor exception check with mock of abstract class not possible I guess?
// () -> assertThrows(AssertionException.class,
// () -> mock(Ticket.class, withSettings().useConstructor((TicketSystem) null)))
);
}
@Test
public void testGetAssignees()
{
assertEquals(instance.assignees, instance.getAssignees());
}
@Test
public void testClearAssignees()
{
Set<TicketAssignee> expected = instance.assignees;
instance.clearAssignees();
assertSame(expected, instance.assignees);
}
@Test
public void testGetDescription()
{
String expected = "some descriptive text";
instance.description = expected;
assertEquals(expected, instance.getDescription());
}
@Test
public void testSetDescription()
{
String expected = "some other descriptive stuff";
instance.setDescription(expected);
assertEquals(expected, instance.description);
}
@Test
public void testGetId()
{
String expected = "T13";
instance.id = expected;
assertEquals(expected, instance.getId());
}
@Test
public void testAddLabel()
{
Set<String> expected = new HashSet<>(Arrays.asList("unifiedticketing", "bug", "feature"));
expected.forEach(instance::addLabel);
assertEquals(expected, instance.labels);
}
@Test
public void testGetLabels()
{
Set<String> expected = new HashSet<>(Arrays.asList("unifiedticketing", "To Do", "enhancement"));
instance.labels = expected;
assertEquals(expected, instance.getLabels());
}
@Test
public void testSetLabelsByList()
{
Set<String> expected = new HashSet<>(Arrays.asList("unifiedticketing", "Doing", "review"));
instance.setLabels(expected);
assertEquals(expected, instance.labels);
}
@Test
public void testSetLabelsByArray()
{
String[] expected = new String[]{"unifiedticketing", "abandoned", "superseded"};
instance.setLabels(expected);
verify(instance, times(1)).setLabels(new HashSet<>(Arrays.asList(expected)));
}
@Test
public void testIsOpen()
{
instance.open = true;
assertTrue(instance.isOpen());
instance.open = false;
assertFalse(instance.isOpen());
}
@Test
public void testOpen()
{
instance.open();
assertTrue(instance.open);
}
@Test
public void testClose()
{
instance.close();
assertFalse(instance.open);
}
@Test
public void testGetParent()
{
assertSame(instance.parent, instance.getParent());
}
@Test
public void testGetTitle()
{
String expected = "fancy title";
instance.title = expected;
assertEquals(expected, instance.getTitle());
}
@Test
public void testSetTitle()
{
String expected = "other title";
instance.setTitle(expected);
assertEquals(expected, instance.title);
}
}
package de.hft.unifiedticketing.systems.gitlab;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import de.hft.unifiedticketing.exceptions.DeserializationException;
import de.hft.unifiedticketing.exceptions.HttpResponseException;
import okhttp3.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.io.IOException;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
public class GitlabFilterTest
{
public GitlabFilter instance;
public Call call;
public ArgumentCaptor<Request> requestCaptor;
public Response.Builder responseBuilder;
@BeforeEach
public void initBeforeEach()
{
GitlabTicketSystem parent = mock(GitlabTicketSystem.class);
parent.baseUrl = "https://gitlab.some.tld";
instance = spy(new GitlabFilter(parent));
OkHttpClient client = mock(OkHttpClient.class);
call = mock(Call.class);
requestCaptor = ArgumentCaptor.forClass(Request.class);
responseBuilder = new Response.Builder()
.request(new Request.Builder().url("http://test.some.tld/").build())
.protocol(Protocol.HTTP_1_1)
.message("some message");
doReturn(client).when(instance).getHttpClient();
doReturn(call).when(client).newCall(requestCaptor.capture());
}
@Test
public void testGetServerError() throws IOException
{
doReturn(responseBuilder.code(500).build()).when(call).execute();
assertThrows(HttpResponseException.class, () -> instance.get());
}
@Test
public void testGetClientError() throws IOException
{
doReturn(responseBuilder.code(400).build()).when(call).execute();
assertThrows(HttpResponseException.class, () -> instance.get());
}
@Test
public void testGetNullBody() throws IOException
{
doReturn(responseBuilder.code(200).build()).when(call).execute();
assertThrows(HttpResponseException.class, () -> instance.get());
}
@Test
public void testGetNoJsonBody() throws IOException
{
doReturn(
responseBuilder
.code(200)
.body(ResponseBody.create("somestrangething", MediaType.get("application/json")))
.build())
.when(call).execute();
assertThrows(DeserializationException.class, () -> instance.get());
}
@Test
public void testGetRequestParamsPart1() throws IOException
{
doReturn(
responseBuilder
.code(200)
.body(ResponseBody.create("[]".getBytes(), MediaType.get("application/json")))
.build())
.when(call).execute();
String[] values = new String[]
{
"title contain",
"5",
"8",
"bug",
"label1",
"2",
"50"
};
instance
.withTitleContain(values[0])
.withId(values[1])
.withAssigneeId(values[2])
.withLabel(values[3])
.withLabel(values[4])
.setPage(Integer.parseInt(values[5]))
.setPageSize(Integer.parseInt(values[6]))
.isOpen()
.get();
HttpUrl url = requestCaptor.getValue().url();
assertAll(
() -> assertEquals(values[0], url.queryParameter("search")),
() -> assertEquals(values[1], url.queryParameter("iids")),
() -> assertEquals(values[2], url.queryParameter("assignee_id")),
() -> assertEquals(String.format("%s,%s", values[3], values[4]), url.queryParameter("labels")),
() -> assertEquals(values[5], url.queryParameter("page")),
() -> assertEquals(values[6], url.queryParameter("per_page")),
() -> assertEquals("opened", url.queryParameter("state"))
);
}
@Test
public void testGetRequestParamsPart2() throws IOException
{
doReturn(
responseBuilder
.code(200)
.body(ResponseBody.create("[]".getBytes(), MediaType.get("application/json")))
.build())
.when(call).execute();
String[] values = new String[]
{
"description contain",
"SomeName"
};
instance
.withDescriptionContain(values[0])
.withAssigneeName(values[1])
.isClosed()
.get();
HttpUrl url = requestCaptor.getValue().url();
assertAll(
() -> assertEquals(values[0], url.queryParameter("search")),
() -> assertEquals(values[1], url.queryParameter("assignee_username")),
() -> assertEquals("closed", url.queryParameter("state"))
);
}
@Test
public void testGetLocalFilter() throws IOException
{
GitlabTicketResponse res = new GitlabTicketResponse();
res.iid = 5;
res.title = "some title";
res.description = "descriptive text";
res.assignees = new LinkedList<>();
res.state = "open";
res.labels = new HashSet<>(Arrays.asList("unifiedticketing", "bug"));
ObjectMapper mapper = new ObjectMapper();
ArrayNode arrayNode = mapper.createArrayNode();
arrayNode.add(mapper.valueToTree(res));
res.iid = 8;
res.title = "some special title";
arrayNode.add(mapper.valueToTree(res));
res.iid = 94;
res.description = "description with @username marked";
arrayNode.add(mapper.valueToTree(res));
doReturn(
responseBuilder
.code(200)
.body(ResponseBody.create(arrayNode.toString().getBytes(), MediaType.get("application/json")))
.build())
.when(call).execute();
List<GitlabTicket> result = instance
.withTitleMatch("^.*special.*$")
.withDescriptionMatch("^.*@username.*$")
.get();
assertAll(
() -> assertEquals(1, result.size()),
() -> assertEquals("94", result.get(0).getId())
);
}
@Test
public void testGetDeserialization() throws IOException
{
GitlabTicketResponse res = new GitlabTicketResponse();
res.iid = 99;
res.title = "some title";
res.description = "descriptive text";
res.assignees = new LinkedList<>();
res.state = "open";
res.labels = new HashSet<>(Arrays.asList("unifiedticketing", "feature-request"));
ObjectMapper mapper = new ObjectMapper();
ArrayNode arrayNode = mapper.createArrayNode();
arrayNode.add(mapper.valueToTree(res));
doReturn(
responseBuilder
.code(200)
.body(ResponseBody.create(arrayNode.toString().getBytes(), MediaType.get("application/json")))
.build())
.when(call).execute();
List<GitlabTicket> expected = new LinkedList<>(
Collections.singleton(GitlabTicket.fromTicketResponse(instance.parent, res)));
List<GitlabTicket> actual = instance.get();
assertEquals(expected, actual);
assertTrue(expected.get(0).deepEquals(actual.get(0)));
}
}
package de.hft.unifiedticketing.systems.gitlab;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.hft.unifiedticketing.exceptions.AssertionException;
import de.hft.unifiedticketing.exceptions.DeserializationException;
import de.hft.unifiedticketing.exceptions.HttpResponseException;
import okhttp3.*;
import okio.Buffer;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
public class GitlabTicketBuilderTest
{
public GitlabTicketBuilder instance;
public Call call;
public ArgumentCaptor<Request> requestCaptor;
public Response.Builder responseBuilder;
@BeforeEach
public void initBeforeEach()
{
GitlabTicketSystem parent = mock(GitlabTicketSystem.class);
parent.baseUrl = "https://example.org";
instance = spy(new GitlabTicketBuilder(parent));
OkHttpClient client = mock(OkHttpClient.class);
call = mock(Call.class);
requestCaptor = ArgumentCaptor.forClass(Request.class);
responseBuilder = new Response.Builder()
.request(new Request.Builder().url("http://test.some.tld/").build())
.protocol(Protocol.HTTP_1_1)
.message("some message");
doReturn(client).when(instance).getHttpClient();
doReturn(call).when(client).newCall(requestCaptor.capture());
}
@Test
public void testSaveNoCreationWithoutMinimumRequirements()
{
assertThrows(AssertionException.class, () -> instance.create());
verify(instance, never()).getHttpClient();
}
@Test
public void testSaveServerError() throws IOException
{
doReturn(responseBuilder.code(500).build()).when(call).execute();
instance.title("we have a new title");
assertThrows(HttpResponseException.class, () -> instance.create());
}
@Test
public void testSaveClientError() throws IOException
{
doReturn(responseBuilder.code(400).build()).when(call).execute();
instance.title("we have another new title");
assertThrows(HttpResponseException.class, () -> instance.create());
}
@Test
public void testSaveNullBody() throws IOException
{
doReturn(responseBuilder.code(200).build()).when(call).execute();
instance.title("we have no body this time");
assertThrows(HttpResponseException.class, () -> instance.create());
}
@Test
public void testSaveNoJsonBody() throws IOException
{
doReturn(
responseBuilder
.code(200)
.body(ResponseBody.create("somestrangething", MediaType.get("application/json")))
.build())
.when(call).execute();
instance.title("this body is no json");
assertThrows(DeserializationException.class, () -> instance.create());
}
@Test
public void testSaveSuccessfulUpdate() throws IOException
{
GitlabTicketResponse ticketResponse = new GitlabTicketResponse();
ticketResponse.title = "title of ticket";
ticketResponse.description = "description";
ticketResponse.iid = 5;
ticketResponse.labels = new HashSet<>(Arrays.asList("bug", "unifiedticketing"));
GitlabTicketResponse.Assignee assignee = new GitlabTicketResponse.Assignee();
assignee.id = 234;
assignee.name = "Full name";
assignee.username = "username";
ticketResponse.assignees = new LinkedList<>(Collections.singleton(assignee));
GitlabTicket expected = GitlabTicket.fromTicketResponse(instance.parent, ticketResponse);
String responseJson = new ObjectMapper().writeValueAsString(ticketResponse);
doReturn(
responseBuilder
.code(200)
.body(ResponseBody.create(responseJson.getBytes(), MediaType.get("application/json")))
.build())
.when(call).execute();
GitlabTicket actual = instance.title("some title").create();
assertEquals(expected, actual);
assertTrue(expected.deepEquals(actual));
}
@Test
public void testSaveRequestJson() throws IOException
{
doReturn(
responseBuilder
.code(200)
.body(ResponseBody.create("{}".getBytes(), MediaType.get("application/json")))
.build())
.when(call).execute();
instance.title("title of ticket")
.description("description")
.labels(new HashSet<>(Arrays.asList("bug", "unifiedticketing")))
.assignees(234)
.create();
Buffer buffer = new Buffer();
ObjectMapper mapper = new ObjectMapper();
requestCaptor.getValue().body().writeTo(buffer);
String expectedJson = "{\"assignee_ids\":[234],\"description\":\"description\"," +
"\"title\":\"title of ticket\",\"labels\":\"bug,unifiedticketing\"}";
assertEquals(mapper.readTree(expectedJson), mapper.readTree(buffer.readUtf8()));
}
}
package de.hft.unifiedticketing.systems.gitlab;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.*;
public class GitlabTicketResponseTest
{
@Test
public void testDeserialization() throws IOException
{
ObjectMapper mapper = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
String[] values = new String[]
// title descr iid label label userid user full-/username
{"title of ticket", "description", "5", "bug", "unifiedticketing", "234", "Full name", "username"};
String responseJson = String.format(
"{\"title\":\"%s\",\"description\":\"%s\",\"iid\":%s," +
"\"labels\":[\"%s\",\"%s\"],\"assignees\":[{\"id\":%s,\"name\":\"%s\",\"username\":\"%s\"}]}",
(Object[]) values);
GitlabTicketResponse response = mapper.readValue(responseJson.getBytes(), GitlabTicketResponse.class);
assertAll(
() -> assertEquals(values[0], response.title),
() -> assertEquals(values[1], response.description),
() -> assertEquals(values[2], String.valueOf(response.iid)),
() -> assertTrue(response.labels.contains(values[3])),
() -> assertTrue(response.labels.contains(values[4])),
() -> assertEquals(1, response.assignees.size()),
() -> assertEquals(values[5], String.valueOf(response.assignees.get(0).id)),
() -> assertEquals(values[6], response.assignees.get(0).name),
() -> assertEquals(values[7], response.assignees.get(0).username)
);
}
}
package de.hft.unifiedticketing.systems.gitlab;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import de.hft.unifiedticketing.exceptions.AssertionException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.regex.Pattern;
public class GitlabTicketSystemBuilderTest
{
public GitlabTicketSystemBuilder instance;
@BeforeEach
public void initBeforeEach()
{
instance = spy(new GitlabTicketSystemBuilder());
}
@Test
public void testInit()
{
assertAll(
() -> assertNull(instance.apiKey),
() -> assertEquals("v4", instance.apiVersion),
() -> assertEquals(-1, instance.projectId),
() -> assertTrue(instance.https)
);
}
@Test
public void testWithApiKey()
{
String expected = "asoashdboahasjhdfbeuazhvfef4q34v3h4v435v2";
instance.withApiKey(expected);
assertEquals(expected, instance.apiKey);
}
@Test
public void testWithHttp()
{
instance.https = true;
instance.withHttp();
assertFalse(instance.https);
}
@Test
public void testWithHttps()
{
instance.https = false;
instance.withHttps();
assertTrue(instance.https);
}
@Test
public void testWithProjectIdByInt()
{
int expected = 255254123;
instance.withProjectId(expected);
assertEquals(expected, instance.projectId);
}
@Test
public void testWithProjectIdByString()
{
int expected = 23523423;
instance.withProjectId(String.valueOf(expected));
verify(instance, times(1)).withProjectId(expected);
assertThrows(AssertionException.class, () -> instance.withProjectId("asdf3asd"));
}
@Test
public void testBuild()
{
instance.withBaseUrl("blabla.tld");
assertThrows(AssertionException.class, () -> instance.build());
instance = new GitlabTicketSystemBuilder();
instance.withProjectId(42);
assertThrows(AssertionException.class, () -> instance.build());
instance = new GitlabTicketSystemBuilder();
String baseUrl = "gitlab.some.tld";
int projectId = 42;
String apiKey = "aaesfsef32qqfq3f";
String regex = "^%s://%s/api/v4/projects/%d$";
Pattern pattern = Pattern.compile(
String.format(regex, "https", baseUrl, projectId));
instance.withBaseUrl(baseUrl).withProjectId(projectId);
GitlabTicketSystem system = instance.build();
assertTrue(pattern.matcher(system.baseUrl).matches());
pattern = Pattern.compile(String.format(regex, "http", baseUrl, projectId));
instance.withHttp().withApiKey(apiKey);
system = instance.build();
assertTrue(pattern.matcher(system.baseUrl).matches());
assertEquals(apiKey, system.apiKey);
}
}
package de.hft.unifiedticketing.systems.gitlab;
import de.hft.unifiedticketing.core.TicketSystem;
import de.hft.unifiedticketing.exceptions.AssertionException;
import de.hft.unifiedticketing.exceptions.UnifiedticketingException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.LinkedList;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
public class GitlabTicketSystemTest
{
public GitlabTicketSystem instance;
@BeforeEach
public void initBeforeEach()
{
instance = new GitlabTicketSystem();
}
@Test
public void testFromUri()
{
String base = "gitlab.com";
int projectId = 23554234;
String apikey = "afdaf3aqraf3afafmyxcbvmyxvbas3wrawra";
TicketSystem actual = TicketSystem.fromUri(buildTestUri(true, base, projectId, apikey));
assertEquals(buildFinalBaseurl(true, base, projectId), actual.baseUrl);
assertEquals(apikey, actual.apiKey);
assertEquals(GitlabTicketSystem.class, actual.getClass());
base = "gitlab.somedomain.tld:8080";
projectId = 5;
apikey = "asfewfa3r2rfa34fraf";
actual = TicketSystem.fromUri(buildTestUri(false, base, projectId, apikey));
assertEquals(buildFinalBaseurl(false, base, projectId), actual.baseUrl);
assertEquals(apikey, actual.apiKey);
assertEquals(GitlabTicketSystem.class, actual.getClass());
actual = TicketSystem.fromUri(buildTestUri(false, base, projectId, null));
assertEquals(buildFinalBaseurl(false, base, projectId), actual.baseUrl);
assertNull(actual.apiKey);
assertEquals(GitlabTicketSystem.class, actual.getClass());
assertThrows(AssertionException.class, () -> TicketSystem.fromUri("unifiedticketing:gitlab:blablabal"));
}
@Test
public void testCreateTicket()
{
assertEquals(GitlabTicketBuilder.class, instance.createTicket().getClass());
assertSame(instance, instance.createTicket().parent);
}
@Test
public void testFind()
{
assertEquals(GitlabFilter.class, instance.find().getClass());
assertSame(instance, instance.find().parent);
}
@Test
public void testGetTicketById()
{
String ticketId = "5";
GitlabFilter filter = spy(instance.find());
instance = spy(instance);
doReturn(filter).when(instance).find();
doReturn(null).when(filter).get();
assertNull(instance.getTicketById(ticketId));
verify(instance, times(1)).find();
verify(filter, times(1)).withId(ticketId);
verify(filter, times(1)).get();
doReturn(new LinkedList<>()).when(filter).get();
assertThrows(UnifiedticketingException.class, () -> instance.getTicketById(ticketId));
GitlabTicket ticket = new GitlabTicket(instance);
doReturn(new LinkedList<>(Collections.singleton(ticket))).when(filter).get();
assertSame(ticket, instance.getTicketById(ticketId));
}
@Test
public void testSupport()
{
assertAll(
() -> assertTrue(instance.hasAssigneeSupport()),
() -> assertTrue(instance.hasDefaultPagination()),
() -> assertTrue(instance.hasLabelSupport()),
() -> assertTrue(instance.hasPaginationSupport()),
() -> assertTrue(instance.hasReturnNullOnErrorSupport())
);
}
private static String buildTestUri(boolean https, String base, int projectId, String apikey)
{
return String.format(
"unifiedticketing:gitlab:%s://%s:%d%s",
(https) ? "https": "http",
base,
projectId,
(apikey == null) ? "" : ":" + apikey);
}
private static String buildFinalBaseurl(boolean https, String base, int projectId)
{
return String.format("%s://%s/api/v4/projects/%d", (https) ? "https" : "http", base, projectId);
}
}
package de.hft.unifiedticketing.systems.gitlab;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.hft.unifiedticketing.exceptions.AssertionException;
import de.hft.unifiedticketing.exceptions.DeserializationException;
import de.hft.unifiedticketing.exceptions.HttpResponseException;
import okhttp3.*;
import okio.Buffer;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
public class GitlabTicketTest
{
public GitlabTicket instance;
public Call call;
public ArgumentCaptor<Request> requestCaptor;
public Response.Builder responseBuilder;
@BeforeEach
public void initBeforeEach()
{
instance = spy(new GitlabTicket(mock(GitlabTicketSystem.class)));
instance.getParent().baseUrl = "https://example.org";
OkHttpClient client = mock(OkHttpClient.class);
call = mock(Call.class);
requestCaptor = ArgumentCaptor.forClass(Request.class);
responseBuilder = new Response.Builder()
.request(new Request.Builder().url("http://test.some.tld/").build())
.protocol(Protocol.HTTP_1_1)
.message("some message");
doReturn(client).when(instance).getHttpClient();
doReturn(call).when(client).newCall(requestCaptor.capture());
}
@Test
public void testFromTicketResponse()
{
GitlabTicketResponse res = new GitlabTicketResponse();
GitlabTicket ticket = GitlabTicket.fromTicketResponse(instance.getParent(), res);
assertAll(
() -> assertSame(instance.getParent(), ticket.getParent()),
() -> assertNull(ticket.getTitle()),
() -> assertNull(ticket.getDescription()),
() -> assertEquals("0", ticket.getId()),
() -> assertNotNull(ticket.getLabels()),
() -> assertTrue(ticket.isOpen()),
() -> assertNull(ticket.getTitle()),
() -> assertNotNull(ticket.getAssignees())
);
}
@Test
public void testAddAssigneeByString()
{
assertThrows(AssertionException.class, () -> instance.addAssignee("blbal"));
instance = spy(instance);
int id = 4;
instance.addAssignee(String.valueOf(id));
verify(instance, times(1)).addAssignee(id);
}
@Test
public void testAddAssigneeByInt()
{
int id = 5;
instance.addAssignee(id);
assertEquals(1, instance.getAssignees().size());
assertEquals(String.valueOf(id), instance.getAssignees().stream().findAny().get().id);
for (int i=0; i < 5; i++)
{
instance.addAssignee(id);
}
assertEquals(1, instance.getAssignees().size());
}
@Test
public void testRemoveAssigneeByString()
{
assertThrows(AssertionException.class, () -> instance.removeAssignee("nonparsableint"));
instance = spy(instance);
int id = 4;
instance.removeAssignee(String.valueOf(id));
verify(instance, times(1)).removeAssignee(id);
}
@Test
public void testRemoveAssigneeByInt()
{
int[] ids = new int[]{4, 8, 19, 500};
for (int id: ids)
{
instance.addAssignee(id);
}
assertEquals(ids.length, instance.getAssignees().size());
instance.removeAssignee(ids[0]);
assertEquals(ids.length -1, instance.getAssignees().size());
Set<Integer> leftover = instance.getAssignees().stream()
.map(a -> Integer.parseInt(a.id))
.collect(Collectors.toSet());
for (int i=1; i < ids.length; i++)
{
assertTrue(leftover.contains(ids[i]));
}
}
@Test
public void testSaveNoHttpClientWithoutChanges()
{
GitlabTicket actual = instance.save();
verify(instance, never()).getHttpClient();
assertSame(instance, actual);
}
@Test
public void testSaveServerError() throws IOException
{
doReturn(responseBuilder.code(500).build()).when(call).execute();
instance.setTitle("we have a new title");
assertThrows(HttpResponseException.class, () -> instance.save());
}
@Test
public void testSaveClientError() throws IOException
{
doReturn(responseBuilder.code(400).build()).when(call).execute();
instance.setTitle("we have another new title");
assertThrows(HttpResponseException.class, () -> instance.save());
}
@Test
public void testSaveNullBody() throws IOException
{
doReturn(responseBuilder.code(200).build()).when(call).execute();
instance.setTitle("we have no body this time");
assertThrows(HttpResponseException.class, () -> instance.save());
}
@Test
public void testSaveNoJsonBody() throws IOException
{
doReturn(
responseBuilder
.code(200)
.body(ResponseBody.create("somestrangething", MediaType.get("application/json")))
.build())
.when(call).execute();
instance.setTitle("this body is no json");
assertThrows(DeserializationException.class, () -> instance.save());
}
@Test
public void testSaveSuccessfulUpdate() throws IOException
{
GitlabTicketResponse ticketResponse = new GitlabTicketResponse();
ticketResponse.title = "title of ticket";
ticketResponse.description = "description";
ticketResponse.iid = 5;
ticketResponse.labels = new HashSet<>(Arrays.asList("bug", "unifiedticketing"));
GitlabTicketResponse.Assignee assignee = new GitlabTicketResponse.Assignee();
assignee.id = 234;
assignee.name = "Full name";
assignee.username = "username";
ticketResponse.assignees = new LinkedList<>(Collections.singleton(assignee));
GitlabTicket expected = GitlabTicket.fromTicketResponse(instance.getParent(), ticketResponse);
String responseJson = new ObjectMapper().writeValueAsString(ticketResponse);
doReturn(
responseBuilder
.code(200)
.body(ResponseBody.create(responseJson.getBytes(), MediaType.get("application/json")))
.build())
.when(call).execute();
GitlabTicket actual = instance.close().save();
assertEquals(expected, actual);
assertTrue(expected.deepEquals(actual));
}
@Test
public void testSaveRequestJson() throws IOException
{
doReturn(
responseBuilder
.code(200)
.body(ResponseBody.create("{}".getBytes(), MediaType.get("application/json")))
.build())
.when(call).execute();
instance.setTitle("title of ticket")
.setDescription("description")
.setLabels(new HashSet<>(Arrays.asList("bug", "unifiedticketing")))
.addAssignee(234)
.save();
Buffer buffer = new Buffer();
ObjectMapper mapper = new ObjectMapper();
requestCaptor.getValue().body().writeTo(buffer);
String expectedJson = "{\"assignee_ids\":[234],\"description\":\"description\"," +
"\"title\":\"title of ticket\",\"labels\":\"bug,unifiedticketing\"}";
assertEquals(mapper.readTree(expectedJson), mapper.readTree(buffer.readUtf8()));
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment