Skip to content

Commit

Permalink
fix #52
Browse files Browse the repository at this point in the history
  • Loading branch information
jonsequitur committed Jul 1, 2022
1 parent 1515b07 commit effb835
Show file tree
Hide file tree
Showing 8 changed files with 143 additions and 106 deletions.
65 changes: 65 additions & 0 deletions src/dotnet-repl.Tests/Notebooks/NotebookAutomationTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using System;
using System.CommandLine.IO;
using System.CommandLine.Parsing;
using System.IO;
using System.Threading.Tasks;
using dotnet_repl.Tests.Utility;
using FluentAssertions;
using Pocket;
using Spectre.Console;
using Xunit;

namespace dotnet_repl.Tests.Notebooks;

public class NotebookAutomationTests : IDisposable
{
private readonly IAnsiConsole _ansiConsole;

private readonly StringWriter _writer;

public NotebookAutomationTests()
{
_ansiConsole = AnsiConsole.Create(new AnsiConsoleSettings
{
Ansi = AnsiSupport.Yes,
Interactive = InteractionSupport.Yes,
Out = new AnsiConsoleOutput(_writer = new StringWriter())
});
}

public void Dispose() => _writer.Dispose();

[Fact]
public async Task When_an_ipynb_is_run_and_no_error_is_produced_then_the_exit_code_is_0()
{
using var disposables = new CompositeDisposable();
var directory = Path.GetDirectoryName(PathUtility.PathToCurrentSourceFile());

var parser = CommandLineParser.Create(_ansiConsole, registerForDisposal: d => disposables.Add(d));

var console = new TestConsole();
var result = await parser.InvokeAsync($"--notebook \"{directory}/succeed.ipynb\" --exit-after-run", console);

var output = _writer.ToString();
console.Error.ToString().Should().BeEmpty();
result.Should().Be(0);
output.Should().Contain("Success!");
}

[Fact]
public async Task When_an_ipynb_is_run_and_an_error_is_produced_from_a_cell_then_the_exit_code_is_1()
{
using var disposables = new CompositeDisposable();
var directory = Path.GetDirectoryName(PathUtility.PathToCurrentSourceFile());

var parser = CommandLineParser.Create(_ansiConsole, registerForDisposal: d => disposables.Add(d));

var console = new TestConsole();
var result = await parser.InvokeAsync($"--notebook \"{directory}/fail.ipynb\" --exit-after-run", console);

var output = _writer.ToString();
console.Error.ToString().Should().BeEmpty();
result.Should().Be(1);
output.Should().Contain("Oops!");
}
}
51 changes: 51 additions & 0 deletions src/dotnet-repl.Tests/Notebooks/fail.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Here is a Markdown heading\n",
"\n",
"And here is some text."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"dotnet_interactive": {
"language": "csharp"
}
},
"source": [
"throw new Exception(\"Oops!\");"
],
"outputs": [
{
"output_type": "error",
"ename": "",
"evalue": "System.Exception: oops!\r\n at Submission#2.<<Initialize>>d__0.MoveNext()\r\n--- End of stack trace from previous location ---\r\n at Microsoft.CodeAnalysis.Scripting.ScriptExecutionState.RunSubmissionsAsync[TResult](ImmutableArray`1 precedingExecutors, Func`2 currentExecutor, StrongBox`1 exceptionHolderOpt, Func`2 catchExceptionOpt, CancellationToken cancellationToken)",
"traceback": [
null
]
}
]
}
],
"metadata": {
"kernelspec": {
"display_name": ".NET (C#)",
"language": "C#",
"name": ".net-csharp"
},
"language_info": {
"file_extension": ".cs",
"mimetype": "text/x-csharp",
"name": "C#",
"pygments_lexer": "csharp",
"version": "8.0"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,50 +11,21 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 1,
"metadata": {
"dotnet_interactive": {
"language": "csharp"
},
"vscode": {
"languageId": "dotnet-interactive.csharp"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello from C#"
]
}
],
"source": [
"Console.Write(\"Hello from C#\");"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"dotnet_interactive": {
"language": "fsharp"
},
"vscode": {
"languageId": "dotnet-interactive.fsharp"
}
},
"Console.Write(\"Success!\");"
],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello from F#"
]
"name": "stdout",
"text": "Hello from C#"
}
],
"source": [
"\"Hello from F#\" |> Console.Write"
]
}
],
Expand All @@ -74,4 +45,4 @@
},
"nbformat": 4,
"nbformat_minor": 4
}
}
62 changes: 0 additions & 62 deletions src/dotnet-repl.Tests/StartWithNotebookTests.cs

This file was deleted.

5 changes: 4 additions & 1 deletion src/dotnet-repl.Tests/dotnet-repl.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,10 @@
</ItemGroup>

<ItemGroup>
<None Update="test.ipynb">
<None Update="Notebooks\fail.ipynb">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="Notebooks\succeed.ipynb">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion src/dotnet-repl/Bind.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ internal class ServiceProviderBinder<T> : BinderBase<T>
{
public static ServiceProviderBinder<T> Instance { get; } = new();

protected override T GetBoundValue(BindingContext bindingContext) => (T)bindingContext.GetService(typeof(T));
protected override T GetBoundValue(BindingContext bindingContext) => (T)bindingContext.GetService(typeof(T))!;
}
}
5 changes: 4 additions & 1 deletion src/dotnet-repl/KeyBindings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ internal static class KeyBindings
{
public static void AddKeyBindings(this Repl repl)
{
var editor = repl.LineEditor;
if (repl.LineEditor is not { } editor)
{
return;
}

// Remove old keybinding for autocomplete
editor.KeyBindings.Remove(ConsoleKey.Tab);
Expand Down
18 changes: 12 additions & 6 deletions src/dotnet-repl/Repl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,11 @@ public Repl(

_disposables.Add(() => { _disposalTokenSource.Cancel(); });

LineEditorProvider = new LineEditorServiceProvider(new KernelCompletion(_kernel));
LineEditor = GetLineEditorLanguageLocal(_kernel.DefaultKernelName);
if (inputSource?.IsKeyAvailable() == true)
{
LineEditorProvider = new LineEditorServiceProvider(new KernelCompletion(_kernel));
LineEditor = GetLineEditorLanguageLocal(_kernel.DefaultKernelName);
}

_kernel.AddMiddleware(async (command, context, next) =>
{
Expand Down Expand Up @@ -92,7 +95,7 @@ public Repl(

public IInputSource? InputSource { get; }

public LineEditor LineEditor { get; private set; }
public LineEditor? LineEditor { get; private set; }

internal Action QuitAction { get; }

Expand Down Expand Up @@ -129,12 +132,15 @@ public async Task RunAsync(
{
SetTheme();
_readyForInput.OnNext(Unit.Default);
input = await LineEditor.ReadLine(_disposalTokenSource.Token);
input = await LineEditor!.ReadLine(_disposalTokenSource.Token);
}
}
else
{
LineEditor.History.Add(input);
if (!exitAfterRun)
{
LineEditor!.History.Add(input);
}
}

if (_disposalTokenSource.IsCancellationRequested)
Expand Down Expand Up @@ -162,7 +168,7 @@ private void SetTheme()
{
Theme = theme;

if (LineEditor.Prompt is DelegatingPrompt d)
if (LineEditor?.Prompt is DelegatingPrompt d)
{
d.InnerPrompt = theme.Prompt;
}
Expand Down

0 comments on commit effb835

Please sign in to comment.