Standardization of using order and object initialization (#1028)

* Code cleanup KubernetesClient

* KubernetesClient.Basic code cleanup

* KubernetesClient.Models cleanup

* LibKubernetesGenerator code cleanup

* Improved readability of object initialization

* FIx namespace order

* Fixed some compilation warning
This commit is contained in:
Manuel Menegazzo
2022-09-28 22:34:32 +02:00
committed by GitHub
parent bbd3b6cd50
commit 3702fd6e90
47 changed files with 201 additions and 165 deletions

View File

@@ -35,9 +35,9 @@ namespace @namespace
{
foreach (var innerEx in ex.InnerExceptions)
{
if (innerEx is k8s.Autorest.HttpOperationException)
if (innerEx is k8s.Autorest.HttpOperationException exception)
{
var code = ((k8s.Autorest.HttpOperationException)innerEx).Response.StatusCode;
var code = exception.Response.StatusCode;
if (code == HttpStatusCode.NotFound)
{
return;

View File

@@ -10,10 +10,12 @@ namespace yaml
{
private static async Task Main(string[] args)
{
var typeMap = new Dictionary<String, Type>();
typeMap.Add("v1/Pod", typeof(V1Pod));
typeMap.Add("v1/Service", typeof(V1Service));
typeMap.Add("apps/v1/Deployment", typeof(V1Deployment));
var typeMap = new Dictionary<String, Type>
{
{ "v1/Pod", typeof(V1Pod) },
{ "v1/Service", typeof(V1Service) },
{ "apps/v1/Deployment", typeof(V1Deployment) }
};
var objects = await KubernetesYaml.LoadAllFromFileAsync(args[0], typeMap);

View File

@@ -19,7 +19,7 @@ public abstract partial class AbstractKubernetes
private sealed class QueryBuilder
{
private List<string> parameters = new List<string>();
private readonly List<string> parameters = new List<string>();
public void Append(string key, params object[] values)
{

View File

@@ -30,12 +30,10 @@ namespace k8s.Autorest
this.Content = content;
this.Method = httpRequest.Method;
this.RequestUri = httpRequest.RequestUri;
#pragma warning disable CS0618 // Type or member is obsolete
if (httpRequest.Properties != null)
{
Properties = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> pair in httpRequest.Properties)
#pragma warning restore CS0618 // Type or member is obsolete
{
this.Properties[pair.Key] = pair.Value;
}

View File

@@ -98,7 +98,7 @@ namespace k8s.Autorest
/// <returns>
/// Task that will complete when processing has completed.
/// </returns>
public async override Task ProcessHttpRequestAsync(
public override async Task ProcessHttpRequestAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{

View File

@@ -1,8 +1,8 @@
global using System;
global using System.Collections.Generic;
global using System.Linq;
global using k8s.Autorest;
global using k8s.Models;
global using System;
global using System.Collections.Generic;
global using System.IO;
global using System.Linq;
global using System.Threading;
global using System.Threading.Tasks;

View File

@@ -1,6 +1,6 @@
using k8s.Models;
using System.Reflection;
using System.Text.RegularExpressions;
using k8s.Models;
namespace k8s
{

View File

@@ -17,6 +17,11 @@ namespace k8s
{
public static IEnumerator<T> GetEnumerator<T>(this IItems<T> items)
{
if (items is null)
{
throw new ArgumentNullException(nameof(items));
}
return items.Items.GetEnumerator();
}
}

View File

@@ -13,8 +13,8 @@ namespace k8s.KubeConfigModels
public bool IsValid()
{
return (!string.IsNullOrEmpty(Token) ||
(!string.IsNullOrEmpty(ClientCertificateData) && !string.IsNullOrEmpty(ClientKeyData)));
return !string.IsNullOrEmpty(Token) ||
(!string.IsNullOrEmpty(ClientCertificateData) && !string.IsNullOrEmpty(ClientKeyData));
}
}

View File

@@ -1,3 +1,4 @@
using k8s.Models;
using System.IO;
using System.Reflection;
using System.Text;
@@ -6,7 +7,6 @@ using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
using k8s.Models;
namespace k8s
{

View File

@@ -1,6 +1,6 @@
using Fractions;
using System.Globalization;
using System.Numerics;
using Fractions;
namespace k8s.Models
{

View File

@@ -1,8 +1,8 @@
// WARNING: DO NOT LEAVE COMMENTED CODE IN THIS FILE. IT GETS SCANNED BY GEN PROJECT SO IT CAN EXCLUDE ANY MANUALLY DEFINED MAPS
using System.Reflection;
using AutoMapper;
using k8s.Models;
using System.Reflection;
namespace k8s.Versioning
{

View File

@@ -1,8 +1,8 @@
using k8s.Autorest;
using k8s.KubeConfigModels;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using k8s.KubeConfigModels;
using k8s.Autorest;
namespace k8s.Authentication
{

View File

@@ -1,9 +1,9 @@
using k8s.Autorest;
using k8s.Exceptions;
using System.Diagnostics;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using k8s.Exceptions;
using k8s.Autorest;
namespace k8s.Authentication
{

View File

@@ -1,6 +1,6 @@
using IdentityModel.OidcClient;
using k8s.Exceptions;
using k8s.Autorest;
using k8s.Exceptions;
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http.Headers;
using System.Threading;
@@ -10,7 +10,7 @@ namespace k8s.Authentication
{
public class OidcTokenProvider : ITokenProvider
{
private OidcClient _oidcClient;
private readonly OidcClient _oidcClient;
private string _idToken;
private string _refreshToken;
private DateTimeOffset _expiry;

View File

@@ -1,8 +1,8 @@
using System.Net.Http.Headers;
using k8s.Autorest;
using System.IO;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using k8s.Autorest;
namespace k8s.Authentication
{

View File

@@ -156,8 +156,7 @@ namespace k8s
using (var reader = new StreamReader(new MemoryStream(keyData)))
{
obj = new PemReader(reader).ReadObject();
var key = obj as AsymmetricCipherKeyPair;
if (key != null)
if (obj is AsymmetricCipherKeyPair key)
{
var cipherKey = key;
obj = cipherKey.Private;
@@ -169,18 +168,17 @@ namespace k8s
var store = new Pkcs12StoreBuilder().Build();
store.SetKeyEntry("K8SKEY", new AsymmetricKeyEntry(keyParams), new[] { new X509CertificateEntry(cert) });
using (var pkcs = new MemoryStream())
{
store.Save(pkcs, new char[0], new SecureRandom());
using var pkcs = new MemoryStream();
if (config.ClientCertificateKeyStoreFlags.HasValue)
{
return new X509Certificate2(pkcs.ToArray(), "", config.ClientCertificateKeyStoreFlags.Value);
}
else
{
return new X509Certificate2(pkcs.ToArray());
}
store.Save(pkcs, new char[0], new SecureRandom());
if (config.ClientCertificateKeyStoreFlags.HasValue)
{
return new X509Certificate2(pkcs.ToArray(), "", config.ClientCertificateKeyStoreFlags.Value);
}
else
{
return new X509Certificate2(pkcs.ToArray());
}
#endif
}

View File

@@ -1,9 +1,9 @@
using k8s.Autorest;
using k8s.Exceptions;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using k8s.Exceptions;
using k8s.Autorest;
namespace k8s
{

View File

@@ -1,5 +1,5 @@
using k8s.Models;
using k8s.Autorest;
using k8s.Models;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
@@ -19,31 +19,31 @@ namespace k8s
try
{
using (var muxedStream = await MuxedStreamNamespacedPodExecAsync(
using var muxedStream = await MuxedStreamNamespacedPodExecAsync(
name,
@namespace, command, container, tty: tty,
cancellationToken: cancellationToken).ConfigureAwait(false))
using (var stdIn = muxedStream.GetStream(null, ChannelIndex.StdIn))
using (var stdOut = muxedStream.GetStream(ChannelIndex.StdOut, null))
using (var stdErr = muxedStream.GetStream(ChannelIndex.StdErr, null))
using (var error = muxedStream.GetStream(ChannelIndex.Error, null))
using (var errorReader = new StreamReader(error))
{
muxedStream.Start();
cancellationToken: cancellationToken).ConfigureAwait(false);
await action(stdIn, stdOut, stdErr).ConfigureAwait(false);
using var stdIn = muxedStream.GetStream(null, ChannelIndex.StdIn);
using var stdOut = muxedStream.GetStream(ChannelIndex.StdOut, null);
using var stdErr = muxedStream.GetStream(ChannelIndex.StdErr, null);
using var error = muxedStream.GetStream(ChannelIndex.Error, null);
using var errorReader = new StreamReader(error);
var errors = await errorReader.ReadToEndAsync().ConfigureAwait(false);
muxedStream.Start();
// StatusError is defined here:
// https://github.com/kubernetes/kubernetes/blob/068e1642f63a1a8c48c16c18510e8854a4f4e7c5/staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go#L37
var returnMessage = KubernetesJson.Deserialize<V1Status>(errors);
return GetExitCodeOrThrow(returnMessage);
}
await action(stdIn, stdOut, stdErr).ConfigureAwait(false);
var errors = await errorReader.ReadToEndAsync().ConfigureAwait(false);
// StatusError is defined here:
// https://github.com/kubernetes/kubernetes/blob/068e1642f63a1a8c48c16c18510e8854a4f4e7c5/staging/src/k8s.io/apimachinery/pkg/api/errors/errors.go#L37
var returnMessage = KubernetesJson.Deserialize<V1Status>(errors);
return GetExitCodeOrThrow(returnMessage);
}
catch (HttpOperationException httpEx) when (httpEx.Body is V1Status)
catch (HttpOperationException httpEx) when (httpEx.Body is V1Status status)
{
throw new KubernetesException((V1Status)httpEx.Body, httpEx);
throw new KubernetesException(status, httpEx);
}
}

View File

@@ -1,13 +1,13 @@
using k8s.Models;
using k8s.Autorest;
using k8s.Models;
using System.Globalization;
using System.Net;
using System.Net.Http;
using System.Net.WebSockets;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Text;
using System.Globalization;
namespace k8s
{
@@ -84,8 +84,10 @@ namespace k8s
}
// Construct URL
var uriBuilder = new UriBuilder(BaseUri);
uriBuilder.Scheme = BaseUri.Scheme == "https" ? "wss" : "ws";
var uriBuilder = new UriBuilder(BaseUri)
{
Scheme = BaseUri.Scheme == "https" ? "wss" : "ws",
};
if (!uriBuilder.Path.EndsWith("/", StringComparison.InvariantCulture))
{
@@ -143,8 +145,10 @@ namespace k8s
// Construct URL
var uriBuilder = new UriBuilder(BaseUri);
uriBuilder.Scheme = BaseUri.Scheme == "https" ? "wss" : "ws";
var uriBuilder = new UriBuilder(BaseUri)
{
Scheme = BaseUri.Scheme == "https" ? "wss" : "ws",
};
if (!uriBuilder.Path.EndsWith("/", StringComparison.InvariantCulture))
{
@@ -187,8 +191,10 @@ namespace k8s
}
// Construct URL
var uriBuilder = new UriBuilder(BaseUri);
uriBuilder.Scheme = BaseUri.Scheme == "https" ? "wss" : "ws";
var uriBuilder = new UriBuilder(BaseUri)
{
Scheme = BaseUri.Scheme == "https" ? "wss" : "ws",
};
if (!uriBuilder.Path.EndsWith("/", StringComparison.InvariantCulture))
{
@@ -294,8 +300,10 @@ namespace k8s
{
// This usually indicates the server sent an error message, like 400 Bad Request. Unfortunately, the WebSocket client
// class doesn't give us a lot of information about what went wrong. So, retry the connection.
var uriBuilder = new UriBuilder(uri);
uriBuilder.Scheme = uri.Scheme == "wss" ? "https" : "http";
var uriBuilder = new UriBuilder(uri)
{
Scheme = uri.Scheme == "wss" ? "https" : "http",
};
var response = await HttpClient.GetAsync(uriBuilder.Uri, cancellationToken).ConfigureAwait(false);
@@ -327,7 +335,7 @@ namespace k8s
$"The operation returned an invalid status code: {response.StatusCode}", wse)
{
Response = new HttpResponseMessageWrapper(response, content),
Body = status != null ? (object)status : content,
Body = status != null ? status : content,
};
response.Dispose();

View File

@@ -1,9 +1,9 @@
using k8s.Autorest;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using k8s.Autorest;
namespace k8s
{
@@ -101,9 +101,12 @@ namespace k8s
protected override HttpRequestMessage CreateRequest(string relativeUri, HttpMethod method, IReadOnlyDictionary<string, IReadOnlyList<string>> customHeaders)
{
var httpRequest = new HttpRequestMessage();
httpRequest.Method = method;
httpRequest.RequestUri = new Uri(BaseUri, relativeUri);
var httpRequest = new HttpRequestMessage
{
Method = method,
RequestUri = new Uri(BaseUri, relativeUri),
};
#if NETSTANDARD2_1_OR_GREATER || NET5_0_OR_GREATER
httpRequest.Version = HttpVersion.Version20;
#endif

View File

@@ -61,8 +61,11 @@ namespace k8s
return InClusterConfig();
}
var config = new KubernetesClientConfiguration();
config.Host = "http://localhost:8080";
var config = new KubernetesClientConfiguration
{
Host = "http://localhost:8080",
};
return config;
}
@@ -274,14 +277,18 @@ namespace k8s
{
if (IPAddress.Equals(IPAddress.Any, ipAddress))
{
var builder = new UriBuilder(Host);
builder.Host = $"{IPAddress.Loopback}";
var builder = new UriBuilder(Host)
{
Host = $"{IPAddress.Loopback}",
};
Host = builder.ToString();
}
else if (IPAddress.Equals(IPAddress.IPv6Any, ipAddress))
{
var builder = new UriBuilder(Host);
builder.Host = $"{IPAddress.IPv6Loopback}";
var builder = new UriBuilder(Host)
{
Host = $"{IPAddress.IPv6Loopback}",
};
Host = builder.ToString();
}
}

View File

@@ -1,6 +1,6 @@
using System.IO;
using k8s.Authentication;
using k8s.Exceptions;
using System.IO;
namespace k8s
{

View File

@@ -1,6 +1,6 @@
using k8s.Autorest;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using k8s.Autorest;
namespace k8s
{

View File

@@ -8,7 +8,7 @@ namespace k8s
{
internal class KubernetesRequestDigest
{
private static Regex resourcePattern =
private static readonly Regex ResourcePattern =
new Regex(@"^/(api|apis)(/\S+)?/v\d\w*/\S+", RegexOptions.Compiled);
public string Path { get; }
@@ -94,13 +94,13 @@ namespace k8s
private static KubernetesRequestDigest NonResource(string urlPath)
{
KubernetesRequestDigest digest = new KubernetesRequestDigest(urlPath, true, "nonresource", "na", "na", "na");
var digest = new KubernetesRequestDigest(urlPath, true, "nonresource", "na", "na", "na");
return digest;
}
public static bool IsResourceRequest(string urlPath)
{
return resourcePattern.Matches(urlPath).Count > 0;
return ResourcePattern.Matches(urlPath).Count > 0;
}
private static bool HasWatchParameter(HttpRequestMessage request)

View File

@@ -62,7 +62,7 @@ namespace k8s.LeaderElection
{
unchecked
{
var hashCode = (HolderIdentity != null ? HolderIdentity.GetHashCode() : 0);
var hashCode = HolderIdentity != null ? HolderIdentity.GetHashCode() : 0;
hashCode = (hashCode * 397) ^ AcquireTime.GetHashCode();
hashCode = (hashCode * 397) ^ RenewTime.GetHashCode();
return hashCode;

View File

@@ -1,7 +1,7 @@
using k8s.Autorest;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using k8s.Autorest;
namespace k8s.LeaderElection
{

View File

@@ -1,7 +1,7 @@
using k8s.Autorest;
using k8s.Models;
using System.Threading;
using System.Threading.Tasks;
using k8s.Models;
using k8s.Autorest;
namespace k8s.LeaderElection.ResourceLock
@@ -9,10 +9,10 @@ namespace k8s.LeaderElection.ResourceLock
public abstract class MetaObjectLock<T> : ILock
where T : class, IMetadata<V1ObjectMeta>, new()
{
private IKubernetes client;
private string ns;
private string name;
private string identity;
private readonly IKubernetes client;
private readonly string ns;
private readonly string name;
private readonly string identity;
private T metaObjCache;
protected MetaObjectLock(IKubernetes client, string @namespace, string name, string identity)

View File

@@ -5,8 +5,8 @@ namespace k8s.LeaderElection.ResourceLock
{
public class MultiLock : ILock
{
private ILock primary;
private ILock secondary;
private readonly ILock primary;
private readonly ILock secondary;
public MultiLock(ILock primary, ILock secondary)
{

View File

@@ -7,9 +7,9 @@ namespace k8s
/// </summary>
public class MuxedStream : Stream
{
private ByteBuffer inputBuffer;
private byte? outputIndex;
private StreamDemuxer muxer;
private readonly ByteBuffer inputBuffer;
private readonly byte? outputIndex;
private readonly StreamDemuxer muxer;
/// <summary>
/// Initializes a new instance of the <see cref="MuxedStream"/> class.

View File

@@ -1,9 +1,9 @@
using k8s.Models;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using k8s.Models;
namespace k8s
{

View File

@@ -1,7 +1,7 @@
using k8s.Autorest;
using k8s.Exceptions;
using System.IO;
using System.Threading.Tasks;
using k8s.Exceptions;
using k8s.Autorest;
namespace k8s
{

View File

@@ -1,8 +1,8 @@
using System.Collections.Generic;
using System.Linq;
using CaseExtensions;
using Microsoft.CodeAnalysis;
using NSwag;
using System.Collections.Generic;
using System.Linq;
namespace LibKubernetesGenerator
{

View File

@@ -1,9 +1,9 @@
using System.Collections.Generic;
using System.Linq;
using CaseExtensions;
using NJsonSchema;
using NSwag;
using Nustache.Core;
using System.Collections.Generic;
using System.Linq;
namespace LibKubernetesGenerator
{

View File

@@ -1,10 +1,10 @@
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using CaseExtensions;
using NJsonSchema;
using NSwag;
using Nustache.Core;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace LibKubernetesGenerator
{
@@ -91,7 +91,7 @@ namespace LibKubernetesGenerator
var parameter = arguments[0] as OpenApiParameter;
context.Write(GetDotNetName(parameter.Name));
if (arguments.Count > 1 && arguments[1] as string == "true" && !parameter.IsRequired)
if (arguments.Count > 1 && (arguments[1] as string) == "true" && !parameter.IsRequired)
{
context.Write(" = null");
}

View File

@@ -12,11 +12,11 @@ namespace LibKubernetesGenerator
[Generator]
public class KubernetesClientSourceGenerator : ISourceGenerator
{
private static object execlock = new object();
private static readonly object Execlock = new object();
public void ExecuteInner(GeneratorExecutionContext context)
{
lock (execlock)
lock (Execlock)
{
var swaggerfile = context.AdditionalFiles.First(f => f.Path.EndsWith("swagger.json"));
var swagger = OpenApiDocument.FromJsonAsync(swaggerfile.GetText().ToString()).GetAwaiter().GetResult();
@@ -131,11 +131,11 @@ namespace LibKubernetesGenerator
public void Initialize(GeneratorInitializationContext context)
{
#if DEBUG
// if (!Debugger.IsAttached)
// {
// Debugger.Launch();
// }
// if (!Debugger.IsAttached)
// {
// Debugger.Launch();
// }
#endif
}
}
}
}

View File

@@ -1,8 +1,8 @@
using System;
using System.Collections.Generic;
using NJsonSchema;
using NSwag;
using Nustache.Core;
using System;
using System.Collections.Generic;
namespace LibKubernetesGenerator
{

View File

@@ -1,7 +1,7 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using NSwag;
using System.Collections.Generic;
using System.Linq;
namespace LibKubernetesGenerator
{

View File

@@ -1,8 +1,8 @@
using System.Collections.Generic;
using System.Linq;
using NJsonSchema;
using NSwag;
using Nustache.Core;
using System.Collections.Generic;
using System.Linq;
namespace LibKubernetesGenerator
{

View File

@@ -1,9 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using NJsonSchema;
using NSwag;
using Nustache.Core;
using System;
using System.Collections.Generic;
using System.Linq;
namespace LibKubernetesGenerator
{
@@ -11,7 +11,7 @@ namespace LibKubernetesGenerator
{
private readonly Dictionary<string, string> _classNameToPluralMap;
private readonly ClassNameHelper classNameHelper;
private HashSet<string> opblackList = new HashSet<string>()
private readonly HashSet<string> opblackList = new HashSet<string>()
{
"listClusterCustomObject",
"listNamespacedCustomObject",

View File

@@ -1,11 +1,11 @@
using NJsonSchema;
using Nustache.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security;
using System.Text.RegularExpressions;
using NJsonSchema;
using Nustache.Core;
namespace LibKubernetesGenerator
{

View File

@@ -1,9 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using NJsonSchema;
using NSwag;
using Nustache.Core;
using System;
using System.Collections.Generic;
using System.Linq;
namespace LibKubernetesGenerator
{

View File

@@ -1,8 +1,8 @@
using NSwag;
using Nustache.Core;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using NSwag;
using Nustache.Core;
namespace LibKubernetesGenerator
{

View File

@@ -1,5 +1,5 @@
using Xunit;
using k8s.Models;
using Xunit;
namespace k8s.Tests;

View File

@@ -23,13 +23,17 @@ namespace k8s.Tests
[Fact]
public async Task WebSocketNamespacedPodExecAsync()
{
Kubernetes client = new Kubernetes(new KubernetesClientConfiguration()
var clientConfiguration = new KubernetesClientConfiguration()
{
Host = "http://localhost",
Username = "my-user",
Password = "my-secret-password",
});
client.BaseUri = new Uri("http://localhost");
};
var client = new Kubernetes(clientConfiguration)
{
BaseUri = new Uri("http://localhost"),
};
MockWebSocketBuilder mockWebSocketBuilder = new MockWebSocketBuilder();
client.CreateWebSocketBuilder = () => mockWebSocketBuilder;
@@ -113,8 +117,10 @@ namespace k8s.Tests
Host = "http://localhost",
Username = "my-user",
Password = "my-secret-password",
});
client.BaseUri = new Uri("http://localhost");
})
{
BaseUri = new Uri("http://localhost"),
};
MockWebSocketBuilder mockWebSocketBuilder = new MockWebSocketBuilder();
client.CreateWebSocketBuilder = () => mockWebSocketBuilder;

View File

@@ -40,8 +40,10 @@ metadata:
[Fact]
public void LoadAllFromStringWithTypes()
{
var types = new Dictionary<string, Type>();
types.Add("v1/Pod", typeof(MyPod));
var types = new Dictionary<string, Type>
{
{ "v1/Pod", typeof(MyPod) },
};
var content = @"apiVersion: v1
kind: Pod
@@ -89,8 +91,11 @@ metadata:
[Fact]
public void LoadAllFromStringWithAdditionalPropertiesAndTypes()
{
var types = new Dictionary<string, Type>();
types.Add("v1/Pod", typeof(MyPod));
var types = new Dictionary<string, Type>
{
{ "v1/Pod", typeof(MyPod) },
};
var content = @"apiVersion: v1
kind: Pod
metadata:
@@ -150,8 +155,10 @@ metadata:
[Fact]
public async Task LoadAllFromFileWithTypes()
{
var types = new Dictionary<string, Type>();
types.Add("v1/Pod", typeof(MyPod));
var types = new Dictionary<string, Type>
{
{ "v1/Pod", typeof(MyPod) },
};
var content = @"apiVersion: v1
kind: Pod
@@ -279,12 +286,11 @@ metadata:
name: foo
";
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(content)))
{
var obj = KubernetesYaml.LoadFromStreamAsync<V1Pod>(stream).Result;
using var stream = new MemoryStream(Encoding.UTF8.GetBytes(content));
Assert.Equal("foo", obj.Metadata.Name);
}
var obj = KubernetesYaml.LoadFromStreamAsync<V1Pod>(stream).Result;
Assert.Equal("foo", obj.Metadata.Name);
}
[Fact]
@@ -430,18 +436,17 @@ spec:
private static IEnumerable<string> ToLines(string s)
{
using (var reader = new StringReader(s))
{
for (; ; )
{
var line = reader.ReadLine();
if (line == null)
{
yield break;
}
using var reader = new StringReader(s);
yield return line;
for (; ; )
{
var line = reader.ReadLine();
if (line == null)
{
yield break;
}
yield return line;
}
}

View File

@@ -111,8 +111,12 @@ namespace k8s.Tests
public void TestReferences()
{
// test object references
var pod = new V1Pod() { ApiVersion = "v1", Kind = "Pod" };
pod.Metadata = new V1ObjectMeta() { Name = "name", NamespaceProperty = "ns", ResourceVersion = "ver", Uid = "id" };
var pod = new V1Pod
{
ApiVersion = "v1",
Kind = "Pod",
Metadata = new V1ObjectMeta() { Name = "name", NamespaceProperty = "ns", ResourceVersion = "ver", Uid = "id" },
};
var objr = new V1ObjectReference() { ApiVersion = pod.ApiVersion, Kind = pod.Kind, Name = pod.Name(), NamespaceProperty = pod.Namespace(), Uid = pod.Uid() };
Assert.True(objr.Matches(pod));