src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
PRNG extends Random { public int nextInt(final int origin, final int bound) { return nextInt(origin, bound, this); } protected PRNG(final long seed); protected PRNG(); int nextInt(final int origin, final int bound); long nextLong(final long origin, final long bound); long nextLong(final long n); float nextFloat(final float origin, final float bound); double nextDouble(final double origin, final double bound); static int nextInt(
final int origin, final int bound,
final Random random
); static long nextLong(
final long origin, final long bound,
final Random random
); static long nextLong(final long n, final Random random); static float nextFloat(
final float origin, final float bound,
final Random random
); static double nextDouble(
final double origin, final double bound,
final Random random
); static byte[] seedBytes(final int length); static byte[] seedBytes(final byte[] seed); static byte[] seedBytes(final long seed, final byte[] seedBytes); static byte[] seedBytes(final long seed, final int length); static long seed(); static long seed(final long base); } | @Test public void nextIntMinMax() { final int min = 10; final int max = Integer.MAX_VALUE; for (int i = 0; i < 1000; ++i) { final int value = prng.nextInt(min, max - 1); Assert.assertTrue(value < max - 1); Assert.assertTrue(value >= min); } }
@Test public void nextIntMinMaxCompatibility() { final Random random1 = new Random(123); final Random random2 = new Random(123); final int origin = 100; final int bound = 100000; random1.ints(origin, bound).limit(1000).forEach(i -> { Assert.assertEquals(i, PRNG.nextInt(origin, bound, random2)); }); }
@Test(expectedExceptions = IllegalArgumentException.class) public void nextIntIllegalArgumentException() { prng.nextInt(1000, 10); } |
Indexer { void saveRDDToEs(JavaRDD javaRDD, String docName) { JavaEsSpark.saveToEs(javaRDD, docName); } } | @Test @Ignore public void saveToEs() { Map<String, ?> numbers = ImmutableMap.of("one", 11, "two", 22); Map<String, ?> airports = ImmutableMap.of("OTP", "Otopeni1", "SFO", "San Fran1"); JavaRDD<Map<String, ?>> javaRDD = jsc.parallelize(ImmutableList.of(numbers, airports)); indexer.saveRDDToEs(javaRDD, "spark/docs"); } |
SoundcloudParsingHelper { static boolean checkIfHardcodedClientIdIsValid() { try { SoundcloudStreamExtractor e = (SoundcloudStreamExtractor) SoundCloud .getStreamExtractor("https: e.fetchPage(); return e.getAudioStreams().size() >= 1; } catch (Exception ignored) { return false; } } private SoundcloudParsingHelper(); synchronized static String clientId(); static Calendar parseDateFrom(String textualUploadDate); static JsonObject resolveFor(Downloader downloader, String url); static String resolveUrlWithEmbedPlayer(String apiUrl); static String resolveIdWithEmbedPlayer(String url); static String getUsersFromApiMinItems(int minItems, ChannelInfoItemsCollector collector, String apiUrl); static String getUsersFromApi(ChannelInfoItemsCollector collector, String apiUrl); static String getStreamsFromApiMinItems(int minItems, StreamInfoItemsCollector collector, String apiUrl); static String getStreamsFromApi(StreamInfoItemsCollector collector, String apiUrl, boolean charts); static String getStreamsFromApi(StreamInfoItemsCollector collector, String apiUrl); @Nonnull static String getUploaderUrl(JsonObject object); @Nonnull static String getAvatarUrl(JsonObject object); static String getUploaderName(JsonObject object); } | @Test public void assertThatHardcodedClientIdIsValid() throws Exception { assertTrue("Hardcoded client id is not valid anymore", SoundcloudParsingHelper.checkIfHardcodedClientIdIsValid()); } |
Utils { public static long mixedNumberWordToLong(String numberWord) throws NumberFormatException, ParsingException { String multiplier = ""; try { multiplier = Parser.matchGroup("[\\d]+([\\.,][\\d]+)?([KMBkmb])+", numberWord, 2); } catch (ParsingException ignored) { } double count = Double.parseDouble(Parser.matchGroup1("([\\d]+([\\.,][\\d]+)?)", numberWord) .replace(",", ".")); switch (multiplier.toUpperCase()) { case "K": return (long) (count * 1e3); case "M": return (long) (count * 1e6); case "B": return (long) (count * 1e9); default: return (long) (count); } } private Utils(); static String removeNonDigitCharacters(String toRemove); static long mixedNumberWordToLong(String numberWord); static void checkUrl(String pattern, String url); static void printErrors(List<Throwable> errors); static String replaceHttpWithHttps(final String url); static String getQueryValue(URL url, String parameterName); static URL stringToURL(String url); static boolean isHTTP(URL url); static String removeUTF8BOM(String s); static String getBaseUrl(String url); static boolean isNullOrEmpty(final String str); static boolean isNullOrEmpty(final Collection<?> collection); static boolean isNullOrEmpty(final Map map); static boolean isWhitespace(final int c); static boolean isBlank(final String string); static String join(final CharSequence delimiter, final Iterable<? extends CharSequence> elements); static final String HTTP; static final String HTTPS; } | @Test public void testMixedNumberWordToLong() throws ParsingException { assertEquals(10, Utils.mixedNumberWordToLong("10")); assertEquals(10.5e3, Utils.mixedNumberWordToLong("10.5K"), 0.0); assertEquals(10.5e6, Utils.mixedNumberWordToLong("10.5M"), 0.0); assertEquals(10.5e6, Utils.mixedNumberWordToLong("10,5M"), 0.0); assertEquals(1.5e9, Utils.mixedNumberWordToLong("1,5B"), 0.0); } |
Utils { public static String join(final CharSequence delimiter, final Iterable<? extends CharSequence> elements) { final StringBuilder stringBuilder = new StringBuilder(); final Iterator<? extends CharSequence> iterator = elements.iterator(); while (iterator.hasNext()) { stringBuilder.append(iterator.next()); if (iterator.hasNext()) { stringBuilder.append(delimiter); } } return stringBuilder.toString(); } private Utils(); static String removeNonDigitCharacters(String toRemove); static long mixedNumberWordToLong(String numberWord); static void checkUrl(String pattern, String url); static void printErrors(List<Throwable> errors); static String replaceHttpWithHttps(final String url); static String getQueryValue(URL url, String parameterName); static URL stringToURL(String url); static boolean isHTTP(URL url); static String removeUTF8BOM(String s); static String getBaseUrl(String url); static boolean isNullOrEmpty(final String str); static boolean isNullOrEmpty(final Collection<?> collection); static boolean isNullOrEmpty(final Map map); static boolean isWhitespace(final int c); static boolean isBlank(final String string); static String join(final CharSequence delimiter, final Iterable<? extends CharSequence> elements); static final String HTTP; static final String HTTPS; } | @Test public void testJoin() { assertEquals("some,random,stuff", Utils.join(",", Arrays.asList("some", "random", "stuff"))); } |
NewPipe { public static List<StreamingService> getServices() { return ServiceList.all(); } private NewPipe(); static void init(Downloader d); static void init(Downloader d, Localization l); static void init(Downloader d, Localization l, ContentCountry c); static Downloader getDownloader(); static List<StreamingService> getServices(); static StreamingService getService(int serviceId); static StreamingService getService(String serviceName); static StreamingService getServiceByUrl(String url); static int getIdOfService(String serviceName); static String getNameOfService(int id); static void setupLocalization(Localization preferredLocalization); static void setupLocalization(Localization preferredLocalization, @Nullable ContentCountry preferredContentCountry); @Nonnull static Localization getPreferredLocalization(); static void setPreferredLocalization(Localization preferredLocalization); @Nonnull static ContentCountry getPreferredContentCountry(); static void setPreferredContentCountry(ContentCountry preferredContentCountry); } | @Test public void getAllServicesTest() throws Exception { assertEquals(NewPipe.getServices().size(), ServiceList.all().size()); }
@Test public void testAllServicesHaveDifferentId() throws Exception { HashSet<Integer> servicesId = new HashSet<>(); for (StreamingService streamingService : NewPipe.getServices()) { String errorMsg = "There are services with the same id = " + streamingService.getServiceId() + " (current service > " + streamingService.getServiceInfo().getName() + ")"; assertTrue(errorMsg, servicesId.add(streamingService.getServiceId())); } } |
NewPipe { public static StreamingService getService(int serviceId) throws ExtractionException { for (StreamingService service : ServiceList.all()) { if (service.getServiceId() == serviceId) { return service; } } throw new ExtractionException("There's no service with the id = \"" + serviceId + "\""); } private NewPipe(); static void init(Downloader d); static void init(Downloader d, Localization l); static void init(Downloader d, Localization l, ContentCountry c); static Downloader getDownloader(); static List<StreamingService> getServices(); static StreamingService getService(int serviceId); static StreamingService getService(String serviceName); static StreamingService getServiceByUrl(String url); static int getIdOfService(String serviceName); static String getNameOfService(int id); static void setupLocalization(Localization preferredLocalization); static void setupLocalization(Localization preferredLocalization, @Nullable ContentCountry preferredContentCountry); @Nonnull static Localization getPreferredLocalization(); static void setPreferredLocalization(Localization preferredLocalization); @Nonnull static ContentCountry getPreferredContentCountry(); static void setPreferredContentCountry(ContentCountry preferredContentCountry); } | @Test public void getServiceWithId() throws Exception { assertEquals(NewPipe.getService(YouTube.getServiceId()), YouTube); }
@Test public void getServiceWithName() throws Exception { assertEquals(NewPipe.getService(YouTube.getServiceInfo().getName()), YouTube); } |
NewPipe { public static StreamingService getServiceByUrl(String url) throws ExtractionException { for (StreamingService service : ServiceList.all()) { if (service.getLinkTypeByUrl(url) != StreamingService.LinkType.NONE) { return service; } } throw new ExtractionException("No service can handle the url = \"" + url + "\""); } private NewPipe(); static void init(Downloader d); static void init(Downloader d, Localization l); static void init(Downloader d, Localization l, ContentCountry c); static Downloader getDownloader(); static List<StreamingService> getServices(); static StreamingService getService(int serviceId); static StreamingService getService(String serviceName); static StreamingService getServiceByUrl(String url); static int getIdOfService(String serviceName); static String getNameOfService(int id); static void setupLocalization(Localization preferredLocalization); static void setupLocalization(Localization preferredLocalization, @Nullable ContentCountry preferredContentCountry); @Nonnull static Localization getPreferredLocalization(); static void setPreferredLocalization(Localization preferredLocalization); @Nonnull static ContentCountry getPreferredContentCountry(); static void setPreferredContentCountry(ContentCountry preferredContentCountry); } | @Test public void getServiceWithUrl() throws Exception { assertEquals(getServiceByUrl("https: assertEquals(getServiceByUrl("https: assertEquals(getServiceByUrl("https: assertNotEquals(getServiceByUrl("https: } |
NewPipe { public static int getIdOfService(String serviceName) { try { return getService(serviceName).getServiceId(); } catch (ExtractionException ignored) { return -1; } } private NewPipe(); static void init(Downloader d); static void init(Downloader d, Localization l); static void init(Downloader d, Localization l, ContentCountry c); static Downloader getDownloader(); static List<StreamingService> getServices(); static StreamingService getService(int serviceId); static StreamingService getService(String serviceName); static StreamingService getServiceByUrl(String url); static int getIdOfService(String serviceName); static String getNameOfService(int id); static void setupLocalization(Localization preferredLocalization); static void setupLocalization(Localization preferredLocalization, @Nullable ContentCountry preferredContentCountry); @Nonnull static Localization getPreferredLocalization(); static void setPreferredLocalization(Localization preferredLocalization); @Nonnull static ContentCountry getPreferredContentCountry(); static void setPreferredContentCountry(ContentCountry preferredContentCountry); } | @Test public void getIdWithServiceName() throws Exception { assertEquals(NewPipe.getIdOfService(YouTube.getServiceInfo().getName()), YouTube.getServiceId()); } |
NewPipe { public static String getNameOfService(int id) { try { return getService(id).getServiceInfo().getName(); } catch (Exception e) { System.err.println("Service id not known"); e.printStackTrace(); return "<unknown>"; } } private NewPipe(); static void init(Downloader d); static void init(Downloader d, Localization l); static void init(Downloader d, Localization l, ContentCountry c); static Downloader getDownloader(); static List<StreamingService> getServices(); static StreamingService getService(int serviceId); static StreamingService getService(String serviceName); static StreamingService getServiceByUrl(String url); static int getIdOfService(String serviceName); static String getNameOfService(int id); static void setupLocalization(Localization preferredLocalization); static void setupLocalization(Localization preferredLocalization, @Nullable ContentCountry preferredContentCountry); @Nonnull static Localization getPreferredLocalization(); static void setPreferredLocalization(Localization preferredLocalization); @Nonnull static ContentCountry getPreferredContentCountry(); static void setPreferredContentCountry(ContentCountry preferredContentCountry); } | @Test public void getServiceNameWithId() throws Exception { assertEquals(NewPipe.getNameOfService(YouTube.getServiceId()), YouTube.getServiceInfo().getName()); } |
SoundcloudParsingHelper { public static String resolveUrlWithEmbedPlayer(String apiUrl) throws IOException, ReCaptchaException, ParsingException { String response = NewPipe.getDownloader().get("https: + URLEncoder.encode(apiUrl, "UTF-8"), SoundCloud.getLocalization()).responseBody(); return Jsoup.parse(response).select("link[rel=\"canonical\"]").first().attr("abs:href"); } private SoundcloudParsingHelper(); synchronized static String clientId(); static Calendar parseDateFrom(String textualUploadDate); static JsonObject resolveFor(Downloader downloader, String url); static String resolveUrlWithEmbedPlayer(String apiUrl); static String resolveIdWithEmbedPlayer(String url); static String getUsersFromApiMinItems(int minItems, ChannelInfoItemsCollector collector, String apiUrl); static String getUsersFromApi(ChannelInfoItemsCollector collector, String apiUrl); static String getStreamsFromApiMinItems(int minItems, StreamInfoItemsCollector collector, String apiUrl); static String getStreamsFromApi(StreamInfoItemsCollector collector, String apiUrl, boolean charts); static String getStreamsFromApi(StreamInfoItemsCollector collector, String apiUrl); @Nonnull static String getUploaderUrl(JsonObject object); @Nonnull static String getAvatarUrl(JsonObject object); static String getUploaderName(JsonObject object); } | @Test public void resolveUrlWithEmbedPlayerTest() throws Exception { Assert.assertEquals("https: Assert.assertEquals("https: Assert.assertEquals("https: Assert.assertEquals("https: } |
SoundcloudParsingHelper { public static String resolveIdWithEmbedPlayer(String url) throws IOException, ReCaptchaException, ParsingException { String response = NewPipe.getDownloader().get("https: + URLEncoder.encode(url, "UTF-8"), SoundCloud.getLocalization()).responseBody(); if (url.contains("sets") && !url.endsWith("sets") && !url.endsWith("sets/")) return Parser.matchGroup1("\"uri\":\\s*\"https:\\/\\/api\\.soundcloud\\.com\\/playlists\\/((\\d)*?)\"", response); return Parser.matchGroup1(",\"id\":(([^}\\n])*?),", response); } private SoundcloudParsingHelper(); synchronized static String clientId(); static Calendar parseDateFrom(String textualUploadDate); static JsonObject resolveFor(Downloader downloader, String url); static String resolveUrlWithEmbedPlayer(String apiUrl); static String resolveIdWithEmbedPlayer(String url); static String getUsersFromApiMinItems(int minItems, ChannelInfoItemsCollector collector, String apiUrl); static String getUsersFromApi(ChannelInfoItemsCollector collector, String apiUrl); static String getStreamsFromApiMinItems(int minItems, StreamInfoItemsCollector collector, String apiUrl); static String getStreamsFromApi(StreamInfoItemsCollector collector, String apiUrl, boolean charts); static String getStreamsFromApi(StreamInfoItemsCollector collector, String apiUrl); @Nonnull static String getUploaderUrl(JsonObject object); @Nonnull static String getAvatarUrl(JsonObject object); static String getUploaderName(JsonObject object); } | @Test public void resolveIdWithEmbedPlayerTest() throws Exception { Assert.assertEquals("26057743", SoundcloudParsingHelper.resolveIdWithEmbedPlayer("https: Assert.assertEquals("16069159", SoundcloudParsingHelper.resolveIdWithEmbedPlayer("https: } |
YoutubeParsingHelper { public static boolean isHardcodedClientVersionValid() throws IOException, ExtractionException { final String url = "https: Map<String, List<String>> headers = new HashMap<>(); headers.put("X-YouTube-Client-Name", Collections.singletonList("1")); headers.put("X-YouTube-Client-Version", Collections.singletonList(HARDCODED_CLIENT_VERSION)); final String response = getDownloader().get(url, headers).responseBody(); return response.length() > 50; } private YoutubeParsingHelper(); static Document parseAndCheckPage(final String url, final Response response); static boolean isYoutubeURL(URL url); static boolean isYoutubeServiceURL(URL url); static boolean isHooktubeURL(URL url); static boolean isInvidioURL(URL url); static int parseDurationString(final String input); static String getFeedUrlFrom(final String channelIdOrUser); static Calendar parseDateFrom(String textualUploadDate); static JsonObject getInitialData(String html); static boolean isHardcodedClientVersionValid(); static String getClientVersion(); static String getKey(); static boolean areHardcodedYoutubeMusicKeysValid(); static String[] getYoutubeMusicKeys(); static String getUrlFromNavigationEndpoint(JsonObject navigationEndpoint); static String getTextFromObject(JsonObject textObject, boolean html); static String getTextFromObject(JsonObject textObject); static String fixThumbnailUrl(String thumbnailUrl); static String getValidJsonResponseBody(final Response response); static JsonArray getJsonResponse(final String url, final Localization localization); static void defaultAlertsCheck(final JsonObject initialData); final static String BASE_YOUTUBE_INTENT_URL; } | @Test public void testIsHardcodedClientVersionValid() throws IOException, ExtractionException { assertTrue("Hardcoded client version is not valid anymore", YoutubeParsingHelper.isHardcodedClientVersionValid()); } |
YoutubeParsingHelper { public static boolean areHardcodedYoutubeMusicKeysValid() throws IOException, ReCaptchaException { final String url = "https: byte[] json = JsonWriter.string() .object() .object("context") .object("client") .value("clientName", "WEB_REMIX") .value("clientVersion", HARDCODED_YOUTUBE_MUSIC_KEYS[2]) .value("hl", "en") .value("gl", "GB") .array("experimentIds").end() .value("experimentsToken", "") .value("utcOffsetMinutes", 0) .object("locationInfo").end() .object("musicAppInfo").end() .end() .object("capabilities").end() .object("request") .array("internalExperimentFlags").end() .object("sessionIndex").end() .end() .object("activePlayers").end() .object("user") .value("enableSafetyMode", false) .end() .end() .value("query", "test") .value("params", "Eg-KAQwIARAAGAAgACgAMABqChAEEAUQAxAKEAk%3D") .end().done().getBytes("UTF-8"); Map<String, List<String>> headers = new HashMap<>(); headers.put("X-YouTube-Client-Name", Collections.singletonList(HARDCODED_YOUTUBE_MUSIC_KEYS[1])); headers.put("X-YouTube-Client-Version", Collections.singletonList(HARDCODED_YOUTUBE_MUSIC_KEYS[2])); headers.put("Origin", Collections.singletonList("https: headers.put("Referer", Collections.singletonList("music.youtube.com")); headers.put("Content-Type", Collections.singletonList("application/json")); String response = getDownloader().post(url, headers, json).responseBody(); return response.length() > 50; } private YoutubeParsingHelper(); static Document parseAndCheckPage(final String url, final Response response); static boolean isYoutubeURL(URL url); static boolean isYoutubeServiceURL(URL url); static boolean isHooktubeURL(URL url); static boolean isInvidioURL(URL url); static int parseDurationString(final String input); static String getFeedUrlFrom(final String channelIdOrUser); static Calendar parseDateFrom(String textualUploadDate); static JsonObject getInitialData(String html); static boolean isHardcodedClientVersionValid(); static String getClientVersion(); static String getKey(); static boolean areHardcodedYoutubeMusicKeysValid(); static String[] getYoutubeMusicKeys(); static String getUrlFromNavigationEndpoint(JsonObject navigationEndpoint); static String getTextFromObject(JsonObject textObject, boolean html); static String getTextFromObject(JsonObject textObject); static String fixThumbnailUrl(String thumbnailUrl); static String getValidJsonResponseBody(final Response response); static JsonArray getJsonResponse(final String url, final Localization localization); static void defaultAlertsCheck(final JsonObject initialData); final static String BASE_YOUTUBE_INTENT_URL; } | @Test public void testAreHardcodedYoutubeMusicKeysValid() throws IOException, ExtractionException { assertTrue("Hardcoded YouTube Music keys are not valid anymore", YoutubeParsingHelper.areHardcodedYoutubeMusicKeysValid()); } |
YoutubeParsingHelper { public static int parseDurationString(final String input) throws ParsingException, NumberFormatException { final String[] splitInput = input.contains(":") ? input.split(":") : input.split("\\."); String days = "0"; String hours = "0"; String minutes = "0"; final String seconds; switch (splitInput.length) { case 4: days = splitInput[0]; hours = splitInput[1]; minutes = splitInput[2]; seconds = splitInput[3]; break; case 3: hours = splitInput[0]; minutes = splitInput[1]; seconds = splitInput[2]; break; case 2: minutes = splitInput[0]; seconds = splitInput[1]; break; case 1: seconds = splitInput[0]; break; default: throw new ParsingException("Error duration string with unknown format: " + input); } return ((Integer.parseInt(Utils.removeNonDigitCharacters(days)) * 24 + Integer.parseInt(Utils.removeNonDigitCharacters(hours))) * 60 + Integer.parseInt(Utils.removeNonDigitCharacters(minutes))) * 60 + Integer.parseInt(Utils.removeNonDigitCharacters(seconds)); } private YoutubeParsingHelper(); static Document parseAndCheckPage(final String url, final Response response); static boolean isYoutubeURL(URL url); static boolean isYoutubeServiceURL(URL url); static boolean isHooktubeURL(URL url); static boolean isInvidioURL(URL url); static int parseDurationString(final String input); static String getFeedUrlFrom(final String channelIdOrUser); static Calendar parseDateFrom(String textualUploadDate); static JsonObject getInitialData(String html); static boolean isHardcodedClientVersionValid(); static String getClientVersion(); static String getKey(); static boolean areHardcodedYoutubeMusicKeysValid(); static String[] getYoutubeMusicKeys(); static String getUrlFromNavigationEndpoint(JsonObject navigationEndpoint); static String getTextFromObject(JsonObject textObject, boolean html); static String getTextFromObject(JsonObject textObject); static String fixThumbnailUrl(String thumbnailUrl); static String getValidJsonResponseBody(final Response response); static JsonArray getJsonResponse(final String url, final Localization localization); static void defaultAlertsCheck(final JsonObject initialData); final static String BASE_YOUTUBE_INTENT_URL; } | @Test public void testParseDurationString() throws ParsingException { assertEquals(1162567, YoutubeParsingHelper.parseDurationString("12:34:56:07")); assertEquals(4445767, YoutubeParsingHelper.parseDurationString("1,234:56:07")); assertEquals(754, YoutubeParsingHelper.parseDurationString("12:34 ")); } |
JsonUtils { @Nonnull public static Object getValue(@Nonnull JsonObject object, @Nonnull String path) throws ParsingException { List<String> keys = Arrays.asList(path.split("\\.")); object = getObject(object, keys.subList(0, keys.size() - 1)); if (null == object) throw new ParsingException("Unable to get " + path); Object result = object.get(keys.get(keys.size() - 1)); if (null == result) throw new ParsingException("Unable to get " + path); return result; } private JsonUtils(); @Nonnull static Object getValue(@Nonnull JsonObject object, @Nonnull String path); @Nonnull static String getString(@Nonnull JsonObject object, @Nonnull String path); @Nonnull static Boolean getBoolean(@Nonnull JsonObject object, @Nonnull String path); @Nonnull static Number getNumber(@Nonnull JsonObject object, @Nonnull String path); @Nonnull static JsonObject getObject(@Nonnull JsonObject object, @Nonnull String path); @Nonnull static JsonArray getArray(@Nonnull JsonObject object, @Nonnull String path); @Nonnull static List<Object> getValues(@Nonnull JsonArray array, @Nonnull String path); static final JsonObject EMPTY_OBJECT; static final JsonArray EMPTY_ARRAY; static final String EMPTY_STRING; } | @Test public void testGetValueFlat() throws JsonParserException, ParsingException { JsonObject obj = JsonParser.object().from("{\"name\":\"John\",\"age\":30,\"cars\":{\"car1\":\"Ford\",\"car2\":\"BMW\",\"car3\":\"Fiat\"}}"); assertTrue("John".equals(JsonUtils.getValue(obj, "name"))); }
@Test public void testGetValueNested() throws JsonParserException, ParsingException { JsonObject obj = JsonParser.object().from("{\"name\":\"John\",\"age\":30,\"cars\":{\"car1\":\"Ford\",\"car2\":\"BMW\",\"car3\":\"Fiat\"}}"); assertTrue("BMW".equals(JsonUtils.getValue(obj, "cars.car2"))); } |
JsonUtils { @Nonnull public static JsonArray getArray(@Nonnull JsonObject object, @Nonnull String path) throws ParsingException { Object value = getValue(object, path); if (value instanceof JsonArray) { return (JsonArray) value; } else { throw new ParsingException("Unable to get " + path); } } private JsonUtils(); @Nonnull static Object getValue(@Nonnull JsonObject object, @Nonnull String path); @Nonnull static String getString(@Nonnull JsonObject object, @Nonnull String path); @Nonnull static Boolean getBoolean(@Nonnull JsonObject object, @Nonnull String path); @Nonnull static Number getNumber(@Nonnull JsonObject object, @Nonnull String path); @Nonnull static JsonObject getObject(@Nonnull JsonObject object, @Nonnull String path); @Nonnull static JsonArray getArray(@Nonnull JsonObject object, @Nonnull String path); @Nonnull static List<Object> getValues(@Nonnull JsonArray array, @Nonnull String path); static final JsonObject EMPTY_OBJECT; static final JsonArray EMPTY_ARRAY; static final String EMPTY_STRING; } | @Test public void testGetArray() throws JsonParserException, ParsingException { JsonObject obj = JsonParser.object().from("{\"id\":\"0001\",\"type\":\"donut\",\"name\":\"Cake\",\"ppu\":0.55,\"batters\":{\"batter\":[{\"id\":\"1001\",\"type\":\"Regular\"},{\"id\":\"1002\",\"type\":\"Chocolate\"},{\"id\":\"1003\",\"type\":\"Blueberry\"},{\"id\":\"1004\",\"type\":\"Devil's Food\"}]},\"topping\":[{\"id\":\"5001\",\"type\":\"None\"},{\"id\":\"5002\",\"type\":\"Glazed\"},{\"id\":\"5005\",\"type\":\"Sugar\"},{\"id\":\"5007\",\"type\":\"Powdered Sugar\"},{\"id\":\"5006\",\"type\":\"Chocolate with Sprinkles\"},{\"id\":\"5003\",\"type\":\"Chocolate\"},{\"id\":\"5004\",\"type\":\"Maple\"}]}"); JsonArray arr = (JsonArray) JsonUtils.getValue(obj, "batters.batter"); assertTrue(!arr.isEmpty()); } |
JsonUtils { @Nonnull public static List<Object> getValues(@Nonnull JsonArray array, @Nonnull String path) throws ParsingException { List<Object> result = new ArrayList<>(); for (int i = 0; i < array.size(); i++) { JsonObject obj = array.getObject(i); result.add(getValue(obj, path)); } return result; } private JsonUtils(); @Nonnull static Object getValue(@Nonnull JsonObject object, @Nonnull String path); @Nonnull static String getString(@Nonnull JsonObject object, @Nonnull String path); @Nonnull static Boolean getBoolean(@Nonnull JsonObject object, @Nonnull String path); @Nonnull static Number getNumber(@Nonnull JsonObject object, @Nonnull String path); @Nonnull static JsonObject getObject(@Nonnull JsonObject object, @Nonnull String path); @Nonnull static JsonArray getArray(@Nonnull JsonObject object, @Nonnull String path); @Nonnull static List<Object> getValues(@Nonnull JsonArray array, @Nonnull String path); static final JsonObject EMPTY_OBJECT; static final JsonArray EMPTY_ARRAY; static final String EMPTY_STRING; } | @Test public void testGetValues() throws JsonParserException, ParsingException { JsonObject obj = JsonParser.object().from("{\"id\":\"0001\",\"type\":\"donut\",\"name\":\"Cake\",\"ppu\":0.55,\"batters\":{\"batter\":[{\"id\":\"1001\",\"type\":\"Regular\"},{\"id\":\"1002\",\"type\":\"Chocolate\"},{\"id\":\"1003\",\"type\":\"Blueberry\"},{\"id\":\"1004\",\"type\":\"Devil's Food\"}]},\"topping\":[{\"id\":\"5001\",\"type\":\"None\"},{\"id\":\"5002\",\"type\":\"Glazed\"},{\"id\":\"5005\",\"type\":\"Sugar\"},{\"id\":\"5007\",\"type\":\"Powdered Sugar\"},{\"id\":\"5006\",\"type\":\"Chocolate with Sprinkles\"},{\"id\":\"5003\",\"type\":\"Chocolate\"},{\"id\":\"5004\",\"type\":\"Maple\"}]}"); JsonArray arr = (JsonArray) JsonUtils.getValue(obj, "topping"); List<Object> types = JsonUtils.getValues(arr, "type"); assertTrue(types.contains("Chocolate with Sprinkles")); } |
ServiceTree { @NonNull public Node createRootNode(@NonNull Object nodeKey) { checkKey(nodeKey); return createChildNode(root, nodeKey); } boolean hasNodeWithKey(@NonNull Object key); @NonNull Node createRootNode(@NonNull Object nodeKey); @NonNull Node createChildNode(@NonNull Node parentNode, @NonNull Object nodeKey); @NonNull Node getNode(@NonNull Object key); void traverseTree(@Walk.Mode final int mode, @NonNull final Walk walk); void traverseTree(@Walk.Mode final int mode, boolean includeTreeRoot, @NonNull final Walk walk); void removeAllNodes(); void removeNodeAndChildren(@NonNull Node node); void traverseSubtree(@NonNull final Node node, @Walk.Mode final int mode, @NonNull final Walk walk); void traverseChain(@NonNull Node node, @NonNull Walk walk); void traverseChain(@NonNull Node node, boolean includeTreeRoot, @NonNull Walk walk); void traverseChain(@NonNull Node node, @Walk.Mode final int mode, @NonNull Walk walk); void traverseChain(@NonNull Node node, @Walk.Mode final int mode, final boolean includeTreeRoot, @NonNull Walk walk); @NonNull Node findRoot(@NonNull Node child); @NonNull Set<Object> getKeys(); Node getTreeRoot(); void registerRootService(@NonNull String name, @NonNull Object service); boolean hasRootService(String name); @NonNull T getRootService(String name); T unregisterRootService(String name); } | @Test public void bindingServiceWorks() { TestKey rootKey = new TestKey("root"); ServiceTree.Scoped service = Mockito.mock(ServiceTree.Scoped.class); ServiceTree serviceTree = new ServiceTree(); ServiceTree.Node node = serviceTree.createRootNode(rootKey).bindService("SERVICE", service); List<ServiceTree.Node.Entry> entries = node.getBoundServices(); boolean didFind = false; for(ServiceTree.Node.Entry entry : entries) { if(entry.getService() == service) { assertThat(entry.getName()).isEqualTo("SERVICE"); didFind = true; break; } } assertThat(didFind).isTrue(); assertThat(node.getService("SERVICE")).isSameAs(service); assertThat(node.hasBoundService("SERVICE")).isTrue(); Mockito.verify(service, Mockito.never()).onExitScope(); node.removeService("SERVICE"); Mockito.verify(service, Mockito.atLeastOnce()).onExitScope(); }
@Test public void serviceCannotBeNull() { TestKey rootKey = new TestKey("root"); ServiceTree serviceTree = new ServiceTree(); ServiceTree.Node root = serviceTree.createRootNode(rootKey); try { root.bindService("SERVICE", null); } catch(NullPointerException e) { } }
@Test public void serviceNameCannotBeNull() { TestKey rootKey = new TestKey("root"); ServiceTree serviceTree = new ServiceTree(); ServiceTree.Node root = serviceTree.createRootNode(rootKey); try { root.hasService(null); } catch(NullPointerException e) { } } |
ServiceTree { public boolean hasNodeWithKey(@NonNull Object key) { checkKey(key); return nodeMap.containsKey(key); } boolean hasNodeWithKey(@NonNull Object key); @NonNull Node createRootNode(@NonNull Object nodeKey); @NonNull Node createChildNode(@NonNull Node parentNode, @NonNull Object nodeKey); @NonNull Node getNode(@NonNull Object key); void traverseTree(@Walk.Mode final int mode, @NonNull final Walk walk); void traverseTree(@Walk.Mode final int mode, boolean includeTreeRoot, @NonNull final Walk walk); void removeAllNodes(); void removeNodeAndChildren(@NonNull Node node); void traverseSubtree(@NonNull final Node node, @Walk.Mode final int mode, @NonNull final Walk walk); void traverseChain(@NonNull Node node, @NonNull Walk walk); void traverseChain(@NonNull Node node, boolean includeTreeRoot, @NonNull Walk walk); void traverseChain(@NonNull Node node, @Walk.Mode final int mode, @NonNull Walk walk); void traverseChain(@NonNull Node node, @Walk.Mode final int mode, final boolean includeTreeRoot, @NonNull Walk walk); @NonNull Node findRoot(@NonNull Node child); @NonNull Set<Object> getKeys(); Node getTreeRoot(); void registerRootService(@NonNull String name, @NonNull Object service); boolean hasRootService(String name); @NonNull T getRootService(String name); T unregisterRootService(String name); } | @Test public void rootIsNotInNodeMap() { ServiceTree serviceTree = new ServiceTree(); assertThat(serviceTree.hasNodeWithKey(serviceTree.root.getKey())).isFalse(); }
@Test public void keyCannotBeNull() { ServiceTree serviceTree = new ServiceTree(); try { serviceTree.hasNodeWithKey(null); } catch(NullPointerException e) { } } |
ServiceTree { public void traverseTree(@Walk.Mode final int mode, @NonNull final Walk walk) { traverseTree(mode, false, walk); } boolean hasNodeWithKey(@NonNull Object key); @NonNull Node createRootNode(@NonNull Object nodeKey); @NonNull Node createChildNode(@NonNull Node parentNode, @NonNull Object nodeKey); @NonNull Node getNode(@NonNull Object key); void traverseTree(@Walk.Mode final int mode, @NonNull final Walk walk); void traverseTree(@Walk.Mode final int mode, boolean includeTreeRoot, @NonNull final Walk walk); void removeAllNodes(); void removeNodeAndChildren(@NonNull Node node); void traverseSubtree(@NonNull final Node node, @Walk.Mode final int mode, @NonNull final Walk walk); void traverseChain(@NonNull Node node, @NonNull Walk walk); void traverseChain(@NonNull Node node, boolean includeTreeRoot, @NonNull Walk walk); void traverseChain(@NonNull Node node, @Walk.Mode final int mode, @NonNull Walk walk); void traverseChain(@NonNull Node node, @Walk.Mode final int mode, final boolean includeTreeRoot, @NonNull Walk walk); @NonNull Node findRoot(@NonNull Node child); @NonNull Set<Object> getKeys(); Node getTreeRoot(); void registerRootService(@NonNull String name, @NonNull Object service); boolean hasRootService(String name); @NonNull T getRootService(String name); T unregisterRootService(String name); } | @Test public void walkCannotBeNull() { ServiceTree serviceTree = new ServiceTree(); try { serviceTree.traverseTree(ServiceTree.Walk.POST_ORDER, null); } catch(NullPointerException e) { } } |
ServiceTree { public void registerRootService(@NonNull String name, @NonNull Object service) { checkName(name); checkService(name); root.bindService(name, service); } boolean hasNodeWithKey(@NonNull Object key); @NonNull Node createRootNode(@NonNull Object nodeKey); @NonNull Node createChildNode(@NonNull Node parentNode, @NonNull Object nodeKey); @NonNull Node getNode(@NonNull Object key); void traverseTree(@Walk.Mode final int mode, @NonNull final Walk walk); void traverseTree(@Walk.Mode final int mode, boolean includeTreeRoot, @NonNull final Walk walk); void removeAllNodes(); void removeNodeAndChildren(@NonNull Node node); void traverseSubtree(@NonNull final Node node, @Walk.Mode final int mode, @NonNull final Walk walk); void traverseChain(@NonNull Node node, @NonNull Walk walk); void traverseChain(@NonNull Node node, boolean includeTreeRoot, @NonNull Walk walk); void traverseChain(@NonNull Node node, @Walk.Mode final int mode, @NonNull Walk walk); void traverseChain(@NonNull Node node, @Walk.Mode final int mode, final boolean includeTreeRoot, @NonNull Walk walk); @NonNull Node findRoot(@NonNull Node child); @NonNull Set<Object> getKeys(); Node getTreeRoot(); void registerRootService(@NonNull String name, @NonNull Object service); boolean hasRootService(String name); @NonNull T getRootService(String name); T unregisterRootService(String name); } | @Test public void rootServiceCannotBeNull() { ServiceTree serviceTree = new ServiceTree(); try { serviceTree.registerRootService("SERVICE", null); } catch(NullPointerException e) { } }
@Test public void rootServiceNameCannotBeNull() { ServiceTree serviceTree = new ServiceTree(); try { serviceTree.registerRootService(null, new Object()); } catch(NullPointerException e) { } } |
ServiceTree { @NonNull public Node createChildNode(@NonNull Node parentNode, @NonNull Object nodeKey) { checkNode(parentNode); checkKey(nodeKey); Node node = new Node(this, parentNode, nodeKey); parentNode.children.add(node); this.addNode(node); return node; } boolean hasNodeWithKey(@NonNull Object key); @NonNull Node createRootNode(@NonNull Object nodeKey); @NonNull Node createChildNode(@NonNull Node parentNode, @NonNull Object nodeKey); @NonNull Node getNode(@NonNull Object key); void traverseTree(@Walk.Mode final int mode, @NonNull final Walk walk); void traverseTree(@Walk.Mode final int mode, boolean includeTreeRoot, @NonNull final Walk walk); void removeAllNodes(); void removeNodeAndChildren(@NonNull Node node); void traverseSubtree(@NonNull final Node node, @Walk.Mode final int mode, @NonNull final Walk walk); void traverseChain(@NonNull Node node, @NonNull Walk walk); void traverseChain(@NonNull Node node, boolean includeTreeRoot, @NonNull Walk walk); void traverseChain(@NonNull Node node, @Walk.Mode final int mode, @NonNull Walk walk); void traverseChain(@NonNull Node node, @Walk.Mode final int mode, final boolean includeTreeRoot, @NonNull Walk walk); @NonNull Node findRoot(@NonNull Node child); @NonNull Set<Object> getKeys(); Node getTreeRoot(); void registerRootService(@NonNull String name, @NonNull Object service); boolean hasRootService(String name); @NonNull T getRootService(String name); T unregisterRootService(String name); } | @Test public void nodeCannotBeNull() { ServiceTree serviceTree = new ServiceTree(); try { serviceTree.createChildNode(null, "key"); } catch(NullPointerException e) { } } |
LessProfile extends ProfileDefinition { @Override public RulesProfile createProfile(ValidationMessages messages) { AnnotationBasedProfileBuilder annotationBasedProfileBuilder = new AnnotationBasedProfileBuilder(ruleFinder); return annotationBasedProfileBuilder.build( CheckList.LESS_REPOSITORY_KEY, SONARQUBE_WAY_PROFILE_NAME, LessLanguage.KEY, CheckList.getLessChecks(), messages); } LessProfile(RuleFinder ruleFinder); @Override RulesProfile createProfile(ValidationMessages messages); static final String SONARQUBE_WAY_PROFILE_NAME; } | @Test public void should_create_sonarqube_way_profile() { ValidationMessages validation = ValidationMessages.create(); LessProfile definition = new LessProfile(universalRuleFinder()); RulesProfile profile = definition.createProfile(validation); assertThat(profile.getName()).isEqualTo("SonarQube Way"); assertThat(profile.getLanguage()).isEqualTo("less"); assertThat(profile.getActiveRulesByRepository("less")).hasSize(73); assertThat(validation.hasErrors()).isFalse(); } |
ScssVariableNamingConventionCheck extends DoubleDispatchVisitorCheck { @VisibleForTesting void setFormat(String format) { this.format = format; } @Override void visitScssVariableDeclaration(ScssVariableDeclarationTree tree); @Override void validateParameters(); } | @Test public void test_with_custom_format() { check.setFormat("^[-a-z]+$"); CssCheckVerifier.verifyScssFile(check, CheckTestUtils.getScssTestFile("variable-naming-convention/scssVariableNamingConventionCustomFormat.scss")); }
@Test public void should_throw_an_illegal_state_exception_as_the_format_parameter_is_not_valid() { try { check.setFormat("("); CssCheckVerifier.issuesOnScssFile(check, CheckTestUtils.getScssTestFile("variable-naming-convention/scssVariableNamingConvention.scss")).noMore(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Check scss:scss-variable-naming-convention (SCSS variables should follow a naming convention): " + "format parameter \"(\" is not a valid regular expression."); } }
@Test public void test_with_default_format() { check.setFormat("^[a-z][-a-z0-9]*$"); CssCheckVerifier.verifyScssFile(check, CheckTestUtils.getScssTestFile("variable-naming-convention/scssVariableNamingConvention.scss")); } |
TypeSelectorCheck extends DoubleDispatchVisitorCheck { @VisibleForTesting void setAllowedTypes(String allowedTypes) { this.allowedTypes = allowedTypes; } @Override void visitTypeSelector(TypeSelectorTree tree); } | @Test public void test_css_with_excludes() { TypeSelectorCheck check = new TypeSelectorCheck(); check.setAllowedTypes("a, span"); CssCheckVerifier.verifyCssFile(check, CheckTestUtils.getCommonTestFile("type-selector/typeSelectorExcluded.css")); }
@Test public void test_css_with_excludes_case_insensitive() { TypeSelectorCheck check = new TypeSelectorCheck(); check.setAllowedTypes("A, SpAn"); CssCheckVerifier.verifyCssFile(check, CheckTestUtils.getCommonTestFile("type-selector/typeSelectorExcluded.css")); } |
IdSelectorNamingConventionCheck extends DoubleDispatchVisitorCheck { @VisibleForTesting void setFormat(String format) { this.format = format; } @Override void visitIdSelector(IdSelectorTree tree); @Override void validateParameters(); } | @Test public void test_with_default_format() { check.setFormat("^[a-z][-a-z0-9]*$"); CssCheckVerifier.verifyCssFile(check, getTestFile("selectorNamingConvention.css")); }
@Test public void test_with_custom_format() { check.setFormat("^[-a-z]+$"); CssCheckVerifier.verifyCssFile(check, getTestFile("selectorNamingConventionCustomFormat.css")); }
@Test public void test_interpolated_selectors_not_checked_on_less_file() { check.setFormat("^[a-z][-a-z0-9]*$"); CssCheckVerifier.verifyLessFile(check, getTestFile("selectorNamingConvention.less")); }
@Test public void test_interpolated_selectors_not_checked_on_scss_file() { check.setFormat("^[a-z][-a-z0-9]*$"); CssCheckVerifier.verifyScssFile(check, getTestFile("selectorNamingConvention.scss")); }
@Test public void should_throw_an_illegal_state_exception_as_the_format_parameter_is_not_valid() { try { check.setFormat("("); CssCheckVerifier.issuesOnCssFile(check, CheckTestUtils.getCommonTestFile("selectorNamingConvention/selectorNamingConvention.css")).noMore(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Check css:id-selector-naming-convention (ID selectors should follow a naming convention): " + "format parameter \"(\" is not a valid regular expression."); } } |
ExperimentalAtRuleCheck extends DoubleDispatchVisitorCheck { @VisibleForTesting void setAtRulesToExclude(String atRulesToExclude) { this.atRulesToExclude = atRulesToExclude; } @Override void visitAtRule(AtRuleTree tree); @Override void validateParameters(); } | @Test public void test_css_exclude_at_rules() { ExperimentalAtRuleCheck check = new ExperimentalAtRuleCheck(); check.setAtRulesToExclude("custom-media|count.*"); CssCheckVerifier.verifyCssFile(check, getTestFile("experimentalAtRuleUsageExcludeAtRules.css")); }
@Test public void test_less_exclude_at_rules() { ExperimentalAtRuleCheck check = new ExperimentalAtRuleCheck(); check.setAtRulesToExclude("custom-media|count.*"); CssCheckVerifier.verifyLessFile(check, getTestFile("experimentalAtRuleUsageExcludeAtRules.less")); }
@Test public void test_scss_exclude_at_rules() { ExperimentalAtRuleCheck check = new ExperimentalAtRuleCheck(); check.setAtRulesToExclude("custom-media|count.*"); CssCheckVerifier.verifyScssFile(check, getTestFile("experimentalAtRuleUsageExcludeAtRules.scss")); }
@Test public void should_throw_an_illegal_state_exception_as_the_atRulesToExclude_parameter_is_not_valid() { try { ExperimentalAtRuleCheck check = new ExperimentalAtRuleCheck(); check.setAtRulesToExclude("("); CssCheckVerifier.issuesOnCssFile(check, getTestFile("experimentalAtRuleUsage.css")).noMore(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Check css:experimental-atrule-usage (Experimental @-rules should not be used): " + "atRulesToExclude parameter \"(\" is not a valid regular expression."); } } |
Plugin implements org.sonar.api.Plugin { @Override public void define(Context context) { context.addExtensions( CssLanguage.class, ScssLanguage.class, LessLanguage.class, CssAnalyzerSensor.class, EmbeddedCssAnalyzerSensor.class, ScssAnalyzerSensor.class, LessAnalyzerSensor.class, CssProfile.class, ScssProfile.class, LessProfile.class, CssRulesDefinition.class, ScssRulesDefinition.class, LessRulesDefinition.class); } @Override void define(Context context); static final String CSS_FILE_SUFFIXES_KEY; static final String CSS_FILE_SUFFIXES_DEFAULT_VALUE; static final String EMBEDDED_CSS_FILE_SUFFIXES_KEY; static final String EMBEDDED_CSS_FILE_SUFFIXES_DEFAULT_VALUE; static final String SCSS_FILE_SUFFIXES_KEY; static final String SCSS_FILE_SUFFIXES_DEFAULT_VALUE; static final String LESS_FILE_SUFFIXES_KEY; static final String LESS_FILE_SUFFIXES_DEFAULT_VALUE; } | @Test public void should_get_the_right_version() { Context context = new Context(Version.create(5, 6)); new Plugin().define(context); assertThat(context.getSonarQubeVersion().major()).isEqualTo(5); assertThat(context.getSonarQubeVersion().minor()).isEqualTo(6); }
@Test public void should_get_the_right_number_of_extensions() { Context context = new Context(Version.create(5, 6)); new Plugin().define(context); assertThat(context.getExtensions()).hasSize(13); } |
ExperimentalPropertyCheck extends DoubleDispatchVisitorCheck { @VisibleForTesting void setPropertiesToExclude(String propertiesToExclude) { this.propertiesToExclude = propertiesToExclude; } @Override void visitProperty(PropertyTree tree); @Override void validateParameters(); } | @Test public void test_css_exclude_properties() { ExperimentalPropertyCheck check = new ExperimentalPropertyCheck(); check.setPropertiesToExclude("user-select|voice.*"); CssCheckVerifier.verifyCssFile(check, getTestFile("experimentalPropertyUsageExcludeProperties.css")); }
@Test public void test_less_exclude_properties() { ExperimentalPropertyCheck check = new ExperimentalPropertyCheck(); check.setPropertiesToExclude("user-select|voice.*"); CssCheckVerifier.verifyCssFile(check, getTestFile("experimentalPropertyUsageExcludeProperties.less")); }
@Test public void test_scss_exclude_properties() { ExperimentalPropertyCheck check = new ExperimentalPropertyCheck(); check.setPropertiesToExclude("user-select|voice.*"); CssCheckVerifier.verifyCssFile(check, getTestFile("experimentalPropertyUsageExcludeProperties.scss")); }
@Test public void should_throw_an_illegal_state_exception_as_the_propertiesToExclude_parameter_is_not_valid() { try { ExperimentalPropertyCheck check = new ExperimentalPropertyCheck(); check.setPropertiesToExclude("("); CssCheckVerifier.issuesOnCssFile(check, getTestFile("experimentalPropertyUsage.css")).noMore(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Check css:experimental-property-usage (Experimental properties should not be used): " + "propertiesToExclude parameter \"(\" is not a valid regular expression."); } } |
ExperimentalPseudoCheck extends DoubleDispatchVisitorCheck { @VisibleForTesting void setPseudosToExclude(String pseudosToExclude) { this.pseudosToExclude = pseudosToExclude; } @Override void visitPseudoFunction(PseudoFunctionTree tree); @Override void visitPseudoIdentifier(PseudoIdentifierTree tree); @Override void validateParameters(); } | @Test public void test_css_exclude_pseudos() { ExperimentalPseudoCheck check = new ExperimentalPseudoCheck(); check.setPseudosToExclude("any-link|cont.*"); CssCheckVerifier.verifyCssFile(check, getTestFile("experimentalPseudoUsageExcludePseudos.css")); }
@Test public void test_less_exclude_pseudos() { ExperimentalPseudoCheck check = new ExperimentalPseudoCheck(); check.setPseudosToExclude("any-link|cont.*"); CssCheckVerifier.verifyLessFile(check, getTestFile("experimentalPseudoUsageExcludePseudos.less")); }
@Test public void test_scss_exclude_pseudos() { ExperimentalPseudoCheck check = new ExperimentalPseudoCheck(); check.setPseudosToExclude("any-link|cont.*"); CssCheckVerifier.verifyScssFile(check, getTestFile("experimentalPseudoUsageExcludePseudos.scss")); }
@Test public void should_throw_an_illegal_state_exception_as_the_pseudosToExclude_parameter_is_not_valid() { try { ExperimentalPseudoCheck check = new ExperimentalPseudoCheck(); check.setPseudosToExclude("("); CssCheckVerifier.issuesOnCssFile(check, getTestFile("experimentalPseudoUsage.css")).noMore(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Check css:experimental-pseudo-usage (Experimental pseudo-elements and pseudo-classes should not be used): " + "pseudosToExclude parameter \"(\" is not a valid regular expression."); } } |
NumberOfRulesPerSheetCheck extends DoubleDispatchVisitorCheck { @VisibleForTesting void setMax(int max) { this.max = max; } @Override void visitStyleSheet(StyleSheetTree tree); @Override void visitAtRule(AtRuleTree tree); @Override void visitRuleset(RulesetTree tree); } | @Test public void should_contain_more_rules_than_the_allowed_number_and_raise_an_issue() { NumberOfRulesPerSheetCheck check = new NumberOfRulesPerSheetCheck(); check.setMax(9); CssCheckVerifier.verifyCssFile(check, CheckTestUtils.getCommonTestFile("maximumNumberOfRulesPerSheet9.css")); }
@Test public void should_contain_fewer_rules_than_the_allowed_number_and_not_raise_an_issue() { NumberOfRulesPerSheetCheck check = new NumberOfRulesPerSheetCheck(); check.setMax(11); CssCheckVerifier.verifyCssFile(check, CheckTestUtils.getCommonTestFile("maximumNumberOfRulesPerSheet11.css")); }
@Test public void should_contain_the_same_number_of_rules_than_the_allowed_number_and_not_raise_an_issue() { NumberOfRulesPerSheetCheck check = new NumberOfRulesPerSheetCheck(); check.setMax(10); CssCheckVerifier.verifyCssFile(check, CheckTestUtils.getCommonTestFile("maximumNumberOfRulesPerSheet10.css")); } |
TooManyWebFontsCheck extends DoubleDispatchVisitorCheck { @VisibleForTesting void setFontFaceThreshold(int fontFaceThreshold) { this.fontFaceThreshold = fontFaceThreshold; } @Override void visitStyleSheet(StyleSheetTree tree); @Override void visitAtKeyword(AtKeywordTree tree); } | @Test public void test() { TooManyWebFontsCheck check = new TooManyWebFontsCheck(); check.setFontFaceThreshold(3); CssCheckVerifier.verifyCssFile(check, CheckTestUtils.getCommonTestFile("toomanywebfonts.css")); } |
OverspecificSelectorCheck extends DoubleDispatchVisitorCheck { @VisibleForTesting void setDeepnessThreshold(int deepnessThreshold) { this.deepnessThreshold = deepnessThreshold; } @Override void visitSelector(SelectorTree tree); } | @Test public void test_with_custom_threshold() { check.setDeepnessThreshold(5); CssCheckVerifier.verifyCssFile(check, CheckTestUtils.getCommonTestFile("overspecselectorCustom.css")); } |
LineLengthCheck extends DoubleDispatchVisitorCheck implements CharsetAwareVisitor { @VisibleForTesting void setMaximumLineLength(int maximumLineLength) { this.maximumLineLength = maximumLineLength; } @Override void visitStyleSheet(StyleSheetTree tree); @Override void setCharset(Charset charset); } | @Test public void should_find_one_line_longer_than_50_characters_and_raise_an_issue() { check.setMaximumLineLength(50); CssCheckVerifier.verifyCssFile(check, CheckTestUtils.getCommonTestFile("lineLength50.css")); }
@Test public void should_find_two_lines_longer_than_30_characters_and_raise_issues() { check.setMaximumLineLength(30); CssCheckVerifier.verifyCssFile(check, CheckTestUtils.getCommonTestFile("lineLength30.css")); } |
FileTooManyLinesCheck extends DoubleDispatchVisitorCheck implements CharsetAwareVisitor { @VisibleForTesting void setMax(int max) { this.max = max; } @Override void visitStyleSheet(StyleSheetTree tree); @Override void setCharset(Charset charset); } | @Test public void should_contain_more_lines_than_the_allowed_number_and_raise_an_issue() { check.setMax(9); CssCheckVerifier.verifyCssFile(check, CheckTestUtils.getCommonTestFile("file-too-many-lines/fileTooManyLines9.css")); }
@Test public void should_contain_fewer_lines_than_the_allowed_number_and_not_raise_an_issue() { check.setMax(11); CssCheckVerifier.verifyCssFile(check, CheckTestUtils.getCommonTestFile("file-too-many-lines/fileTooManyLines10.css")); }
@Test public void should_contain_the_same_number_of_lines_than_the_allowed_number_and_not_raise_an_issue() { check.setMax(10); CssCheckVerifier.verifyCssFile(check, CheckTestUtils.getCommonTestFile("file-too-many-lines/fileTooManyLines11.css")); } |
CssLanguage extends AbstractLanguage { @Override public String[] getFileSuffixes() { String[] suffixes = settings.getStringArray(Plugin.CSS_FILE_SUFFIXES_KEY); if (suffixes == null || suffixes.length == 0) { suffixes = StringUtils.split(Plugin.CSS_FILE_SUFFIXES_DEFAULT_VALUE, ","); } return suffixes; } CssLanguage(Settings settings); @Override String[] getFileSuffixes(); static final String KEY; static final String NAME; } | @Test public void default_file_suffix() { CssLanguage language = new CssLanguage(mock(Settings.class)); assertThat(language.getFileSuffixes()).containsOnly("css"); }
@Test public void custom_file_suffixes() { Settings settings = new Settings(); settings.setProperty("sonar.css.file.suffixes", "css,css3"); CssLanguage language = new CssLanguage(settings); assertThat(language.getFileSuffixes()).containsOnly("css", "css3"); } |
FontFaceBrowserCompatibilityCheck extends DoubleDispatchVisitorCheck { @VisibleForTesting void setBrowserSupportLevel(String browserSupportLevel) { this.browserSupportLevel = browserSupportLevel; } @Override void visitAtRule(AtRuleTree tree); @Override void validateParameters(); } | @Test public void deep() { FontFaceBrowserCompatibilityCheck check = new FontFaceBrowserCompatibilityCheck(); check.setBrowserSupportLevel("deep"); CssCheckVerifier.verifyCssFile(check, CheckTestUtils.getCommonTestFile("fontface/deep.css")); }
@Test public void deepest() { FontFaceBrowserCompatibilityCheck check = new FontFaceBrowserCompatibilityCheck(); check.setBrowserSupportLevel("deepest"); CssCheckVerifier.verifyCssFile(check, CheckTestUtils.getCommonTestFile("fontface/deepest.css")); }
@Test public void should_throw_an_illegal_state_exception_as_the_browserLevelSupport_parameter_is_not_valid() { try { FontFaceBrowserCompatibilityCheck check = new FontFaceBrowserCompatibilityCheck(); check.setBrowserSupportLevel("blabla"); CssCheckVerifier.issuesOnCssFile(check, CheckTestUtils.getCommonTestFile("fontface/deepest.css")).noMore(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Check css:font-face-browser-compatibility (\"@font-face\" rule should " + "be made compatible with the required browsers): parameter value is not valid.\n" + "Actual: 'blabla'\n" + "Expected: 'basic' or 'deep' or 'deepest'"); } } |
FontFamilyNotEndingWithGenericFontFamilyCheck extends DoubleDispatchVisitorCheck { @VisibleForTesting void setExclusions(String exclusions) { this.exclusions = exclusions; } @Override void visitPropertyDeclaration(PropertyDeclarationTree tree); @Override void validateParameters(); } | @Test public void test_with_custom_format() { FontFamilyNotEndingWithGenericFontFamilyCheck check = new FontFamilyNotEndingWithGenericFontFamilyCheck(); check.setExclusions("^My-.+$"); CssCheckVerifier.verifyCssFile(check, getTestFile("fontFamilyNotEndingWithGenericFontFamilyCustomExclusions.css")); }
@Test public void should_throw_an_illegal_state_exception_as_the_exclusions_parameter_is_not_valid() { try { FontFamilyNotEndingWithGenericFontFamilyCheck check = new FontFamilyNotEndingWithGenericFontFamilyCheck(); check.setExclusions("("); CssCheckVerifier.issuesOnCssFile(check, getTestFile("fontFamilyNotEndingWithGenericFontFamily.css")).noMore(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Check css:font-family-not-ending-with-generic-font-family (font-family properties should end with a generic font family): " + "exclusions parameter \"(\" is not a valid regular expression."); } } |
NumberPrecisionCheck extends DoubleDispatchVisitorCheck { @VisibleForTesting void setPrecision(int precision) { this.precision = precision; } @Override void visitNumber(NumberTree tree); } | @Test public void test_css_custom_threshold() { NumberPrecisionCheck check = new NumberPrecisionCheck(); check.setPrecision(2); CssCheckVerifier.verifyCssFile(check, getTestFile("numberPrecisionCustomThreshold.css")); } |
ClassSelectorNamingConventionCheck extends DoubleDispatchVisitorCheck { @VisibleForTesting void setFormat(String format) { this.format = format; } @Override void visitClassSelector(ClassSelectorTree tree); @Override void validateParameters(); } | @Test public void test_with_default_format() { check.setFormat("^[a-z][-a-z0-9]*$"); CssCheckVerifier.verifyCssFile(check, getTestFile("selectorNamingConvention.css")); }
@Test public void test_with_custom_format() { check.setFormat("^[-a-z]+$"); CssCheckVerifier.verifyCssFile(check, getTestFile("selectorNamingConventionCustomFormat.css")); }
@Test public void test_interpolated_selectors_not_checked_on_less_file() { check.setFormat("^[a-z][-a-z0-9]*$"); CssCheckVerifier.verifyLessFile(check, getTestFile("selectorNamingConvention.less")); }
@Test public void test_interpolated_selectors_not_checked_on_scss_file() { check.setFormat("^[a-z][-a-z0-9]*$"); CssCheckVerifier.verifyScssFile(check, getTestFile("selectorNamingConvention.scss")); }
@Test public void should_throw_an_illegal_state_exception_as_the_format_parameter_is_not_valid() { try { check.setFormat("("); CssCheckVerifier.issuesOnCssFile(check, CheckTestUtils.getCommonTestFile("selectorNamingConvention/selectorNamingConvention.css")).noMore(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Check css:class-selector-naming-convention (Class selectors should follow a naming convention): " + "format parameter \"(\" is not a valid regular expression."); } } |
UnknownTypeSelectorCheck extends DoubleDispatchVisitorCheck { @VisibleForTesting void setExclusions(String exclusions) { this.exclusions = exclusions; } @Override void visitTypeSelector(TypeSelectorTree tree); @Override void validateParameters(); static final List<String> KNOWN_HTML_TAGS; static final List<String> KNOWN_SVG_TAGS; } | @Test public void test_css_custom_type_selector() { UnknownTypeSelectorCheck check = new UnknownTypeSelectorCheck(); check.setExclusions("custom-.*"); CssCheckVerifier.verifyCssFile(check, getTestFile("unknownTypeSelectorCustom.css")); }
@Test public void test_less_custom_type_selector() { UnknownTypeSelectorCheck check = new UnknownTypeSelectorCheck(); check.setExclusions("custom-.*"); CssCheckVerifier.verifyLessFile(check, getTestFile("unknownTypeSelectorCustom.less")); }
@Test public void test_scss_custom_type_selector() { UnknownTypeSelectorCheck check = new UnknownTypeSelectorCheck(); check.setExclusions("custom-.*"); CssCheckVerifier.verifyScssFile(check, getTestFile("unknownTypeSelectorCustom.scss")); }
@Test public void should_throw_an_illegal_state_exception_as_the_exclusions_parameter_is_not_valid() { try { UnknownTypeSelectorCheck check = new UnknownTypeSelectorCheck(); check.setExclusions("("); CssCheckVerifier.issuesOnCssFile(check, getTestFile("unknownTypeSelector.css")).noMore(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Check css:unknown-type-selector (Unknown type selectors " + "should be removed): exclusions parameter \"(\" is not a valid regular expression."); } } |
ExperimentalIdentifierCheck extends DoubleDispatchVisitorCheck { @VisibleForTesting void setIdentifiersToExclude(String identifiersToExclude) { this.identifiersToExclude = identifiersToExclude; } @Override void visitValue(ValueTree tree); @Override void validateParameters(); } | @Test public void test_exclude_identifiers() { ExperimentalIdentifierCheck check = new ExperimentalIdentifierCheck(); check.setIdentifiersToExclude("flex|defin.*"); CssCheckVerifier.verifyCssFile(check, getTestFile("experimentalIdentifierUsageExcludeIdentifiers.css")); }
@Test public void should_throw_an_illegal_state_exception_as_the_identifiersToExclude_parameter_is_not_valid() { try { ExperimentalIdentifierCheck check = new ExperimentalIdentifierCheck(); check.setIdentifiersToExclude("("); CssCheckVerifier.issuesOnCssFile(check, getTestFile("experimentalIdentifierUsage.css")).noMore(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Check css:experimental-identifier-usage (Experimental identifiers should not be used): " + "identifiersToExclude parameter \"(\" is not a valid regular expression."); } } |
ExperimentalCssFunctionCheck extends DoubleDispatchVisitorCheck { @VisibleForTesting void setFunctionsToExclude(String functionsToExclude) { this.functionsToExclude = functionsToExclude; } @Override void visitFunction(FunctionTree tree); @Override void validateParameters(); } | @Test public void test_exclude_functions() { ExperimentalCssFunctionCheck check = new ExperimentalCssFunctionCheck(); check.setFunctionsToExclude("conic-gradient|count.*"); CssCheckVerifier.verifyCssFile(check, CheckTestUtils.getCssTestFile("experimentalFunctionUsageExcludeFunctions.css")); }
@Test public void should_throw_an_illegal_state_exception_as_the_functionsToExclude_parameter_is_not_valid() { try { ExperimentalCssFunctionCheck check = new ExperimentalCssFunctionCheck(); check.setFunctionsToExclude("("); CssCheckVerifier.issuesOnCssFile(check, CheckTestUtils.getCssTestFile("experimentalFunctionUsage.css")).noMore(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Check css:experimental-function-usage (Experimental functions should not be used): " + "functionsToExclude parameter \"(\" is not a valid regular expression."); } } |
CssRulesDefinition implements RulesDefinition { @Override public void define(Context context) { NewRepository repository = context .createRepository(CheckList.CSS_REPOSITORY_KEY, CssLanguage.KEY) .setName(CheckList.CSS_REPOSITORY_NAME); new AnnotationBasedRulesDefinition(repository, CssLanguage.KEY).addRuleClasses(false, CheckList.getCssChecks()); repository.done(); } @Override void define(Context context); } | @Test public void test() { CssRulesDefinition rulesDefinition = new CssRulesDefinition(); RulesDefinition.Context context = new RulesDefinition.Context(); rulesDefinition.define(context); RulesDefinition.Repository repository = context.repository("css"); assertThat(repository.name()).isEqualTo("SonarQube"); assertThat(repository.language()).isEqualTo("css"); assertThat(repository.rules()).hasSize(88); assertThat(CheckList.getEmbeddedCssChecks()).hasSize(repository.rules().size() - 6); RulesDefinition.Rule todoRule = repository.rule(TodoTagCheck.class.getAnnotation(Rule.class).key()); assertThat(todoRule).isNotNull(); assertThat(todoRule.name()).isEqualTo(TodoTagCheck.class.getAnnotation(Rule.class).name()); } |
CssVariableNamingConventionCheck extends DoubleDispatchVisitorCheck { @VisibleForTesting void setFormat(String format) { this.format = format; } @Override void visitVariableDeclaration(VariableDeclarationTree tree); @Override void validateParameters(); } | @Test public void test_with_default_format() { check.setFormat("^[a-z][-a-z0-9]*$"); CssCheckVerifier.verifyCssFile(check, CheckTestUtils.getCssTestFile("variable-naming-convention/variableNamingConvention.css")); }
@Test public void test_with_custom_format() { check.setFormat("^[-a-z]+$"); CssCheckVerifier.verifyCssFile(check, CheckTestUtils.getCssTestFile("variable-naming-convention/variableNamingConventionCustomFormat.css")); }
@Test public void should_throw_an_illegal_state_exception_as_the_format_parameter_is_not_valid() { try { check.setFormat("("); CssCheckVerifier.issuesOnCssFile(check, CheckTestUtils.getCssTestFile("variable-naming-convention/variableNamingConvention.css")).noMore(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Check css:css-variable-naming-convention (CSS variables should follow a naming convention): " + "format parameter \"(\" is not a valid regular expression."); } } |
CssAnalyzerSensor extends AbstractLanguageAnalyzerSensor { @Override public void describe(SensorDescriptor descriptor) { descriptor .onlyOnLanguage(CssLanguage.KEY) .name("CSS Analyzer Sensor") .onlyOnFileType(Type.MAIN); } CssAnalyzerSensor(FileSystem fileSystem, CheckFactory checkFactory, Settings settings, NoSonarFilter noSonarFilter); CssAnalyzerSensor(FileSystem fileSystem, CheckFactory checkFactory, Settings settings, NoSonarFilter noSonarFilter,
@Nullable CustomCssRulesDefinition[] customRulesDefinition); @Override void describe(SensorDescriptor descriptor); @Override String analyzerName(); @Override String language(); @Override ActionParser<Tree> parser(FileSystem fileSystem); @Override List<InputFile> filesToAnalyze(FileSystem fileSystem); @Override Checks checks(CheckFactory checkFactory, CustomRulesDefinition[] customRulesDefinitions); @Override List<TreeVisitor> treeVisitors(SensorContext sensorContext, Checks checks, NoSonarFilter noSonarFilter); @Override Class parsingErrorCheck(); } | @Test public void should_create_a_valid_sensor_descriptor() { DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor(); createCssSquidSensor().describe(descriptor); assertThat(descriptor.name()).isEqualTo("CSS Analyzer Sensor"); assertThat(descriptor.languages()).containsOnly("css"); assertThat(descriptor.type()).isEqualTo(InputFile.Type.MAIN); } |
CssProfile extends ProfileDefinition { @Override public RulesProfile createProfile(ValidationMessages messages) { AnnotationBasedProfileBuilder annotationBasedProfileBuilder = new AnnotationBasedProfileBuilder(ruleFinder); return annotationBasedProfileBuilder.build( CheckList.CSS_REPOSITORY_KEY, SONARQUBE_WAY_PROFILE_NAME, CssLanguage.KEY, CheckList.getCssChecks(), messages); } CssProfile(RuleFinder ruleFinder); @Override RulesProfile createProfile(ValidationMessages messages); static final String SONARQUBE_WAY_PROFILE_NAME; } | @Test public void should_create_sonarqube_way_profile() { ValidationMessages validation = ValidationMessages.create(); CssProfile definition = new CssProfile(universalRuleFinder()); RulesProfile profile = definition.createProfile(validation); assertThat(profile.getName()).isEqualTo("SonarQube Way"); assertThat(profile.getLanguage()).isEqualTo("css"); assertThat(profile.getActiveRulesByRepository("css")).hasSize(73); assertThat(validation.hasErrors()).isFalse(); } |
EmbeddedCssAnalyzerSensor extends AbstractLanguageAnalyzerSensor { @Override public void describe(SensorDescriptor descriptor) { descriptor.name("Embedded CSS Analyzer Sensor"); } EmbeddedCssAnalyzerSensor(FileSystem fileSystem, CheckFactory checkFactory, Settings settings, NoSonarFilter noSonarFilter); EmbeddedCssAnalyzerSensor(FileSystem fileSystem, CheckFactory checkFactory, Settings settings, NoSonarFilter noSonarFilter,
@Nullable CustomCssRulesDefinition[] customRulesDefinition); @Override void describe(SensorDescriptor descriptor); @Override String analyzerName(); @Override String language(); @Override ActionParser<Tree> parser(FileSystem fileSystem); @Override List<InputFile> filesToAnalyze(FileSystem fileSystem); @Override Checks checks(CheckFactory checkFactory, CustomRulesDefinition[] customRulesDefinitions); @Override List<TreeVisitor> treeVisitors(SensorContext sensorContext, Checks checks, NoSonarFilter noSonarFilter); @Override Class parsingErrorCheck(); } | @Test public void should_create_a_valid_sensor_descriptor() { DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor(); createEmbeddedCssSquidSensor().describe(descriptor); assertThat(descriptor.name()).isEqualTo("Embedded CSS Analyzer Sensor"); assertThat(descriptor.languages()).isEmpty(); assertThat(descriptor.type()).isNull(); } |
CustomScssRulesDefinition implements CustomRulesDefinition { @Override public void define(Context context) { NewRepository repo = context.createRepository(repositoryKey(), "scss").setName(repositoryName()); new AnnotationBasedRulesDefinition(repo, "scss").addRuleClasses(false, ImmutableList.copyOf(checkClasses())); repo.done(); } @Override void define(Context context); } | @Test public void test() { MyCustomScssRulesDefinition rulesDefinition = new MyCustomScssRulesDefinition(); RulesDefinition.Context context = new RulesDefinition.Context(); rulesDefinition.define(context); RulesDefinition.Repository repository = context.repository(REPOSITORY_KEY); assertThat(repository.name()).isEqualTo(REPOSITORY_NAME); assertThat(repository.language()).isEqualTo("scss"); assertThat(repository.rules()).hasSize(1); RulesDefinition.Rule customRule = repository.rule(RULE_KEY); assertThat(customRule).isNotNull(); assertThat(customRule.key()).isEqualTo(RULE_KEY); assertThat(customRule.name()).isEqualTo(RULE_NAME); RulesDefinition.Param param = repository.rules().get(0).params().get(0); assertThat(param.key()).isEqualTo("customParam"); assertThat(param.description()).isEqualTo("Custom parameter"); assertThat(param.defaultValue()).isEqualTo("Default value"); } |
CustomCssRulesDefinition implements CustomRulesDefinition { @Override public void define(Context context) { NewRepository repo = context.createRepository(repositoryKey(), "css").setName(repositoryName()); new AnnotationBasedRulesDefinition(repo, "css").addRuleClasses(false, ImmutableList.copyOf(checkClasses())); repo.done(); } @Override void define(Context context); } | @Test public void test() { MyCustomCssRulesDefinition rulesDefinition = new MyCustomCssRulesDefinition(); RulesDefinition.Context context = new RulesDefinition.Context(); rulesDefinition.define(context); RulesDefinition.Repository repository = context.repository(REPOSITORY_KEY); assertThat(repository.name()).isEqualTo(REPOSITORY_NAME); assertThat(repository.language()).isEqualTo("css"); assertThat(repository.rules()).hasSize(1); RulesDefinition.Rule customRule = repository.rule(RULE_KEY); assertThat(customRule).isNotNull(); assertThat(customRule.key()).isEqualTo(RULE_KEY); assertThat(customRule.name()).isEqualTo(RULE_NAME); RulesDefinition.Param param = repository.rules().get(0).params().get(0); assertThat(param.key()).isEqualTo("customParam"); assertThat(param.description()).isEqualTo("Custom parameter"); assertThat(param.defaultValue()).isEqualTo("Default value"); } |
LessAnalyzerSensor extends AbstractLanguageAnalyzerSensor { @Override public void describe(SensorDescriptor descriptor) { descriptor .onlyOnLanguage(LessLanguage.KEY) .name("Less Analyzer Sensor") .onlyOnFileType(Type.MAIN); } LessAnalyzerSensor(FileSystem fileSystem, CheckFactory checkFactory, Settings settings, NoSonarFilter noSonarFilter); LessAnalyzerSensor(FileSystem fileSystem, CheckFactory checkFactory, Settings settings, NoSonarFilter noSonarFilter,
@Nullable CustomLessRulesDefinition[] customRulesDefinition); @Override void describe(SensorDescriptor descriptor); @Override String analyzerName(); @Override String language(); @Override ActionParser<Tree> parser(FileSystem fileSystem); @Override List<InputFile> filesToAnalyze(FileSystem fileSystem); @Override Checks checks(CheckFactory checkFactory, CustomRulesDefinition[] customRulesDefinitions); @Override List<TreeVisitor> treeVisitors(SensorContext sensorContext, Checks checks, NoSonarFilter noSonarFilter); @Override Class parsingErrorCheck(); } | @Test public void should_create_a_valid_sensor_descriptor() { DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor(); createLessSquidSensor().describe(descriptor); assertThat(descriptor.name()).isEqualTo("Less Analyzer Sensor"); assertThat(descriptor.languages()).containsOnly("less"); assertThat(descriptor.type()).isEqualTo(InputFile.Type.MAIN); } |
CustomLessRulesDefinition implements CustomRulesDefinition { @Override public void define(Context context) { NewRepository repo = context.createRepository(repositoryKey(), "less").setName(repositoryName()); new AnnotationBasedRulesDefinition(repo, "less").addRuleClasses(false, ImmutableList.copyOf(checkClasses())); repo.done(); } @Override void define(Context context); } | @Test public void test() { MyCustomLessRulesDefinition rulesDefinition = new MyCustomLessRulesDefinition(); RulesDefinition.Context context = new RulesDefinition.Context(); rulesDefinition.define(context); RulesDefinition.Repository repository = context.repository(REPOSITORY_KEY); assertThat(repository.name()).isEqualTo(REPOSITORY_NAME); assertThat(repository.language()).isEqualTo("less"); assertThat(repository.rules()).hasSize(1); RulesDefinition.Rule customRule = repository.rule(RULE_KEY); assertThat(customRule).isNotNull(); assertThat(customRule.key()).isEqualTo(RULE_KEY); assertThat(customRule.name()).isEqualTo(RULE_NAME); RulesDefinition.Param param = repository.rules().get(0).params().get(0); assertThat(param.key()).isEqualTo("customParam"); assertThat(param.description()).isEqualTo("Custom parameter"); assertThat(param.defaultValue()).isEqualTo("Default value"); } |
LessCommentAnalyser extends CssCommentAnalyser { @Override public String getContents(String comment) { if (comment.startsWith("/*")) { return comment.substring(2, comment.length() - 2); } else if (comment.startsWith("<!--")) { return comment.substring(4, comment.length() - 3); } else if (comment.startsWith(" return comment.substring(2, comment.length()); } else { throw new IllegalArgumentException("Unknown Less comment type"); } } @Override String getContents(String comment); } | @Test public void content() { assertThat(analyser.getContents("")).isEqualTo("comment"); assertThat(analyser.getContents("")).isEqualTo(" comment "); assertThat(analyser.getContents("<!--comment-->")).isEqualTo("comment"); assertThat(analyser.getContents("<!-- comment -->")).isEqualTo(" comment "); assertThat(analyser.getContents(" assertThat(analyser.getContents(" }
@Test(expected = IllegalArgumentException.class) public void unknown_type_of_comments() { analyser.getContents(""); } |
ScssCommentAnalyser extends CssCommentAnalyser { @Override public String getContents(String comment) { if (comment.startsWith("/*")) { return comment.substring(2, comment.length() - 2); } else if (comment.startsWith(" return comment.substring(2, comment.length()); } else { throw new IllegalArgumentException("Unknown SCSS comment type"); } } @Override String getContents(String comment); } | @Test public void content() { assertThat(analyser.getContents("")).isEqualTo("comment"); assertThat(analyser.getContents("")).isEqualTo(" comment "); assertThat(analyser.getContents(" assertThat(analyser.getContents(" }
@Test(expected = IllegalArgumentException.class) public void unknown_type_of_comments() { analyser.getContents(""); } |
CssCommentAnalyser extends CommentAnalyser { @Override public String getContents(String comment) { if (comment.startsWith("/*")) { return comment.substring(2, comment.length() - 2); } else if (comment.startsWith("<!--")) { return comment.substring(4, comment.length() - 3); } else { throw new IllegalArgumentException(); } } @Override boolean isBlank(String line); @Override String getContents(String comment); } | @Test public void content() { assertThat(analyser.getContents("")).isEqualTo("comment"); assertThat(analyser.getContents("")).isEqualTo(" comment "); assertThat(analyser.getContents("<!--comment-->")).isEqualTo("comment"); assertThat(analyser.getContents("<!-- comment -->")).isEqualTo(" comment "); }
@Test(expected = IllegalArgumentException.class) public void unknown_type_of_comments() { analyser.getContents(""); } |
CssCommentAnalyser extends CommentAnalyser { @Override public boolean isBlank(String line) { for (int i = 0; i < line.length(); i++) { if (Character.isLetterOrDigit(line.charAt(i))) { return false; } } return true; } @Override boolean isBlank(String line); @Override String getContents(String comment); } | @Test public void blank() { assertThat(analyser.isBlank(" ")).isTrue(); assertThat(analyser.isBlank(" ")).isTrue(); } |
CssSyntaxHighlighterVisitor extends SubscriptionVisitor { protected void highlight(SyntaxToken token, TypeOfText type) { highlighting.highlight(token.line(), token.column(), token.endLine(), token.endColumn(), type); } CssSyntaxHighlighterVisitor(SensorContext sensorContext); @Override List<Tree.Kind> nodesToVisit(); @Override void visitFile(Tree tree); @Override void leaveFile(Tree scriptTree); @Override void visitNode(Tree tree); } | @Test public void empty_input() throws Exception { highlight(""); assertThat(sensorContext.highlightingTypeAt("moduleKey:" + file.getName(), 1, 0)).isEmpty(); }
@Test public void string_simple_quote() throws Exception { highlight(".mybox {\nprop: 'string';\n}"); assertHighlighting(2, 6, 8, STRING); }
@Test public void string_double_quote() throws Exception { highlight(".mybox {\nprop: \"string\";\n}"); assertHighlighting(2, 6, 8, STRING); }
@Test public void property() throws Exception { highlight(".mybox {\nprop: \"string\";\n}"); assertHighlighting(2, 0, 4, CONSTANT); }
@Test public void variable() throws Exception { highlight(".mybox {\n--prop: \"string\";\n}"); assertHighlighting(2, 0, 6, CONSTANT); }
@Test public void class_selector() throws Exception { highlight(".mybox {\n--prop: \"string\";\n}"); assertHighlighting(1, 0, 6, KEYWORD_LIGHT); }
@Test public void class_selector2() throws Exception { highlight(".mybox.mybox2 {\n--prop: \"string\";\n}"); assertHighlighting(1, 0, 13, KEYWORD_LIGHT); }
@Test public void id_selector() throws Exception { highlight(" #abc {\n--prop: \"string\";\n}"); assertHighlighting(1, 1, 4, KEYWORD_LIGHT); }
@Test public void comment() throws Exception { highlight(" #abc {\n--prop: \"string\"; \n}"); assertHighlighting(2, 18, 12, COMMENT); }
@Test public void html_comment() throws Exception { highlight(" #abc {\n--prop: \"string\"; <!-- blabla -->\n}"); assertHighlighting(2, 18, 15, COMMENT); }
@Test public void multiline_comment() throws Exception { highlight(""); assertHighlighting(1, 0, 13, COMMENT); assertHighlighting(2, 0, 13, COMMENT); assertHighlighting(3, 1, 13, COMMENT); }
@Test public void byte_order_mark() throws Exception { highlight("\uFEFF#abc {\n--prop: \"string\";\n}"); assertHighlighting(1, 0, 4, KEYWORD_LIGHT); assertHighlighting(2, 0, 4, CONSTANT); } |
LessRulesDefinition implements RulesDefinition { @Override public void define(Context context) { NewRepository repository = context .createRepository(CheckList.LESS_REPOSITORY_KEY, LessLanguage.KEY) .setName(CheckList.LESS_REPOSITORY_NAME); new AnnotationBasedRulesDefinition(repository, LessLanguage.KEY).addRuleClasses(false, CheckList.getLessChecks()); repository.done(); } @Override void define(Context context); } | @Test public void test() { LessRulesDefinition rulesDefinition = new LessRulesDefinition(); RulesDefinition.Context context = new RulesDefinition.Context(); rulesDefinition.define(context); RulesDefinition.Repository repository = context.repository("less"); assertThat(repository.name()).isEqualTo("SonarQube"); assertThat(repository.language()).isEqualTo("less"); assertThat(repository.rules()).hasSize(89); RulesDefinition.Rule rule = repository.rule(DeprecatedEscapingFunctionCheck.class.getAnnotation(Rule.class).key()); assertThat(rule).isNotNull(); assertThat(rule.name()).isEqualTo(DeprecatedEscapingFunctionCheck.class.getAnnotation(Rule.class).name()); } |
LessLanguage extends AbstractLanguage { @Override public String[] getFileSuffixes() { String[] suffixes = settings.getStringArray(Plugin.LESS_FILE_SUFFIXES_KEY); if (suffixes == null || suffixes.length == 0) { suffixes = StringUtils.split(Plugin.LESS_FILE_SUFFIXES_DEFAULT_VALUE, ","); } return suffixes; } LessLanguage(Settings settings); @Override String[] getFileSuffixes(); static final String KEY; static final String NAME; } | @Test public void default_file_suffix() { LessLanguage language = new LessLanguage(mock(Settings.class)); assertThat(language.getFileSuffixes()).containsOnly("less"); }
@Test public void custom_file_suffixes() { Settings settings = new Settings(); settings.setProperty("sonar.less.file.suffixes", "less,less3"); LessLanguage language = new LessLanguage(settings); assertThat(language.getFileSuffixes()).containsOnly("less", "less3"); } |
StandardPropertyFactory { public static StandardProperty getByName(String propertyName) { StandardProperty standardProperty = ALL.get(propertyName.toLowerCase(Locale.ENGLISH)); return standardProperty != null ? standardProperty : new UnknownProperty(propertyName); } private StandardPropertyFactory(); static StandardProperty getByName(String propertyName); static List<StandardProperty> getAll(); } | @Test public void should_return_a_valid_border_property_object() { StandardProperty property = StandardPropertyFactory.getByName("border"); assertEquals(Border.class, property.getClass()); assertEquals("border", property.getName()); assertEquals(2, property.getLinks().size()); assertEquals("https: assertEquals("https: assertEquals(0, property.getVendors().size()); assertFalse(property.isObsolete()); }
@Test public void should_return_a_valid_border_property_object_uppercase_test() { StandardProperty property = StandardPropertyFactory.getByName("BORDER"); assertEquals(Border.class, property.getClass()); assertEquals("border", property.getName()); assertEquals(2, property.getLinks().size()); assertEquals("https: assertEquals("https: assertEquals(0, property.getVendors().size()); assertFalse(property.isObsolete()); }
@Test public void should_return_a_valid_border_end_property_object() { StandardProperty property = StandardPropertyFactory.getByName("border-end"); assertEquals(BorderEnd.class, property.getClass()); assertEquals("border-end", property.getName()); assertEquals(0, property.getLinks().size()); assertEquals(0, property.getValidators().size()); assertEquals(0, property.getVendors().size()); assertTrue(property.isObsolete()); }
@Test public void should_return_a_valid_column_count_object() { StandardProperty property = StandardPropertyFactory.getByName("column-count"); assertEquals(ColumnCount.class, property.getClass()); assertEquals("column-count", property.getName()); assertEquals(2, property.getLinks().size()); assertEquals("http: assertEquals("https: assertEquals(2, property.getValidators().size()); assertEquals(0, property.getVendors().size()); assertFalse(property.isObsolete()); }
@Test public void should_return_an_unknown_property_object() { StandardProperty property = StandardPropertyFactory.getByName("Bla-bla"); assertEquals(UnknownProperty.class, property.getClass()); assertEquals("bla-bla", property.getName()); assertEquals(0, property.getLinks().size()); assertEquals(0, property.getValidators().size()); assertEquals(0, property.getVendors().size()); assertFalse(property.isObsolete()); } |
StandardPropertyFactory { public static List<StandardProperty> getAll() { return new ArrayList<>(ALL.values()); } private StandardPropertyFactory(); static StandardProperty getByName(String propertyName); static List<StandardProperty> getAll(); } | @Test public void number_of_standard_properties() { assertEquals(625, StandardPropertyFactory.getAll().size()); }
@Test public void number_of_experimental_properties() { assertEquals( 339, StandardPropertyFactory .getAll() .stream() .filter(StandardProperty::isExperimental) .collect(Collectors.toList()) .size()); }
@Test public void should_not_find_any_property_set_to_both_obsolete_and_experimental() { assertEquals( 0, StandardPropertyFactory .getAll() .stream() .filter(p -> p.isExperimental() && p.isObsolete()) .collect(Collectors.toList()) .size()); }
@Test public void should_not_find_any_property_set_to_obsolete_with_vendors() { assertEquals( 0, StandardPropertyFactory .getAll() .stream() .filter(p -> p.isObsolete() && p.hasVendors()) .collect(Collectors.toList()) .size()); }
@Test public void should_not_find_any_property_not_set_to_experimental_with_vendors() { assertEquals( 0, StandardPropertyFactory .getAll() .stream() .filter(p -> !p.isExperimental() && p.hasVendors()) .collect(Collectors.toList()) .size()); }
@Test public void should_not_find_any_property_set_to_obsolete_with_validators() { assertEquals( 0, StandardPropertyFactory .getAll() .stream() .filter(p -> p.isObsolete() && p.hasValidators()) .collect(Collectors.toList()) .size()); }
@Test public void should_not_find_any_property_set_to_obsolete_with_shorthand() { assertEquals( 0, StandardPropertyFactory .getAll() .stream() .filter(p -> p.isObsolete() && p.isShorthand()) .collect(Collectors.toList()) .size()); } |
StandardAtRuleFactory { public static StandardAtRule getByName(String atRuleName) { StandardAtRule standardAtRule = ALL.get(atRuleName.toLowerCase(Locale.ENGLISH)); return standardAtRule != null ? standardAtRule : new UnknownAtRule(atRuleName); } private StandardAtRuleFactory(); static StandardAtRule getByName(String atRuleName); static List<StandardAtRule> getAll(); } | @Test public void should_return_a_valid_charset_at_rule_object() { StandardAtRule atRule = StandardAtRuleFactory.getByName("charset"); assertEquals(Charset.class, atRule.getClass()); assertEquals("charset", atRule.getName()); assertEquals(1, atRule.getLinks().size()); assertEquals("https: assertFalse(atRule.isObsolete()); assertFalse(atRule.isExperimental()); }
@Test public void should_return_a_valid_charset_at_rule_object_uppercase_test() { StandardAtRule atRule = StandardAtRuleFactory.getByName("CHARSET"); assertEquals(Charset.class, atRule.getClass()); assertEquals("charset", atRule.getName()); assertEquals(1, atRule.getLinks().size()); assertEquals("https: assertFalse(atRule.isObsolete()); assertFalse(atRule.isExperimental()); }
@Test public void should_return_a_valid_character_variant_at_rule_object() { StandardAtRule atRule = StandardAtRuleFactory.getByName("character-variant"); assertEquals(CharacterVariant.class, atRule.getClass()); assertEquals("character-variant", atRule.getName()); assertEquals(2, atRule.getLinks().size()); assertEquals("https: assertEquals("https: assertFalse(atRule.isObsolete()); assertTrue(atRule.isExperimental()); }
@Test public void should_return_a_valid_keyframes_at_rule_object() { StandardAtRule atRule = StandardAtRuleFactory.getByName("keyframes"); assertEquals(Keyframes.class, atRule.getClass()); assertEquals("keyframes", atRule.getName()); assertEquals(1, atRule.getLinks().size()); assertFalse(atRule.isObsolete()); assertFalse(atRule.isExperimental()); } |
StandardAtRuleFactory { public static List<StandardAtRule> getAll() { return new ArrayList<>(ALL.values()); } private StandardAtRuleFactory(); static StandardAtRule getByName(String atRuleName); static List<StandardAtRule> getAll(); } | @Test public void number_of_standard_at_rules() { assertEquals(37, StandardAtRuleFactory.getAll().size()); }
@Test public void number_of_experimental_standard_at_rules() { assertEquals( 29, StandardAtRuleFactory.getAll() .stream() .filter(StandardAtRule::isExperimental) .collect(Collectors.toList()) .size()); }
@Test public void number_of_obsolete_standard_at_rules() { assertEquals( 0, StandardAtRuleFactory.getAll() .stream() .filter(StandardAtRule::isObsolete) .collect(Collectors.toList()) .size()); } |
StandardFunctionFactory { public static StandardFunction getByName(String functionName) { StandardFunction standardFunction = ALL.get(functionName.toLowerCase(Locale.ENGLISH)); return standardFunction != null ? standardFunction : new UnknownFunction(functionName); } private StandardFunctionFactory(); static StandardFunction getByName(String functionName); static List<StandardFunction> getAll(); } | @Test public void should_return_a_valid_rotatex_function_object() { StandardFunction function = StandardFunctionFactory.getByName("rotatex"); assertEquals(Rotatex.class, function.getClass()); assertEquals("rotatex", function.getName()); assertEquals(1, function.getLinks().size()); assertEquals("https: assertFalse(function.isExperimental()); assertFalse(function.isObsolete()); }
@Test public void should_return_a_valid_rotatex_function_object_uppercase_test() { StandardFunction function = StandardFunctionFactory.getByName("ROTATEX"); assertEquals(Rotatex.class, function.getClass()); assertEquals("rotatex", function.getName()); assertEquals(1, function.getLinks().size()); assertEquals("https: assertFalse(function.isExperimental()); assertFalse(function.isObsolete()); }
@Test public void should_return_a_valid_rotatex_function_object_mix_uppercase_lowercase_test() { StandardFunction function = StandardFunctionFactory.getByName("rotateX"); assertEquals(Rotatex.class, function.getClass()); assertEquals("rotatex", function.getName()); assertEquals(1, function.getLinks().size()); assertEquals("https: assertFalse(function.isExperimental()); assertFalse(function.isObsolete()); }
@Test public void should_return_a_valid_repeating_linear_gradient_function_object() { StandardFunction function = StandardFunctionFactory.getByName("repeating-linear-gradient"); assertEquals(RepeatingLinearGradient.class, function.getClass()); assertEquals("repeating-linear-gradient", function.getName()); assertEquals(1, function.getLinks().size()); assertFalse(function.isExperimental()); assertFalse(function.isObsolete()); }
@Test public void should_return_a_valid_repeating_linear_gradient_function_object_mix_uppercase_lowercase_test() { StandardFunction function = StandardFunctionFactory.getByName("repEating-Linear-gradient"); assertEquals(RepeatingLinearGradient.class, function.getClass()); assertEquals("repeating-linear-gradient", function.getName()); assertEquals(1, function.getLinks().size()); assertFalse(function.isExperimental()); assertFalse(function.isObsolete()); } |
ScssAnalyzerSensor extends AbstractLanguageAnalyzerSensor { @Override public void describe(SensorDescriptor descriptor) { descriptor .onlyOnLanguage(ScssLanguage.KEY) .name("SCSS Analyzer Sensor") .onlyOnFileType(Type.MAIN); } ScssAnalyzerSensor(FileSystem fileSystem, CheckFactory checkFactory, Settings settings, NoSonarFilter noSonarFilter); ScssAnalyzerSensor(FileSystem fileSystem, CheckFactory checkFactory, Settings settings, NoSonarFilter noSonarFilter,
@Nullable CustomScssRulesDefinition[] customRulesDefinition); @Override void describe(SensorDescriptor descriptor); @Override String analyzerName(); @Override String language(); @Override ActionParser<Tree> parser(FileSystem fileSystem); @Override List<InputFile> filesToAnalyze(FileSystem fileSystem); @Override Checks checks(CheckFactory checkFactory, CustomRulesDefinition[] customRulesDefinitions); @Override List<TreeVisitor> treeVisitors(SensorContext sensorContext, Checks checks, NoSonarFilter noSonarFilter); @Override Class parsingErrorCheck(); } | @Test public void should_create_a_valid_sensor_descriptor() { DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor(); createScssSquidSensor().describe(descriptor); assertThat(descriptor.name()).isEqualTo("SCSS Analyzer Sensor"); assertThat(descriptor.languages()).containsOnly("scss"); assertThat(descriptor.type()).isEqualTo(InputFile.Type.MAIN); } |
StandardFunctionFactory { public static List<StandardFunction> getAll() { return new ArrayList<>(ALL.values()); } private StandardFunctionFactory(); static StandardFunction getByName(String functionName); static List<StandardFunction> getAll(); } | @Test public void number_of_standard_css_functions() { assertEquals(154, StandardFunctionFactory.getAll().stream().filter(StandardFunction::isCss).count()); }
@Test public void number_of_standard_less_functions() { assertEquals(83, StandardFunctionFactory.getAll().stream().filter(StandardFunction::isLess).count()); }
@Test public void number_of_obsolete_functions() { assertEquals(71, StandardFunctionFactory.getAll().stream().filter(StandardFunction::isObsolete).count()); }
@Test public void number_of_experimental_functions() { assertEquals(13, StandardFunctionFactory.getAll().stream().filter(StandardFunction::isExperimental).count()); } |
StandardPseudoIdentifierFactory { public static StandardPseudoIdentifier getByName(String identifier) { StandardPseudoIdentifier standardPseudoIdentifier = ALL.get(identifier.toLowerCase(Locale.ENGLISH)); return standardPseudoIdentifier != null ? standardPseudoIdentifier : new UnknownPseudoIdentifier(identifier); } private StandardPseudoIdentifierFactory(); static StandardPseudoIdentifier getByName(String identifier); static List<StandardPseudoIdentifier> getAll(); } | @Test public void should_return_a_valid_first_line_identifier_function_object() { StandardPseudoIdentifier identifier = StandardPseudoIdentifierFactory.getByName("first-line"); assertEquals(FirstLine.class, identifier.getClass()); assertEquals("first-line", identifier.getName()); assertEquals(1, identifier.getLinks().size()); assertEquals("https: assertFalse(identifier.isExperimental()); assertFalse(identifier.isObsolete()); }
@Test public void should_return_a_valid_first_line_pseudo_identifier_object_uppercase_test() { StandardPseudoIdentifier identifier = StandardPseudoIdentifierFactory.getByName("FIRST-LINE"); assertEquals(FirstLine.class, identifier.getClass()); assertEquals("first-line", identifier.getName()); assertEquals(1, identifier.getLinks().size()); assertEquals("https: assertFalse(identifier.isExperimental()); assertFalse(identifier.isObsolete()); }
@Test public void should_return_a_valid_first_line_pseudo_identifier_object_mix_uppercase_lowercase_test() { StandardPseudoIdentifier identifier = StandardPseudoIdentifierFactory.getByName("FIRSt-LINE"); assertEquals(FirstLine.class, identifier.getClass()); assertEquals("first-line", identifier.getName()); assertEquals(1, identifier.getLinks().size()); assertEquals("https: assertFalse(identifier.isExperimental()); assertFalse(identifier.isObsolete()); } |
ScssRulesDefinition implements RulesDefinition { @Override public void define(Context context) { NewRepository repository = context .createRepository(CheckList.SCSS_REPOSITORY_KEY, ScssLanguage.KEY) .setName(CheckList.SCSS_REPOSITORY_NAME); new AnnotationBasedRulesDefinition(repository, ScssLanguage.KEY).addRuleClasses(false, CheckList.getScssChecks()); repository.done(); } @Override void define(Context context); } | @Test public void test() { ScssRulesDefinition rulesDefinition = new ScssRulesDefinition(); RulesDefinition.Context context = new RulesDefinition.Context(); rulesDefinition.define(context); RulesDefinition.Repository repository = context.repository("scss"); assertThat(repository.name()).isEqualTo("SonarQube"); assertThat(repository.language()).isEqualTo("scss"); assertThat(repository.rules()).hasSize(100); RulesDefinition.Rule rule = repository.rule(ScssVariableNamingConventionCheck.class.getAnnotation(Rule.class).key()); assertThat(rule).isNotNull(); assertThat(rule.name()).isEqualTo(ScssVariableNamingConventionCheck.class.getAnnotation(Rule.class).name()); } |
StandardPseudoIdentifierFactory { public static List<StandardPseudoIdentifier> getAll() { return new ArrayList<>(ALL.values()); } private StandardPseudoIdentifierFactory(); static StandardPseudoIdentifier getByName(String identifier); static List<StandardPseudoIdentifier> getAll(); } | @Test public void number_of_standard_pseudo_identifiers() { assertEquals(59, StandardPseudoIdentifierFactory.getAll().size()); }
@Test public void number_of_obsolete_pseudo_identifiers() { assertEquals(1, StandardPseudoIdentifierFactory.getAll().stream().filter(StandardPseudoIdentifier::isObsolete).count()); }
@Test public void number_of_experimental_pseudo_identifiers() { assertEquals(31, StandardPseudoIdentifierFactory.getAll().stream().filter(StandardPseudoIdentifier::isExperimental).count()); } |
StandardPseudoFunctionFactory { public static StandardPseudoFunction getByName(String functionName) { StandardPseudoFunction standardPseudoFunction = ALL.get(functionName.toLowerCase(Locale.ENGLISH)); return standardPseudoFunction != null ? standardPseudoFunction : new UnknownPseudoFunction(functionName); } private StandardPseudoFunctionFactory(); static StandardPseudoFunction getByName(String functionName); static List<StandardPseudoFunction> getAll(); } | @Test public void should_return_a_valid_has_pseudo_function_object() { StandardPseudoFunction function = StandardPseudoFunctionFactory.getByName("has"); assertEquals(Has.class, function.getClass()); assertEquals("has", function.getName()); assertEquals(1, function.getLinks().size()); assertEquals("https: assertTrue(function.isExperimental()); assertFalse(function.isObsolete()); }
@Test public void should_return_a_valid_has_pseudo_function_object_uppercase_test() { StandardPseudoFunction function = StandardPseudoFunctionFactory.getByName("HAS"); assertEquals(Has.class, function.getClass()); assertEquals("has", function.getName()); assertEquals(1, function.getLinks().size()); assertEquals("https: assertTrue(function.isExperimental()); assertFalse(function.isObsolete()); }
@Test public void should_return_a_valid_has_pseudo_function_object_mix_uppercase_lowercase_test() { StandardPseudoFunction function = StandardPseudoFunctionFactory.getByName("HaS"); assertEquals(Has.class, function.getClass()); assertEquals("has", function.getName()); assertEquals(1, function.getLinks().size()); assertEquals("https: assertTrue(function.isExperimental()); assertFalse(function.isObsolete()); } |
StandardPseudoFunctionFactory { public static List<StandardPseudoFunction> getAll() { return new ArrayList<>(ALL.values()); } private StandardPseudoFunctionFactory(); static StandardPseudoFunction getByName(String functionName); static List<StandardPseudoFunction> getAll(); } | @Test public void number_of_standard_pseudo_functions() { assertEquals(19, StandardPseudoFunctionFactory.getAll().size()); }
@Test public void number_of_obsolete_pseudo_functions() { assertEquals(1, StandardPseudoFunctionFactory.getAll().stream().filter(StandardPseudoFunction::isObsolete).count()); }
@Test public void number_of_experimental_pseudo_functions() { assertEquals(10, StandardPseudoFunctionFactory.getAll().stream().filter(StandardPseudoFunction::isExperimental).count()); } |
ScssLanguage extends AbstractLanguage { @Override public String[] getFileSuffixes() { String[] suffixes = settings.getStringArray(Plugin.SCSS_FILE_SUFFIXES_KEY); if (suffixes == null || suffixes.length == 0) { suffixes = StringUtils.split(Plugin.SCSS_FILE_SUFFIXES_DEFAULT_VALUE, ","); } return suffixes; } ScssLanguage(Settings settings); @Override String[] getFileSuffixes(); static final String KEY; static final String NAME; } | @Test public void default_file_suffix() { ScssLanguage language = new ScssLanguage(mock(Settings.class)); assertThat(language.getFileSuffixes()).containsOnly("scss"); }
@Test public void custom_file_suffixes() { Settings settings = new Settings(); settings.setProperty("sonar.scss.file.suffixes", "scss,scss3"); ScssLanguage language = new ScssLanguage(settings); assertThat(language.getFileSuffixes()).containsOnly("scss", "scss3"); } |
StandardPseudoComponentFactory { public static List<? extends StandardPseudoComponent> getAll() { return Stream .concat(StandardPseudoIdentifierFactory.getAll().stream(), StandardPseudoFunctionFactory.getAll().stream()) .collect(Collectors.toList()); } private StandardPseudoComponentFactory(); static List<? extends StandardPseudoComponent> getAll(); } | @Test public void number_of_standard_pseudo_components() { assertEquals(78, StandardPseudoComponentFactory.getAll().size()); } |
ExperimentalNotLessFunctionCheck extends DoubleDispatchVisitorCheck { @VisibleForTesting void setFunctionsToExclude(String functionsToExclude) { this.functionsToExclude = functionsToExclude; } @Override void visitFunction(FunctionTree tree); @Override void validateParameters(); } | @Test public void test_exclude_functions() { ExperimentalNotLessFunctionCheck check = new ExperimentalNotLessFunctionCheck(); check.setFunctionsToExclude("conic-gradient|count.*"); CssCheckVerifier.verifyLessFile(check, CheckTestUtils.getLessTestFile("experimentalFunctionUsageExcludeFunctions.less")); }
@Test public void should_throw_an_illegal_state_exception_as_the_functionsToExclude_parameter_is_not_valid() { try { ExperimentalNotLessFunctionCheck check = new ExperimentalNotLessFunctionCheck(); check.setFunctionsToExclude("("); CssCheckVerifier.issuesOnLessFile(check, CheckTestUtils.getLessTestFile("experimentalFunctionUsage.less")).noMore(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Check less:experimental-not-less-function-usage (Experimental functions should not be used): " + "functionsToExclude parameter \"(\" is not a valid regular expression."); } } |
LessVariableNamingConventionCheck extends DoubleDispatchVisitorCheck { @VisibleForTesting void setFormat(String format) { this.format = format; } @Override void visitLessVariableDeclaration(LessVariableDeclarationTree tree); @Override void validateParameters(); } | @Test public void test_with_default_format() { check.setFormat("^[a-z][-a-z0-9]*$"); CssCheckVerifier.verifyLessFile(check, CheckTestUtils.getLessTestFile("lessVariableNamingConvention.less")); }
@Test public void test_with_custom_format() { check.setFormat("^[-a-z]+$"); CssCheckVerifier.verifyLessFile(check, CheckTestUtils.getLessTestFile("lessVariableNamingConventionCustomFormat.less")); }
@Test public void should_throw_an_illegal_state_exception_as_the_format_parameter_is_not_valid() { try { check.setFormat("("); CssCheckVerifier.issuesOnLessFile(check, CheckTestUtils.getLessTestFile("lessVariableNamingConvention.less")).noMore(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Check less:less-variable-naming-convention (Less variables should follow a naming convention): " + "format parameter \"(\" is not a valid regular expression."); } } |
NestedRulesetsCheck extends DoubleDispatchVisitorCheck { @VisibleForTesting void setMax(int max) { this.max = max; } @Override void visitStyleSheet(StyleSheetTree tree); @Override void visitRuleset(RulesetTree tree); } | @Test public void test_with_custom_threshold() { NestedRulesetsCheck check = new NestedRulesetsCheck(); check.setMax(2); CssCheckVerifier.verifyLessFile(check, CheckTestUtils.getLessTestFile("nestedRulesets/nestedRulesetsCustomThreshold.less")); }
@Test public void test_with_custom_threshold() { NestedRulesetsCheck check = new NestedRulesetsCheck(); check.setMax(2); CssCheckVerifier.verifyScssFile(check, CheckTestUtils.getScssTestFile("nested-rulesets/nestedRulesetsCustomThreshold.scss")); } |
TooComplexConditionCheck extends DoubleDispatchVisitorCheck { @VisibleForTesting void setMax(int max) { this.max = max; } @Override void visitScssCondition(ScssConditionTree tree); } | @Test public void test_custom_threshold() { TooComplexConditionCheck check = new TooComplexConditionCheck(); check.setMax(4); CssCheckVerifier.verifyScssFile( check, CheckTestUtils.getScssTestFile("too-complex-condition/tooComplexConditionCustom.scss")); } |
CustomFunctionNamingConventionCheck extends DoubleDispatchVisitorCheck { @VisibleForTesting void setFormat(String format) { this.format = format; } @Override void visitScssFunction(ScssFunctionTree tree); @Override void validateParameters(); } | @Test public void test_with_default_format() { check.setFormat("^[a-z][-a-z0-9]*$"); CssCheckVerifier.verifyScssFile(check, CheckTestUtils.getScssTestFile("custom-function-naming-convention/customFunctionNamingConvention.scss")); }
@Test public void test_with_custom_format() { check.setFormat("^[-a-z]+$"); CssCheckVerifier.verifyScssFile(check, CheckTestUtils.getScssTestFile("custom-function-naming-convention/customFunctionNamingConventionCustomFormat.scss")); }
@Test public void should_throw_an_illegal_state_exception_as_the_format_parameter_is_not_valid() { try { check.setFormat("("); CssCheckVerifier.issuesOnScssFile(check, CheckTestUtils.getScssTestFile("custom-function-naming-convention/customFunctionNamingConvention.scss")).noMore(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Check scss:custom-function-naming-convention (Custom functions should follow a naming convention): " + "format parameter \"(\" is not a valid regular expression."); } } |
PlaceholderSelectorNamingConventionCheck extends DoubleDispatchVisitorCheck { @VisibleForTesting void setFormat(String format) { this.format = format; } @Override void visitScssPlaceholderSelector(ScssPlaceholderSelectorTree tree); @Override void validateParameters(); } | @Test public void test_with_default_format() { check.setFormat("^[a-z][-a-z0-9]*$"); CssCheckVerifier.verifyScssFile(check, getTestFile("selectorNamingConvention.scss")); }
@Test public void test_with_custom_format() { check.setFormat("^[-a-z]+$"); CssCheckVerifier.verifyScssFile(check, getTestFile("selectorNamingConventionCustomFormat.scss")); }
@Test public void should_throw_an_illegal_state_exception_as_the_format_parameter_is_not_valid() { try { check.setFormat("("); CssCheckVerifier.issuesOnScssFile(check, CheckTestUtils.getCommonTestFile("selectorNamingConvention/selectorNamingConvention.css")).noMore(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Check scss:placeholder-selector-naming-convention (Placeholder selectors should follow a naming convention): " + "format parameter \"(\" is not a valid regular expression."); } } |
MixinNamingConventionCheck extends DoubleDispatchVisitorCheck { @VisibleForTesting void setFormat(String format) { this.format = format; } @Override void visitScssMixin(ScssMixinTree tree); @Override void validateParameters(); } | @Test public void test_with_default_format() { check.setFormat("^[a-z][-a-z0-9]*$"); CssCheckVerifier.verifyScssFile(check, CheckTestUtils.getScssTestFile("mixin-naming-convention/mixinNamingConvention.scss")); }
@Test public void test_with_custom_format() { check.setFormat("^[-a-z]+$"); CssCheckVerifier.verifyScssFile(check, CheckTestUtils.getScssTestFile("mixin-naming-convention/mixinNamingConventionCustomFormat.scss")); }
@Test public void should_throw_an_illegal_state_exception_as_the_format_parameter_is_not_valid() { try { check.setFormat("("); CssCheckVerifier.issuesOnScssFile(check, CheckTestUtils.getScssTestFile("mixin-naming-convention/mixinNamingConvention.scss")).noMore(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Check scss:mixin-naming-convention (Mixins should follow a naming convention): " + "format parameter \"(\" is not a valid regular expression."); } } |
NestedControlFlowDirectivesCheck extends DoubleDispatchVisitorCheck { @VisibleForTesting void setMax(int max) { this.max = max; } @Override void visitStyleSheet(StyleSheetTree tree); @Override void visitScssIf(ScssIfTree tree); @Override void visitScssElseIf(ScssElseIfTree tree); @Override void visitScssElse(ScssElseTree tree); @Override void visitScssFor(ScssForTree tree); @Override void visitScssWhile(ScssWhileTree tree); @Override void visitScssEach(ScssEachTree tree); } | @Test public void test_with_custom_format() { NestedControlFlowDirectivesCheck check = new NestedControlFlowDirectivesCheck(); check.setMax(2); CssCheckVerifier.verifyScssFile( check, CheckTestUtils.getScssTestFile("nested-control-flow-directives/nestedControlFlowDirectivesCustomThreshold.scss")); } |
ScssProfile extends ProfileDefinition { @Override public RulesProfile createProfile(ValidationMessages messages) { AnnotationBasedProfileBuilder annotationBasedProfileBuilder = new AnnotationBasedProfileBuilder(ruleFinder); return annotationBasedProfileBuilder.build( CheckList.SCSS_REPOSITORY_KEY, SONARQUBE_WAY_PROFILE_NAME, ScssLanguage.KEY, CheckList.getScssChecks(), messages); } ScssProfile(RuleFinder ruleFinder); @Override RulesProfile createProfile(ValidationMessages messages); static final String SONARQUBE_WAY_PROFILE_NAME; } | @Test public void should_create_sonarqube_way_profile() { ValidationMessages validation = ValidationMessages.create(); ScssProfile definition = new ScssProfile(universalRuleFinder()); RulesProfile profile = definition.createProfile(validation); assertThat(profile.getName()).isEqualTo("SonarQube Way"); assertThat(profile.getLanguage()).isEqualTo("scss"); assertThat(profile.getActiveRulesByRepository("scss")).hasSize(84); assertThat(validation.hasErrors()).isFalse(); } |
StableTicksAxis extends ValueAxis<Number> { public static double calculateTickSpacing( double delta, int maxTicks ) { if ( delta == 0.0 ) return 0.0; if ( delta <= 0.0 ) throw new IllegalArgumentException( "delta must be positive" ); if ( maxTicks < 1 ) throw new IllegalArgumentException( "must be at least one tick" ); int factor = (int) Math.log10( delta ); int divider = 0; double numTicks = delta / ( dividers[divider] * Math.pow( 10, factor ) ); if ( numTicks < maxTicks ) { while ( numTicks < maxTicks ) { --divider; if ( divider < 0 ) { --factor; divider = dividers.length - 1; } numTicks = delta / ( dividers[divider] * Math.pow( 10, factor ) ); } if ( numTicks != maxTicks ) { ++divider; if ( divider >= dividers.length ) { ++factor; divider = 0; } } } else { while ( numTicks > maxTicks ) { ++divider; if ( divider >= dividers.length ) { ++factor; divider = 0; } numTicks = delta / ( dividers[divider] * Math.pow( 10, factor ) ); } } return dividers[divider] * Math.pow( 10, factor ); } StableTicksAxis(); StableTicksAxis( double lowerBound, double upperBound ); AxisTickFormatter getAxisTickFormatter(); void setAxisTickFormatter( AxisTickFormatter axisTickFormatter ); double getAutoRangePadding(); DoubleProperty autoRangePaddingProperty(); void setAutoRangePadding( double autoRangePadding ); boolean isForceZeroInRange(); BooleanProperty forceZeroInRangeProperty(); void setForceZeroInRange( boolean forceZeroInRange ); static double calculateTickSpacing( double delta, int maxTicks ); } | @Test public void testCalculateTickSpacing() { assertEquals( 1.0, StableTicksAxis.calculateTickSpacing( 3.0, 5 ), 0.0001 ); assertEquals( 2.5, StableTicksAxis.calculateTickSpacing( 9.0, 5 ), 0.0001 ); assertEquals( 2.5, StableTicksAxis.calculateTickSpacing( 10.0, 5 ), 0.0001 ); assertEquals( 2.5, StableTicksAxis.calculateTickSpacing( 11.0, 5 ), 0.0001 ); assertEquals( 5.0, StableTicksAxis.calculateTickSpacing( 14.0, 5 ), 0.0001 ); assertEquals( 10.0, StableTicksAxis.calculateTickSpacing( 50.0, 5 ), 0.0001 ); assertEquals( 0.5, StableTicksAxis.calculateTickSpacing( 2.5, 5 ), 0.0001 ); assertEquals( 0.5 * 10000, StableTicksAxis.calculateTickSpacing( 2.5 * 10000, 5 ), 0.0001 ); }
@Test public void testCalculateTickSpacingHuge() { assertEquals( 5e10, StableTicksAxis.calculateTickSpacing( 23e10, 5 ), 0.0001e10 ); }
@Test public void testCalculateTickSpacingTiny() { assertEquals( 5e-10, StableTicksAxis.calculateTickSpacing( 23e-10, 5 ), 0.001e-10 ); } |
HystrixS3Decorator extends S3Decorator { public static HystrixS3Decorator decorate(AmazonS3 s3) { return decorate(s3, defaultSetter(s3)); } private HystrixS3Decorator(AmazonS3 delegate, Setter setter); static HystrixS3Decorator decorate(AmazonS3 s3); static HystrixS3Decorator decorate(AmazonS3 s3, Setter setter); } | @Test public void succeedingClientWorks() { AmazonS3 s3 = HystrixS3Decorator.decorate(new SucceedingS3Client()); assertThat(s3.getObjectMetadata("test-bucket", "test-key")).isNotNull(); }
@Test public void itShortCircuitsFailingClientEventually() throws InterruptedException { AmazonS3 s3 = HystrixS3Decorator.decorate(new FailingS3Client()); for (int i = 0; i < 100; i++ ) { try { s3.getObjectMetadata("test-bucket", "test-key"); } catch (AmazonServiceException e) { assertThat(e.getStatusCode()).isEqualTo(500); } catch (HystrixRuntimeException e) { assertThat(e.getFailureType()).isEqualTo(FailureType.SHORTCIRCUIT); return; } Thread.sleep(50); } fail("Hystrix never short-circuited"); }
@Test public void itDoesntCount404AsFailure() throws InterruptedException { AmazonS3 s3 = HystrixS3Decorator.decorate(new MissingS3Client()); for (int i = 0; i < 100; i++ ) { try { s3.getObjectMetadata("test-bucket", "test-key"); } catch (AmazonServiceException e) { assertThat(e.getStatusCode()).isEqualTo(404); } Thread.sleep(50); } }
@Test public void itDoesntCount403AsFailure() throws InterruptedException { AmazonS3 s3 = HystrixS3Decorator.decorate(new NotAuthedS3Client()); for (int i = 0; i < 100; i++ ) { try { s3.getObjectMetadata("test-bucket", "test-key"); } catch (AmazonServiceException e) { assertThat(e.getStatusCode()).isEqualTo(403); } Thread.sleep(50); } } |
FailsafeS3Decorator extends S3Decorator { public static FailsafeS3Decorator decorate(AmazonS3 s3) { return decorate(s3, defaultCircuitBreaker()); } private FailsafeS3Decorator(AmazonS3 delegate, CircuitBreaker circuitBreaker); static FailsafeS3Decorator decorate(AmazonS3 s3); static FailsafeS3Decorator decorate(AmazonS3 s3, CircuitBreaker circuitBreaker); } | @Test public void succeedingClientWorks() throws InterruptedException { AmazonS3 s3 = FailsafeS3Decorator.decorate(new SucceedingS3Client()); assertThat(s3.getObjectMetadata("test-bucket", "test-key")).isNotNull(); }
@Test public void itShortCircuitsFailingClientEventually() throws InterruptedException { AmazonS3 s3 = FailsafeS3Decorator.decorate(new FailingS3Client()); for (int i = 0; i < 100; i++ ) { try { s3.getObjectMetadata("test-bucket", "test-key"); } catch (AmazonServiceException e) { assertThat(e.getStatusCode()).isEqualTo(500); } catch (CircuitBreakerOpenException e) { return; } Thread.sleep(50); } fail("Failsafe never short-circuited"); }
@Test public void itDoesntCount404AsFailure() throws InterruptedException { AmazonS3 s3 = FailsafeS3Decorator.decorate(new MissingS3Client()); for (int i = 0; i < 100; i++ ) { try { s3.getObjectMetadata("test-bucket", "test-key"); } catch (AmazonServiceException e) { assertThat(e.getStatusCode()).isEqualTo(404); } Thread.sleep(50); } }
@Test public void itDoesntCount403AsFailure() throws InterruptedException { AmazonS3 s3 = FailsafeS3Decorator.decorate(new NotAuthedS3Client()); for (int i = 0; i < 100; i++ ) { try { s3.getObjectMetadata("test-bucket", "test-key"); } catch (AmazonServiceException e) { assertThat(e.getStatusCode()).isEqualTo(403); } Thread.sleep(50); } } |
SizeUnitTypeAdapter extends TypeAdapter<SizeUnit> { @Override public void write(final JsonWriter out, final SizeUnit value) throws IOException { out.value(value.toString().toLowerCase(Locale.US)); } @Override void write(final JsonWriter out, final SizeUnit value); @Override SizeUnit read(final JsonReader in); } | @Test public void write() throws IOException { final JsonWriter writer = mock(JsonWriter.class); this.typeAdapter.write(writer, SizeUnit.BYTES); verify(writer).value("bytes"); } |
RequestSupplier implements Supplier<Request> { @Override public Request get() { final Map<String, String> requestContext = Maps.newHashMap(); for (final Function<Map<String, String>, String> function : this.context) { function.apply(requestContext); } if (this.delimiter != null) { this.delimiter.apply(requestContext); } if (this.container != null) { this.container.apply(requestContext); } if (this.credentials != null) { Credential credential = this.credentials.apply(requestContext); String username = credential.getUsername(); String password = credential.getPassword(); String keystoneToken = credential.getKeystoneToken(); String IAMToken = credential.getIAMToken(); String storageAccountName = credential.getStorageAccountName(); if(username != null) requestContext.put(Context.X_OG_USERNAME, username); if(password != null) requestContext.put(Context.X_OG_PASSWORD, password); if(keystoneToken != null) requestContext.put(Context.X_OG_KEYSTONE_TOKEN, keystoneToken); if(IAMToken != null) requestContext.put(Context.X_OG_IAM_TOKEN, IAMToken); if(storageAccountName != null) { requestContext.put(Context.X_OG_STORAGE_ACCOUNT_NAME, storageAccountName); } } if (this.sseSourceContext != null) { for (final Function<Map<String, String>, String> function : this.sseSourceContext) { function.apply(requestContext); } } Function<Map<String, String>, String> legalholdFunction; if (this.legalHold != null) { legalholdFunction = this.legalHold.get(); if (legalholdFunction != null) { legalholdFunction.apply(requestContext); } } if (this.staticWebsiteVirtualHostSuffix != null) { this.staticWebsiteVirtualHostSuffix.apply(requestContext); } URI uri = getUrl(requestContext); final HttpRequest.Builder builder = new HttpRequest.Builder(this.method, uri, this.operation); for (final Map.Entry<String, Function<Map<String, String>, String>> header : this.headers .entrySet()) { String key = header.getKey(); String value = header.getValue().apply(requestContext); builder.withHeader(key, value); } if (this.retention != null) { this.retention.apply(requestContext); if (this.operation != Operation.EXTEND_RETENTION) { if (requestContext.get(Context.X_OG_OBJECT_RETENTION) != null) { builder.withHeader(Context.X_OG_OBJECT_RETENTION, requestContext.get(Context.X_OG_OBJECT_RETENTION)); } } else { if (requestContext.get(Context.X_OG_OBJECT_RETENTION_EXT) != null) { builder.withHeader(Context.X_OG_OBJECT_RETENTION_EXT, requestContext.get(Context.X_OG_OBJECT_RETENTION_EXT)); } } } if (requestContext.get(Context.X_OG_LEGAL_HOLD) != null) { builder.withHeader(Context.X_OG_LEGAL_HOLD, requestContext.get(Context.X_OG_LEGAL_HOLD)); } if (requestContext.get(Context.X_OG_STATIC_WEBSITE_VIRTUAL_HOST_SUFFIX) != null) { builder.withHeader("Host", requestContext.get(Context.X_OG_CONTAINER_NAME).concat(".") .concat(requestContext.get(Context.X_OG_STATIC_WEBSITE_VIRTUAL_HOST_SUFFIX))); } if (this.id != null) { builder.withContext(Context.X_OG_REQUEST_ID, this.id.apply(requestContext)); } for (final Map.Entry<String, String> entry : requestContext.entrySet()) { builder.withContext(entry.getKey(), entry.getValue()); } if (this.body != null) { Body body = this.body.apply(requestContext); builder.withBody(body); if (this.contentMd5) { try { Long size = body.getSize(); byte[] md5; if (this.operation == Operation.PUT_CONTAINER_LIFECYCLE || this.operation == Operation.PUT_CONTAINER_PROTECTION || this.operation == Operation.MULTI_DELETE) { builder.withHeader(Context.X_OG_CONTENT_MD5, BaseEncoding.base64().encode(Hashing.md5() .newHasher() .putString(body.getContent(), Charsets.UTF_8).hash().asBytes())); } else { md5 = md5ContentCache.get(size); builder.withHeader(Context.X_OG_CONTENT_MD5, BaseEncoding.base64().encode(md5)); } } catch (Exception e) { _logger.error(e.getMessage()); } } } String queryParameters = uri.getQuery(); if (queryParameters != null) { String[] params = queryParameters.split("&"); for (String s: params) { String[] keyValue = s.split("="); String key = s.split("=")[0]; if (keyValue.length > 1) { String value = s.split("=")[1]; builder.withQueryParameter(keyValue[0], keyValue[1]); } else { builder.withQueryParameter(keyValue[0], ""); } if (this.operation == Operation.LIST && key.equals(QueryParameters.S3_LIST_MAX_KEYS)) { builder.withContext(Context.X_OG_LIST_MAX_KEYS, keyValue[1]); } } } if (this.operation == Operation.MULTI_DELETE) { builder.withContext(Context.X_OG_RESPONSE_BODY_CONSUMER, "s3.multi_delete"); } return builder.build(); } RequestSupplier(final Operation operation, final Function<Map<String, String>, String> id,
final Method method, final Scheme scheme, final Function<Map<String, String>, String> host,
final Integer port, final String uriRoot, final Function<Map<String, String>, String> container,
final String apiVersion,
final Function<Map<String, String>, String> object,
final Map<String, Function<Map<String, String>, String>> queryParameters,
final boolean trailingSlash, final Map<String, Function<Map<String, String>, String>> headers,
final List<Function<Map<String, String>, String>> context,
final List<Function<Map<String, String>, String>> sseSourceContext,
final Function<Map<String, String>, Credential> credentials,
final Function<Map<String, String>, Body> body, final boolean virtualHost,
final Function<Map<String, String>, Long> retention,
final Supplier<Function<Map<String, String>, String>> legalHold,
final boolean contentMd5, final Function<Map<String, String>, String> delimiter,
final Function<Map<String, String>, String> staticWebsiteVirtualHostSuffix); @Override Request get(); @Override String toString(); } | @Test public void createRequestSupplierWithObjectURIRootVirtualHostStyleTest() throws URISyntaxException { final String objectName = "s3/test.txt"; final URI uri = new URI("http: final RequestSupplier request = createRequestSupplier(true, this.vaultName, this.hostName, null, objectName, null, false, null); final Request req = request.get(); Assert.assertNotNull(req); Assert.assertEquals(Method.PUT, req.getMethod()); Assert.assertEquals(uri, req.getUri()); }
@Test public void createRequestSupplierWithoutObjectVirtualHostStyleTest() throws URISyntaxException { final String objectName = null; final URI uri = new URI("http: final RequestSupplier request = createRequestSupplier(true, this.vaultName, this.hostName, null, objectName, null, this.trailingSlash, null); final Request req = request.get(); Assert.assertNotNull(req); Assert.assertEquals(Method.PUT, req.getMethod()); Assert.assertEquals(uri, req.getUri()); }
@Test public void createRequestSupplierWithoutObjectAndTrailingSlashVirtualHostStyleTest() throws URISyntaxException { final String objectName = null; final URI uri = new URI("http: final RequestSupplier request = createRequestSupplier(true, this.vaultName, this.hostName, null, objectName, null, false, null); final Request req = request.get(); Assert.assertNotNull(req); Assert.assertEquals(Method.PUT, req.getMethod()); Assert.assertEquals(uri, req.getUri()); }
@Test public void createRequestSupplierWithURIRootVirtualHostStyleTest() throws URISyntaxException { final String objectName = null; final URI uri = new URI("http: final RequestSupplier request = createRequestSupplier(true, this.vaultName, this.hostName, null, objectName, this.uriRoot, this.trailingSlash, null); final Request req = request.get(); Assert.assertNotNull(req); Assert.assertEquals(Method.PUT, req.getMethod()); Assert.assertEquals(uri, req.getUri()); }
@Test public void createRequestSupplierWithStaticWebsiteRead() throws URISyntaxException { final String objectName = "cafebeef0000"; final URI uri = new URI("http: Function<Map<String, String>, String> staticHostSuffix = new Function<Map<String, String>, String>() { @Nullable @Override public String apply(@Nullable Map<String, String> input) { final String suffix = "ibm.com"; input.put(Context.X_OG_STATIC_WEBSITE_VIRTUAL_HOST_SUFFIX, suffix); return suffix; } }; final RequestSupplier request = createRequestSupplier(false, this.vaultName, this.hostName, null, objectName, null, false, staticHostSuffix); final Request req = request.get(); Assert.assertNotNull(req); Assert.assertEquals(Method.GET, req.getMethod()); Assert.assertEquals(uri, req.getUri()); }
@Test public void createRequestSupplierPathStyleTest() throws URISyntaxException { final URI uri = new URI("http: final RequestSupplier request = createRequestSupplier(false, this.vaultName, this.hostName, null, this.objectName, null, false, null); final Request req = request.get(); Assert.assertNotNull(req); Assert.assertEquals(Method.PUT, req.getMethod()); Assert.assertEquals(uri, req.getUri()); }
@Test public void createRequestSupplierWithUriRootPathStyleTest() throws URISyntaxException { final URI uri = new URI("http: + this.vaultName + "/" + this.objectName); final RequestSupplier request = createRequestSupplier(false, this.vaultName, this.hostName, null, this.objectName, this.uriRoot, false, null); final Request req = request.get(); Assert.assertNotNull(req); Assert.assertEquals(Method.PUT, req.getMethod()); Assert.assertEquals(uri, req.getUri()); }
@Test public void createRequestSupplierWithoutObjectPathStyleTest() throws URISyntaxException { final String objectName = null; final URI uri = new URI("http: final RequestSupplier request = createRequestSupplier(false, this.vaultName, this.hostName, null, objectName, this.uriRoot, this.trailingSlash, null); final Request req = request.get(); Assert.assertNotNull(req); Assert.assertEquals(Method.PUT, req.getMethod()); Assert.assertEquals(uri, req.getUri()); }
@Test public void createRequestSupplierWithoutObjectAndUriRootPathStyleTest() throws URISyntaxException { final String objectName = null; final String uriRoot = null; final URI uri = new URI("http: final RequestSupplier request = createRequestSupplier(false, this.vaultName, this.hostName, null, objectName, uriRoot, this.trailingSlash, null); final Request req = request.get(); Assert.assertNotNull(req); Assert.assertEquals(Method.PUT, req.getMethod()); Assert.assertEquals(uri, req.getUri()); }
@Test public void createRequestSupplierVirtualHostStyleTest() throws URISyntaxException { final URI uri = new URI("http: final RequestSupplier request = createRequestSupplier(true, this.vaultName, this.hostName, null, this.objectName, null, false, null); final Request req = request.get(); Assert.assertNotNull(req); Assert.assertEquals(Method.PUT, req.getMethod()); Assert.assertEquals(uri, req.getUri()); } |
ReadObjectNameFunction implements Function<Map<String, String>, String> { @Override public String apply(final Map<String, String> context) { final ObjectMetadata objectMetadata = this.objectManager.get(); context.put(Context.X_OG_OBJECT_NAME, objectMetadata.getName()); context.put(Context.X_OG_OBJECT_SIZE, String.valueOf(objectMetadata.getSize())); context.put(Context.X_OG_CONTAINER_SUFFIX, String.valueOf(objectMetadata.getContainerSuffix())); context.put(Context.X_OG_LEGAL_HOLD_SUFFIX, String.valueOf(objectMetadata.getNumberOfLegalHolds())); context.put(Context.X_OG_OBJECT_RETENTION, String.valueOf(objectMetadata.getRetention())); return objectMetadata.getName(); } ReadObjectNameFunction(final ObjectManager objectManager); @Override String apply(final Map<String, String> context); @Override String toString(); } | @Test public void readObjectNameSupplier() { final String object = "objectName"; final ObjectMetadata objectName = mock(ObjectMetadata.class); when(objectName.getName()).thenReturn(object); when(this.objectManager.get()).thenReturn(objectName); final Map<String, String> context = Maps.newHashMap(); assertThat(new ReadObjectNameFunction(this.objectManager).apply(context), is(object)); assertThat(context.get(Context.X_OG_OBJECT_NAME), is(object)); }
@Test(expected = ObjectManagerException.class) public void supplierException() { when(this.objectManager.get()).thenThrow(new ObjectManagerException()); new ReadObjectNameFunction(this.objectManager).apply(Maps.<String, String>newHashMap()); } |
ThrottledInputStream extends FilterInputStream { private void throttle(final int bytes) { if (bytes == 1) { this.rateLimiter.acquire(); } else if (bytes > 1) { this.rateLimiter.acquire(bytes - 1); this.rateLimiter.acquire(); } } ThrottledInputStream(final InputStream in, final long bytesPerSecond); @Override int read(); @Override int read(final byte[] b); @Override int read(final byte[] b, final int off, final int len); @Override String toString(); } | @Test @UseDataProvider("provideInvalidThrottleInputStream") public void invalidInputStream(final InputStream in, final long bytesPerSecond, final Class<Exception> expectedException) { this.thrown.expect(expectedException); Streams.throttle(in, bytesPerSecond); } |
Suppliers { public static <T> Supplier<T> of(final T value) { checkNotNull(value); return new Supplier<T>() { @Override public T get() { return value; } @Override public String toString() { return value.toString(); } }; } private Suppliers(); static Supplier<T> of(final T value); static Supplier<T> cycle(final List<T> values); static Supplier<Long> cycle(final long minValue, final long maxValue); static RandomSupplier.Builder<T> random(); static Supplier<Long> random(final long minValue, final long maxValue); } | @Test(expected = NullPointerException.class) public void nullOf() { Suppliers.of(null); }
@Test public void of() { final Supplier<Integer> s = Suppliers.of(1); for (int i = 0; i < 10; i++) { assertThat(s.get(), is(1)); } } |
Suppliers { public static <T> Supplier<T> cycle(final List<T> values) { final List<T> copy = ImmutableList.copyOf(values); checkArgument(!copy.isEmpty(), "values must not be empty"); final Iterator<T> it = Iterators.cycle(copy); return new Supplier<T>() { @Override public T get() { return it.next(); } @Override public String toString() { return String.format("cycle %s", copy); } }; } private Suppliers(); static Supplier<T> of(final T value); static Supplier<T> cycle(final List<T> values); static Supplier<Long> cycle(final long minValue, final long maxValue); static RandomSupplier.Builder<T> random(); static Supplier<Long> random(final long minValue, final long maxValue); } | @Test(expected = NullPointerException.class) public void nullCycle() { Suppliers.cycle(null); }
@Test(expected = NullPointerException.class) public void nullCycleElement() { final List<Integer> list = Lists.newArrayList(); list.add(null); Suppliers.cycle(list); }
@Test public void cycleModification() { final List<Integer> list = Lists.newArrayList(); list.add(1); list.add(2); final Supplier<Integer> p = Suppliers.cycle(list); list.add(3); for (int i = 0; i < 10; i++) { assertThat(p.get(), is(1)); assertThat(p.get(), is(2)); } }
@Test(expected = IllegalArgumentException.class) public void cycleNegativeMinValue() { Suppliers.cycle(-1, 100); }
@Test(expected = IllegalArgumentException.class) public void cycleMaxValueLessThanMinValue() { Suppliers.cycle(10, 9); }
@Test public void cycleMinValueMaxValue() { final Supplier<Long> cycle = Suppliers.cycle(0, 3); assertThat(cycle.get(), is(0L)); assertThat(cycle.get(), is(1L)); assertThat(cycle.get(), is(2L)); assertThat(cycle.get(), is(3L)); assertThat(cycle.get(), is(0L)); assertThat(cycle.get(), is(1L)); } |
Suppliers { public static <T> RandomSupplier.Builder<T> random() { return new RandomSupplier.Builder<T>(); } private Suppliers(); static Supplier<T> of(final T value); static Supplier<T> cycle(final List<T> values); static Supplier<Long> cycle(final long minValue, final long maxValue); static RandomSupplier.Builder<T> random(); static Supplier<Long> random(final long minValue, final long maxValue); } | @Test(expected = IllegalArgumentException.class) public void randomNegativeMinValue() { Suppliers.random(-1, 100); }
@Test(expected = IllegalArgumentException.class) public void randomMaxValueLessThanMinValue() { Suppliers.random(10, 9); } |
ThrottledInputStream extends FilterInputStream { @Override public int read() throws IOException { final int b = super.read(); if (b > -1) { throttle(1); } return b; } ThrottledInputStream(final InputStream in, final long bytesPerSecond); @Override int read(); @Override int read(final byte[] b); @Override int read(final byte[] b, final int off, final int len); @Override String toString(); } | @Test public void readOneByteAtATime() throws IOException { final InputStream in = new ThrottledInputStream(Streams.create(this.body), 1000); final long timestampStart = System.nanoTime(); for (int i = 0; i < 100; i++) { in.read(); } final long duration = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - timestampStart); final long delta = Math.abs(duration - 100); assertThat(delta, lessThan(15L)); }
@Test public void read() throws IOException { final InputStream in = new ThrottledInputStream(Streams.create(this.body), 1000); final long timestampStart = System.nanoTime(); in.read(new byte[100]); final long duration = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - timestampStart); final long delta = Math.abs(duration - 100); assertThat(delta, lessThan(15L)); } |
DeleteObjectNameFunction implements Function<Map<String, String>, String> { @Override public String apply(final Map<String, String> context) { final ObjectMetadata objectMetadata = this.objectManager.removeForUpdate(); context.put(Context.X_OG_OBJECT_NAME, objectMetadata.getName()); context.put(Context.X_OG_OBJECT_SIZE, String.valueOf(objectMetadata.getSize())); context.put(Context.X_OG_CONTAINER_SUFFIX, String.valueOf(objectMetadata.getContainerSuffix())); return objectMetadata.getName(); } DeleteObjectNameFunction(final ObjectManager objectManager); @Override String apply(final Map<String, String> context); @Override String toString(); } | @Test public void deleteObjectNameSupplier() { final String object = "objectName"; final ObjectMetadata objectName = mock(ObjectMetadata.class); when(objectName.getName()).thenReturn(object); when(this.objectManager.removeForUpdate()).thenReturn(objectName); final Map<String, String> context = Maps.newHashMap(); assertThat(new DeleteObjectNameFunction(this.objectManager).apply(context), is(object)); assertThat(context.get(Context.X_OG_OBJECT_NAME), is(object)); }
@Test(expected = ObjectManagerException.class) public void supplierException() { when(this.objectManager.removeForUpdate()).thenThrow(new ObjectManagerException()); new DeleteObjectNameFunction(this.objectManager).apply(Maps.<String, String>newHashMap()); } |
RandomPercentageSupplier implements Supplier<T> { @Override public T get() { final double totalPercent = getCurrentPercents(); final double rnd = this.random.nextDouble() * totalPercent; double previousPercents = 0.0; RandomPercentageSupplier.Choice<T> unUsedChoice = this.choices.get(this.choices.size()-1); for (final RandomPercentageSupplier.Choice<T> choice : this.choices) { if (rnd < previousPercents + choice.currentPercentage) { if (choice.value != null) { return choice.value; } else { return null; } } previousPercents += choice.currentPercentage; } throw new IllegalStateException("Incorrect percentage calculation"); } private RandomPercentageSupplier(final RandomPercentageSupplier.Builder<T> builder); @Override T get(); @Override String toString(); } | @Test public void oneChoice() { final Supplier<Integer> s = new RandomPercentageSupplier.Builder<Integer>().withChoice(1, 100.00).build(); int count = 0; for (int i = 0; i < 100; i++) { Integer val = s.get(); if (val != null && val == 1) { count++; } } assertThat(count, comparesEqualTo(100)); }
@Test public void multipleChoices() { final Supplier<Integer> s = new RandomPercentageSupplier.Builder<Integer>().withChoice(1, 25.0).withChoice(2, 25.0) .withChoice(3, 25.0).withRandom(new Random()).build(); final Map<Integer, Integer> counts = Maps.newHashMap(); counts.put(1, 0); counts.put(2, 0); counts.put(3, 0); for (int i = 0; i < 100; i++) { final Integer value = s.get(); if (value != null) { counts.put(value, counts.get(value) + 1); } } for (final int count : counts.values()) { assertThat(count, greaterThan(0)); } } |
KeystoneAuth implements HttpAuth { @Override public AuthenticatedRequest authenticate(final Request request) { final String keystoneToken = checkNotNull(request.getContext().get(Context.X_OG_KEYSTONE_TOKEN)); final AuthenticatedHttpRequest authenticatedRequest = new AuthenticatedHttpRequest(request); authenticatedRequest.addHeader("X-Auth-Token", keystoneToken); return authenticatedRequest; } @Override AuthenticatedRequest authenticate(final Request request); @Override String toString(); } | @Test(expected = RuntimeException.class) public void noToken() { final Request badRequest = new HttpRequest.Builder(Method.PUT, this.uri, Operation.WRITE).build(); this.keystoneAuth.authenticate(badRequest); } |
ApacheClient implements Client { @Override public ListenableFuture<Integer> shutdown(final boolean immediate, final int timeout) { final SettableFuture<Integer> future = SettableFuture.create(); final Thread t = new Thread(getShutdownRunnable(future, immediate, timeout)); t.setName("client-shutdown"); this.running = false; t.start(); return future; } private ApacheClient(final Builder builder); @Override ListenableFuture<Response> execute(final Request request); @Override ListenableFuture<Integer> shutdown(final boolean immediate, final int timeout); @Override String toString(); } | @Test public void positiveMaxIdleTime() { new ApacheClient.Builder().withMaxIdleTime(100).build().shutdown(true, 0); } |
ApacheClient implements Client { @Override public ListenableFuture<Response> execute(final Request request) { checkNotNull(request); final BlockingHttpOperation operation = new BlockingHttpOperation(request); final ListenableFuture<Response> baseFuture = this.executorService.submit(operation); return new ForwardingListenableFuture.SimpleForwardingListenableFuture<Response>(baseFuture) { @Override public boolean cancel(final boolean mayInterruptIfRunning) { operation.getApacheRequest().abort(); return delegate().cancel(mayInterruptIfRunning); } }; } private ApacheClient(final Builder builder); @Override ListenableFuture<Response> execute(final Request request); @Override ListenableFuture<Integer> shutdown(final boolean immediate, final int timeout); @Override String toString(); } | @Test @UseDataProvider("provideExecute") public void execute(final Method method, final Body requestBody, final String requestData, final Body responseBody) throws InterruptedException, ExecutionException { final Request request = new HttpRequest.Builder(method, this.objectUri, this.operation) .withBody(requestBody).build(); final Response response = this.client.execute(request).get(); assertThat(response.getStatusCode(), is(200)); assertThat(response.getBody().getDataType(), is(responseBody.getDataType())); assertThat(response.getBody().getSize(), is(responseBody.getSize())); verify(requestedFor(method, this.objectUri.getPath()).withRequestBody(equalTo(requestData))); }
@Test public void requestHeaders() throws InterruptedException, ExecutionException { final Request request = new HttpRequest.Builder(Method.PUT, this.objectUri, this.operation) .withHeader("key", "value").build(); this.client.execute(request).get(); verify( putRequestedFor(urlEqualTo(this.objectUri.getPath())).withHeader("key", equalTo("value"))); }
@Test @UseDataProvider("provideEncode") public void encode(final boolean chunk, final String key, final String value, final String absent) throws InterruptedException, ExecutionException { final Client client = new ApacheClient.Builder().usingChunkedEncoding(chunk).build(); final Request request = new HttpRequest.Builder(Method.PUT, this.objectUri, this.operation) .withBody(Bodies.zeroes(2048)).build(); client.execute(request).get(); verify(putRequestedFor(urlEqualTo(this.objectUri.getPath())).withHeader(key, equalTo(value)) .withoutHeader(absent)); }
@Test public void expect100Continue() throws InterruptedException, ExecutionException { final Client client = new ApacheClient.Builder().usingExpectContinue(true).build(); final Request request = new HttpRequest.Builder(Method.PUT, this.objectUri, this.operation) .withBody(Bodies.zeroes(2048)).build(); client.execute(request).get(); verify(putRequestedFor(urlEqualTo(this.objectUri.getPath())).withHeader("Expect", equalTo("100-continue"))); }
@Test public void noExpect100Continue() throws InterruptedException, ExecutionException { final Client client = new ApacheClient.Builder().usingExpectContinue(false).build(); final Request request = new HttpRequest.Builder(Method.PUT, this.objectUri, this.operation) .withBody(Bodies.zeroes(2048)).build(); client.execute(request).get(); verify(putRequestedFor(urlEqualTo(this.objectUri.getPath())).withoutHeader("Expect")); }
@Test public void authentication() throws InterruptedException, ExecutionException { final Client client = new ApacheClient.Builder().withAuthentication(new BasicAuth()).build(); final Request request = new HttpRequest.Builder(Method.GET, this.objectUri, this.operation) .withContext(Context.X_OG_USERNAME, "test").withContext(Context.X_OG_PASSWORD, "test") .build(); client.execute(request).get(); verify(getRequestedFor(urlEqualTo(this.objectUri.getPath())).withHeader("Authorization", matching("Basic .*"))); }
@Test public void noAuthentication() throws InterruptedException, ExecutionException { final Request request = new HttpRequest.Builder(Method.GET, this.objectUri, this.operation).build(); this.client.execute(request).get(); verify(getRequestedFor(urlEqualTo(this.objectUri.getPath())).withoutHeader("Authorization")); }
@Test public void userAgent() throws InterruptedException, ExecutionException { final Client client = new ApacheClient.Builder().withUserAgent("testUserAgent").build(); final Request request = new HttpRequest.Builder(Method.GET, this.objectUri, this.operation).build(); client.execute(request).get(); verify(getRequestedFor(urlEqualTo(this.objectUri.getPath())).withHeader("User-Agent", equalTo("testUserAgent"))); }
@Test public void noUserAgent() throws InterruptedException, ExecutionException { final Request request = new HttpRequest.Builder(Method.GET, this.objectUri, this.operation).build(); this.client.execute(request).get(); verify(getRequestedFor(urlEqualTo(this.objectUri.getPath())).withHeader("User-Agent", matching("Apache.*"))); }
@Test public void soTimeoutExceeded() throws InterruptedException, ExecutionException { final Client client = new ApacheClient.Builder().withSoTimeout(1).build(); final Request request = new HttpRequest.Builder(Method.GET, this.delayUri, this.operation).build(); final Response response = client.execute(request).get(); assertThat(response.getStatusCode(), is(599)); }
@Test public void requestId() throws InterruptedException, ExecutionException { final Request request = new HttpRequest.Builder(Method.GET, this.objectUri, this.operation) .withContext(Context.X_OG_REQUEST_ID, "1").build(); final Response response = this.client.execute(request).get(); assertThat(response.getContext(), hasEntry(Context.X_OG_REQUEST_ID, "1")); }
@Test @UseDataProvider("provideRedirect") public void redirect(final Method method, final URI uri, final Operation operation, final Body requestBody, final String requestData, final Body responseBody, final boolean chunkedEncoding) throws InterruptedException, ExecutionException { final Client client = new ApacheClient.Builder().usingChunkedEncoding(chunkedEncoding).build(); final HttpRequest.Builder builder = new HttpRequest.Builder(method, uri, operation); builder.withBody(requestBody); builder.withContext(Context.X_OG_OBJECT_SIZE, String.valueOf(requestBody.getSize())); final Request request = builder.build(); final Response response = client.execute(request).get(); assertThat(response.getStatusCode(), is(200)); assertThat(response.getBody().getDataType(), is(responseBody.getDataType())); assertThat(response.getBody().getSize(), is(responseBody.getSize())); verify(requestedFor(method, uri.getPath()).withRequestBody(equalTo(requestData))); verify(requestedFor(method, "/container/").withRequestBody(equalTo(requestData))); }
@Test public void writeThroughput() throws InterruptedException, ExecutionException { final Client client = new ApacheClient.Builder().withWriteThroughput(1000).build(); final Request request = new HttpRequest.Builder(Method.PUT, this.objectUri, this.operation) .withBody(Bodies.zeroes(50)).build(); final long timestampStart = System.nanoTime(); client.execute(request).get(); final long duration = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - timestampStart); assertThat(duration, greaterThanOrEqualTo(40L)); }
@Test public void readThroughput() throws InterruptedException, ExecutionException { final Client client = new ApacheClient.Builder().withReadThroughput(20000).build(); final Request request = new HttpRequest.Builder(Method.GET, this.objectUri, this.operation).build(); final long timestampStart = System.nanoTime(); client.execute(request).get(); final long duration = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - timestampStart); assertThat(duration, greaterThanOrEqualTo(40L)); }
@Test public void responseBodyConsumer() throws InterruptedException, ExecutionException { final Request request = new HttpRequest.Builder(Method.GET, this.objectUri, this.operation) .withContext(Context.X_OG_RESPONSE_BODY_CONSUMER, "consumer").build(); final Client client = new ApacheClient.Builder().withResponseBodyConsumer("consumer", new ResponseBodyConsumer() { @Override public Map<String, String> consume(final int statusCode, final InputStream response) { return ImmutableMap.of("key", "value"); } }).build(); final Response response = client.execute(request).get(); assertThat(response.getContext(), hasEntry("key", "value")); } |
Streams { public static InputStream create(final Body body) { checkNotNull(body); switch (body.getDataType()) { case NONE: return NONE_INPUTSTREAM; case ZEROES: return create(ZERO_BUF, body.getSize()); case CUSTOM: return create(body.getContent().getBytes(Charsets.UTF_8), body.getSize()); default: return create(createRandomBuffer(body.getRandomSeed()), body.getSize()); } } private Streams(); static InputStream create(final Body body); static InputStream throttle(final InputStream in, final long bytesPerSecond); static OutputStream throttle(final OutputStream out, final long bytesPerSecond); static final int REPEAT_LENGTH; } | @Test(expected = NullPointerException.class) public void nullBody() { Streams.create(null); }
@Test public void createNone() throws IOException { when(this.body.getDataType()).thenReturn(DataType.NONE); when(this.body.getSize()).thenReturn(0L); assertThat(Streams.create(this.body).read(), is(-1)); }
@Test public void createRandom() throws IOException { when(this.body.getDataType()).thenReturn(DataType.RANDOM); when(this.body.getSize()).thenReturn(1024L); final InputStream in = Streams.create(this.body); final byte[] buf = new byte[1024]; boolean nonZero = false; assertThat(in.read(buf), is(1024)); for (int i = 0; i < buf.length; i++) { if (buf[i] != 0) { nonZero = true; } } assertThat(nonZero, is(true)); }
@Test public void createZeroes() throws IOException { when(this.body.getDataType()).thenReturn(DataType.ZEROES); when(this.body.getSize()).thenReturn(1024L); final InputStream in = Streams.create(this.body); final byte[] buf = new byte[1024]; assertThat(in.read(buf), is(1024)); for (int i = 0; i < buf.length; i++) { assertThat((int) buf[i], is(0)); } } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.