   (is (= (format-serial-number 42) "002A")))
 
 (deftest next-serial-number!-test
-  (let [serial-file (:serial (ca-test-settings))]
-    (is (fs/exists? serial-file))
-    (is (= (next-serial-number! serial-file) 1))
+  (let [serial-file (str (ks/temp-file))]
+    (testing "Serial file is initialized to 1"
+      (initialize-serial-file! serial-file)
+      (is (= (next-serial-number! serial-file) 1)))
 
     (testing "The serial number file should contain the next serial number"
       (is (= "0002" (slurp serial-file))))

            "/CN=localhost"))))))

(deftest process-csr-submission!-test
  (testing "throws an exception if a CSR already exists for that subject"
    (is (thrown-with-slingshot?
         {:type    :duplicate-cert
          :message "test-agent already has a requested certificate; ignoring certificate request"}
         (process-csr-submission! "test-agent" (csr-stream "test-agent") (ca-test-settings))))

    (testing "unless $allow-duplicate-certs is true"
      (let [settings  (assoc (ca-test-settings) :allow-duplicate-certs true)
            cert-path (path-to-cert (:signeddir settings) "test-agent")]
        (logutils/with-test-logging
          (is (false? (fs/exists? cert-path)))
          (process-csr-submission! "test-agent" (csr-stream "test-agent") settings)
          (is (logged? #"test-agent already has a requested certificate; new certificate will overwrite it" :info))
          (is (true? (fs/exists? cert-path))))
        (fs/delete cert-path))))

  (testing "throws an exception if a certificate already exists for that subject"
    (is (thrown-with-slingshot?
         {:type    :duplicate-cert
          :message "localhost already has a signed certificate; ignoring certificate request"}
         (process-csr-submission! "localhost" (csr-stream "test-agent") (ca-test-settings))))

    (testing "unless $allow-duplicate-certs is true"
      (let [settings (-> (ca-test-settings)
                         (assoc :allow-duplicate-certs true :autosign false))
            csr-path (path-to-cert-request (:csrdir settings) "localhost")]
        (logutils/with-test-logging
          (is (false? (fs/exists? csr-path)))
          (process-csr-submission! "localhost" (csr-stream "test-agent") settings)
          (is (logged? #"localhost already has a signed certificate; new certificate will overwrite it" :info))
          (is (true? (fs/exists? csr-path))))
        (fs/delete csr-path)))))

        (assert-no-autosign "this-THAT-")))

    (testing "domain-name globs"
      (doto (tmp-whitelist! "*.red"
                            "*.black.local"
                            "*.UPPER.case")
        (assert-autosign "red")
        (assert-autosign ".red")
        (assert-autosign "green.red")
