基于alpine:edge构建中文环境的web自动化测试docker镜像

805 阅读2分钟

起因:

  之前断断续续地学了一些docker知识,但是没有怎么实践过,刚好手里有些项目要开始做web自动化,但是搞自动化的环境是公共机器,里面有其它项目,不好在整台机器上搭建自动化环境,所以想把整个执行自动化的环境打包成docker,在docker里面执行不影响机器上的其它项目。

环境构成:

python3,chromium,selenium,pytest,allure2

Dockerfile:

FROM alpine:edge

# 使用清华大学源
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories
RUN apk update --allow-untrusted

# 安装python3
RUN apk add --no-cache python3 python3-dev --allow-untrusted
RUN ln -sf python3 /usr/bin/python

# 安装pip
RUN python3 -m ensurepip

# 安装 chromium,openjdk11等其它需要的模块
RUN apk add --quiet --no-cache wget gcc g++ libexif udev chromium chromium-chromedriver chromium-lang ttf-dejavu fontconfig icu-data-full openjdk11 --allow-untrusted

# 安装中文字体
RUN apk add wqy-zenhei --update-cache --repository http://nl.alpinelinux.org/alpine/edge/testing --allow-untrusted
RUN mkfontscale && mkfontdir && fc-cache

# 安装allure2
RUN wget https://repo.maven.apache.org/maven2/io/qameta/allure/allure-commandline/2.19.0/allure-commandline-2.19.0.zip
RUN unzip allure-commandline-2.19.0.zip -d /opt/

# 下载安装设置中文环境所需的模板(此处需要访问github,可能有下载失败的情况,可以多安装几次,或者下载下来执行dockerfile构建镜像的时候再cp到里面安装)
RUN apk --quiet --no-cache add ca-certificates --allow-untrusted
RUN wget -q -O /etc/apk/keys/sgerrand.rsa.pub https://alpine-pkgs.sgerrand.com/sgerrand.rsa.pub
RUN wget https://github.com/sgerrand/alpine-pkg-glibc/releases/download/2.35-r0/glibc-2.35-r0.apk
RUN wget https://github.com/sgerrand/alpine-pkg-glibc/releases/download/2.35-r0/glibc-bin-2.35-r0.apk
RUN wget https://github.com/sgerrand/alpine-pkg-glibc/releases/download/2.35-r0/glibc-i18n-2.35-r0.apk
RUN apk add --allow-untrusted glibc-bin-2.35-r0.apk glibc-i18n-2.35-r0.apk glibc-2.35-r0.apk
RUN /usr/glibc-compat/bin/localedef -i zh_CN -f UTF-8 zh_CN.UTF-8

# 删除下载的模块
RUN rm -rf *.zip && \
	rm -rf *.apk && \
	rm -rf /var/cache/apk/*

# pip安装需要用的模块
RUN pip3 install --upgrade pip -i https://pypi.douban.com/simple/
RUN pip3 install selenium pytest allure-python-commons allure-pytest six==1.14.0 -i https://pypi.douban.com/simple/

# 设置环境变量
ENV LANG=zh_CN.UTF-8 \
    LANGUAGE=zh_CN.UTF-8 \
	LC_ALL=zh_CN.UTF-8 \
	PATH="/opt/allure-2.19.0/bin:${PATH}"

过程的一些坑:

1.由于项目使用的框架里面的文本对系统环境语言做了适配,但是我们本地访问项目网页和调试脚本的时候都是中文环境,放到alpine环境里面文本就变成英文的了,这个是我构建了docker后在里面调试脚本的时候才发现的,所以docker需要设置成中文环境;

2.如果没有安装中文字体,chromium打开网页后文本就都是空洞的方块字体,而且需要安装一个模块chromium-lang。这个是我一筹莫展在网站上查不到任何资料的时候,跑到chromium目录下,发现了个lang文件夹,进去看了下只有一个en的文件,瞬间明白可能是这个语言文件导致的,经过一番搜索找到了chromium-lang,安装完才搞出了网页的中文界面;