EnvTest.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace think\tests;
  3. use org\bovigo\vfs\vfsStream;
  4. use PHPUnit\Framework\TestCase;
  5. use think\Env;
  6. use think\Exception;
  7. class EnvTest extends TestCase
  8. {
  9. public function testEnvFile()
  10. {
  11. $root = vfsStream::setup();
  12. $envFile = vfsStream::newFile('.env')->setContent("key1=value1\nkey2=value2");
  13. $root->addChild($envFile);
  14. $env = new Env();
  15. $env->load($envFile->url());
  16. $this->assertEquals('value1', $env->get('key1'));
  17. $this->assertEquals('value2', $env->get('key2'));
  18. }
  19. public function testServerEnv()
  20. {
  21. $env = new Env();
  22. $this->assertEquals('value2', $env->get('key2', 'value2'));
  23. putenv('PHP_KEY7=value7');
  24. putenv('PHP_KEY8=false');
  25. putenv('PHP_KEY9=true');
  26. $this->assertEquals('value7', $env->get('key7'));
  27. $this->assertFalse($env->get('KEY8'));
  28. $this->assertTrue($env->get('key9'));
  29. }
  30. public function testSetEnv()
  31. {
  32. $env = new Env();
  33. $env->set([
  34. 'key1' => 'value1',
  35. 'key2' => [
  36. 'key1' => 'value1-2',
  37. ],
  38. ]);
  39. $env->set('key3', 'value3');
  40. $env->key4 = 'value4';
  41. $env['key5'] = 'value5';
  42. $this->assertEquals('value1', $env->get('key1'));
  43. $this->assertEquals('value1-2', $env->get('key2.key1'));
  44. $this->assertEquals('value3', $env->get('key3'));
  45. $this->assertEquals('value4', $env->key4);
  46. $this->assertEquals('value5', $env['key5']);
  47. $this->expectException(Exception::class);
  48. unset($env['key5']);
  49. }
  50. public function testHasEnv()
  51. {
  52. $env = new Env();
  53. $env->set(['foo' => 'bar']);
  54. $this->assertTrue($env->has('foo'));
  55. $this->assertTrue(isset($env->foo));
  56. $this->assertTrue($env->offsetExists('foo'));
  57. }
  58. }