1 /** 2 * Copyright © 2019 IBM Corporation 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #include "sysfs.hpp" 18 19 #include <sys/param.h> 20 21 #include <cerrno> 22 #include <cstdlib> 23 #include <fstream> 24 25 #include <gtest/gtest.h> 26 27 namespace fs = std::filesystem; 28 29 constexpr unsigned long MAX_BRIGHTNESS_VAL = 128; 30 31 class FakeSysfsLed : public phosphor::led::SysfsLed 32 { 33 public: 34 static FakeSysfsLed create() 35 { 36 static constexpr auto tmplt = "/tmp/FakeSysfsLed.XXXXXX"; 37 char buffer[MAXPATHLEN] = {0}; 38 39 strncpy(buffer, tmplt, sizeof(buffer) - 1); 40 char* dir = mkdtemp(buffer); 41 if (!dir) 42 throw std::system_error(errno, std::system_category()); 43 44 return FakeSysfsLed(fs::path(dir)); 45 } 46 47 ~FakeSysfsLed() 48 { 49 fs::remove_all(root); 50 } 51 52 private: 53 explicit FakeSysfsLed(fs::path&& path) : SysfsLed(std::move(path)) 54 { 55 std::string attrs[4] = {BRIGHTNESS, TRIGGER, DELAY_ON, DELAY_OFF}; 56 for (const auto& attr : attrs) 57 { 58 fs::path p = root / attr; 59 std::ofstream f(p, std::ios::out); 60 f.exceptions(f.failbit); 61 } 62 63 fs::path p = root / MAX_BRIGHTNESS; 64 std::ofstream f(p, std::ios::out); 65 f.exceptions(f.failbit); 66 f << MAX_BRIGHTNESS_VAL; 67 } 68 }; 69 70 TEST(Sysfs, getBrightness) 71 { 72 constexpr unsigned long brightness = 127; 73 FakeSysfsLed fsl = FakeSysfsLed::create(); 74 75 fsl.setBrightness(brightness); 76 ASSERT_EQ(brightness, fsl.getBrightness()); 77 } 78 79 TEST(Sysfs, getMaxBrightness) 80 { 81 FakeSysfsLed fsl = FakeSysfsLed::create(); 82 83 ASSERT_EQ(MAX_BRIGHTNESS_VAL, fsl.getMaxBrightness()); 84 } 85 86 TEST(Sysfs, getTrigger) 87 { 88 constexpr auto trigger = "none"; 89 FakeSysfsLed fsl = FakeSysfsLed::create(); 90 91 fsl.setTrigger(trigger); 92 ASSERT_EQ(trigger, fsl.getTrigger()); 93 } 94 95 TEST(Sysfs, getDelayOn) 96 { 97 constexpr unsigned long delayOn = 250; 98 FakeSysfsLed fsl = FakeSysfsLed::create(); 99 100 fsl.setDelayOn(delayOn); 101 ASSERT_EQ(delayOn, fsl.getDelayOn()); 102 } 103 104 TEST(Sysfs, getDelayOff) 105 { 106 constexpr unsigned long delayOff = 750; 107 FakeSysfsLed fsl = FakeSysfsLed::create(); 108 109 fsl.setDelayOff(delayOff); 110 ASSERT_EQ(delayOff, fsl.getDelayOff()); 111 } 112