method2testcases
stringlengths
118
3.08k
### Question: CGather implements ChocoConstraint { @Override public Set<VM> getMisPlacedVMs(Instance i) { if (!cstr.isSatisfied(i.getModel())) { return new HashSet<>(cstr.getInvolvedVMs()); } return Collections.emptySet(); } CGather(Gather g); @Override boolean inject(Parameters ps, ReconfigurationProblem rp); @Override String toString(); @Override Set<VM> getMisPlacedVMs(Instance i); }### Answer: @Test public void testGetMisplaced() { Model mo = new DefaultModel(); VM vm1 = mo.newVM(); VM vm2 = mo.newVM(); Node n1 = mo.newNode(); Node n2 = mo.newNode(); Mapping map = mo.getMapping().ready(vm1).on(n1, n2).run(n2, vm2); Instance i = new Instance(mo, Collections.emptyList(), new MinMTTR()); Gather g = new Gather(map.getAllVMs()); CGather c = new CGather(g); Assert.assertTrue(c.getMisPlacedVMs(i).isEmpty()); map.addRunningVM(vm1, n2); Assert.assertTrue(c.getMisPlacedVMs(i).isEmpty()); map.addRunningVM(vm1, n1); Assert.assertEquals(c.getMisPlacedVMs(i), map.getAllVMs()); }
### Question: Or extends BinaryProp { @Override public And not() { return new And(p1.not(), p2.not()); } Or(Proposition p1, Proposition p2); @Override String operator(); @Override And not(); @Override Boolean eval(Context m); @Override String toString(); }### Answer: @Test public void testNot() { Or or = new Or(Proposition.True, Proposition.False); And o = or.not(); Assert.assertEquals(o.first(), Proposition.False); Assert.assertEquals(o.second(), Proposition.True); }
### Question: CSleeping implements ChocoConstraint { @Override public Set<VM> getMisPlacedVMs(Instance i) { VM v = cstr.getInvolvedVMs().iterator().next(); Mapping map = i.getModel().getMapping(); if (!map.isSleeping(v)) { return Collections.singleton(v); } return Collections.emptySet(); } CSleeping(Sleeping c); @Override boolean inject(Parameters ps, ReconfigurationProblem rp); @Override Set<VM> getMisPlacedVMs(Instance i); @Override String toString(); }### Answer: @Test public void testGetMisplaced() { Model mo = new DefaultModel(); VM vm1 = mo.newVM(); VM vm2 = mo.newVM(); VM vm3 = mo.newVM(); Node n1 = mo.newNode(); mo.getMapping().on(n1).ready(vm1).run(n1, vm2).sleep(n1, vm3); Instance i = new Instance(mo, Collections.emptyList(), new MinMTTR()); CSleeping k = new CSleeping(new Sleeping(vm3)); Assert.assertEquals(0, k.getMisPlacedVMs(i).size()); k = new CSleeping(new Sleeping(vm1)); Assert.assertEquals(1, k.getMisPlacedVMs(i).size()); Assert.assertTrue(k.getMisPlacedVMs(i).contains(vm1)); k = new CSleeping(new Sleeping(vm3)); Assert.assertEquals(0, k.getMisPlacedVMs(i).size()); }
### Question: CReady implements ChocoConstraint { @Override public Set<VM> getMisPlacedVMs(Instance i) { VM v = cstr.getInvolvedVMs().iterator().next(); Mapping map = i.getModel().getMapping(); if (!map.isReady(v)) { return Collections.singleton(v); } return Collections.emptySet(); } CReady(Ready c); @Override boolean inject(Parameters ps, ReconfigurationProblem rp); @Override Set<VM> getMisPlacedVMs(Instance i); @Override String toString(); }### Answer: @Test public void testGetMisplaced() { Model mo = new DefaultModel(); VM vm1 = mo.newVM(); VM vm2 = mo.newVM(); VM vm3 = mo.newVM(); Node n1 = mo.newNode(); mo.getMapping().ready(vm1).on(n1).run(n1, vm2, vm3); Instance i = new Instance(mo, Collections.emptyList(), new MinMTTR()); CReady k = new CReady(new Ready(vm1)); Assert.assertEquals(0, k.getMisPlacedVMs(i).size()); k = new CReady(new Ready(vm2)); Assert.assertEquals(1, k.getMisPlacedVMs(i).size()); Assert.assertTrue(k.getMisPlacedVMs(i).contains(vm2)); }
### Question: BootableNode implements NodeTransition { @Override public Node getNode() { return node; } BootableNode(ReconfigurationProblem rp, Node nId); @Override boolean insertActions(Solution s, ReconfigurationPlan plan); @Override String toString(); @Override IntVar getStart(); @Override IntVar getEnd(); @Override IntVar getDuration(); @Override Node getNode(); @Override BoolVar getState(); @Override IntVar getHostingStart(); @Override IntVar getHostingEnd(); @Override NodeState getSourceState(); static final String PREFIX; }### Answer: @Test public void testBasic() throws SchedulerException { Model mo = new DefaultModel(); Mapping map = mo.getMapping(); Node n1 = mo.newNode(); map.addOfflineNode(n1); ReconfigurationProblem rp = new DefaultReconfigurationProblemBuilder(mo).build(); BootableNode na = (BootableNode) rp.getNodeAction(n1); Assert.assertEquals(na.getNode(), n1); }
### Question: TransitionFactory { public boolean remove(VMTransitionBuilder b) { Map<VMState, VMTransitionBuilder> m = vmAMB2.get(b.getDestinationState()); for (VMState src : b.getSourceStates()) { m.remove(src); } return true; } TransitionFactory(); void add(VMTransitionBuilder b); boolean remove(VMTransitionBuilder b); boolean remove(NodeTransitionBuilder b); void add(NodeTransitionBuilder b); VMTransitionBuilder getBuilder(VMState srcState, VMState dstState); NodeTransitionBuilder getBuilder(NodeState srcState); static TransitionFactory newBundle(); @Override String toString(); }### Answer: @Test public void testRemove() { TransitionFactory amf = TransitionFactory.newBundle(); MockVMBuilder vmb = new MockVMBuilder(); amf.remove(vmb); for (VMState src : vmb.getSourceStates()) { Assert.assertNull(amf.getBuilder(src, vmb.getDestinationState())); } MockNodeBuilder nb = new MockNodeBuilder(); amf.remove(nb); Assert.assertNull(amf.getBuilder(nb.getSourceState())); }
### Question: TransitionFactory { public void add(VMTransitionBuilder b) { Map<VMState, VMTransitionBuilder> m = vmAMB2.get(b.getDestinationState()); for (VMState src : b.getSourceStates()) { m.put(src, b); } } TransitionFactory(); void add(VMTransitionBuilder b); boolean remove(VMTransitionBuilder b); boolean remove(NodeTransitionBuilder b); void add(NodeTransitionBuilder b); VMTransitionBuilder getBuilder(VMState srcState, VMState dstState); NodeTransitionBuilder getBuilder(NodeState srcState); static TransitionFactory newBundle(); @Override String toString(); }### Answer: @Test public void testAdd() { TransitionFactory amf = TransitionFactory.newBundle(); MockVMBuilder vmb = new MockVMBuilder(); amf.add(vmb); for (VMState src : vmb.getSourceStates()) { Assert.assertEquals(amf.getBuilder(src, vmb.getDestinationState()), vmb); } MockNodeBuilder nb = new MockNodeBuilder(); amf.add(nb); Assert.assertEquals(amf.getBuilder(nb.getSourceState()), nb); }
### Question: RelocatableVM implements KeepRunningVM { public IntVar getRelocationMethod() { return doReinstantiation; } RelocatableVM(ReconfigurationProblem p, VM e); Task getMigrationTask(); @Override boolean isManaged(); @Override boolean insertActions(Solution s, ReconfigurationPlan plan); IntVar getBandwidth(); boolean usesPostCopy(); @Override VM getVM(); @Override IntVar getStart(); @Override IntVar getEnd(); @Override IntVar getDuration(); @Override Slice getCSlice(); @Override Slice getDSlice(); @Override BoolVar getState(); @Override BoolVar isStaying(); IntVar getRelocationMethod(); @Override String toString(); @Override VMState getSourceState(); @Override VMState getFutureState(); static final String PREFIX; static final String PREFIX_STAY; }### Answer: @Test public void testNotWorthyReInstantiation() throws SchedulerException { Model mo = new DefaultModel(); Mapping map = mo.getMapping(); final VM vm1 = mo.newVM(); Node n1 = mo.newNode(); Node n2 = mo.newNode(); map.addOnlineNode(n1); map.addOnlineNode(n2); map.addRunningVM(vm1, n1); Parameters ps = new DefaultParameters(); DurationEvaluators dev = ps.getDurationEvaluators(); dev.register(MigrateVM.class, new ConstantActionDuration<>(2)); mo.getAttributes().put(vm1, "template", "small"); mo.getAttributes().put(vm1, "clone", true); ReconfigurationProblem rp = new DefaultReconfigurationProblemBuilder(mo) .setNextVMsStates(Collections.emptySet(), map.getAllVMs(), Collections.emptySet(), Collections.emptySet()) .setParams(ps) .build(); RelocatableVM am = (RelocatableVM) rp.getVMAction(vm1); Assert.assertFalse(am.getRelocationMethod().isInstantiated()); }
### Question: DurationEvaluators { public boolean unRegister(Class<? extends Action> a) { return durations.remove(a) != null; } DurationEvaluators(); boolean register(Class<? extends Action> a, ActionDurationEvaluator e); boolean unRegister(Class<? extends Action> a); boolean isRegistered(Class<? extends Action> a); ActionDurationEvaluator<Element> getEvaluator(Class<? extends Action> a); int evaluate(Model mo, Class<? extends Action> a, Element e); static DurationEvaluators newBundle(); }### Answer: @Test(dependsOnMethods = {"testInstantiateAndIsRegistered"}) public void testUnregister() { DurationEvaluators d = DurationEvaluators.newBundle(); Assert.assertTrue(d.unRegister(MigrateVM.class)); Assert.assertFalse(d.isRegistered(MigrateVM.class)); Assert.assertFalse(d.unRegister(MigrateVM.class)); }
### Question: DurationEvaluators { public boolean register(Class<? extends Action> a, ActionDurationEvaluator e) { return durations.put(a, e) == null; } DurationEvaluators(); boolean register(Class<? extends Action> a, ActionDurationEvaluator e); boolean unRegister(Class<? extends Action> a); boolean isRegistered(Class<? extends Action> a); ActionDurationEvaluator<Element> getEvaluator(Class<? extends Action> a); int evaluate(Model mo, Class<? extends Action> a, Element e); static DurationEvaluators newBundle(); }### Answer: @Test(dependsOnMethods = {"testInstantiateAndIsRegistered", "testUnregister"}) public void testRegister() { DurationEvaluators d = new DurationEvaluators(); Assert.assertTrue(d.register(MigrateVM.class, new ConstantActionDuration<>(7))); Assert.assertFalse(d.register(MigrateVM.class, new ConstantActionDuration<>(3))); }
### Question: DurationEvaluators { public ActionDurationEvaluator<Element> getEvaluator(Class<? extends Action> a) { return durations.get(a); } DurationEvaluators(); boolean register(Class<? extends Action> a, ActionDurationEvaluator e); boolean unRegister(Class<? extends Action> a); boolean isRegistered(Class<? extends Action> a); ActionDurationEvaluator<Element> getEvaluator(Class<? extends Action> a); int evaluate(Model mo, Class<? extends Action> a, Element e); static DurationEvaluators newBundle(); }### Answer: @Test(dependsOnMethods = {"testInstantiateAndIsRegistered", "testUnregister", "testRegister"}) public void testGetEvaluator() { DurationEvaluators d = new DurationEvaluators(); ActionDurationEvaluator<Element> ev = new ConstantActionDuration<>(7); d.register(MigrateVM.class, ev); Assert.assertEquals(d.getEvaluator(MigrateVM.class), ev); }
### Question: DurationEvaluators { public int evaluate(Model mo, Class<? extends Action> a, Element e) throws SchedulerException { ActionDurationEvaluator<Element> ev = durations.get(a); if (ev == null) { throw new SchedulerModelingException(null, "Unable to estimate the duration of action '" + a.getSimpleName() + "' related to '" + e + "'"); } int d = ev.evaluate(mo, e); if (d <= 0) { throw new SchedulerModelingException(null, "The duration for action " + a.getSimpleName() + " over '" + e + "' has been evaluated to a negative value (" + d + "). Unsupported"); } return d; } DurationEvaluators(); boolean register(Class<? extends Action> a, ActionDurationEvaluator e); boolean unRegister(Class<? extends Action> a); boolean isRegistered(Class<? extends Action> a); ActionDurationEvaluator<Element> getEvaluator(Class<? extends Action> a); int evaluate(Model mo, Class<? extends Action> a, Element e); static DurationEvaluators newBundle(); }### Answer: @Test(dependsOnMethods = {"testInstantiateAndIsRegistered", "testUnregister", "testRegister"}) public void testEvaluate() throws SchedulerException { DurationEvaluators d = new DurationEvaluators(); ActionDurationEvaluator<Element> ev = new ConstantActionDuration<>(7); d.register(MigrateVM.class, ev); Assert.assertEquals(d.evaluate(mo, MigrateVM.class, vm1), 7); } @Test(dependsOnMethods = {"testInstantiateAndIsRegistered", "testUnregister"}, expectedExceptions = {SchedulerException.class}) public void testEvaluateUnregisteredAction() throws SchedulerException { DurationEvaluators d = new DurationEvaluators(); d.evaluate(mo, MigrateVM.class, vm1); }
### Question: CShareableResource implements ChocoView { public String getResourceIdentifier() { return rc.getResourceIdentifier(); } CShareableResource(ShareableResource r); @Override boolean inject(Parameters ps, ReconfigurationProblem p); String getResourceIdentifier(); ShareableResource getSourceResource(); List<IntVar> getPhysicalUsage(); IntVar getPhysicalUsage(int nIdx); List<IntVar> getVirtualUsage(); int getVMAllocation(int vmIdx); int minVMAllocation(int vmIdx, int v); double getOverbookRatio(int nId); double capOverbookRatio(int nIdx, double d); @Override String getIdentifier(); @Override String toString(); @Override boolean beforeSolve(ReconfigurationProblem p); @Override boolean insertActions(ReconfigurationProblem r, Solution s, ReconfigurationPlan p); @Override Set<VM> getMisPlacedVMs(Instance i); boolean overloaded(Mapping m, Node n); @Override boolean cloneVM(VM vm, VM clone); @Override List<String> getDependencies(); static TObjectIntMap<VM> getWeights(ReconfigurationProblem rp, List<CShareableResource> rcs); static final double UNCHECKED_RATIO; }### Answer: @Test public void testMaintainResourceUsage() throws SchedulerException { Model mo = new DefaultModel(); VM vm1 = mo.newVM(); VM vm2 = mo.newVM(); Node n1 = mo.newNode(); mo.getMapping().on(n1).run(n1, vm1, vm2); ShareableResource rc = new ShareableResource("foo"); rc.setConsumption(vm1, 5); rc.setConsumption(vm2, 7); rc.setCapacity(n1, 25); mo.attach(rc); ChocoScheduler s = new DefaultChocoScheduler(); ReconfigurationPlan p = s.solve(mo, new ArrayList<>()); Assert.assertNotNull(p); Model res = p.getResult(); ShareableResource resRc = ShareableResource.get(res, rc.getResourceIdentifier()); Assert.assertEquals(resRc.getConsumption(vm1), 5); Assert.assertEquals(resRc.getConsumption(vm2), 7); }
### Question: Running extends SimpleConstraint { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Running running = (Running) o; return Objects.equals(vm, running.vm); } Running(VM vm); @Override Collection<VM> getInvolvedVMs(); @Override boolean equals(Object o); @Override int hashCode(); @Override RunningChecker getChecker(); @Override boolean setContinuous(boolean b); @Override String toString(); static List<Running> newRunning(Collection<VM> vms); static List<Running> newRunning(VM... vms); }### Answer: @Test public void testEquals() { Model mo = new DefaultModel(); VM vm = mo.newVM(); Running s = new Running(vm); Assert.assertTrue(s.equals(s)); Assert.assertTrue(new Running(vm).equals(s)); Assert.assertEquals(new Running(vm).hashCode(), s.hashCode()); Assert.assertFalse(new Running(mo.newVM()).equals(s)); }
### Question: Fence extends SimpleConstraint { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Fence fence = (Fence) o; return isContinuous() == fence.isContinuous() && Objects.equals(vm, fence.vm) && nodes.size() == fence.nodes.size() && nodes.containsAll(fence.nodes) && fence.nodes.containsAll(nodes); } Fence(VM vm, Collection<Node> nodes); Fence(VM vm, Node... n); Fence(VM vm, Collection<Node> nodes, boolean continuous); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override FenceChecker getChecker(); @Override Collection<Node> getInvolvedNodes(); @Override Collection<VM> getInvolvedVMs(); static List<Fence> newFence(Collection<VM> vms, Collection<Node> nodes); }### Answer: @Test public void testEquals() { Model mo = new DefaultModel(); VM v = mo.newVM(); Set<Node> nodes = new HashSet<>(Arrays.asList(mo.newNode(), mo.newNode())); Fence f = new Fence(v, nodes); Assert.assertTrue(f.equals(f)); Assert.assertTrue(new Fence(v, nodes).equals(f)); Assert.assertFalse(new Fence(mo.newVM(), nodes).equals(f)); Assert.assertEquals(new Fence(v, nodes).hashCode(), f.hashCode()); }
### Question: Seq implements SatConstraint { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Seq seq = (Seq) o; return Objects.equals(order, seq.order); } Seq(List<VM> seq); @Override List<VM> getInvolvedVMs(); @Override String toString(); @Override boolean setContinuous(boolean b); @Override SatConstraintChecker<Seq> getChecker(); @Override boolean isContinuous(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test(dependsOnMethods = {"testInstantiation"}) public void testEquals() { Model mo = new DefaultModel(); List<VM> l = Arrays.asList(mo.newVM(), mo.newVM(), mo.newVM()); Seq c = new Seq(l); List<VM> l2 = new ArrayList<>(l); Seq c2 = new Seq(l2); Assert.assertTrue(c.equals(c2)); Assert.assertEquals(c.hashCode(), c2.hashCode()); l2.add(l2.remove(0)); Assert.assertFalse(c.equals(c2)); }
### Question: Spread extends SimpleConstraint { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Spread spread = (Spread) o; return isContinuous() == spread.isContinuous() && Objects.equals(vms, spread.vms); } Spread(Set<VM> vms); Spread(Set<VM> vms, boolean continuous); @Override String toString(); @Override SpreadChecker getChecker(); @Override Set<VM> getInvolvedVMs(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testEquals() { Model mo = new DefaultModel(); Set<VM> x = new HashSet<>(Arrays.asList(mo.newVM(), mo.newVM())); Spread s = new Spread(x); Assert.assertTrue(s.equals(s)); Assert.assertTrue(new Spread(x).equals(s)); Assert.assertEquals(s.hashCode(), new Spread(x).hashCode()); Assert.assertNotEquals(s.hashCode(), new Spread(new HashSet<>()).hashCode()); x = new HashSet<>(Collections.singletonList(mo.newVM())); Assert.assertFalse(new Spread(x).equals(s)); Assert.assertFalse(new Spread(x, false).equals(new Spread(x, true))); Assert.assertNotSame(new Spread(x, false).hashCode(), new Spread(x, true).hashCode()); }
### Question: Sleeping extends SimpleConstraint { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Sleeping sleeping = (Sleeping) o; return Objects.equals(vm, sleeping.vm); } Sleeping(VM vm); @Override boolean setContinuous(boolean b); @Override SleepingChecker getChecker(); @Override String toString(); @Override Collection<VM> getInvolvedVMs(); @Override boolean equals(Object o); @Override int hashCode(); static List<Sleeping> newSleeping(Collection<VM> vms); }### Answer: @Test public void testEquals() { Model mo = new DefaultModel(); VM v = mo.newVM(); Sleeping s = new Sleeping(v); Assert.assertTrue(s.equals(s)); Assert.assertTrue(new Sleeping(v).equals(s)); Assert.assertEquals(new Sleeping(v).hashCode(), s.hashCode()); Assert.assertFalse(new Sleeping(mo.newVM()).equals(s)); }
### Question: MinMTTRConverter implements ConstraintConverter<MinMTTR> { @Override public String getJSONId() { return "minimizeMTTR"; } @Override Class<MinMTTR> getSupportedConstraint(); @Override String getJSONId(); @Override MinMTTR fromJSON(Model mo, JSONObject o); @Override JSONObject toJSON(MinMTTR o); }### Answer: @Test public void testBundle() { Assert.assertTrue(ConstraintsConverter.newBundle().getSupportedJavaConstraints().contains(MinMTTR.class)); Assert.assertTrue(ConstraintsConverter.newBundle().getSupportedJSONConstraints().contains(new MinMTTRConverter().getJSONId())); }
### Question: Sleeping extends SimpleConstraint { public Sleeping(VM vm) { super(false); this.vm = vm; } Sleeping(VM vm); @Override boolean setContinuous(boolean b); @Override SleepingChecker getChecker(); @Override String toString(); @Override Collection<VM> getInvolvedVMs(); @Override boolean equals(Object o); @Override int hashCode(); static List<Sleeping> newSleeping(Collection<VM> vms); }### Answer: @Test public void testSleeping() { Model mo = new DefaultModel(); List<VM> vms = Util.newVMs(mo, 5); List<Sleeping> c = Sleeping.newSleeping(vms); Assert.assertEquals(vms.size(), c.size()); c.stream().forEach((q) -> { Assert.assertTrue(vms.containsAll(q.getInvolvedVMs())); Assert.assertFalse(q.isContinuous()); }); }
### Question: Root implements SatConstraint { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Root root = (Root) o; return Objects.equals(vm, root.vm); } Root(VM vm); @Override String toString(); @Override Collection<VM> getInvolvedVMs(); @Override boolean setContinuous(boolean b); @Override RootChecker getChecker(); @Override boolean equals(Object o); @Override int hashCode(); @Override boolean isContinuous(); static List<Root> newRoots(Collection<VM> vms); }### Answer: @Test public void testEquals() { Model mo = new DefaultModel(); VM v = mo.newVM(); Root s = new Root(v); Assert.assertTrue(s.equals(s)); Assert.assertTrue(new Root(v).equals(s)); Assert.assertEquals(s.hashCode(), new Root(v).hashCode()); Assert.assertFalse(new Root(mo.newVM()).equals(s)); }
### Question: Ready extends SimpleConstraint { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Ready ready = (Ready) o; return Objects.equals(vm, ready.vm); } Ready(VM vm); @Override ReadyChecker getChecker(); @Override String toString(); @Override boolean equals(Object o); @Override boolean setContinuous(boolean b); @Override int hashCode(); @Override Collection<VM> getInvolvedVMs(); static List<Ready> newReady(Collection<VM> vms); static List<Ready> newReady(VM... vms); }### Answer: @Test public void testEquals() { Model mo = new DefaultModel(); VM v = mo.newVM(); Ready s = new Ready(v); Assert.assertTrue(s.equals(s)); Assert.assertTrue(new Ready(v).equals(s)); Assert.assertEquals(new Ready(v).hashCode(), s.hashCode()); Assert.assertFalse(new Ready(mo.newVM()).equals(s)); }
### Question: Ready extends SimpleConstraint { public Ready(VM vm) { super(false); this.vm = vm; } Ready(VM vm); @Override ReadyChecker getChecker(); @Override String toString(); @Override boolean equals(Object o); @Override boolean setContinuous(boolean b); @Override int hashCode(); @Override Collection<VM> getInvolvedVMs(); static List<Ready> newReady(Collection<VM> vms); static List<Ready> newReady(VM... vms); }### Answer: @Test public void testReady() { Model mo = new DefaultModel(); List<VM> vms = Util.newVMs(mo, 5); List<Ready> c = Ready.newReady(vms); Assert.assertEquals(vms.size(), c.size()); c.stream().forEach((q) -> { Assert.assertTrue(vms.containsAll(q.getInvolvedVMs())); Assert.assertFalse(q.isContinuous()); }); }
### Question: Online extends SimpleConstraint { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Online online = (Online) o; return Objects.equals(node, online.node); } Online(Node n); @Override OnlineChecker getChecker(); @Override String toString(); @Override boolean setContinuous(boolean b); @Override boolean equals(Object o); @Override int hashCode(); @Override Collection<Node> getInvolvedNodes(); static List<Online> newOnline(Collection<Node> nodes); static List<Online> newOnline(Node... nodes); }### Answer: @Test public void testEquals() { Model mo = new DefaultModel(); Node n = mo.newNode(); Online s = new Online(n); Assert.assertTrue(s.equals(s)); Assert.assertTrue(new Online(n).equals(s)); Assert.assertEquals(new Online(n).hashCode(), s.hashCode()); Assert.assertFalse(new Online(mo.newNode()).equals(s)); }
### Question: Overbook extends SimpleConstraint implements ResourceRelated { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Overbook overbook = (Overbook) o; return Double.compare(overbook.ratio, ratio) == 0 && isContinuous() == overbook.isContinuous() && Objects.equals(rcId, overbook.rcId) && Objects.equals(node, overbook.node); } Overbook(Node n, String rc, double r); Overbook(Node n, String rc, double r, boolean continuous); static List<Overbook> newOverbooks(Collection<Node> nodes, String rc, double r); @Override String getResource(); double getRatio(); @Override String toString(); @Override Collection<Node> getInvolvedNodes(); @Override boolean equals(Object o); @Override int hashCode(); @Override SatConstraintChecker<Overbook> getChecker(); }### Answer: @Test public void testEquals() { Model mo = new DefaultModel(); Node n = mo.newNode(); Overbook s = new Overbook(n, "foo", 3); Assert.assertTrue(s.equals(s)); Overbook o2 = new Overbook(n, "foo", 3); Assert.assertTrue(o2.equals(s)); Assert.assertEquals(o2.hashCode(), s.hashCode()); Assert.assertFalse(new Overbook(n, "bar", 3).equals(s)); Assert.assertFalse(new Overbook(n, "foo", 2).equals(s)); Assert.assertFalse(new Overbook(mo.newNode(), "foo", 3).equals(s)); Assert.assertNotEquals(new Overbook(mo.newNode(), "foo", 3, true), new Overbook(mo.newNode(), "foo", 3, false)); Assert.assertNotEquals(new Overbook(mo.newNode(), "foo", 3, true).hashCode(), new Overbook(mo.newNode(), "foo", 3, false).hashCode()); }
### Question: Killed extends SimpleConstraint { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Killed killed = (Killed) o; return Objects.equals(vm, killed.vm); } Killed(VM vm); @Override KilledChecker getChecker(); @Override String toString(); @Override Collection<VM> getInvolvedVMs(); @Override boolean equals(Object o); @Override boolean setContinuous(boolean b); @Override int hashCode(); static List<Killed> newKilled(Collection<VM> vms); }### Answer: @Test public void testEquals() { Model mo = new DefaultModel(); VM v = mo.newVM(); Killed s = new Killed(v); Assert.assertTrue(s.equals(s)); Assert.assertTrue(new Killed(v).equals(s)); Assert.assertEquals(new Killed(v).hashCode(), s.hashCode()); Assert.assertFalse(new Killed(mo.newVM()).equals(s)); Assert.assertFalse(new Killed(mo.newVM()).equals(new Object())); }
### Question: Killed extends SimpleConstraint { public Killed(VM vm) { super(false); this.vm = vm; } Killed(VM vm); @Override KilledChecker getChecker(); @Override String toString(); @Override Collection<VM> getInvolvedVMs(); @Override boolean equals(Object o); @Override boolean setContinuous(boolean b); @Override int hashCode(); static List<Killed> newKilled(Collection<VM> vms); }### Answer: @Test public void testKilled() { Model mo = new DefaultModel(); List<VM> vms = Util.newVMs(mo, 5); List<Killed> c = Killed.newKilled(vms); Assert.assertEquals(vms.size(), c.size()); c.stream().forEach((q) -> { Assert.assertTrue(vms.containsAll(q.getInvolvedVMs())); Assert.assertFalse(q.isContinuous()); }); }
### Question: Split extends SimpleConstraint { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Split split = (Split) o; return isContinuous() == split.isContinuous() && Objects.equals(sets, split.sets); } Split(Collection<Collection<VM>> parts); Split(Collection<Collection<VM>> parts, boolean continuous); @Override Set<VM> getInvolvedVMs(); Collection<Collection<VM>> getSets(); Collection<VM> getAssociatedVGroup(VM u); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); @Override SplitChecker getChecker(); }### Answer: @Test public void testEquals() { Model mo = new DefaultModel(); Util.newNodes(mo, 3); List<VM> vms = Util.newVMs(mo, 3); Collection<VM> s1 = Collections.singleton(vms.get(0)); Collection<VM> s2 = Collections.singleton(vms.get(1)); List<Collection<VM>> args = Arrays.asList(s1, s2); Split sp = new Split(args); Assert.assertTrue(sp.equals(sp)); Assert.assertTrue(new Split(args).equals(sp)); Assert.assertEquals(new Split(args).hashCode(), sp.hashCode()); List<Collection<VM>> args2 = new ArrayList<>(args); args2.add(Collections.singleton(vms.get(2))); Assert.assertFalse(new Split(args2).equals(sp)); Assert.assertNotEquals(new Split(args, true), new Split(args, false)); }
### Question: Offline extends SimpleConstraint { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Offline offline = (Offline) o; return Objects.equals(node, offline.node); } Offline(Node n); @Override boolean setContinuous(boolean b); @Override OfflineChecker getChecker(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Collection<Node> getInvolvedNodes(); static List<Offline> newOffline(Collection<Node> nodes); static List<Offline> newOffline(Node... nodes); }### Answer: @Test public void testEquals() { Model mo = new DefaultModel(); List<Node> ns = Util.newNodes(mo, 10); Offline s = new Offline(ns.get(0)); Assert.assertTrue(s.equals(s)); Assert.assertTrue(new Offline(ns.get(0)).equals(s)); Assert.assertEquals(new Offline(ns.get(0)).hashCode(), s.hashCode()); Assert.assertFalse(new Offline(ns.get(1)).equals(s)); }
### Question: MaxOnlineConverter implements ConstraintConverter<MaxOnline> { @Override public String getJSONId() { return "maxOnline"; } @Override Class<MaxOnline> getSupportedConstraint(); @Override String getJSONId(); @Override MaxOnline fromJSON(Model mo, JSONObject in); @Override JSONObject toJSON(MaxOnline maxOnline); }### Answer: @Test public void testBundle() { Assert.assertTrue(ConstraintsConverter.newBundle().getSupportedJavaConstraints().contains(MaxOnline.class)); Assert.assertTrue(ConstraintsConverter.newBundle().getSupportedJSONConstraints().contains(new MaxOnlineConverter().getJSONId())); }
### Question: StringUtil { public static String[] splitKeepEmpty(final String string, final String split) { final String[] result = new String[count(string, split) + 1]; int from, index = -split.length(); for (int i = 0; i < result.length; i++) { from = index + split.length(); index = string.indexOf(split, from); if (index == -1) { index = string.length(); } result[i] = string.substring(from, index); } return result; } static String toString(final Vector vect); static Vector toVector(final String string); static String toLowerCamelCase(final String originalString); static String joinStrings(final String[] array, final int start); static String joinStrings(final String[] array, final int start, final int end); static String joinStrings(final String joinString, final String[] array, final int start); static String joinStrings(final String joinString, final String[] array, final int start, final int end); static String joinStrings(final String... strings); static String joinStrings(final String joinString, final String... strings); static String getPossibleSeparator(final List<String> strings, final int size); static String[] splitKeepEmpty(final String string, final String split); static int count(final String inString, final String substring); static String prependLines(final String string, final String prefix); }### Answer: @Test public void testSplitKeepEmpty() { Assert.assertEquals(1, StringUtil.splitKeepEmpty(";;;;", ".").length); Assert.assertEquals(5, StringUtil.splitKeepEmpty(";;;;", ";").length); Assert.assertEquals(5, StringUtil.splitKeepEmpty("blah;foo;;bar;test", ";").length); Assert.assertEquals(5, StringUtil.splitKeepEmpty("blah;;foo;;;;bar;;test", ";;").length); Assert.assertEquals(5, StringUtil.splitKeepEmpty(";;;;;;;;", ";;").length); }
### Question: StringUtil { public static int count(final String inString, final String substring) { int result = 0; int index = inString.indexOf(substring); while (index != -1) { result++; index = inString.indexOf(substring, index + substring.length()); } return result; } static String toString(final Vector vect); static Vector toVector(final String string); static String toLowerCamelCase(final String originalString); static String joinStrings(final String[] array, final int start); static String joinStrings(final String[] array, final int start, final int end); static String joinStrings(final String joinString, final String[] array, final int start); static String joinStrings(final String joinString, final String[] array, final int start, final int end); static String joinStrings(final String... strings); static String joinStrings(final String joinString, final String... strings); static String getPossibleSeparator(final List<String> strings, final int size); static String[] splitKeepEmpty(final String string, final String split); static int count(final String inString, final String substring); static String prependLines(final String string, final String prefix); }### Answer: @Test public void testCount() { Assert.assertEquals(0, StringUtil.count("test", ";")); Assert.assertEquals(1, StringUtil.count(";", ";")); Assert.assertEquals(4, StringUtil.count(";;;;", ";")); Assert.assertEquals(4, StringUtil.count(";;test;test;", ";")); Assert.assertEquals(4, StringUtil.count(";;;;;;;;;", ";;")); }
### Question: Trie { public T check(final String aString) { final char[] chars = aString.toCharArray(); for (int i = 0; i < chars.length; i++) { final Node<T> root = this.roots.get(chars[i]); if (root != null) { final T res = root.check(chars, i); if (res != null) { return res; } } } return null; } Trie(); void insert(final T elem); Set<T> checkAll(final String aString); T check(final String aString); Set<T> getAll(); void clear(); }### Answer: @Test public void testTrieCheckNotIn() { final String toBeChecked = "Test"; final Elem z = this.trie.check(toBeChecked); Assert.assertNull(z); } @Test public void testTrieCheckInSimple() { final String toBeChecked = "12h"; final Elem aBis = this.trie.check(toBeChecked); Assert.assertNotNull(aBis); Assert.assertEquals(this.a, aBis); } @Test public void testTrieCheckInLessSimple() { final String toBeChecked = "Test-gsgd42gtegzrkeifhze-42k fefsief"; final Elem bBis = this.trie.check(toBeChecked); Assert.assertNotNull(bBis); Assert.assertEquals(this.b, bBis); } @Test public void testTrieCheckInABitComplex() { final String toBeChecked = "Test" + Integer.MIN_VALUE + " jifjzoigzTest--42k"; final Elem cBis = this.trie.check(toBeChecked); Assert.assertNotNull(cBis); Assert.assertEquals(this.c, cBis); }
### Question: Trie { public Set<T> getAll() { final Set<T> result = new HashSet<>(); for (final Node<T> node : this.roots.values()) { node.addAllTo(result); } return result; } Trie(); void insert(final T elem); Set<T> checkAll(final String aString); T check(final String aString); Set<T> getAll(); void clear(); }### Answer: @Test public void testTrieGetAll() { final Set<Elem> content = this.trie.getAll(); Assert.assertEquals(3, content.size()); Assert.assertTrue(content.contains(this.a)); Assert.assertTrue(content.contains(this.b)); Assert.assertTrue(content.contains(this.c)); }
### Question: TableParser { static public List<Record> readTable(String urlString, String format, int maxLines) throws IOException, NumberFormatException { InputStream ios; if (urlString.startsWith("http:")) { URL url = new URL(urlString); ios = url.openStream(); } else { ios = new FileInputStream(urlString); } return readTable(ios, format, maxLines); } TableParser(String format); static List<Record> readTable(String urlString, String format, int maxLines); static List<Record> readTable(InputStream ios, String format, int maxLines); Field getField(int fldno); int getNumberOfFields(); List<Record> readAllRecords(InputStream ios, int maxLines); Record readRecord(String line); DerivedField addDerivedField(Field from, Transform transform, Class type ); }### Answer: @Test public void testRead() throws IOException { Class c = TableParser.class; InputStream is = c.getResourceAsStream(testName3); List recs = TableParser.readTable(is, "3,15,54,60d,67d,73d", 50000); for (int i = 0; i < recs.size(); i++) { TableParser.Record record = (TableParser.Record) recs.get(i); for (int j = 0; j < record.values.size(); j++) { Object s = record.values.get(j); System.out.print(" " + s.toString()); } System.out.println(); } }
### Question: ServiceImpl implements Service, ServiceBuilder { public List<Service> getServices() { if ( !this.isBuilt ) throw new IllegalStateException( "This Service has escaped from its ServiceBuilder without being built." ); return this.serviceContainer.getServices(); } ServiceImpl( String name, ServiceType type, URI baseUri, GlobalServiceContainer globalServiceContainer ); String getName(); void setDescription( String description ); String getDescription(); void setType( ServiceType type ); ServiceType getType(); void setBaseUri( URI baseUri ); URI getBaseUri(); void setSuffix( String suffix ); String getSuffix(); void addProperty( String name, String value ); boolean removeProperty( String name ); List<String> getPropertyNames(); String getPropertyValue( String name ); List<Property> getProperties(); Property getPropertyByName( String name ); ServiceBuilder addService( String name, ServiceType type, URI baseUri ); boolean removeService( ServiceBuilder serviceBuilder ); List<Service> getServices(); Service getServiceByName( String name ); Service findServiceByNameGlobally( String name ); List<ServiceBuilder> getServiceBuilders(); ServiceBuilder getServiceBuilderByName( String name ); ServiceBuilder findServiceBuilderByNameGlobally( String name ); boolean isBuilt(); BuilderIssues getIssues(); Service build(); }### Answer: @Test(expected=IllegalStateException.class) public void checkExceptionOnPreBuildGetServices() { odapService.getServices(); }
### Question: ServiceImpl implements Service, ServiceBuilder { public Service getServiceByName( String name ) { if ( !this.isBuilt ) throw new IllegalStateException( "This Service has escaped from its ServiceBuilder without being built." ); return this.serviceContainer.getServiceByName( name ); } ServiceImpl( String name, ServiceType type, URI baseUri, GlobalServiceContainer globalServiceContainer ); String getName(); void setDescription( String description ); String getDescription(); void setType( ServiceType type ); ServiceType getType(); void setBaseUri( URI baseUri ); URI getBaseUri(); void setSuffix( String suffix ); String getSuffix(); void addProperty( String name, String value ); boolean removeProperty( String name ); List<String> getPropertyNames(); String getPropertyValue( String name ); List<Property> getProperties(); Property getPropertyByName( String name ); ServiceBuilder addService( String name, ServiceType type, URI baseUri ); boolean removeService( ServiceBuilder serviceBuilder ); List<Service> getServices(); Service getServiceByName( String name ); Service findServiceByNameGlobally( String name ); List<ServiceBuilder> getServiceBuilders(); ServiceBuilder getServiceBuilderByName( String name ); ServiceBuilder findServiceBuilderByNameGlobally( String name ); boolean isBuilt(); BuilderIssues getIssues(); Service build(); }### Answer: @Test(expected=IllegalStateException.class) public void checkExceptionOnPreBuildGetServiceByName() { odapService.getServiceByName( "name"); }
### Question: ServiceContainer { boolean isEmpty() { if ( this.services == null ) return true; return this.services.isEmpty(); } ServiceContainer( GlobalServiceContainer globalServiceContainer ); }### Answer: @Test public void checkThatNewlyCreatedContainerIsEmpty() { GlobalServiceContainer gsc = new GlobalServiceContainer(); ServiceContainer sc = new ServiceContainer( gsc); assertTrue( sc.isEmpty()); assertNotNull( gsc ); assertTrue( gsc.isEmpty() ); }
### Question: ServiceContainer { Service getServiceByName( String name ) { if ( ! this.isBuilt ) throw new IllegalStateException( "This Service has escaped from its ServiceBuilder without being finished()." ); if ( name == null ) return null; return this.getServiceImplByName( name ); } ServiceContainer( GlobalServiceContainer globalServiceContainer ); }### Answer: @Test(expected = IllegalStateException.class) public void checkExceptionOnPreBuildGetServiceByName() { this.serviceContainer.getServiceByName( "odap" ); }
### Question: ServiceContainer { List<Service> getServices() { if ( ! this.isBuilt ) throw new IllegalStateException( "This Service has escaped from its ServiceBuilder without being finished()." ); if ( this.services == null ) return Collections.emptyList(); return Collections.unmodifiableList( new ArrayList<Service>( this.services ) ); } ServiceContainer( GlobalServiceContainer globalServiceContainer ); }### Answer: @Test(expected = IllegalStateException.class) public void checkExceptionOnPreBuildGetServices() { this.serviceContainer.getServices(); }
### Question: CatalogImpl implements Catalog, CatalogBuilder { public void setDocBaseUri( URI docBaseUri ) { if ( isBuilt ) throw new IllegalStateException( "This CatalogBuilder has been built." ); if ( docBaseUri == null ) throw new IllegalArgumentException( "Catalog base URI must not be null." ); this.docBaseUri = docBaseUri; } CatalogImpl( String name, URI docBaseUri, String version, DateType expires, DateType lastModified ); void setName( String name ); String getName(); void setDocBaseUri( URI docBaseUri ); URI getDocBaseUri(); void setVersion( String version ); String getVersion(); void setExpires( DateType expires ); DateType getExpires(); void setLastModified( DateType lastModified ); DateType getLastModified(); ServiceBuilder addService( String name, ServiceType type, URI baseUri ); boolean removeService( ServiceBuilder serviceBuilder ); List<Service> getServices(); Service getServiceByName( String name ); Service findServiceByNameGlobally( String name ); List<ServiceBuilder> getServiceBuilders(); ServiceBuilder getServiceBuilderByName( String name ); ServiceBuilder findServiceBuilderByNameGlobally( String name ); void addProperty( String name, String value ); boolean removeProperty( String name ); List<String> getPropertyNames(); String getPropertyValue( String name ); List<Property> getProperties(); Property getPropertyByName( String name ); DatasetBuilder addDataset( String name ); CatalogRefBuilder addCatalogRef( String name, URI reference ); boolean removeDataset( DatasetNodeBuilder builder ); List<DatasetNode> getDatasets(); DatasetNode getDatasetById( String id ); DatasetNode findDatasetByIdGlobally( String id ); List<DatasetNodeBuilder> getDatasetNodeBuilders(); DatasetNodeBuilder getDatasetNodeBuilderById( String id ); DatasetNodeBuilder findDatasetNodeBuilderByIdGlobally( String id ); boolean isBuilt(); BuilderIssues getIssues(); Catalog build(); }### Answer: @Test(expected=IllegalArgumentException.class) public void checkForExceptionWhenNullSetDocBaseUri() { this.catImpl.setDocBaseUri( null ); }
### Question: DeepCopyUtils { public static InvCatalog copyCatalog( InvCatalog catalog ) { if ( catalog == null ) throw new IllegalArgumentException( "Catalog may not be null." ); InvCatalogImpl resultCatalog = new InvCatalogImpl( catalog.getName(), "1.0", catalog.getExpires(), ((InvCatalogImpl) catalog).getBaseURI() ); List<InvService> copiedServices = copyServicesIntoCopiedCatalog( catalog, resultCatalog ); for ( InvDataset curDs : catalog.getDatasets()) { resultCatalog.addDataset( (InvDatasetImpl) DeepCopyUtils.copyDataset( curDs, copiedServices, false ) ); } resultCatalog.finish(); return resultCatalog; } private DeepCopyUtils(); static InvCatalog copyCatalog( InvCatalog catalog ); static InvCatalog subsetCatalogOnDataset( InvCatalog catalog, String datasetId ); static InvCatalog subsetCatalogOnDataset( InvCatalog catalog, InvDataset dataset); static InvDataset copyDataset( InvDataset dataset, List<InvService> availableServices, boolean copyInheritedMetadataFromParents ); static InvAccess copyAccess( InvAccess access, InvDataset parentDataset, List<InvService> availableServices ); static InvService copyService( InvService service ); static InvProperty copyProperty( InvProperty property); }### Answer: @Test public void checkCopyCatalog() throws URISyntaxException, IOException { String docBaseUriString = "http: URI docBaseUri = new URI( docBaseUriString ); String catalogAsString = setupCatalogWithNestedDatasets(); InvCatalogFactory fac = InvCatalogFactory.getDefaultFactory( true ); InvCatalogImpl catalog = fac.readXML( catalogAsString, docBaseUri ); assertCatalogAsExpected( catalog, docBaseUri ); String origCatAsString = fac.writeXML( catalog ); InvCatalog resultCatalog = DeepCopyUtils.copyCatalog( catalog ); assertCatalogAsExpected( resultCatalog, docBaseUri); String resultCatalogAsString = fac.writeXML( (InvCatalogImpl) resultCatalog ); assertEquals( origCatAsString, resultCatalogAsString ); assertEquals( catalog, resultCatalog); }
### Question: DeepCopyUtils { public static InvCatalog subsetCatalogOnDataset( InvCatalog catalog, String datasetId ) { if ( catalog == null ) throw new IllegalArgumentException( "Catalog may not be null." ); if ( datasetId == null ) throw new IllegalArgumentException( "Dataset ID may not be null." ); InvDataset ds = catalog.findDatasetByID( datasetId ); if ( ds == null ) throw new IllegalArgumentException( "The dataset ID [" + datasetId + "] does not match the ID of a dataset in the catalog." ); return subsetCatalogOnDataset( catalog, ds ); } private DeepCopyUtils(); static InvCatalog copyCatalog( InvCatalog catalog ); static InvCatalog subsetCatalogOnDataset( InvCatalog catalog, String datasetId ); static InvCatalog subsetCatalogOnDataset( InvCatalog catalog, InvDataset dataset); static InvDataset copyDataset( InvDataset dataset, List<InvService> availableServices, boolean copyInheritedMetadataFromParents ); static InvAccess copyAccess( InvAccess access, InvDataset parentDataset, List<InvService> availableServices ); static InvService copyService( InvService service ); static InvProperty copyProperty( InvProperty property); }### Answer: @Test public void checkSubsetCatalogOnDataset() throws URISyntaxException, IOException { String docBaseUriString = "http: URI docBaseUri = new URI( docBaseUriString ); String catalogAsString = setupCatalogWithNestedDatasets(); InvCatalogFactory fac = InvCatalogFactory.getDefaultFactory( true ); InvCatalogImpl catalog = fac.readXML( catalogAsString, docBaseUri ); InvCatalog resultCatalog = DeepCopyUtils.subsetCatalogOnDataset( catalog, "ds2" ); assertCatalogAsExpected( catalog, docBaseUri ); assertSubsetCatalogOnDatasetAsExpected( resultCatalog, docBaseUri ); }
### Question: DeepCopyUtils { public static InvProperty copyProperty( InvProperty property) { return new InvProperty( property.getName(), property.getValue()); } private DeepCopyUtils(); static InvCatalog copyCatalog( InvCatalog catalog ); static InvCatalog subsetCatalogOnDataset( InvCatalog catalog, String datasetId ); static InvCatalog subsetCatalogOnDataset( InvCatalog catalog, InvDataset dataset); static InvDataset copyDataset( InvDataset dataset, List<InvService> availableServices, boolean copyInheritedMetadataFromParents ); static InvAccess copyAccess( InvAccess access, InvDataset parentDataset, List<InvService> availableServices ); static InvService copyService( InvService service ); static InvProperty copyProperty( InvProperty property); }### Answer: @Test public void checkPropertyCopy() { String propName = "propName"; String propValue = "propVal"; InvProperty prop = new InvProperty( propName, propValue ); InvProperty copyProp = DeepCopyUtils.copyProperty( prop ); assertFalse( prop == copyProp ); assertEquals( prop.getName(), copyProp.getName() ); assertEquals( prop.getValue(), copyProp.getValue() ); }
### Question: CalendarDateUnit { static public CalendarDateUnit of(String calendarName, String udunitString) { Calendar calt = Calendar.get(calendarName); if (calt == null) calt = Calendar.getDefault(); return new CalendarDateUnit(calt, udunitString); } private CalendarDateUnit(Calendar calt, String dateUnitString); static CalendarDateUnit of(String calendarName, String udunitString); static CalendarDateUnit withCalendar(Calendar calt, String udunitString); CalendarDate makeCalendarDate(double value); CalendarDate makeCalendarDate(int value); @Override String toString(); CalendarDate getBaseCalendarDate(); CalendarPeriod getTimeUnit(); Calendar getCalendar(); boolean isCalendarField(); static void main(String[] args); static final String udunitPatternString; }### Answer: @Test public void testMinMax() { CalendarDate max = CalendarDate.of(Long.MAX_VALUE); System.out.printf("CalendarDate%n"); System.out.printf(" max = %s%n", max); CalendarDate min = CalendarDate.of(Long.MIN_VALUE); System.out.printf(" min = %s%n", min); System.out.printf("%nDate%n"); Date d = new Date(Long.MAX_VALUE); System.out.printf("max = %s%n", d); Date ds = new Date(Long.MIN_VALUE); System.out.printf("min = %s%n", ds); }
### Question: ServiceImpl implements Service, ServiceBuilder { public void setType( ServiceType type ) { if ( this.isBuilt ) throw new IllegalStateException( "This ServiceBuilder has been built." ); if ( type == null ) throw new IllegalArgumentException( "Service type must not be null." ); this.type = type; } ServiceImpl( String name, ServiceType type, URI baseUri, GlobalServiceContainer globalServiceContainer ); String getName(); void setDescription( String description ); String getDescription(); void setType( ServiceType type ); ServiceType getType(); void setBaseUri( URI baseUri ); URI getBaseUri(); void setSuffix( String suffix ); String getSuffix(); void addProperty( String name, String value ); boolean removeProperty( String name ); List<String> getPropertyNames(); String getPropertyValue( String name ); List<Property> getProperties(); Property getPropertyByName( String name ); ServiceBuilder addService( String name, ServiceType type, URI baseUri ); boolean removeService( ServiceBuilder serviceBuilder ); List<Service> getServices(); Service getServiceByName( String name ); Service findServiceByNameGlobally( String name ); List<ServiceBuilder> getServiceBuilders(); ServiceBuilder getServiceBuilderByName( String name ); ServiceBuilder findServiceBuilderByNameGlobally( String name ); boolean isBuilt(); BuilderIssues getIssues(); Service build(); }### Answer: @Test(expected=IllegalArgumentException.class) public void checkExceptionOnChangeToNullType() { odapService.setType( null ); }
### Question: ServiceImpl implements Service, ServiceBuilder { public void setBaseUri( URI baseUri ) { if ( this.isBuilt ) throw new IllegalStateException( "This ServiceBuilder has been built." ); if ( baseUri == null ) throw new IllegalArgumentException( "Base URI must not be null." ); this.baseUri = baseUri; } ServiceImpl( String name, ServiceType type, URI baseUri, GlobalServiceContainer globalServiceContainer ); String getName(); void setDescription( String description ); String getDescription(); void setType( ServiceType type ); ServiceType getType(); void setBaseUri( URI baseUri ); URI getBaseUri(); void setSuffix( String suffix ); String getSuffix(); void addProperty( String name, String value ); boolean removeProperty( String name ); List<String> getPropertyNames(); String getPropertyValue( String name ); List<Property> getProperties(); Property getPropertyByName( String name ); ServiceBuilder addService( String name, ServiceType type, URI baseUri ); boolean removeService( ServiceBuilder serviceBuilder ); List<Service> getServices(); Service getServiceByName( String name ); Service findServiceByNameGlobally( String name ); List<ServiceBuilder> getServiceBuilders(); ServiceBuilder getServiceBuilderByName( String name ); ServiceBuilder findServiceBuilderByNameGlobally( String name ); boolean isBuilt(); BuilderIssues getIssues(); Service build(); }### Answer: @Test(expected=IllegalArgumentException.class) public void checkExceptionOnChangeToNullBaseUri() { odapService.setBaseUri( null ); }
### Question: ServiceImpl implements Service, ServiceBuilder { public List<Property> getProperties() { if ( !this.isBuilt ) throw new IllegalStateException( "This Service has escaped from its ServiceBuilder before build() was called." ); return this.propertyContainer.getProperties(); } ServiceImpl( String name, ServiceType type, URI baseUri, GlobalServiceContainer globalServiceContainer ); String getName(); void setDescription( String description ); String getDescription(); void setType( ServiceType type ); ServiceType getType(); void setBaseUri( URI baseUri ); URI getBaseUri(); void setSuffix( String suffix ); String getSuffix(); void addProperty( String name, String value ); boolean removeProperty( String name ); List<String> getPropertyNames(); String getPropertyValue( String name ); List<Property> getProperties(); Property getPropertyByName( String name ); ServiceBuilder addService( String name, ServiceType type, URI baseUri ); boolean removeService( ServiceBuilder serviceBuilder ); List<Service> getServices(); Service getServiceByName( String name ); Service findServiceByNameGlobally( String name ); List<ServiceBuilder> getServiceBuilders(); ServiceBuilder getServiceBuilderByName( String name ); ServiceBuilder findServiceBuilderByNameGlobally( String name ); boolean isBuilt(); BuilderIssues getIssues(); Service build(); }### Answer: @Test(expected=IllegalStateException.class) public void checkExceptionOnPreBuildGetProperties() { odapService.getProperties(); }
### Question: ServiceImpl implements Service, ServiceBuilder { public Property getPropertyByName( String name ) { if ( !this.isBuilt ) throw new IllegalStateException( "This Service has escaped from its ServiceBuilder before build() was called." ); return this.propertyContainer.getPropertyByName( name ); } ServiceImpl( String name, ServiceType type, URI baseUri, GlobalServiceContainer globalServiceContainer ); String getName(); void setDescription( String description ); String getDescription(); void setType( ServiceType type ); ServiceType getType(); void setBaseUri( URI baseUri ); URI getBaseUri(); void setSuffix( String suffix ); String getSuffix(); void addProperty( String name, String value ); boolean removeProperty( String name ); List<String> getPropertyNames(); String getPropertyValue( String name ); List<Property> getProperties(); Property getPropertyByName( String name ); ServiceBuilder addService( String name, ServiceType type, URI baseUri ); boolean removeService( ServiceBuilder serviceBuilder ); List<Service> getServices(); Service getServiceByName( String name ); Service findServiceByNameGlobally( String name ); List<ServiceBuilder> getServiceBuilders(); ServiceBuilder getServiceBuilderByName( String name ); ServiceBuilder findServiceBuilderByNameGlobally( String name ); boolean isBuilt(); BuilderIssues getIssues(); Service build(); }### Answer: @Test(expected=IllegalStateException.class) public void checkExceptionOnPreBuildGetPropertyByNAme() { odapService.getPropertyByName( "name"); }
### Question: MoviesRemoteRepository implements MoviesRepository { @Override public Observable<List<Movie>> getPopularMovies(int page) { Observable<DiscoverMoviesResponse> discoverMoviesResponseObservable = apiService.discover("popularity.desc", page, ApiUtils.getApiKey()); return discoverMoviesResponseObservable .flatMap(new Function<DiscoverMoviesResponse, ObservableSource<? extends List<Movie>>>() { @Override public ObservableSource<? extends List<Movie>> apply(DiscoverMoviesResponse discoverMoviesResponse) throws Exception { return Observable.just(discoverMoviesResponse.getResults()); } }); } MoviesRemoteRepository(MovieApiService apiService); @Override Observable<List<Movie>> getPopularMovies(int page); @Override Observable<Movie> getMovieDetails(long movieId); }### Answer: @Test public void getPopularMoviesMakesApiCall() { when(apiService.discover(SORT_BY_POPULARITY, PAGE, API_KEY)) .thenReturn(Observable.just(mDiscoverMoviesResponse)); mRemoteRepository.getPopularMovies(1).subscribeWith(mMovieListTestSubscriber); verify(apiService).discover(SORT_BY_POPULARITY, PAGE, API_KEY); mMovieListTestSubscriber.assertValue(mMovieList); }
### Question: MoviesRemoteRepository implements MoviesRepository { @Override public Observable<Movie> getMovieDetails(long movieId) { return apiService.getMovieDetails(movieId, ApiUtils.getApiKey()); } MoviesRemoteRepository(MovieApiService apiService); @Override Observable<List<Movie>> getPopularMovies(int page); @Override Observable<Movie> getMovieDetails(long movieId); }### Answer: @Test public void getMovieDetails() { Movie movie = mMovieList.get(1); when(apiService.getMovieDetails(MOVIE_ID, API_KEY)).thenReturn(Observable.just(movie)); mRemoteRepository.getMovieDetails(MOVIE_ID).subscribeWith(mMovieTestSubscriber); verify(apiService).getMovieDetails(MOVIE_ID, API_KEY); mMovieTestSubscriber.assertValue(movie); }
### Question: MovieDetailsViewModel extends MovieViewModel { public void getMovieDetails(long movieId) { isMovieLoading.set(true); errorViewShowing.set(false); mMoviesRepository.getMovieDetails(movieId) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribeWith(new DisposableObserver<Movie>() { @Override public void onNext(Movie value) { setMovie(value); } @Override public void onError(Throwable e) { errorViewShowing.set(true); isMovieLoading.set(false); } @Override public void onComplete() { isMovieLoading.set(false); errorViewShowing.set(false); } }); } MovieDetailsViewModel(MoviesRepository moviesRepository); void getMovieDetails(long movieId); final ObservableBoolean isMovieLoading; final ObservableBoolean errorViewShowing; final ObservableField<String> errorString; }### Answer: @Test public void getMovieDetailsWithoutError() { setupRepository(); mDetailsViewModel.getMovieDetails(MOVIE_ID); verify(mMovieRepository).getMovieDetails(MOVIE_ID); assertFalse(mDetailsViewModel.isMovieLoading.get()); assertFalse(mDetailsViewModel.errorViewShowing.get()); verifyThatMovieFieldsAreSet(mDetailsViewModel, mMovie); } @Test public void errorViewIsShownWhenGetMovieDetailsGivesError() { when(mMovieRepository.getMovieDetails(MOVIE_ID)).thenReturn( Observable.<Movie>error(new Throwable("Exception"))); mDetailsViewModel.getMovieDetails(MOVIE_ID); assertTrue(mDetailsViewModel.errorViewShowing.get()); assertFalse(mDetailsViewModel.isMovieLoading.get()); }
### Question: MovieItemViewModel extends MovieViewModel { public void clickMovieItem() { Movie movie = getMovie(); if (movie != null) { interactor.showMovieDetails(movie); } } MovieItemViewModel(MoviesRepository moviesRepository, Interactor interactor); void clickMovieItem(); }### Answer: @Test public void clickOnItemShowsMovieDetails() { mMovieItemViewModel.setMovie(mMovie); mMovieItemViewModel.clickMovieItem(); verify(interactor).showMovieDetails(mMovie); }
### Question: RtmClientBuilder { URI createUri(String endpoint, String appKey) { if (Strings.isNullOrEmpty(endpoint)) { throw new IllegalArgumentException(); } Pattern verPattern = Pattern.compile("/(v\\d+)$"); Matcher m = verPattern.matcher(endpoint); String fullEndpoint = endpoint; if (!m.find()) { if (!fullEndpoint.endsWith("/")) { fullEndpoint += "/"; } fullEndpoint += RTM_VER; } else { String ver = m.group(1); LOG.warn("Specifying a version as a part of the endpoint is deprecated. " + "Please remove the {} from {}", ver, endpoint); } String uri = String.format("%s?appkey=%s", fullEndpoint, appKey); try { return new URI(uri); } catch (URISyntaxException e) { LOG.error("Unable to parse URI {}", uri, e); throw new RuntimeException(e); } } RtmClientBuilder(String endpoint, String appKey); RtmClient build(); RtmClientBuilder setConnectionTimeout(int connectionTimeout); RtmClientBuilder setProxy(URI proxyUri); RtmClientBuilder setPendingActionQueueLength(int pendingActionQueueLength); RtmClientBuilder setMaxReconnectInterval(long maxReconnectInterval); RtmClientBuilder setMinReconnectInterval(long minReconnectInterval); RtmClientBuilder setListener(RtmClientListener listener); @Deprecated RtmClientBuilder setTransportFactory(final TransportFactory transportFactory); RtmClientBuilder setTransportFactory(AbstractTransportFactory transportFactory); RtmClientBuilder setAuthProvider(AuthProvider authProvider); RtmClientBuilder setAutoReconnect(boolean isAutoReconnect); RtmClientBuilder setScheduler(ScheduledExecutorService service); RtmClientBuilder setDispatcher(ExecutorService dispatcher, boolean shouldDispatchTransport); RtmClientBuilder setJsonSerializer(Serializer serializer); }### Answer: @Test public void appendVersionTest() { RtmClientBuilder builder = new RtmClientBuilder("foo", "bar"); assertThat( builder.createUri("ws: equalTo("ws: ); assertThat( builder.createUri("ws: equalTo("ws: ); assertThat( builder.createUri("ws: equalTo("ws: ); }
### Question: MockServerRule implements TestRule { public MockServerClient getClient() { return clientAndServer; } MockServerRule(Object target); MockServerRule(Object target, boolean perTestSuite); MockServerRule(Object target, Integer... ports); MockServerRule(Object target, boolean perTestSuite, Integer... ports); Integer getPort(); Integer[] getPorts(); Statement apply(Statement base, Description description); MockServerClient getClient(); }### Answer: @Test public void shouldSetTestMockServerFieldWithSameValueFromGetter() { assertThat(mockServerClient, sameInstance(mockServerRule.getClient())); }
### Question: MockServerEventBus { void publish(EventType event) { for (SubscriberHandler subscriber : subscribers.get(event)) { subscriber.handle(); } } void subscribe(SubscriberHandler subscriber, EventType... events); }### Answer: @Test public void shouldPublishStopEventWhenNoRegisterSubscriber() { bus.publish(STOP); }
### Question: BodyServletDecoderEncoder { public void bodyToServletResponse(HttpServletResponse httpServletResponse, Body body, String contentTypeHeader) { byte[] bytes = bodyDecoderEncoder.bodyToBytes(body, contentTypeHeader); if (bytes != null) { ioStreamUtils.writeToOutputStream(bytes, httpServletResponse); } } BodyServletDecoderEncoder(MockServerLogger mockServerLogger); void bodyToServletResponse(HttpServletResponse httpServletResponse, Body body, String contentTypeHeader); BodyWithContentType servletRequestToBody(HttpServletRequest servletRequest); }### Answer: @Test public void shouldSerialiseBodyToServletResponseWithNoContentType() throws IOException { Body body = new StringBody("bytes"); HttpServletResponse servletResponse = mock(HttpServletResponse.class); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); when(servletResponse.getOutputStream()).thenReturn( new DelegatingServletOutputStream(outputStream) ); new BodyServletDecoderEncoder(mockServerLogger).bodyToServletResponse(servletResponse, body, null); assertThat(outputStream.toByteArray(), is("bytes".getBytes(DEFAULT_HTTP_CHARACTER_SET))); } @Test public void shouldSerialiseBodyToServletResponseWithJsonContentType() throws IOException { Body body = new StringBody("şarəs"); HttpServletResponse servletResponse = mock(HttpServletResponse.class); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); when(servletResponse.getOutputStream()).thenReturn( new DelegatingServletOutputStream(outputStream) ); new BodyServletDecoderEncoder(mockServerLogger).bodyToServletResponse(servletResponse, body, MediaType.APPLICATION_JSON_UTF_8.toString()); assertThat(outputStream.toByteArray(), is("şarəs".getBytes(UTF_8))); }
### Question: Parameter extends KeyToMultiValue { public static Parameter param(String name, String... value) { return new Parameter(name, value); } Parameter(String name, String... value); Parameter(NottableString name, NottableString... value); Parameter(NottableString name, String... value); Parameter(String name, Collection<String> value); Parameter(NottableString name, Collection<NottableString> value); static Parameter param(String name, String... value); static Parameter param(NottableString name, NottableString... value); static Parameter param(NottableString name, String... value); static Parameter param(String name, Collection<String> value); static Parameter param(NottableString name, Collection<NottableString> value); static Parameter schemaParam(String name, String... values); static Parameter schemaParam(NottableString name, String... values); static Parameter optionalParam(String name, String... values); Parameter withStyle(ParameterStyle style); }### Answer: @Test public void shouldReturnValueSetInStaticConstructors() { Parameter firstParameter = param("first", "first_one", "first_two"); Parameter secondParameter = param("second", Arrays.asList("second_one", "second_two")); assertThat(firstParameter.getValues(), containsInAnyOrder(string("first_one"), string("first_two"))); assertThat(secondParameter.getValues(), containsInAnyOrder(string("second_one"), string("second_two"))); }
### Question: BinaryBody extends BodyWithContentType<byte[]> { public static BinaryBody binary(byte[] body) { return new BinaryBody(body); } BinaryBody(byte[] bytes); BinaryBody(byte[] bytes, MediaType contentType); static BinaryBody binary(byte[] body); static BinaryBody binary(byte[] body, MediaType contentType); byte[] getValue(); @JsonIgnore byte[] getRawBytes(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void shouldAlwaysCreateNewObject() { byte[] body = DatatypeConverter.parseBase64Binary("some_body"); assertEquals(binary(body), binary(body)); assertNotSame(binary(body), binary(body)); }
### Question: BinaryBody extends BodyWithContentType<byte[]> { public byte[] getValue() { return bytes; } BinaryBody(byte[] bytes); BinaryBody(byte[] bytes, MediaType contentType); static BinaryBody binary(byte[] body); static BinaryBody binary(byte[] body, MediaType contentType); byte[] getValue(); @JsonIgnore byte[] getRawBytes(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void shouldReturnValuesSetInConstructor() { byte[] body = DatatypeConverter.parseBase64Binary("some_body"); BinaryBody binaryBody = new BinaryBody(body); assertThat(binaryBody.getValue(), is(body)); assertThat(binaryBody.getType(), is(Body.Type.BINARY)); assertThat(binaryBody.getCharset(null), nullValue()); assertThat(binaryBody.getCharset(StandardCharsets.UTF_8), is(StandardCharsets.UTF_8)); assertThat(binaryBody.getContentType(), nullValue()); }
### Question: PortBinding extends ObjectWithJsonToString { public List<Integer> getPorts() { return ports; } static PortBinding portBinding(Integer... ports); static PortBinding portBinding(List<Integer> ports); List<Integer> getPorts(); PortBinding setPorts(List<Integer> ports); String getVersion(); String getArtifactId(); String getGroupId(); }### Answer: @Test public void shouldReturnValuesSetInConstructor() { PortBinding portBinding = new PortBinding(); assertThat(portBinding.getPorts(), empty()); }
### Question: HttpObjectCallback extends Action<HttpObjectCallback> { public HttpObjectCallback withClientId(String clientId) { this.clientId = clientId; this.hashCode = 0; return this; } String getClientId(); HttpObjectCallback withClientId(String clientId); Boolean getResponseCallback(); HttpObjectCallback withResponseCallback(Boolean responseCallback); @SuppressWarnings("UnusedReturnValue") HttpObjectCallback withActionType(Type actionType); @Override @JsonIgnore Type getType(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void shouldReturnFormattedRequestInToString() { TestCase.assertEquals("{" + NEW_LINE + " \"clientId\" : \"some_client_id\"" + NEW_LINE + "}", new HttpObjectCallback() .withClientId("some_client_id") .toString() ); }
### Question: HttpForward extends Action<HttpForward> { public static HttpForward forward() { return new HttpForward(); } static HttpForward forward(); @Override @JsonIgnore Type getType(); String getHost(); HttpForward withHost(String host); Integer getPort(); HttpForward withPort(Integer port); Scheme getScheme(); HttpForward withScheme(Scheme scheme); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void shouldAlwaysCreateNewObject() { assertEquals(forward(), forward()); assertNotSame(forward(), forward()); }
### Question: Cookie extends KeyAndValue { public Cookie(String name, String value) { super(name, value); } Cookie(String name, String value); Cookie(NottableString name, NottableString value); Cookie(NottableString name, String value); static Cookie cookie(String name, String value); static Cookie cookie(NottableString name, NottableString value); static Cookie cookie(NottableString name, String value); static Cookie schemaCookie(String name, String value); static Cookie optionalCookie(String name, String value); static Cookie optionalCookie(String name, NottableString value); }### Answer: @Test public void shouldReturnValueSetInStaticConstructors() { Cookie firstCookie = cookie("name", "value"); assertThat(firstCookie.getName(), is(string("name"))); assertThat(firstCookie.getValue(), is(string("value"))); }
### Question: HttpError extends Action<HttpError> { public static HttpError error() { return new HttpError(); } static HttpError error(); HttpError withDropConnection(Boolean dropConnection); Boolean getDropConnection(); HttpError withResponseBytes(byte[] responseBytes); byte[] getResponseBytes(); @Override @JsonIgnore Type getType(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test @SuppressWarnings("AccessStaticViaInstance") public void shouldAlwaysCreateNewObject() { assertEquals(error(), error()); assertNotSame(error(), error()); }
### Question: XmlBody extends BodyWithContentType<String> { public static XmlBody xml(String xml) { return new XmlBody(xml); } XmlBody(String xml); XmlBody(String xml, Charset charset); XmlBody(String xml, MediaType contentType); XmlBody(String xml, byte[] rawBytes, MediaType contentType); static XmlBody xml(String xml); static XmlBody xml(String xml, Charset charset); static XmlBody xml(String xml, MediaType contentType); String getValue(); @JsonIgnore byte[] getRawBytes(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static final MediaType DEFAULT_XML_CONTENT_TYPE; }### Answer: @Test public void shouldAlwaysCreateNewObject() { assertEquals(xml("some_body"), xml("some_body")); assertNotSame(xml("some_body"), xml("some_body")); }
### Question: Cookies extends KeysAndValues<Cookie, Cookies> { @Override public Cookie build(NottableString name, NottableString value) { return new Cookie(name, value); } Cookies(List<Cookie> cookies); Cookies(Cookie... cookies); Cookies(Map<NottableString, NottableString> cookies); @Override Cookie build(NottableString name, NottableString value); @SuppressWarnings("MethodDoesntCallSuperMethod") Cookies clone(); }### Answer: @Test public void shouldBuildCookie() { Cookies cookies = new Cookies(); Cookie cookie = cookies.build(string("name"), string("value")); assertThat(cookie, is(new Cookie(string("name"), string("value")))); }
### Question: HttpTemplate extends Action<HttpTemplate> { public static HttpTemplate template(TemplateType type) { return new HttpTemplate(type); } HttpTemplate(TemplateType type); static HttpTemplate template(TemplateType type); static HttpTemplate template(TemplateType type, String template); TemplateType getTemplateType(); HttpTemplate withTemplate(String template); String getTemplate(); void withActionType(Type actionType); @Override @JsonIgnore Type getType(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test @SuppressWarnings("AccessStaticViaInstance") public void shouldAlwaysCreateNewObject() { assertEquals(template(JAVASCRIPT), template(JAVASCRIPT)); assertEquals(template(VELOCITY), template(VELOCITY)); assertNotSame(template(JAVASCRIPT), template(JAVASCRIPT)); assertNotSame(template(VELOCITY), template(VELOCITY)); }
### Question: HttpTemplate extends Action<HttpTemplate> { public TemplateType getTemplateType() { return templateType; } HttpTemplate(TemplateType type); static HttpTemplate template(TemplateType type); static HttpTemplate template(TemplateType type, String template); TemplateType getTemplateType(); HttpTemplate withTemplate(String template); String getTemplate(); void withActionType(Type actionType); @Override @JsonIgnore Type getType(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void returnsTemplateType() { assertEquals(JAVASCRIPT, new HttpTemplate(JAVASCRIPT).getTemplateType()); }
### Question: StringBody extends BodyWithContentType<String> { public static StringBody exact(String body) { return new StringBody(body); } StringBody(String value); StringBody(String value, Charset charset); StringBody(String value, MediaType contentType); StringBody(String value, byte[] rawBytes, boolean subString, MediaType contentType); static StringBody exact(String body); static StringBody exact(String body, Charset charset); static StringBody exact(String body, MediaType contentType); static StringBody subString(String body); static StringBody subString(String body, Charset charset); static StringBody subString(String body, MediaType contentType); String getValue(); @JsonIgnore byte[] getRawBytes(); boolean isSubString(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static final MediaType DEFAULT_CONTENT_TYPE; }### Answer: @Test public void shouldAlwaysCreateNewObject() { assertEquals(exact("some_body"), exact("some_body")); assertNotSame(exact("some_body"), exact("some_body")); }
### Question: StringBody extends BodyWithContentType<String> { public String getValue() { return value; } StringBody(String value); StringBody(String value, Charset charset); StringBody(String value, MediaType contentType); StringBody(String value, byte[] rawBytes, boolean subString, MediaType contentType); static StringBody exact(String body); static StringBody exact(String body, Charset charset); static StringBody exact(String body, MediaType contentType); static StringBody subString(String body); static StringBody subString(String body, Charset charset); static StringBody subString(String body, MediaType contentType); String getValue(); @JsonIgnore byte[] getRawBytes(); boolean isSubString(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static final MediaType DEFAULT_CONTENT_TYPE; }### Answer: @Test public void shouldReturnValuesSetInConstructor() { StringBody stringBody = new StringBody("some_body"); assertThat(stringBody.getValue(), is("some_body")); assertThat(stringBody.getType(), is(Body.Type.STRING)); assertThat(stringBody.getCharset(null), nullValue()); assertThat(stringBody.getCharset(StandardCharsets.UTF_8), is(StandardCharsets.UTF_8)); assertThat(stringBody.getContentType(), nullValue()); }
### Question: RegexBody extends Body<String> { public String getValue() { return regex; } RegexBody(String regex); String getValue(); static RegexBody regex(String regex); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void shouldReturnValuesSetInConstructor() { RegexBody regexBody = new RegexBody("some_body"); assertThat(regexBody.getValue(), is("some_body")); assertThat(regexBody.getType(), is(Body.Type.REGEX)); assertThat(regexBody.getContentType(), nullValue()); assertThat(regexBody.getCharset(StandardCharsets.UTF_8), is(StandardCharsets.UTF_8)); }
### Question: XmlSchemaBody extends Body<String> { public String getValue() { return xmlSchema; } XmlSchemaBody(String xmlSchema); static XmlSchemaBody xmlSchema(String xmlSchema); static XmlSchemaBody xmlSchemaFromResource(String xmlSchemaPath); String getValue(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void shouldReturnValuesSetInConstructor() { XmlSchemaBody xmlSchemaBody = new XmlSchemaBody("some_body"); assertThat(xmlSchemaBody.getValue(), is("some_body")); assertThat(xmlSchemaBody.getType(), is(Body.Type.XML_SCHEMA)); }
### Question: ObjectWithJsonToString extends ObjectWithReflectiveEqualsHashCodeToString { @Override public String toString() { try { String valueAsString = ObjectMapperFactory .createObjectMapper(true) .writeValueAsString(this); if (valueAsString.startsWith(ESCAPED_QUOTE) && valueAsString.endsWith(ESCAPED_QUOTE)) { valueAsString = valueAsString.substring(1, valueAsString.length() - 1); } return valueAsString; } catch (Exception e) { return super.toString(); } } @Override String toString(); }### Answer: @Test public void shouldConvertObjectToJSON() { assertThat(new TestObject().toString(), is("{" + NEW_LINE + " \"stringField\" : \"stringField\"," + NEW_LINE + " \"intField\" : 100" + NEW_LINE + "}")); }
### Question: ParameterBody extends Body<Parameters> { public Parameters getValue() { return this.parameters; } ParameterBody(Parameter... parameters); ParameterBody(List<Parameter> parameters); ParameterBody(Parameters parameters); static ParameterBody params(Parameters parameters); static ParameterBody params(Parameter... parameters); static ParameterBody params(List<Parameter> parameters); Parameters getValue(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void shouldReturnValuesSetInConstructor() { ParameterBody parameterBody = new ParameterBody( new Parameter("some", "value") ); assertThat(parameterBody.getValue().getEntries(), containsInAnyOrder(new Parameter("some", "value"))); assertThat(parameterBody.getType(), is(Body.Type.PARAMETERS)); } @Test public void shouldReturnValuesSetInConstructorWithList() { ParameterBody parameterBody = new ParameterBody(Collections.singletonList( new Parameter("some", "value") )); assertThat(parameterBody.getValue().getEntries(), containsInAnyOrder(new Parameter("some", "value"))); assertThat(parameterBody.getType(), is(Body.Type.PARAMETERS)); }
### Question: ForwardChainExpectation { public Expectation[] error(final HttpError httpError) { expectation.thenError(httpError); return mockServerClient.upsert(expectation); } ForwardChainExpectation(MockServerLogger mockServerLogger, MockServerEventBus mockServerEventBus, MockServerClient mockServerClient, Expectation expectation); Expectation[] respond(final HttpResponse httpResponse); Expectation[] respond(final HttpTemplate httpTemplate); Expectation[] respond(final HttpClassCallback httpClassCallback); Expectation[] respond(final ExpectationResponseCallback expectationResponseCallback); Expectation[] respond(final ExpectationResponseCallback expectationResponseCallback, Delay delay); Expectation[] forward(final HttpForward httpForward); Expectation[] forward(final HttpTemplate httpTemplate); Expectation[] forward(final HttpClassCallback httpClassCallback); Expectation[] forward(final ExpectationForwardCallback expectationForwardCallback); Expectation[] forward(final ExpectationForwardCallback expectationForwardCallback, final ExpectationForwardAndResponseCallback expectationForwardResponseCallback); Expectation[] forward(final ExpectationForwardCallback expectationForwardCallback, final Delay delay); Expectation[] forward(final ExpectationForwardCallback expectationForwardCallback, final ExpectationForwardAndResponseCallback expectationForwardResponseCallback, final Delay delay); Expectation[] forward(final HttpOverrideForwardedRequest httpOverrideForwardedRequest); Expectation[] error(final HttpError httpError); }### Answer: @Test public void shouldSetError() { HttpError error = error(); Expectation[] upsertedExpectations = forwardChainExpectation.error(error); assertThat(upsertedExpectations, is(new Expectation[]{mockExpectation})); verify(mockExpectation).thenError(same(error)); verify(mockAbstractClient).upsert(mockExpectation); }
### Question: XPathBody extends Body<String> { public String getValue() { return xpath; } XPathBody(String xpath); String getValue(); static XPathBody xpath(String xpath); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void shouldReturnValuesSetInConstructor() { XPathBody xPathBody = new XPathBody("some_body"); assertThat(xPathBody.getValue(), is("some_body")); assertThat(xPathBody.getType(), is(Body.Type.XPATH)); assertThat(xPathBody.getContentType(), nullValue()); assertThat(xPathBody.getCharset(StandardCharsets.UTF_8), is(StandardCharsets.UTF_8)); }
### Question: NottableSchemaString extends NottableString { public static NottableSchemaString notSchema(String value) { return new NottableSchemaString(value, Boolean.TRUE); } private NottableSchemaString(String schema, Boolean not); private NottableSchemaString(String schema); static NottableSchemaString schemaString(String value, Boolean not); static NottableSchemaString schemaString(String value); static NottableSchemaString notSchema(String value); boolean matches(String json); boolean matchesIgnoreCase(String json); @Override String toString(); }### Answer: @Test public void shouldReturnValuesSetInConstructors() { NottableSchemaString nottableString = notSchema("{ \"type\": \"string\" }"); assertThat(nottableString.isNot(), is(true)); assertThat(nottableString.getValue(), is("{ \"type\": \"string\" }")); }
### Question: NottableSchemaString extends NottableString { public static NottableSchemaString schemaString(String value, Boolean not) { return new NottableSchemaString(value, not); } private NottableSchemaString(String schema, Boolean not); private NottableSchemaString(String schema); static NottableSchemaString schemaString(String value, Boolean not); static NottableSchemaString schemaString(String value); static NottableSchemaString notSchema(String value); boolean matches(String json); boolean matchesIgnoreCase(String json); @Override String toString(); }### Answer: @Test public void shouldReturnValuesSetInConstructorsWithDefaultNotSetting() { NottableSchemaString nottableString = schemaString("{ \"type\": \"string\" }"); assertThat(nottableString.isNot(), is(false)); assertThat(nottableString.getValue(), is("{ \"type\": \"string\" }")); } @Test public void shouldReturnValuesSetInConstructorsWithDefaultNottedString() { NottableSchemaString nottableString = schemaString("!{ \"type\": \"string\" }"); assertThat(nottableString.isNot(), is(true)); assertThat(nottableString.getValue(), is("{ \"type\": \"string\" }")); } @Test public void shouldReturnValuesSetInConstructorsWithNullNotParameter() { NottableSchemaString nottableString = schemaString("{ \"type\": \"string\" }", null); assertThat(nottableString.isNot(), is(false)); assertThat(nottableString.getValue(), is("{ \"type\": \"string\" }")); }
### Question: Header extends KeyToMultiValue { public Header(String name, String... value) { super(name, value); } Header(String name, String... value); Header(NottableString name, NottableString... value); Header(NottableString name, String... value); Header(String name, Collection<String> value); Header(NottableString name, Collection<NottableString> value); static Header header(String name, int value); static Header header(String name, String... value); static Header header(NottableString name, NottableString... value); static Header header(String name, Collection<String> value); static Header header(NottableString name, Collection<NottableString> value); static Header schemaHeader(String name, String... values); static Header optionalHeader(String name, String... values); }### Answer: @Test public void shouldReturnValueSetInStaticConstructors() { Header firstHeader = header("first", "first_one", "first_two"); Header secondHeader = header("second", Arrays.asList("second_one", "second_two")); assertThat(firstHeader.getValues(), containsInAnyOrder(string("first_one"), string("first_two"))); assertThat(secondHeader.getValues(), containsInAnyOrder(string("second_one"), string("second_two"))); }
### Question: HttpClassCallback extends Action<HttpClassCallback> { public static HttpClassCallback callback() { return new HttpClassCallback(); } static HttpClassCallback callback(); static HttpClassCallback callback(String callbackClass); static HttpClassCallback callback(Class<? extends ExpectationCallback<HttpRequest>> callbackClass); String getCallbackClass(); HttpClassCallback withCallbackClass(String callbackClass); @SuppressWarnings("rawtypes") HttpClassCallback withCallbackClass(Class<? extends ExpectationCallback<? extends HttpMessage>> callbackClass); HttpClassCallback withActionType(Type actionType); @Override @JsonIgnore Type getType(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test @SuppressWarnings("AccessStaticViaInstance") public void shouldAlwaysCreateNewObject() { assertEquals(callback(), callback()); assertNotSame(callback(), callback()); }
### Question: ObjectWithReflectiveEqualsHashCodeToString { @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this, fieldsExcludedFromEqualsAndHashCode()); } @Override String toString(); @Override @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") boolean equals(Object other); @Override int hashCode(); }### Answer: @Test public void hashCodeIdentical() { assertEquals(new Header("name", "value").hashCode(), new Header("name", "value").hashCode()); } @Test public void hashCodeDifferent() { assertNotEquals(new Header("name", "value").hashCode(), new Header("foo", "bar").hashCode()); }
### Question: ObjectWithReflectiveEqualsHashCodeToString { @Override @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") public boolean equals(Object other) { if (this == other) { return true; } if (other == null) { return false; } return new EqualsBuilder() .setExcludeFields(fieldsExcludedFromEqualsAndHashCode()) .setReflectUpToClass(ObjectWithReflectiveEqualsHashCodeToString.class) .setTestTransients(false) .setTestRecursive(false) .reflectionAppend(this, other) .isEquals(); } @Override String toString(); @Override @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") boolean equals(Object other); @Override int hashCode(); }### Answer: @Test public void equalsIdentical() { assertTrue(new Header("name", "value").equals(new Header("name", "value"))); } @Test public void notEqualsDifferent() { assertFalse(new Header("name", "value").equals(new Header("foo", "bar"))); }
### Question: ObjectWithReflectiveEqualsHashCodeToString { @Override public String toString() { return new ReflectionToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE, null, ObjectWithReflectiveEqualsHashCodeToString.class, false, false).setExcludeFieldNames(fieldsExcludedFromEqualsAndHashCode()).toString(); } @Override String toString(); @Override @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") boolean equals(Object other); @Override int hashCode(); }### Answer: @Test public void toStringReturnStrings() { assertThat(new Header("name", "value").toString(), instanceOf(String.class)); }
### Question: JsonSchemaBody extends Body<String> { public String getValue() { return jsonSchema; } JsonSchemaBody(String jsonSchema); static JsonSchemaBody jsonSchema(String jsonSchema); static JsonSchemaBody jsonSchemaFromResource(String jsonSchemaPath); Map<String, ParameterStyle> getParameterStyles(); JsonSchemaBody withParameterStyles(Map<String, ParameterStyle> parameterStyles); String getValue(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void shouldReturnValuesSetInConstructor() { JsonSchemaBody jsonSchemaBody = new JsonSchemaBody("some_body"); assertThat(jsonSchemaBody.getValue(), is("some_body")); assertThat(jsonSchemaBody.getType(), is(Body.Type.JSON_SCHEMA)); }
### Question: Headers extends KeysToMultiValues<Header, Headers> { @Override public Header build(NottableString name, Collection<NottableString> values) { return new Header(name, values); } Headers(List<Header> headers); Headers(Header... headers); Headers(Multimap<NottableString, NottableString> headers); @Override Header build(NottableString name, Collection<NottableString> values); Headers withKeyMatchStyle(KeyMatchStyle keyMatchStyle); @SuppressWarnings("MethodDoesntCallSuperMethod") Headers clone(); }### Answer: @Test public void shouldBuildHeader() { Headers headers = new Headers(); Header header = headers.build(string("name"), Arrays.asList( string("value_one"), string("value_two") )); assertThat(header, is(new Header(string("name"), string("value_one"), string("value_two")))); }
### Question: CircularConcurrentLinkedDeque extends ConcurrentLinkedDeque<E> { @Override public boolean add(E element) { if (maxSize > 0) { evictExcessElements(); return super.add(element); } else { return false; } } CircularConcurrentLinkedDeque(int maxSize, Consumer<E> onEvictCallback); void setMaxSize(int maxSize); @Override boolean add(E element); @Override boolean addAll(Collection<? extends E> collection); @Override boolean offer(E element); void clear(); @Deprecated boolean remove(Object o); boolean removeItem(E e); }### Answer: @Test public void shouldNotAllowAddingMoreThenMaximumNumberOfEntriesWhenUsingAdd() { CircularConcurrentLinkedDeque<String> concurrentLinkedQueue = new CircularConcurrentLinkedDeque<String>(3, null); concurrentLinkedQueue.add("1"); concurrentLinkedQueue.add("2"); concurrentLinkedQueue.add("3"); concurrentLinkedQueue.add("4"); assertEquals(3, concurrentLinkedQueue.size()); assertThat(concurrentLinkedQueue, not(contains("1"))); assertThat(concurrentLinkedQueue, contains("2", "3", "4")); }
### Question: CircularConcurrentLinkedDeque extends ConcurrentLinkedDeque<E> { @Override public boolean addAll(Collection<? extends E> collection) { if (maxSize > 0) { boolean result = false; for (E element : collection) { if (add(element)) { result = true; } } return result; } else { return false; } } CircularConcurrentLinkedDeque(int maxSize, Consumer<E> onEvictCallback); void setMaxSize(int maxSize); @Override boolean add(E element); @Override boolean addAll(Collection<? extends E> collection); @Override boolean offer(E element); void clear(); @Deprecated boolean remove(Object o); boolean removeItem(E e); }### Answer: @Test public void shouldNotAllowAddingMoreThenMaximumNumberOfEntriesWhenUsingAddAll() { CircularConcurrentLinkedDeque<String> concurrentLinkedQueue = new CircularConcurrentLinkedDeque<String>(3, null); concurrentLinkedQueue.addAll(Arrays.asList("1", "2", "3", "4")); assertEquals(3, concurrentLinkedQueue.size()); assertThat(concurrentLinkedQueue, not(contains("1"))); assertThat(concurrentLinkedQueue, contains("2", "3", "4")); }
### Question: CircularHashMap extends LinkedHashMap<K, V> { public K findKey(V value) { for (Map.Entry<K, V> entry : entrySet()) { V entryValue = entry.getValue(); if (entryValue == value || (value != null && value.equals(entryValue))) { return entry.getKey(); } } return null; } CircularHashMap(int maxSize); K findKey(V value); }### Answer: @Test public void shouldFindKeyByObject() { CircularHashMap<String, String> circularHashMap = new CircularHashMap<>(5); circularHashMap.put("0", "a"); circularHashMap.put("1", "b"); circularHashMap.put("2", "c"); circularHashMap.put("3", "d"); circularHashMap.put("4", "d"); circularHashMap.put("5", "e"); assertThat(circularHashMap.findKey("b"), is("1")); assertThat(circularHashMap.findKey("c"), is("2")); assertThat(circularHashMap.findKey("x"), nullValue()); assertThat(circularHashMap.findKey("a"), nullValue()); assertThat(circularHashMap.findKey("d"), is("3")); }
### Question: PortFactory { public static int findFreePort() { int[] freePorts = findFreePorts(1); return freePorts[random.nextInt(freePorts.length)]; } static int findFreePort(); }### Answer: @Test public void shouldFindFreePort() throws IOException { int freePort = PortFactory.findFreePort(); assertTrue(new ServerSocket(freePort).isBound()); }
### Question: NottableStringToJavaSerializer { public static String serialize(NottableString nottableString, boolean alwaysNottableString) { if (nottableString.isOptional()) { return "optional(\"" + StringEscapeUtils.escapeJava(nottableString.getValue()) + "\")"; } else if (nottableString.isNot()) { return "not(\"" + StringEscapeUtils.escapeJava(nottableString.getValue()) + "\")"; } else if (alwaysNottableString) { return "string(\"" + StringEscapeUtils.escapeJava(nottableString.getValue()) + "\")"; } else { return "\"" + StringEscapeUtils.escapeJava(nottableString.getValue()) + "\""; } } static String serialize(NottableString nottableString, boolean alwaysNottableString); }### Answer: @Test public void shouldSerializeNottedString() { assertEquals("not(\"some_value\")", NottableStringToJavaSerializer.serialize(string("some_value", true), false) ); } @Test public void shouldSerializeString() { assertEquals("\"some_value\"", NottableStringToJavaSerializer.serialize(string("some_value", false), false) ); }
### Question: TimeToLiveToJavaSerializer implements ToJavaSerializer<TimeToLive> { @Override public String serialize(int numberOfSpacesToIndent, TimeToLive timeToLive) { StringBuffer output = new StringBuffer(); if (timeToLive != null) { appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output); if (timeToLive.isUnlimited()) { output.append("TimeToLive.unlimited()"); } else { output.append("TimeToLive.exactly(TimeUnit.").append(timeToLive.getTimeUnit().name()).append(", ").append(timeToLive.getTimeToLive()).append("L)"); } } return output.toString(); } @Override String serialize(int numberOfSpacesToIndent, TimeToLive timeToLive); }### Answer: @Test public void shouldSerializeUnlimitedTimeToLiveAsJava() { assertEquals(NEW_LINE + " TimeToLive.unlimited()", new TimeToLiveToJavaSerializer().serialize(1, TimeToLive.unlimited() ) ); } @Test public void shouldSerializeExactlyTimeToLiveAsJava() { assertEquals(NEW_LINE + " TimeToLive.exactly(TimeUnit.SECONDS, 100L)", new TimeToLiveToJavaSerializer().serialize(1, TimeToLive.exactly(TimeUnit.SECONDS, 100L) ) ); }
### Question: TimesToJavaSerializer implements ToJavaSerializer<Times> { @Override public String serialize(int numberOfSpacesToIndent, Times times) { StringBuffer output = new StringBuffer(); if (times != null) { appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output); if (times.isUnlimited()) { output.append("Times.unlimited()"); } else if (times.getRemainingTimes() == 1) { output.append("Times.once()"); } else { output.append("Times.exactly(").append(times.getRemainingTimes()).append(")"); } } return output.toString(); } @Override String serialize(int numberOfSpacesToIndent, Times times); }### Answer: @Test public void shouldSerializeUnlimitedTimesAsJava() { assertEquals(NEW_LINE + " Times.unlimited()", new TimesToJavaSerializer().serialize(1, Times.unlimited() ) ); } @Test public void shouldSerializeOnceTimesAsJava() { assertEquals(NEW_LINE + " Times.once()", new TimesToJavaSerializer().serialize(1, Times.once() ) ); } @Test public void shouldSerializeExactlyTimesAsJava() { assertEquals(NEW_LINE + " Times.exactly(2)", new TimesToJavaSerializer().serialize(1, Times.exactly(2) ) ); }
### Question: ParameterToJavaSerializer implements MultiValueToJavaSerializer<Parameter> { @Override public String serialize(int numberOfSpacesToIndent, Parameter parameter) { StringBuilder output = new StringBuilder(); output.append(NEW_LINE).append(Strings.padStart("", numberOfSpacesToIndent * INDENT_SIZE, ' ')); String serializedKey = NottableStringToJavaSerializer.serialize(parameter.getName(), false); output.append("new Parameter(").append(serializedKey); for (NottableString value : parameter.getValues()) { output.append(", ").append(NottableStringToJavaSerializer.serialize(value, serializedKey.endsWith(")"))); } output.append(")"); return output.toString(); } @Override String serialize(int numberOfSpacesToIndent, Parameter parameter); @Override String serializeAsJava(int numberOfSpacesToIndent, List<Parameter> parameters); @Override String serializeAsJava(int numberOfSpacesToIndent, Parameter... object); }### Answer: @Test public void shouldSerializeParameter() { assertEquals(NEW_LINE + " new Parameter(\"requestParameterNameOne\", \"requestParameterValueOneOne\", \"requestParameterValueOneTwo\")", new ParameterToJavaSerializer().serialize(1, new Parameter("requestParameterNameOne", "requestParameterValueOneOne", "requestParameterValueOneTwo")) ); }
### Question: HttpClassCallbackToJavaSerializer implements ToJavaSerializer<HttpClassCallback> { @Override public String serialize(int numberOfSpacesToIndent, HttpClassCallback httpClassCallback) { StringBuffer output = new StringBuffer(); if (httpClassCallback != null) { appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append("callback()"); if (httpClassCallback.getCallbackClass() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withCallbackClass(\"").append(httpClassCallback.getCallbackClass()).append("\")"); } if (httpClassCallback.getDelay() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withDelay(").append(new DelayToJavaSerializer().serialize(0, httpClassCallback.getDelay())).append(")"); } } return output.toString(); } @Override String serialize(int numberOfSpacesToIndent, HttpClassCallback httpClassCallback); }### Answer: @Test public void shouldSerializeFullObjectWithCallbackAsJava() { assertEquals(NEW_LINE + " callback()" + NEW_LINE + " .withCallbackClass(\"some_class\")" + NEW_LINE + " .withDelay(new Delay(TimeUnit.MILLISECONDS, 100))", new HttpClassCallbackToJavaSerializer().serialize(1, new HttpClassCallback() .withCallbackClass("some_class") .withDelay(TimeUnit.MILLISECONDS, 100) ) ); }
### Question: SocketAddressToJavaSerializer implements ToJavaSerializer<SocketAddress> { @Override public String serialize(int numberOfSpacesToIndent, SocketAddress socketAddress) { StringBuffer output = new StringBuffer(); if (socketAddress != null) { appendNewLineAndIndent(numberOfSpacesToIndent * INDENT_SIZE, output).append("new SocketAddress()"); if (socketAddress.getHost() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withHost(\"").append(socketAddress.getHost()).append("\")"); } if (socketAddress.getPort() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withPort(").append(socketAddress.getPort()).append(")"); } if (socketAddress.getScheme() != null) { appendNewLineAndIndent((numberOfSpacesToIndent + 1) * INDENT_SIZE, output).append(".withScheme(SocketAddress.Scheme.").append(socketAddress.getScheme()).append(")"); } } return output.toString(); } @Override String serialize(int numberOfSpacesToIndent, SocketAddress socketAddress); }### Answer: @Test public void shouldSerializeFullObjectWithForwardAsJava() { assertEquals(NEW_LINE + " new SocketAddress()" + NEW_LINE + " .withHost(\"some_host\")" + NEW_LINE + " .withPort(9090)" + NEW_LINE + " .withScheme(SocketAddress.Scheme.HTTPS)", new SocketAddressToJavaSerializer().serialize(1, SocketAddress .socketAddress() .withHost("some_host") .withPort(9090) .withScheme(SocketAddress.Scheme.HTTPS) ) ); }
### Question: CookieToJavaSerializer implements MultiValueToJavaSerializer<Cookie> { @Override public String serialize(int numberOfSpacesToIndent, Cookie cookie) { return NEW_LINE + Strings.padStart("", numberOfSpacesToIndent * INDENT_SIZE, ' ') + "new Cookie(" + NottableStringToJavaSerializer.serialize(cookie.getName(), false) + ", " + NottableStringToJavaSerializer.serialize(cookie.getValue(), false) + ")"; } @Override String serialize(int numberOfSpacesToIndent, Cookie cookie); @Override String serializeAsJava(int numberOfSpacesToIndent, List<Cookie> cookies); @Override String serializeAsJava(int numberOfSpacesToIndent, Cookie... object); }### Answer: @Test public void shouldSerializeCookie() { assertEquals(NEW_LINE + " new Cookie(\"requestCookieNameOne\", \"requestCookieValueOne\")", new CookieToJavaSerializer().serialize(1, new Cookie("requestCookieNameOne", "requestCookieValueOne")) ); }
### Question: DelayToJavaSerializer implements ToJavaSerializer<Delay> { @Override public String serialize(int numberOfSpacesToIndent, Delay delay) { StringBuilder output = new StringBuilder(); if (delay != null) { output.append("new Delay(TimeUnit.").append(delay.getTimeUnit().name()).append(", ").append(delay.getValue()).append(")"); } return output.toString(); } @Override String serialize(int numberOfSpacesToIndent, Delay delay); }### Answer: @Test public void shouldSerializeFullObjectWithForwardAsJava() { assertEquals("new Delay(TimeUnit.SECONDS, 10)", new DelayToJavaSerializer().serialize(1, new Delay(TimeUnit.SECONDS, 10) ) ); }
### Question: HeaderToJavaSerializer implements MultiValueToJavaSerializer<Header> { @Override public String serialize(int numberOfSpacesToIndent, Header header) { StringBuilder output = new StringBuilder(); output.append(NEW_LINE).append(Strings.padStart("", numberOfSpacesToIndent * INDENT_SIZE, ' ')); String serializedKey = NottableStringToJavaSerializer.serialize(header.getName(), false); output.append("new Header(").append(serializedKey); for (NottableString value : header.getValues()) { output.append(", ").append(NottableStringToJavaSerializer.serialize(value, serializedKey.endsWith(")"))); } output.append(")"); return output.toString(); } @Override String serialize(int numberOfSpacesToIndent, Header header); @Override String serializeAsJava(int numberOfSpacesToIndent, List<Header> headers); @Override String serializeAsJava(int numberOfSpacesToIndent, Header... object); }### Answer: @Test public void shouldSerializeHeader() { assertEquals(NEW_LINE + " new Header(\"requestHeaderNameOne\", \"requestHeaderValueOneOne\", \"requestHeaderValueOneTwo\")", new HeaderToJavaSerializer().serialize(1, new Header("requestHeaderNameOne", "requestHeaderValueOneOne", "requestHeaderValueOneTwo")) ); }
### Question: XmlSchemaBodyDTO extends BodyDTO { public String getXml() { return xmlSchema; } XmlSchemaBodyDTO(XmlSchemaBody xmlSchemaBody); XmlSchemaBodyDTO(XmlSchemaBody xmlSchemaBody, Boolean not); String getXml(); XmlSchemaBody buildObject(); }### Answer: @Test public void shouldReturnValuesSetInConstructor() { XmlSchemaBodyDTO xmlSchemaBodyDTO = new XmlSchemaBodyDTO(new XmlSchemaBody("some_body")); assertThat(xmlSchemaBodyDTO.getXml(), is("some_body")); assertThat(xmlSchemaBodyDTO.getType(), is(Body.Type.XML_SCHEMA)); }