#!/usr/bin/python
#
# This script checks for that at least 2 kernels are installed post-upgrade
# and that the latest one is active
#
# (C) 2012 Canonical Ltd.
# Author: Jean-Baptiste Lallement <jean-baptiste.lallement@canonical.com>
#         Based on the original version from Michael Vogt
# License: GPL v2 or higher

import unittest
import apt_pkg
import glob
import os

class TestKernel(unittest.TestCase):
    def setUp(self):
        apt_pkg.init()
        self.current_kernelversion = os.uname()[2]
        self.versions = set()
        for kernel in glob.glob('/boot/vmlinuz-*'):
            version = "-".join(kernel.split("-")[1:4])
            self.versions.add(version)

    def test_kernel_in_use(self):
        '''Check latest kernel is in use'''
        if os.path.exists("/run/container_type"):
            with open("/run/container_type") as fd:
                container = fd.read().strip()
            print("Skipping test_kernel_in_use as in a '%s' container." % container)
            return

        for version in self.versions:
            self.assertFalse(
                apt_pkg.version_compare(self.current_kernelversion, version) < 0,
                "There is a kernel version '%s' installed higher than the running kernel '%s'" %
                (version, self.current_kernelversion))

    def test_old_kernel_is_installed(self):
        '''Check that previous kernel is still there after install'''
        self.assertNotEqual(
            len(self.versions), 1,
            "Only one kernel found '%s', expected at least 2 (new + previous)" %
            self.versions)

if __name__ == '__main__':
    unittest.main()
