本文介绍了如何在断言Selenium getCssValue("background")返回的背景色rgb(255,255,255)的同时将#ffffff转换为#fff或#fff转换为#ffffff的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将#ffffff转换为#fff或将#fff转换为#ffffff进行断言?

How to convert #ffffff to #fff or #fff to #ffffff for Assertion?

我正在使用 Selenium 中的"nofollow noreferrer"> getCssValue("background") ,它返回rgb(255, 255, 255),我可以将其拆分为:

I am using getCssValue("background") from Selenium which returns rgb(255, 255, 255) which I can split into:

  • r-> 255
  • g-> 255
  • b-> 255

下面的代码行:

String hex = String.format("#%02x%02x%02x", r, g, b);

rgb 转换为 hex 并给出如下输出:

Converts rgb to hex and gives an output as:

#ffffff

但是从控制台中,背景被提取为 #fff

But from the console, the background is extracted as #fff

那么,哪种理想的方法是:

So what can be the ideal way either to:

  • #ffffff转换为#fff
  • #fff转换为#ffffff
  • convert #ffffff to #fff
  • convert #fff to #ffffff

我经过一些相关的讨论,如下:

I have been through a couple of relevant discussions as:

  • Why use #fff color on body? which mentions that the issue is somewhat subjective.
  • CSS: Which is faster for the browser? color:#fff; or color:#ffffff; which mentions CSS compressors will intelligently optimize to the #fff version.

但是我的测试失败了,需要进行转换.有什么建议吗?

But my tests are failing and there is a need for conversion. Any recommendations?

推荐答案

您可以将replaceAll与正则表达式一起使用,该表达式查找所有三个部分使用相同数字的情况:

You can use replaceAll with a regular expression that looks for the case where all three parts use the same digit:

static String getHex(int r, int g, int b) {
    return String.format("#%02x%02x%02x", r, g, b).replaceAll("^#([a-fA-F])\\1([a-fA-F])\\2([a-fA-F])\\3$", "#$1$2$3");
}

查找以#开头的字符串,然后是三对匹配的十六进制数字,然后将其替换为短格式. (我想我可能只是在您的特定示例中使用了[a-f]而不是[a-fA-F],因为您知道只会使用小写字母,但是...)

That looks for a string starting with # followed by three pairs of matching hex digits, and replaces them with just the short form. (I suppose I could have just used [a-f] instead of [a-fA-F] in your specific example, since you know you'll be getting lower case only, but...)

完整示例(在 Ideone 上):

public class Example {
    public static void main(String[] args) {
        System.out.println(getHex(255, 255, 255)); // #fff
        System.out.println(getHex(255, 240, 255)); // #fff0ff
    }

    static String getHex(int r, int g, int b) {
        return String.format("#%02x%02x%02x", r, g, b).replaceAll("^#([a-fA-F])\\1([a-fA-F])\\2([a-fA-F])\\3$", "#$1$2$3");
    }
}

这篇关于如何在断言Selenium getCssValue("background")返回的背景色rgb(255,255,255)的同时将#ffffff转换为#fff或#fff转换为#ffffff的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 06:56