Commit bf5b5d7c authored by Pierre Smeyers's avatar Pierre Smeyers
Browse files

feat: add maybe_install_packages function

parent 75690780
Loading
Loading
Loading
Loading
+29 −0
Original line number Diff line number Diff line
#!/usr/bin/env bash

set -e

# This function installs packages if required.
# If abstracts the underlying the Linux distro by managing several package systems (Debian and Alpine).
# Determines whether the package is present either by checking the presence of the provided package(s).
# Limitations: assumes the package(s) to install have the same name on all distros
  function maybe_install_packages() {
    if command -v apt-get > /dev/null
    then
      # Debian
      if ! dpkg --status "$@" > /dev/null
      then
        apt-get update
        apt-get install --no-install-recommends --yes --quiet "$@"
      fi
    elif command -v apk > /dev/null
    then
      # Alpine
      if ! apk info --installed "$@" > /dev/null
      then
        apk add --no-cache "$@"
      fi
    else
      log_error "... didn't find any supported package manager to install $*"
      exit 1
    fi
  }
+46 −0
Original line number Diff line number Diff line
#!/usr/bin/env bats
load "${BATS_LIBRARIES_DIR:-$BATS_TEST_DIRNAME/lib}/bats-support/load.bash"
load "${BATS_LIBRARIES_DIR:-$BATS_TEST_DIRNAME/lib}/bats-assert/load.bash"
ROOT_DIR=$(dirname "$BATS_TEST_DIRNAME")
load "$ROOT_DIR/tbc_base.sh"
load "$ROOT_DIR/tbc_maybe_install_packages.sh"

# mocked commands
function dpkg() {
  echo "[mock] dpkg $*"*
  if [[ "$*" == "--status thispkg" ]]
  then
    echo "[mock] dpkg: package thispkg is installed"
  else
    echo "[mock] dpkg: package not installed"
    return 1
  fi
}

function apt-get() {
  echo "[mock] apt-get $*"
}

@test "[deb] package is installed" {
  # GIVEN

  # WHEN
  run maybe_install_packages "thatpkg"

  # THEN
  assert_success
  # assert_equal "$(cmdmock logs dpkg '--status thatpkg' | wc -l)" 0
  assert_line --regexp "\[mock\] apt-get install (.*) thatpkg"
}

@test "[deb] package is not installed" {
  # GIVEN

  # WHEN
  run maybe_install_packages "thispkg"

  # THEN
  assert_success
  # assert_equal "$(cmdmock logs dpkg '--status thispkg' | wc -l)" 0
  refute_output --partial "[mock] apt-get install"
}