Serenity Operating System
at master 95 lines 2.3 kB view raw
1/* 2 * Copyright (c) 2018-2020, Ben Wiederhake <BenWiederhake.GitHub@gmx.de> 3 * 4 * SPDX-License-Identifier: BSD-2-Clause 5 */ 6 7#include <AK/Assertions.h> 8#include <AK/Format.h> 9#include <LibMain/Main.h> 10#include <stdio.h> 11#include <stdlib.h> 12#include <string.h> 13 14static void assert_env(char const* name, char const* value) 15{ 16 char* result = getenv(name); 17 if (!result) { 18 perror("getenv"); 19 outln("(When reading value for '{}'; we expected '{}'.)", name, value); 20 VERIFY(false); 21 } 22 if (strcmp(result, value) != 0) { 23 outln("Expected '{}', got '{}' instead.", value, result); 24 VERIFY(false); 25 } 26} 27 28static void test_getenv_preexisting() 29{ 30 assert_env("HOME", "/home/anon"); 31} 32 33static void test_putenv() 34{ 35 char* to_put = strdup("PUTENVTEST=HELLOPUTENV"); 36 int rc = putenv(to_put); 37 if (rc) { 38 perror("putenv"); 39 VERIFY(false); 40 } 41 assert_env("PUTENVTEST", "HELLOPUTENV"); 42 // Do not free `to_put`! 43} 44 45static void test_setenv() 46{ 47 int rc = setenv("SETENVTEST", "HELLO SETENV!", 0); 48 if (rc) { 49 perror("setenv"); 50 VERIFY(false); 51 } 52 // This used to trigger a very silly bug! :) 53 assert_env("SETENVTEST", "HELLO SETENV!"); 54 55 rc = setenv("SETENVTEST", "How are you today?", 0); 56 if (rc) { 57 perror("setenv"); 58 VERIFY(false); 59 } 60 assert_env("SETENVTEST", "HELLO SETENV!"); 61 62 rc = setenv("SETENVTEST", "Goodbye, friend!", 1); 63 if (rc) { 64 perror("setenv"); 65 VERIFY(false); 66 } 67 assert_env("SETENVTEST", "Goodbye, friend!"); 68} 69 70static void test_setenv_overwrite_empty() 71{ 72 int rc = setenv("EMPTYTEST", "Forcefully overwrite non-existing envvar", 1); 73 if (rc) { 74 perror("setenv"); 75 VERIFY(false); 76 } 77 assert_env("EMPTYTEST", "Forcefully overwrite non-existing envvar"); 78} 79 80ErrorOr<int> serenity_main(Main::Arguments) 81{ 82#define RUNTEST(x) \ 83 { \ 84 outln("Running " #x " ..."); \ 85 x(); \ 86 outln("Success!"); \ 87 } 88 RUNTEST(test_getenv_preexisting); 89 RUNTEST(test_putenv); 90 RUNTEST(test_setenv); 91 RUNTEST(test_setenv_overwrite_empty); 92 outln("PASS"); 93 94 return 0; 95}