如何临时更改我的 ddev web 容器中的时间

How can I temporarily change the time in my ddev web container

我正在尝试调试在另一个事件发生几天后发生的事情,并希望在不绕过日期延迟相关代码的情况下加快测试速度。有没有办法临时更改 ddev 容器中的日期?

感谢 this question and kind support from @rfay. I came up with this solution using the libfaketime

的帮助

我创建了 .ddev/web-build/Dockerfile,内容如下:

ARG BASE_IMAGE
FROM $BASE_IMAGE
RUN apt-get update && apt-get install -y make build-essential
WORKDIR /
RUN git clone https://github.com/wolfcw/libfaketime.git
WORKDIR /libfaketime/src
RUN make install

我 运行 ddev start 以确保容器仍会构建。

然后在.ddev/commands/host/faketime处添加了一条命令:

#!/bin/bash

## Description: Enable or disable faketime
## Usage: faketime on YYYY-mm-dd|off|status
## Example: "ddev faketime on 2020-05-04", "ddev faketime off", "ddev faketime status"

if [ $# -eq 0 ] ; then
 echo "usage faketime YYYY-mm-dd or faketime off"
fi

case  in
    on|true|enable)
    echo 
    echo 
    echo "turning on"
      if date -j -f "%Y-%m-%d" -j  > /dev/null 2>&1
      then
        echo "time set to  11:00:00, restarting..."
      ddev config --web-environment=LD_PRELOAD="/usr/local/lib/faketime/libfaketime.so.1",FAKETIME=" 11:00:00" && ddev start
    else
      echo "faketime on usage:  ddev faketime on YYYY-MM-DD"
    fi
    ;;
    off|false|disable)
      echo "turning faketime off"
      ddev config --web-environment=LD_PRELOAD="" && ddev start
    ;;
    status)
      if grep -q 'FAKETIME' ${DDEV_APPROOT}/.ddev/config.yaml;
      then
        echo "faketime is on."
        ddev exec date +%F
      else
        echo "faketime is off."
        ddev exec date +%F
      fi
    ;;
  *)
    echo "invalid argument"
    ;;
esac

在 Mac 上,这允许我 运行 ddev faketime on 2020-05-4 将容器日期设置为 2020 年 5 月 4 日,并 ddev faketime off 将其关闭。在基于 unix 的系统上,脚本的日期验证部分需要有所不同。

if date -j -f "%Y-%m-%d" -j > /dev/null 2>&1;

需要类似于

if date "+%Y-%m-%d" -d 2>&1;

faketime offfaketime on 都会导致容器重新启动,而 faketime status 只会读取时间是否被伪造并报告当前容器日期。

就我而言,将时间设置为上午 11 点就可以了。我只关心日期本身。对于您的应用程序,您可能希望更改参数并指定时间。