From 8cac3e2424a8d10dd1e0705c8558b71f7e7c37db Mon Sep 17 00:00:00 2001
From: Stefan Prietl <ederst@users.noreply.github.com>
Date: Mon, 13 Feb 2023 19:26:23 +0100
Subject: [PATCH 7/8] disk_setup: use byte string when purging the partition
 table (#2012)

Reference:https://github.com/canonical/cloud-init/commit/bb414c7866c4728b2105e84f7b426ab81cc4bf4d
Conflict:change tests/unittests/test_handler/test_handler_disk_setup.py
not tests/unittests/config/test_cc_disk_setup.py

This writes a byte string to the device instead of a string when
purging the partition table.

Essentially, this will prevent the error "a bytes-like object is
required, not 'str'" from happening.
---
 cloudinit/config/cc_disk_setup.py             |  2 +-
 .../test_handler/test_handler_disk_setup.py   | 19 ++++++++++++++++++-
 2 files changed, 19 insertions(+), 2 deletions(-)

diff --git a/cloudinit/config/cc_disk_setup.py b/cloudinit/config/cc_disk_setup.py
index 440f05f..abdc111 100644
--- a/cloudinit/config/cc_disk_setup.py
+++ b/cloudinit/config/cc_disk_setup.py
@@ -649,7 +649,7 @@ def get_partition_gpt_layout(size, layout):
 def purge_disk_ptable(device):
     # wipe the first and last megabyte of a disk (or file)
     # gpt stores partition table both at front and at end.
-    null = '\0'
+    null = b'\0'
     start_len = 1024 * 1024
     end_len = 1024 * 1024
     with open(device, "rb+") as fp:
diff --git a/tests/unittests/test_handler/test_handler_disk_setup.py b/tests/unittests/test_handler/test_handler_disk_setup.py
index 4f4a57f..2f3a8df 100644
--- a/tests/unittests/test_handler/test_handler_disk_setup.py
+++ b/tests/unittests/test_handler/test_handler_disk_setup.py
@@ -1,6 +1,7 @@
 # This file is part of cloud-init. See LICENSE file for license information.
 
 import random
+import tempfile
 
 from cloudinit.config import cc_disk_setup
 from cloudinit.tests.helpers import CiTestCase, ExitStack, mock, TestCase
@@ -168,6 +169,23 @@ class TestUpdateFsSetupDevices(TestCase):
         }, fs_setup)
 
 
+class TestPurgeDisk(TestCase):
+    @mock.patch(
+        "cloudinit.config.cc_disk_setup.read_parttbl", return_value=None
+    )
+    def test_purge_disk_ptable(self, *args):
+        pseudo_device = tempfile.NamedTemporaryFile()
+
+        cc_disk_setup.purge_disk_ptable(pseudo_device.name)
+
+        with pseudo_device as f:
+            actual = f.read()
+
+        expected = b"\0" * (1024 * 1024)
+
+        self.assertEqual(expected, actual)
+
+
 @mock.patch('cloudinit.config.cc_disk_setup.assert_and_settle_device',
             return_value=None)
 @mock.patch('cloudinit.config.cc_disk_setup.find_device_node',
@@ -175,7 +193,6 @@ class TestUpdateFsSetupDevices(TestCase):
 @mock.patch('cloudinit.config.cc_disk_setup.device_type', return_value=None)
 @mock.patch('cloudinit.config.cc_disk_setup.subp.subp', return_value=('', ''))
 class TestMkfsCommandHandling(CiTestCase):
-
     with_logs = True
 
     def test_with_cmd(self, subp, *args):
-- 
2.40.0

